commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
8bb2356aa9c68f1569b94df8b5b8f0fdd6cb1720
src/dubwizard.cpp
src/dubwizard.cpp
#include "dubwizard.h" #include "dubprojectmanagerconstants.h" #include "duboptionspage.h" #include <projectexplorer/projectexplorerconstants.h> #include <utils/pathchooser.h> #include <texteditor/fontsettings.h> #include <projectexplorer/projectexplorer.h> #include <QDir> #include <QFormLayout> #include <QHBoxLayout> #include <QComboBox> #include <QLabel> #include <QLineEdit> #include <QPlainTextEdit> #include <QFileInfo> #include <QProcess> #include <QMessageBox> #include <QScopedPointer> const char CATEGORY[] = "I.Projects"; const char DISPLAY_CATEGORY[] = QT_TRANSLATE_NOOP("DubWizard", "Non-Qt Project"); const char WIZARD_ID[] = "WI.DubWizard"; const QString DUB_INIT_NO_TYPE = QLatin1String("<no type>"); using namespace DubProjectManager; DubWizard::DubWizard() { setSupportedProjectTypes(supportedProjectTypes() << DubProjectManager::Constants::DUBPROJECT_ID); setCategory(CATEGORY); setDisplayCategory(DISPLAY_CATEGORY); setDescription("Create empty DUB project"); setDisplayName("DUB Project"); setId(WIZARD_ID); setFlags(PlatformIndependent); } Utils::Wizard *DubWizard::runWizardImpl(const QString &path, QWidget *parent, Core::Id platform, const QVariantMap &variables) { Q_UNUSED(path) Q_UNUSED(platform) Q_UNUSED(variables) QScopedPointer<DubWizardWidget> widget(new DubWizardWidget); if (widget->exec() == DubWizardWidget::Accepted) { QDir dir(widget->directory()); const QString ERROR = tr("Error"); if (!dir.exists()) { QMessageBox::critical(parent, ERROR, tr("Directory %1 does not exist").arg(dir.absolutePath())); return widget.take(); } auto entries = dir.entryList(QStringList() << QLatin1String("dub.sdl") << QLatin1String("dub.json"), QDir::Files); if (entries.isEmpty()) { QMessageBox::critical(parent, ERROR, tr("File dub.(sdl|json) does not exist in %1").arg( dir.absolutePath())); return widget.take(); } QFileInfo dubFile(dir, entries.front()); QString errorMessage; auto openProjectResult = ProjectExplorer::ProjectExplorerPlugin::instance()->openProject( dubFile.absoluteFilePath()); if (!openProjectResult) { QMessageBox::critical(parent, ERROR, tr("Failed to open project: ") + openProjectResult.errorMessage()); return widget.take(); } } return widget.take(); } DubWizardWidget::DubWizardWidget() { setWindowTitle(tr("Init DUB project")); addPage(new DubInitSettingsPage(this)); addPage(new DubInitResultsPage(this)); } void DubWizardWidget::setDubCommand(const QString &cmd) { m_dubCommand = cmd; } void DubWizardWidget::setDubArguments(const QStringList &args) { m_dubArguments = args; } QString DubWizardWidget::dubCommand() const { return m_dubCommand; } QStringList DubWizardWidget::dubArguments() const { return m_dubArguments; } void DubWizardWidget::setDirectory(const QString &dir) { m_directory = dir; } QString DubWizardWidget::directory() const { return m_directory; } DubInitSettingsPage::DubInitSettingsPage(DubWizardWidget *parent) : m_wizardWidget(parent) { auto layout = new QFormLayout(this); QLabel *description = new QLabel; description->setWordWrap(true); description->setText( tr("Please enter the directory in which you want to build your DUB project. \n" "Qt Creator will execute DUB with the following arguments " "to initialize the project.")); description->setSizeIncrement(0, 100); layout->addRow(description); m_pc = new Utils::PathChooser; m_pc->setToolTip("Accepts only absolute paths)"); layout->addRow("Directory: ", m_pc); connect(m_pc, &Utils::PathChooser::pathChanged, [this] { this->updateDubCommand(); emit completeChanged(); }); m_dubCommand = new QLabel; layout->addRow("DUB command: ", m_dubCommand); m_dubInitType = new QComboBox; connect(m_dubInitType, &QComboBox::currentTextChanged, [this]() { this->updateDubCommand(); }); layout->addRow("Init type: ", m_dubInitType); m_dubInitExtraArguments = new QLineEdit; connect(m_dubInitExtraArguments, &QLineEdit::textChanged, [this]() { this->updateDubCommand(); }); layout->addRow("Extra arguments: ", m_dubInitExtraArguments); setLayout(layout); m_dubInitType->addItems(QStringList() << DUB_INIT_NO_TYPE << "minimal" << "vibe.d"); emit completeChanged(); setTitle(tr("Configure project")); } bool DubInitSettingsPage::validatePage() { const QString path = m_pc->path(); m_wizardWidget->setDubCommand(getCommand()); m_wizardWidget->setDubArguments(getArguments()); m_wizardWidget->setDirectory(path); QDir dir(path); if (dir.exists()) { return QMessageBox::warning(this, tr("Warning"), tr("Path %1 already exists.\nPress OK to continue creating " "project or CANCEL to cancel.").arg(dir.absolutePath()), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok; } return true; } bool DubInitSettingsPage::isComplete() const { const QString path = m_pc->path(); return !path.isEmpty() && QDir(path).isAbsolute(); } void DubInitSettingsPage::updateDubCommand() { QChar delim = QLatin1Char(' '); m_dubCommand->setText(getCommand() + delim + getArguments().join(delim)); } QStringList DubInitSettingsPage::getArguments() const { QStringList result; result << QLatin1String("init") << m_pc->path(); auto type = m_dubInitType->currentText(); if (type != DUB_INIT_NO_TYPE) { result << type; } auto args = m_dubInitExtraArguments->text(); if (!args.isEmpty()) { result << m_dubInitExtraArguments->text(); } return result; } QString DubInitSettingsPage::getCommand() const { return DubOptionsPage::executable(); } DubInitResultsPage::DubInitResultsPage(DubWizardWidget *parent) : m_wizardWidget(parent), m_isCompleted(false) { setTitle(tr("Run DUB")); auto layout = new QFormLayout; m_output = new QPlainTextEdit; m_output->setReadOnly(true); m_output->setMinimumHeight(15); QFont f(TextEditor::FontSettings::defaultFixedFontFamily()); f.setStyleHint(QFont::TypeWriter); m_output->setFont(f); QSizePolicy pl = m_output->sizePolicy(); pl.setVerticalStretch(2); m_output->setSizePolicy(pl); layout->addRow(m_output); m_exitCode = new QLabel; layout->addRow("Exit code: ", m_exitCode); setLayout(layout); } void DubInitResultsPage::initializePage() { setCompleted(false); m_dubProcess.reset(); m_dubProcess = QSharedPointer<QProcess>(new QProcess); m_dubProcess->setProgram(m_wizardWidget->dubCommand()); m_dubProcess->setArguments(m_wizardWidget->dubArguments()); connect(m_dubProcess.data(), SIGNAL(readyReadStandardOutput()), this, SLOT(dubReadyReadStandardOutput())); connect(m_dubProcess.data(), SIGNAL(readyReadStandardError()), this, SLOT(dubReadyReadStandardError())); connect(m_dubProcess.data(), SIGNAL(finished(int)), this, SLOT(dubFinished())); m_dubProcess->start(QProcess::ReadOnly); } bool DubInitResultsPage::validatePage() { return true; } bool DubInitResultsPage::isComplete() const { return m_isCompleted; } void DubInitResultsPage::cleanupPage() { m_output->clear(); } void DubInitResultsPage::dubReadyReadStandardOutput() { QTextCursor cursor(m_output->document()); cursor.movePosition(QTextCursor::End); QTextCharFormat tf; QFont font = m_output->font(); tf.setFont(font); tf.setForeground(m_output->palette().color(QPalette::Text)); cursor.insertText(QString::fromLocal8Bit(m_dubProcess->readAllStandardOutput()), tf); } static QColor mix_colors(const QColor &a, const QColor &b) { return QColor((a.red() + 2 * b.red()) / 3, (a.green() + 2 * b.green()) / 3, (a.blue() + 2* b.blue()) / 3, (a.alpha() + 2 * b.alpha()) / 3); } void DubInitResultsPage::dubReadyReadStandardError() { QTextCursor cursor(m_output->document()); QTextCharFormat tf; QFont font = m_output->font(); QFont boldFont = font; boldFont.setBold(true); tf.setFont(boldFont); tf.setForeground(mix_colors(m_output->palette().color(QPalette::Text), QColor(Qt::red))); cursor.insertText(QString::fromLocal8Bit(m_dubProcess->readAllStandardError()), tf); } void DubInitResultsPage::dubFinished() { QString exitStatus = QString::number(m_dubProcess->exitCode()); if (m_dubProcess->exitCode() == 0 && m_dubProcess->exitStatus() == QProcess::NormalExit) { setCompleted(true); } else { exitStatus += " (" + m_dubProcess->errorString() + ")"; setCompleted(false); } m_exitCode->setText(exitStatus); } void DubInitResultsPage::setCompleted(bool b) { m_isCompleted = b; emit completeChanged(); }
#include "dubwizard.h" #include "dubprojectmanagerconstants.h" #include "duboptionspage.h" #include <projectexplorer/projectexplorerconstants.h> #include <utils/pathchooser.h> #include <texteditor/fontsettings.h> #include <projectexplorer/projectexplorer.h> #include <QDir> #include <QFormLayout> #include <QHBoxLayout> #include <QComboBox> #include <QLabel> #include <QLineEdit> #include <QPlainTextEdit> #include <QFileInfo> #include <QProcess> #include <QMessageBox> #include <QScopedPointer> const char CATEGORY[] = "I.Projects"; const char DISPLAY_CATEGORY[] = QT_TRANSLATE_NOOP("DubWizard", "Non-Qt Project"); const char WIZARD_ID[] = "WI.DubWizard"; const QString DUB_INIT_NO_TYPE = QLatin1String("<no type>"); using namespace DubProjectManager; DubWizard::DubWizard() { setSupportedProjectTypes(supportedProjectTypes() << DubProjectManager::Constants::DUBPROJECT_ID); setCategory(CATEGORY); setDisplayCategory(DISPLAY_CATEGORY); setDescription("Create empty DUB project"); setDisplayName("DUB Project"); setId(WIZARD_ID); setFlags(PlatformIndependent); } Utils::Wizard *DubWizard::runWizardImpl(const QString &path, QWidget *parent, Core::Id platform, const QVariantMap &variables) { Q_UNUSED(path) Q_UNUSED(platform) Q_UNUSED(variables) QScopedPointer<DubWizardWidget> widget(new DubWizardWidget); if (widget->exec() == DubWizardWidget::Accepted) { QDir dir(widget->directory()); const QString ERROR = tr("Error"); if (!dir.exists()) { QMessageBox::critical(parent, ERROR, tr("Directory %1 does not exist").arg(dir.absolutePath())); return widget.take(); } auto entries = dir.entryList(QStringList() << QLatin1String("dub.sdl") << QLatin1String("dub.json"), QDir::Files); if (entries.isEmpty()) { QMessageBox::critical(parent, ERROR, tr("File dub.(sdl|json) does not exist in %1").arg( dir.absolutePath())); return widget.take(); } QFileInfo dubFile(dir, entries.front()); QString errorMessage; auto openProjectResult = ProjectExplorer::ProjectExplorerPlugin::instance()->openProject( dubFile.absoluteFilePath()); if (!openProjectResult) { QMessageBox::critical(parent, ERROR, tr("Failed to open project: ") + openProjectResult.errorMessage()); return widget.take(); } } return widget.take(); } DubWizardWidget::DubWizardWidget() { setWindowTitle(tr("Init DUB project")); addPage(new DubInitSettingsPage(this)); addPage(new DubInitResultsPage(this)); } void DubWizardWidget::setDubCommand(const QString &cmd) { m_dubCommand = cmd; } void DubWizardWidget::setDubArguments(const QStringList &args) { m_dubArguments = args; } QString DubWizardWidget::dubCommand() const { return m_dubCommand; } QStringList DubWizardWidget::dubArguments() const { return m_dubArguments; } void DubWizardWidget::setDirectory(const QString &dir) { m_directory = dir; } QString DubWizardWidget::directory() const { return m_directory; } DubInitSettingsPage::DubInitSettingsPage(DubWizardWidget *parent) : m_wizardWidget(parent) { auto layout = new QFormLayout(this); QLabel *description = new QLabel; description->setWordWrap(true); description->setText( tr("Please enter the directory in which you want to build your DUB project. \n" "Qt Creator will execute DUB with the following arguments " "to initialize the project.")); description->setSizeIncrement(0, 100); layout->addRow(description); m_pc = new Utils::PathChooser; m_pc->setToolTip("Accepts only absolute paths)"); layout->addRow("Directory: ", m_pc); connect(m_pc, &Utils::PathChooser::pathChanged, [this] { this->updateDubCommand(); emit completeChanged(); }); m_dubCommand = new QLabel; layout->addRow("DUB command: ", m_dubCommand); m_dubInitType = new QComboBox; connect(m_dubInitType, &QComboBox::currentTextChanged, [this]() { this->updateDubCommand(); }); layout->addRow("Init type: ", m_dubInitType); m_dubInitExtraArguments = new QLineEdit; connect(m_dubInitExtraArguments, &QLineEdit::textChanged, [this]() { this->updateDubCommand(); }); layout->addRow("Extra arguments: ", m_dubInitExtraArguments); setLayout(layout); m_dubInitType->addItems(QStringList() << DUB_INIT_NO_TYPE << "minimal" << "vibe.d"); emit completeChanged(); setTitle(tr("Configure project")); } bool DubInitSettingsPage::validatePage() { const QString path = m_pc->path(); m_wizardWidget->setDubCommand(getCommand()); m_wizardWidget->setDubArguments(getArguments()); m_wizardWidget->setDirectory(path); QDir dir(path); if (dir.exists()) { return QMessageBox::warning(this, tr("Warning"), tr("Path %1 already exists.\nPress OK to continue creating " "project or CANCEL to cancel.").arg(dir.absolutePath()), QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Ok; } return true; } bool DubInitSettingsPage::isComplete() const { const QString path = m_pc->path(); return !path.isEmpty() && QDir(path).isAbsolute(); } void DubInitSettingsPage::updateDubCommand() { QChar delim = QLatin1Char(' '); m_dubCommand->setText(getCommand() + delim + getArguments().join(delim)); } QStringList DubInitSettingsPage::getArguments() const { QStringList result; result << QLatin1String("init") << m_pc->path(); auto type = m_dubInitType->currentText(); if (type != DUB_INIT_NO_TYPE) { result << type; } auto args = m_dubInitExtraArguments->text(); if (!args.isEmpty()) { result << m_dubInitExtraArguments->text(); } result << QLatin1String("-n"); return result; } QString DubInitSettingsPage::getCommand() const { return DubOptionsPage::executable(); } DubInitResultsPage::DubInitResultsPage(DubWizardWidget *parent) : m_wizardWidget(parent), m_isCompleted(false) { setTitle(tr("Run DUB")); auto layout = new QFormLayout; m_output = new QPlainTextEdit; m_output->setReadOnly(true); m_output->setMinimumHeight(15); QFont f(TextEditor::FontSettings::defaultFixedFontFamily()); f.setStyleHint(QFont::TypeWriter); m_output->setFont(f); QSizePolicy pl = m_output->sizePolicy(); pl.setVerticalStretch(2); m_output->setSizePolicy(pl); layout->addRow(m_output); m_exitCode = new QLabel; layout->addRow("Exit code: ", m_exitCode); setLayout(layout); } void DubInitResultsPage::initializePage() { setCompleted(false); m_dubProcess.reset(); m_dubProcess = QSharedPointer<QProcess>(new QProcess); m_dubProcess->setProgram(m_wizardWidget->dubCommand()); m_dubProcess->setArguments(m_wizardWidget->dubArguments()); connect(m_dubProcess.data(), SIGNAL(readyReadStandardOutput()), this, SLOT(dubReadyReadStandardOutput())); connect(m_dubProcess.data(), SIGNAL(readyReadStandardError()), this, SLOT(dubReadyReadStandardError())); connect(m_dubProcess.data(), SIGNAL(finished(int)), this, SLOT(dubFinished())); m_dubProcess->start(QProcess::ReadOnly); } bool DubInitResultsPage::validatePage() { return true; } bool DubInitResultsPage::isComplete() const { return m_isCompleted; } void DubInitResultsPage::cleanupPage() { m_output->clear(); } void DubInitResultsPage::dubReadyReadStandardOutput() { QTextCursor cursor(m_output->document()); cursor.movePosition(QTextCursor::End); QTextCharFormat tf; QFont font = m_output->font(); tf.setFont(font); tf.setForeground(m_output->palette().color(QPalette::Text)); cursor.insertText(QString::fromLocal8Bit(m_dubProcess->readAllStandardOutput()), tf); } static QColor mix_colors(const QColor &a, const QColor &b) { return QColor((a.red() + 2 * b.red()) / 3, (a.green() + 2 * b.green()) / 3, (a.blue() + 2* b.blue()) / 3, (a.alpha() + 2 * b.alpha()) / 3); } void DubInitResultsPage::dubReadyReadStandardError() { QTextCursor cursor(m_output->document()); QTextCharFormat tf; QFont font = m_output->font(); QFont boldFont = font; boldFont.setBold(true); tf.setFont(boldFont); tf.setForeground(mix_colors(m_output->palette().color(QPalette::Text), QColor(Qt::red))); cursor.insertText(QString::fromLocal8Bit(m_dubProcess->readAllStandardError()), tf); } void DubInitResultsPage::dubFinished() { QString exitStatus = QString::number(m_dubProcess->exitCode()); if (m_dubProcess->exitCode() == 0 && m_dubProcess->exitStatus() == QProcess::NormalExit) { setCompleted(true); } else { exitStatus += " (" + m_dubProcess->errorString() + ")"; setCompleted(false); } m_exitCode->setText(exitStatus); } void DubInitResultsPage::setCompleted(bool b) { m_isCompleted = b; emit completeChanged(); }
Fix #21: disable interactive mode for dub
Fix #21: disable interactive mode for dub
C++
mit
Groterik/qtcreator-dubmanager,Groterik/qtcreator-dubmanager,Groterik/qtcreator-dubmanager,Groterik/qtcreator-dubmanager
ab491283a4d9530a76e4a42dc6fd5903bc6ca2ef
include/static_math/cmath.inl
include/static_math/cmath.inl
/* * Copyright (C) 2013-2014 Morwenn * * static_math is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * static_math is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, * see <http://www.gnu.org/licenses/>. */ //////////////////////////////////////////////////////////// // Helper functions namespace details { template<typename T, typename Unsigned> constexpr auto pow_helper(T x, Unsigned exponent) -> std::common_type_t<T, Unsigned> { // Exponentiation by squaring return (exponent == 0) ? 1 : (exponent % 2 == 0) ? pow_helper(x*x, exponent/2) : x * pow_helper(x*x, (exponent-1)/2); } template<typename T> constexpr auto sqrt_helper(T x, T y) -> decltype(std::sqrt(x)) { return float_equal(x, y*y) ? y : sqrt_helper(x, (y + x/y) / 2.0); } } //////////////////////////////////////////////////////////// // Basic functions template<typename Number, typename = std::enable_if_t<std::is_arithmetic<Number>::value, void>> constexpr auto abs(Number x) -> Number { return (x >= 0) ? x : -x; } template<typename T, typename U> constexpr auto min(T first, U second) -> std::common_type_t<T, U> { return (first < second) ? first : second; } template<typename T, typename U, typename... Rest> constexpr auto min(T first, U second, Rest... rest) -> std::common_type_t<T, U, Rest...> { return (first < second) ? min(first, rest...) : min(second, rest...); } template<typename T, typename U> constexpr auto max(T first, U second) -> std::common_type_t<T, U> { return (first > second) ? first : second; } template<typename T, typename U, typename... Rest> constexpr auto max(T first, U second, Rest... rest) -> std::common_type_t<T, U, Rest...> { return (first > second) ? max(first, rest...) : max(second, rest...); } //////////////////////////////////////////////////////////// // Number-theoretic and representation functions template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto floor(Float x) -> decltype(std::floor(x)) { return (int(x) == x) ? int(x) : (x >= 0.0) ? int(x) : int(x) - 1; } template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto ceil(Float x) -> decltype(std::ceil(x)) { return (int(x) == x) ? int(x) : (x >= 0.0) ? int(x) + 1 : int(x); } template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto round(Float x) -> decltype(std::round(x)) { return (x >= 0.0) ? int(x + 0.5) : int(x - 0.5); } template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto trunc(Float x) -> decltype(std::trunc(x)) { return int(x); } //////////////////////////////////////////////////////////// // Power and logarithmic functions template<typename Number, typename Integer> constexpr auto pow(Number x, Integer exponent) -> std::common_type_t<Number, Integer> { static_assert(std::is_integral<Integer>::value, "pow only accepts integer exponents"); return (exponent == 0) ? 1 : (exponent > 0) ? details::pow_helper(x, exponent) : 1 / details::pow_helper(x, -exponent); } template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto sqrt(Float x) -> decltype(std::sqrt(x)) { return details::sqrt_helper(x, x); }
/* * Copyright (C) 2013-2014 Morwenn * * static_math is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * static_math is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, * see <http://www.gnu.org/licenses/>. */ //////////////////////////////////////////////////////////// // Helper functions namespace details { template<typename T, typename Unsigned> constexpr auto pow_helper(T x, Unsigned exponent) -> std::common_type_t<T, Unsigned> { // Exponentiation by squaring return (exponent == 0) ? 1 : (exponent % 2 == 0) ? pow_helper(x*x, exponent/2) : x * pow_helper(x*x, (exponent-1)/2); } template<typename T> constexpr auto sqrt_helper(T x, T y) -> decltype(std::sqrt(x)) { return smath::equals(x, y*y) ? y : sqrt_helper(x, (y + x/y) / 2.0); } } //////////////////////////////////////////////////////////// // Basic functions template<typename Number, typename = std::enable_if_t<std::is_arithmetic<Number>::value, void>> constexpr auto abs(Number x) -> Number { return (x >= 0) ? x : -x; } template<typename T, typename U> constexpr auto min(T first, U second) -> std::common_type_t<T, U> { return (first < second) ? first : second; } template<typename T, typename U, typename... Rest> constexpr auto min(T first, U second, Rest... rest) -> std::common_type_t<T, U, Rest...> { return (first < second) ? min(first, rest...) : min(second, rest...); } template<typename T, typename U> constexpr auto max(T first, U second) -> std::common_type_t<T, U> { return (first > second) ? first : second; } template<typename T, typename U, typename... Rest> constexpr auto max(T first, U second, Rest... rest) -> std::common_type_t<T, U, Rest...> { return (first > second) ? max(first, rest...) : max(second, rest...); } //////////////////////////////////////////////////////////// // Number-theoretic and representation functions template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto floor(Float x) -> decltype(std::floor(x)) { return (int(x) == x) ? int(x) : (x >= 0.0) ? int(x) : int(x) - 1; } template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto ceil(Float x) -> decltype(std::ceil(x)) { return (int(x) == x) ? int(x) : (x >= 0.0) ? int(x) + 1 : int(x); } template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto round(Float x) -> decltype(std::round(x)) { return (x >= 0.0) ? int(x + 0.5) : int(x - 0.5); } template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto trunc(Float x) -> decltype(std::trunc(x)) { return int(x); } //////////////////////////////////////////////////////////// // Power and logarithmic functions template<typename Number, typename Integer> constexpr auto pow(Number x, Integer exponent) -> std::common_type_t<Number, Integer> { static_assert(std::is_integral<Integer>::value, "pow only accepts integer exponents"); return (exponent == 0) ? 1 : (exponent > 0) ? details::pow_helper(x, exponent) : 1 / details::pow_helper(x, -exponent); } template<typename Float, typename = std::enable_if_t<std::is_floating_point<Float>::value, void>> constexpr auto sqrt(Float x) -> decltype(std::sqrt(x)) { return details::sqrt_helper(x, x); }
Change float_equal to equals. Fixes #1.
Change float_equal to equals. Fixes #1.
C++
mit
Morwenn/static_math,Morwenn/static_math
2aa2aabc2efe4cc28a5b1ffbcb081f358db0e2b7
ImWindow/ImwPlatformWindow.cpp
ImWindow/ImwPlatformWindow.cpp
#define IMGUI_DEFINE_MATH_OPERATORS #include "ImwPlatformWindow.h" #include "ImwWindowManager.h" namespace ImWindow { //SFF_BEGIN ImwPlatformWindow::ImwPlatformWindow(EPlatformWindowType eType, bool bCreateContext) { m_eType = eType; m_pContainer = new ImwContainer(this); m_pContext = NULL; m_pPreviousContext = NULL; m_bNeedRender = false; m_bShowContent = true; if ( bCreateContext ) { ImGuiContext* pGlobalContext = ImGui::GetCurrentContext(); IM_ASSERT(pGlobalContext != NULL); m_pContext = ImGui::CreateContext( pGlobalContext->IO.MemAllocFn, pGlobalContext->IO.MemFreeFn ); ImGuiIO& oGlobalIO = pGlobalContext->IO; ImGuiIO& oNewIO = m_pContext->IO; memcpy(&(oNewIO.KeyMap), &(oGlobalIO.KeyMap ), sizeof( pGlobalContext->IO.KeyMap )); oNewIO.RenderDrawListsFn = NULL; oNewIO.GetClipboardTextFn = oGlobalIO.GetClipboardTextFn; oNewIO.SetClipboardTextFn = oGlobalIO.SetClipboardTextFn; oNewIO.ImeSetInputScreenPosFn = oGlobalIO.ImeSetInputScreenPosFn; oNewIO.IniFilename = NULL; } } ImwPlatformWindow::~ImwPlatformWindow() { PreDestroy(); } bool ImwPlatformWindow::Init(ImwPlatformWindow* /*pParent*/) { return true; } EPlatformWindowType ImwPlatformWindow::GetType() const { return m_eType; } bool ImwPlatformWindow::IsMainWindow() const { return m_eType == E_PLATFORM_WINDOW_TYPE_MAIN; } const ImVec2 c_oVec2_0 = ImVec2(0,0); ImVec2 ImwPlatformWindow::GetPosition() const { return c_oVec2_0; } ImVec2 ImwPlatformWindow::GetSize() const { return ImGui::GetIO().DisplaySize; } ImVec2 ImwPlatformWindow::GetNormalPosition() const { return GetPosition(); } ImVec2 ImwPlatformWindow::GetNormalSize() const { return GetSize(); } bool ImwPlatformWindow::IsWindowMaximized() const { return false; } bool ImwPlatformWindow::IsWindowMinimized() const { return false; } void ImwPlatformWindow::Show(bool /*bShow*/) { } void ImwPlatformWindow::SetSize(int /*iWidth*/, int /*iHeight*/) { } void ImwPlatformWindow::SetPosition(int /*iX*/, int /*iY*/) { } void ImwPlatformWindow::SetWindowMaximized(bool /*bMaximized*/) { } void ImwPlatformWindow::SetWindowMinimized(bool /*bMinimized*/) { } void ImwPlatformWindow::SetTitle(const char* /*pTtile*/) { } bool ImwPlatformWindow::IsShowContent() const { return m_bShowContent; } void ImwPlatformWindow::SetShowContent(bool bShow) { m_bShowContent = bShow; } void ImwPlatformWindow::PreUpdate() { } void ImwPlatformWindow::PreRender() { } void ImwPlatformWindow::OnOverlay() { } void ImwPlatformWindow::RenderDrawLists(ImDrawData* /*pDrawData */) { } void ImwPlatformWindow::PreDestroy() { ImwSafeDelete(m_pContainer); if (m_pContext != NULL) { m_pContext->IO.Fonts = NULL; SetContext(false); ImGui::Shutdown(); RestoreContext(false); ImGui::DestroyContext(m_pContext); m_pContext = NULL; } if (ImwWindowManager::GetInstance() != NULL && ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow == this) ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow = NULL; } void ImwPlatformWindow::OnFocus(bool bFocused) { if (bFocused) { ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow = this; } else { if (ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow == this) ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow = NULL; if (NULL != m_pContext) { m_pContext->SetNextWindowPosCond = m_pContext->SetNextWindowSizeCond = m_pContext->SetNextWindowContentSizeCond = m_pContext->SetNextWindowCollapsedCond = m_pContext->SetNextWindowFocus = 0; m_pContext->ActiveId = 0; for (int i = 0; i < 512; ++i) m_pContext->IO.KeysDown[i] = false; for (int i = 0; i < 5; ++i) m_pContext->IO.MouseDown[i] = false; m_pContext->IO.KeyAlt = false; m_pContext->IO.KeyCtrl = false; m_pContext->IO.KeyShift = false; } } } void ImwPlatformWindow::Render() { if( m_bNeedRender ) { m_bNeedRender = false; SetContext(false); ImGui::GetIO().DisplaySize = GetSize(); PreRender(); ImGui::Render(); RenderDrawLists(ImGui::GetDrawData()); RestoreContext(false); } } void ImwPlatformWindow::PaintContainer() { m_pContainer->Paint(); } void ImwPlatformWindow::OnClose() { ImwWindowManager::GetInstance()->OnClosePlatformWindow(this); } void ImwPlatformWindow::OnDropFiles(int iCount, char** pFiles, const ImVec2& oPos) { ImwWindow* pWindow = GetWindowAtPos(oPos); IM_ASSERT(pWindow != NULL); if (pWindow != NULL) { pWindow->OnDropFiles(iCount, pFiles, oPos); } } void ImwPlatformWindow::Moving(bool bFirst) { ImVec2 oCursorPos = ImwWindowManager::GetInstance()->GetCursorPos(); if (bFirst) { m_oMovingStartPos = oCursorPos; m_bMoving = false; m_oMovingOffset = oCursorPos - GetPosition(); } else { ImVec2 oCursorDiff = oCursorPos - m_oMovingStartPos; const int c_iPixelThreshold = 2; if (m_bMoving == false && (oCursorDiff.x * oCursorDiff.x + oCursorDiff.y * oCursorDiff.y) > (c_iPixelThreshold * c_iPixelThreshold)) m_bMoving = true; if (m_bMoving) { if (IsWindowMaximized()) { SetWindowMaximized(false); ImVec2 oSize = GetSize(); if (m_oMovingOffset.x > oSize.x / 2.f) { m_oMovingOffset.x = oSize.x / 2.f; } } ImVec2 oNewPos = oCursorPos - m_oMovingOffset; SetPosition((int)oNewPos.x, (int)oNewPos.y); } } } #ifdef IMW_USE_LAYOUT_SERIALIZATION bool ImwPlatformWindow::Save(JsonStthm::JsonValue& oJson) { ImVec2 oSize = GetNormalSize(); ImVec2 oPos = GetNormalPosition(); oJson["Width"] = (int64_t)oSize.x; oJson["Height"] = (int64_t)oSize.y; oJson["Left"] = (int64_t)oPos.x; oJson["Top"] = (int64_t)oPos.y; oJson["Maximized"] = IsWindowMaximized(); oJson["Minimized"] = IsWindowMinimized(); return m_pContainer->Save(oJson["Container"]); } bool ImwPlatformWindow::Load(const JsonStthm::JsonValue& oJson, bool bJustCheck) { if (!oJson["Width"].IsNumeric() || !oJson["Height"].IsNumeric() || !oJson["Left"].IsNumeric() || !oJson["Top"].IsNumeric() || (!oJson["Mode"].IsNumeric() && !oJson["Maximized"].IsBoolean())) return false; if (!bJustCheck) { SetSize((int)oJson["Width"].ToInteger(), (int)oJson["Height"].ToInteger()); SetPosition((int)oJson["Left"].ToInteger(), (int)oJson["Top"].ToInteger()); if (oJson["Mode"].IsNumeric()) { int iMode = (int)oJson["Mode"].ToInteger(); if (iMode < 0) { SetWindowMinimized(true); } else { SetWindowMaximized(iMode > 0); } } if (oJson["Maximized"].IsBoolean()) { SetWindowMaximized(oJson["Maximized"].ToBoolean()); } if( oJson[ "Minimized" ].IsBoolean() ) { SetWindowMinimized(oJson["Minimized"].ToBoolean()); } } return m_pContainer->Load(oJson["Container"], bJustCheck); } #endif //IMW_USE_LAYOUT_SERIALIZATION static bool s_bContextPushed = false; bool ImwPlatformWindow::IsContextSet() { return s_bContextPushed; } bool ImwPlatformWindow::HasContext() const { return m_pContext != NULL; } ImGuiContext* ImwPlatformWindow::GetContext() { if (m_pContext != NULL) return m_pContext; return ImGui::GetCurrentContext(); } void ImwPlatformWindow::SetContext(bool bCopyStyle) { IM_ASSERT(s_bContextPushed == false); s_bContextPushed = true; if (m_pContext != NULL) { IM_ASSERT( m_pPreviousContext == NULL ); m_pPreviousContext = ImGui::GetCurrentContext(); ImGui::SetCurrentContext(m_pContext); if (bCopyStyle) { //Copy style from Global context memcpy(&(m_pContext->Style), &(m_pPreviousContext->Style), sizeof(ImGuiStyle)); } } } void ImwPlatformWindow::RestoreContext(bool bCopyStyle) { IM_ASSERT(s_bContextPushed == true); s_bContextPushed = false; if (m_pContext != NULL) { IM_ASSERT(m_pPreviousContext != NULL); if (bCopyStyle) { //Copy style to Global context memcpy(&(m_pPreviousContext->Style), &(m_pContext->Style), sizeof(ImGuiStyle)); } ImGui::SetCurrentContext(m_pPreviousContext); m_pPreviousContext = NULL; } } void ImwPlatformWindow::Dock(ImwWindow* pWindow) { m_pContainer->Dock(pWindow); } bool ImwPlatformWindow::UnDock(ImwWindow* pWindow) { return m_pContainer->UnDock(pWindow); } ImwContainer* ImwPlatformWindow::GetContainer() { return m_pContainer; } ImwWindow* ImwPlatformWindow::GetWindowAtPos(const ImVec2& oPos) const { return m_pContainer->GetWindowAtPos(oPos); } const ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow) { return m_pContainer->HasWindow(pWindow); } bool ImwPlatformWindow::FocusWindow(ImwWindow* pWindow) { return m_pContainer->FocusWindow(pWindow); } void ImwPlatformWindow::RefreshTitle() { const char* pMainTitle = ImwWindowManager::GetInstance()->GetMainTitle(); ImwWindow* pActiveWindow = m_pContainer->GetActiveWindow(); const char* pActiveWindowTitle = NULL; if (pActiveWindow != NULL) { pActiveWindowTitle = pActiveWindow->GetTitle(); } const size_t c_iMaxTitleLen = 512; char pTitle[c_iMaxTitleLen + 1]; size_t iCurrentIndex = 0; if (pMainTitle != NULL) { size_t iLen = strlen(pMainTitle); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, pMainTitle, iLen); iCurrentIndex += iLen; } } if (pActiveWindowTitle != NULL) { if (iCurrentIndex != 0) { const char* const c_pSeparator = " - "; size_t iLen = strlen(c_pSeparator); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, c_pSeparator, iLen); iCurrentIndex += iLen; } } size_t iLen = strlen(pActiveWindowTitle); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, pActiveWindowTitle, iLen); iCurrentIndex += iLen; } } pTitle[iCurrentIndex] = 0; SetTitle(pTitle); } //SFF_END }
#define IMGUI_DEFINE_MATH_OPERATORS #include "ImwPlatformWindow.h" #include "ImwWindowManager.h" namespace ImWindow { //SFF_BEGIN ImwPlatformWindow::ImwPlatformWindow(EPlatformWindowType eType, bool bCreateContext) { m_eType = eType; m_pContainer = new ImwContainer(this); m_pContext = NULL; m_pPreviousContext = NULL; m_bNeedRender = false; m_bShowContent = true; if ( bCreateContext ) { ImGuiContext* pGlobalContext = ImGui::GetCurrentContext(); IM_ASSERT(pGlobalContext != NULL); m_pContext = ImGui::CreateContext( pGlobalContext->IO.MemAllocFn, pGlobalContext->IO.MemFreeFn ); ImGuiIO& oGlobalIO = pGlobalContext->IO; ImGuiIO& oNewIO = m_pContext->IO; memcpy(&(oNewIO.KeyMap), &(oGlobalIO.KeyMap ), sizeof( pGlobalContext->IO.KeyMap )); oNewIO.RenderDrawListsFn = NULL; oNewIO.GetClipboardTextFn = oGlobalIO.GetClipboardTextFn; oNewIO.SetClipboardTextFn = oGlobalIO.SetClipboardTextFn; oNewIO.ImeSetInputScreenPosFn = oGlobalIO.ImeSetInputScreenPosFn; oNewIO.IniFilename = NULL; } } ImwPlatformWindow::~ImwPlatformWindow() { PreDestroy(); } bool ImwPlatformWindow::Init(ImwPlatformWindow* /*pParent*/) { return true; } EPlatformWindowType ImwPlatformWindow::GetType() const { return m_eType; } bool ImwPlatformWindow::IsMainWindow() const { return m_eType == E_PLATFORM_WINDOW_TYPE_MAIN; } const ImVec2 c_oVec2_0 = ImVec2(0,0); ImVec2 ImwPlatformWindow::GetPosition() const { return c_oVec2_0; } ImVec2 ImwPlatformWindow::GetSize() const { return ImGui::GetIO().DisplaySize; } ImVec2 ImwPlatformWindow::GetNormalPosition() const { return GetPosition(); } ImVec2 ImwPlatformWindow::GetNormalSize() const { return GetSize(); } bool ImwPlatformWindow::IsWindowMaximized() const { return false; } bool ImwPlatformWindow::IsWindowMinimized() const { return false; } void ImwPlatformWindow::Show(bool /*bShow*/) { } void ImwPlatformWindow::SetSize(int /*iWidth*/, int /*iHeight*/) { } void ImwPlatformWindow::SetPosition(int /*iX*/, int /*iY*/) { } void ImwPlatformWindow::SetWindowMaximized(bool /*bMaximized*/) { } void ImwPlatformWindow::SetWindowMinimized(bool /*bMinimized*/) { } void ImwPlatformWindow::SetTitle(const char* /*pTtile*/) { } bool ImwPlatformWindow::IsShowContent() const { return m_bShowContent; } void ImwPlatformWindow::SetShowContent(bool bShow) { m_bShowContent = bShow; } void ImwPlatformWindow::PreUpdate() { } void ImwPlatformWindow::PreRender() { } void ImwPlatformWindow::OnOverlay() { } void ImwPlatformWindow::RenderDrawLists(ImDrawData* /*pDrawData */) { } void ImwPlatformWindow::PreDestroy() { ImwSafeDelete(m_pContainer); if (m_pContext != NULL) { m_pContext->IO.Fonts = NULL; SetContext(false); ImGui::Shutdown(); RestoreContext(false); ImGui::DestroyContext(m_pContext); m_pContext = NULL; } if (ImwWindowManager::GetInstance() != NULL && ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow == this) ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow = NULL; } void ImwPlatformWindow::OnFocus(bool bFocused) { if (bFocused) { ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow = this; } else { if (ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow == this) ImwWindowManager::GetInstance()->m_pFocusedPlatformWindow = NULL; if (NULL != m_pContext) { m_pContext->SetNextWindowPosCond = m_pContext->SetNextWindowSizeCond = m_pContext->SetNextWindowContentSizeCond = m_pContext->SetNextWindowCollapsedCond = m_pContext->SetNextWindowFocus = 0; m_pContext->ActiveId = 0; for (int i = 0; i < 512; ++i) m_pContext->IO.KeysDown[i] = false; for (int i = 0; i < 5; ++i) m_pContext->IO.MouseDown[i] = false; m_pContext->IO.KeyAlt = false; m_pContext->IO.KeyCtrl = false; m_pContext->IO.KeyShift = false; } } } void ImwPlatformWindow::Render() { if( m_bNeedRender ) { m_bNeedRender = false; SetContext(false); ImGui::GetIO().DisplaySize = GetSize(); PreRender(); ImGui::Render(); RenderDrawLists(ImGui::GetDrawData()); RestoreContext(false); } } void ImwPlatformWindow::PaintContainer() { m_pContainer->Paint(); } void ImwPlatformWindow::OnClose() { ImwWindowManager::GetInstance()->OnClosePlatformWindow(this); } void ImwPlatformWindow::OnDropFiles(int iCount, char** pFiles, const ImVec2& oPos) { ImwWindow* pWindow = GetWindowAtPos(oPos); if (pWindow != NULL) { pWindow->OnDropFiles(iCount, pFiles, oPos); } } void ImwPlatformWindow::Moving(bool bFirst) { ImVec2 oCursorPos = ImwWindowManager::GetInstance()->GetCursorPos(); if (bFirst) { m_oMovingStartPos = oCursorPos; m_bMoving = false; m_oMovingOffset = oCursorPos - GetPosition(); } else { ImVec2 oCursorDiff = oCursorPos - m_oMovingStartPos; const int c_iPixelThreshold = 2; if (m_bMoving == false && (oCursorDiff.x * oCursorDiff.x + oCursorDiff.y * oCursorDiff.y) > (c_iPixelThreshold * c_iPixelThreshold)) m_bMoving = true; if (m_bMoving) { if (IsWindowMaximized()) { SetWindowMaximized(false); ImVec2 oSize = GetSize(); if (m_oMovingOffset.x > oSize.x / 2.f) { m_oMovingOffset.x = oSize.x / 2.f; } } ImVec2 oNewPos = oCursorPos - m_oMovingOffset; SetPosition((int)oNewPos.x, (int)oNewPos.y); } } } #ifdef IMW_USE_LAYOUT_SERIALIZATION bool ImwPlatformWindow::Save(JsonStthm::JsonValue& oJson) { ImVec2 oSize = GetNormalSize(); ImVec2 oPos = GetNormalPosition(); oJson["Width"] = (int64_t)oSize.x; oJson["Height"] = (int64_t)oSize.y; oJson["Left"] = (int64_t)oPos.x; oJson["Top"] = (int64_t)oPos.y; oJson["Maximized"] = IsWindowMaximized(); oJson["Minimized"] = IsWindowMinimized(); return m_pContainer->Save(oJson["Container"]); } bool ImwPlatformWindow::Load(const JsonStthm::JsonValue& oJson, bool bJustCheck) { if (!oJson["Width"].IsNumeric() || !oJson["Height"].IsNumeric() || !oJson["Left"].IsNumeric() || !oJson["Top"].IsNumeric() || (!oJson["Mode"].IsNumeric() && !oJson["Maximized"].IsBoolean())) return false; if (!bJustCheck) { SetSize((int)oJson["Width"].ToInteger(), (int)oJson["Height"].ToInteger()); SetPosition((int)oJson["Left"].ToInteger(), (int)oJson["Top"].ToInteger()); if (oJson["Mode"].IsNumeric()) { int iMode = (int)oJson["Mode"].ToInteger(); if (iMode < 0) { SetWindowMinimized(true); } else { SetWindowMaximized(iMode > 0); } } if (oJson["Maximized"].IsBoolean()) { SetWindowMaximized(oJson["Maximized"].ToBoolean()); } if( oJson[ "Minimized" ].IsBoolean() ) { SetWindowMinimized(oJson["Minimized"].ToBoolean()); } } return m_pContainer->Load(oJson["Container"], bJustCheck); } #endif //IMW_USE_LAYOUT_SERIALIZATION static bool s_bContextPushed = false; bool ImwPlatformWindow::IsContextSet() { return s_bContextPushed; } bool ImwPlatformWindow::HasContext() const { return m_pContext != NULL; } ImGuiContext* ImwPlatformWindow::GetContext() { if (m_pContext != NULL) return m_pContext; return ImGui::GetCurrentContext(); } void ImwPlatformWindow::SetContext(bool bCopyStyle) { IM_ASSERT(s_bContextPushed == false); s_bContextPushed = true; if (m_pContext != NULL) { IM_ASSERT( m_pPreviousContext == NULL ); m_pPreviousContext = ImGui::GetCurrentContext(); ImGui::SetCurrentContext(m_pContext); if (bCopyStyle) { //Copy style from Global context memcpy(&(m_pContext->Style), &(m_pPreviousContext->Style), sizeof(ImGuiStyle)); } } } void ImwPlatformWindow::RestoreContext(bool bCopyStyle) { IM_ASSERT(s_bContextPushed == true); s_bContextPushed = false; if (m_pContext != NULL) { IM_ASSERT(m_pPreviousContext != NULL); if (bCopyStyle) { //Copy style to Global context memcpy(&(m_pPreviousContext->Style), &(m_pContext->Style), sizeof(ImGuiStyle)); } ImGui::SetCurrentContext(m_pPreviousContext); m_pPreviousContext = NULL; } } void ImwPlatformWindow::Dock(ImwWindow* pWindow) { m_pContainer->Dock(pWindow); } bool ImwPlatformWindow::UnDock(ImwWindow* pWindow) { return m_pContainer->UnDock(pWindow); } ImwContainer* ImwPlatformWindow::GetContainer() { return m_pContainer; } ImwWindow* ImwPlatformWindow::GetWindowAtPos(const ImVec2& oPos) const { return m_pContainer->GetWindowAtPos(oPos); } const ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow) { return m_pContainer->HasWindow(pWindow); } bool ImwPlatformWindow::FocusWindow(ImwWindow* pWindow) { return m_pContainer->FocusWindow(pWindow); } void ImwPlatformWindow::RefreshTitle() { const char* pMainTitle = ImwWindowManager::GetInstance()->GetMainTitle(); ImwWindow* pActiveWindow = m_pContainer->GetActiveWindow(); const char* pActiveWindowTitle = NULL; if (pActiveWindow != NULL) { pActiveWindowTitle = pActiveWindow->GetTitle(); } const size_t c_iMaxTitleLen = 512; char pTitle[c_iMaxTitleLen + 1]; size_t iCurrentIndex = 0; if (pMainTitle != NULL) { size_t iLen = strlen(pMainTitle); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, pMainTitle, iLen); iCurrentIndex += iLen; } } if (pActiveWindowTitle != NULL) { if (iCurrentIndex != 0) { const char* const c_pSeparator = " - "; size_t iLen = strlen(c_pSeparator); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, c_pSeparator, iLen); iCurrentIndex += iLen; } } size_t iLen = strlen(pActiveWindowTitle); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, pActiveWindowTitle, iLen); iCurrentIndex += iLen; } } pTitle[iCurrentIndex] = 0; SetTitle(pTitle); } //SFF_END }
Remove assert in ImwPlatformWindow::OnDropFiles
Remove assert in ImwPlatformWindow::OnDropFiles
C++
mit
thennequin/ImWindow,thennequin/ImWindow,thennequin/ImWindow
876965a622c07ea1ffc083ef9a227e39e225f21c
benchmark/throughput.cc
benchmark/throughput.cc
#include "dsa/message.h" #include "dsa/network.h" #include "../test/sdk/async_test.h" #include "../test/sdk/test_config.h" #include "network/tcp/tcp_client.h" #include "network/tcp/tcp_server.h" #include <chrono> #include <ctime> #include <atomic> #include <boost/program_options.hpp> using high_resolution_clock = std::chrono::high_resolution_clock; using time_point = std::chrono::high_resolution_clock::time_point; using namespace dsa; namespace opts = boost::program_options; class MockNode : public NodeModel { public: explicit MockNode(LinkStrandRef strand) : NodeModel(std::move(strand)){}; }; int main(int argc, const char *argv[]) { opts::options_description desc{"Options"}; desc.add_options()("help,h", "Help screen")( "client,c", opts::value<int>()->default_value(2), "Number of Clients")( "time,t", opts::value<int>()->default_value(20), "Time (seconds)"); opts::variables_map variables; opts::store(opts::parse_command_line(argc, argv, desc), variables); opts::notify(variables); if (variables.count("help")) { std::cout << desc << '\n'; return 0; } int run_time = 20; int client_count = 2; const int MAX_CLIENT_COUNT = 256; client_count = variables["client"].as<int>(); run_time = variables["time"].as<int>(); if (client_count > MAX_CLIENT_COUNT || client_count < 1) { std::cout << "invalid Number of Clients, ( 1 ~ 255 )"; return 0; } std::cout << std::endl << "benchmark with " << client_count << " clients"; App app; app.async_start(4); // client_count * 2 + 2); TestConfig server_config(app); MockNode *root_node = new MockNode(server_config.strand); server_config.get_link_config()->set_stream_acceptor( make_unique_<NodeStateManager>(ref_<MockNode>(root_node))); // auto tcp_server(new TcpServer(server_config)); auto tcp_server = make_shared_<TcpServer>(server_config); tcp_server->start(); std::vector<WrapperConfig> client_configs; std::vector<shared_ptr_<TcpClient>> clients; std::atomic_int receive_count[MAX_CLIENT_COUNT]; SubscribeOptions initial_options; initial_options.qos = QosLevel::_1; initial_options.queue_size = 655360; for (int i = 0; i < client_count; ++i) { client_configs.emplace_back(server_config.get_client_config(app)); clients.emplace_back(make_shared_<TcpClient>(client_configs[i])); clients[i]->connect(); wait_for_bool(500, *client_configs[i].strand, [&]() { return clients[i]->get_session().is_connected(); }); receive_count[i] = 0; std::atomic_int &count = receive_count[i]; clients[i]->get_session().requester.subscribe( "", [&](ref_<const SubscribeResponseMessage> &&msg, IncomingSubscribeStream &stream) { count.fetch_add(1); }, initial_options); } int msg_per_second = 300000; boost::posix_time::milliseconds interval(10); boost::asio::deadline_timer timer(app.io_service(), interval); int print_count = 0; // print every 100 timer visit; auto ts = high_resolution_clock::now(); std::function<void(const boost::system::error_code &)> tick; tick = [&](const boost::system::error_code &error) { if (!error) { server_config.strand->dispatch([&]() { auto ts2 = high_resolution_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts) .count(); if (ms > 0) { ts = ts2; int count = 0; for (int i = 0; i < client_count; ++i) { count += receive_count[i]; receive_count[i] = 0; } count /= client_count; print_count += ms; if (print_count > 2000) { print_count = 0; std::cout << std::endl << "message per second: " << (msg_per_second * client_count) << " current: " << count * 1000 / ms << " x " << client_count << ", interval " << ms; } msg_per_second = (count * 1000 + msg_per_second * 3000) / (3000 + ms); if (msg_per_second < 1000) msg_per_second = 1000; int num_message = msg_per_second * ms / 800; for (int i = 0; i < num_message; ++i) { root_node->set_value(Variant(i)); } } timer.async_wait(tick); }); } }; timer.async_wait(tick); std::cout << std::endl << "run benchmark for " << run_time << " seconds"; boost::this_thread::sleep(boost::posix_time::seconds(run_time)); std::cout << std::endl << "end benchmark"; timer.cancel(); Server::close_in_strand(tcp_server); for (int i = 0; i < client_count; ++i) { Client::close_in_strand(clients[i]); } app.close(); wait_for_bool(500, [&]() { return app.is_stopped(); }); if (!app.is_stopped()) { app.force_stop(); } app.wait(); return 0; }
#include "dsa/message.h" #include "dsa/network.h" #include "../test/sdk/async_test.h" #include "../test/sdk/test_config.h" #include "network/tcp/tcp_client.h" #include "network/tcp/tcp_server.h" #include <chrono> #include <ctime> #include <atomic> #include <boost/program_options.hpp> using high_resolution_clock = std::chrono::high_resolution_clock; using time_point = std::chrono::high_resolution_clock::time_point; using namespace dsa; namespace opts = boost::program_options; class MockNode : public NodeModel { public: explicit MockNode(LinkStrandRef strand) : NodeModel(std::move(strand)){}; }; int main(int argc, const char *argv[]) { opts::options_description desc{"Options"}; desc.add_options()("help,h", "Help screen")( "client,c", opts::value<int>()->default_value(2), "Number of Clients")( "time,t", opts::value<int>()->default_value(20), "Time (seconds)"); opts::variables_map variables; opts::store(opts::parse_command_line(argc, argv, desc), variables); opts::notify(variables); if (variables.count("help")) { std::cout << desc << '\n'; return 0; } int run_time = 20; int client_count = 2; const int MAX_CLIENT_COUNT = 256; client_count = variables["client"].as<int>(); run_time = variables["time"].as<int>(); if (client_count > MAX_CLIENT_COUNT || client_count < 1) { std::cout << "invalid Number of Clients, ( 1 ~ 255 )"; return 0; } std::cout << std::endl << "benchmark with " << client_count << " clients"; App app; app.async_start(4); // client_count * 2 + 2); TestConfig server_config(app); MockNode *root_node = new MockNode(server_config.strand); server_config.get_link_config()->set_stream_acceptor( make_unique_<NodeStateManager>(ref_<MockNode>(root_node))); // auto tcp_server(new TcpServer(server_config)); auto tcp_server = make_shared_<TcpServer>(server_config); tcp_server->start(); std::vector<WrapperConfig> client_configs; std::vector<shared_ptr_<TcpClient>> clients; std::atomic_int receive_count[MAX_CLIENT_COUNT]; SubscribeOptions initial_options; initial_options.qos = QosLevel::_1; initial_options.queue_size = 655360; for (int i = 0; i < client_count; ++i) { client_configs.emplace_back(server_config.get_client_config(app)); clients.emplace_back(make_shared_<TcpClient>(client_configs[i])); clients[i]->connect(); wait_for_bool(500, *client_configs[i].strand, [&]() { return clients[i]->get_session().is_connected(); }); receive_count[i] = 0; std::atomic_int &count = receive_count[i]; clients[i]->get_session().requester.subscribe( "", [&](ref_<const SubscribeResponseMessage> &&msg, IncomingSubscribeStream &stream) { count.fetch_add(1); }, initial_options); } int64_t msg_per_second = 300000; boost::posix_time::milliseconds interval(10); boost::asio::deadline_timer timer(app.io_service(), interval); int print_count = 0; // print every 100 timer visit; auto ts = high_resolution_clock::now(); int total_ms = 0; int total_message = 0; std::function<void(const boost::system::error_code &)> tick; tick = [&](const boost::system::error_code &error) { if (!error) { server_config.strand->dispatch([&]() { auto ts2 = high_resolution_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts) .count(); if (ms > 0) { ts = ts2; int count = 0; for (int i = 0; i < client_count; ++i) { count += receive_count[i]; receive_count[i] = 0; } total_message += count; count /= client_count; print_count += ms; if (print_count > 2000) { print_count = 0; std::cout << std::endl << "message per second: " << (msg_per_second * client_count) << " current: " << count * 1000 / ms << " x " << client_count << ", interval " << ms; } msg_per_second = (count * 1000 + msg_per_second * total_ms)/ (total_ms + ms); total_ms += ms; if (total_ms > 5000) total_ms = 5000; int tosend_per_second = msg_per_second; if (tosend_per_second < 100000) tosend_per_second = 100000; int num_message = tosend_per_second * ms / 800; for (int i = 0; i < num_message; ++i) { root_node->set_value(Variant(i)); } } timer.async_wait(tick); }); } }; timer.async_wait(tick); std::cout << std::endl << "run benchmark for " << run_time << " seconds"; boost::this_thread::sleep(boost::posix_time::seconds(run_time)); std::cout << std::endl << "end benchmark"; timer.cancel(); std::cout << std::endl << "total message: " << total_message; Server::close_in_strand(tcp_server); for (int i = 0; i < client_count; ++i) { Client::close_in_strand(clients[i]); } app.close(); wait_for_bool(500, [&]() { return app.is_stopped(); }); if (!app.is_stopped()) { app.force_stop(); } app.wait(); return 0; }
fix throughput time calculation
fix throughput time calculation
C++
apache-2.0
iot-dsa-v2/sdk-dslink-cpp,iot-dsa-v2/sdk-dslink-cpp,iot-dsa-v2/sdk-dslink-cpp,iot-dsa-v2/sdk-dslink-cpp
162853f0dfeda91ede8c03ace4d88e0b0b858cd8
src/meshoptimizer.hpp
src/meshoptimizer.hpp
#pragma once #include <cstddef> #include <vector> // Index buffer generator // Generates index buffer from the unindexed vertex stream and returns number of unique vertices (max index + 1) // destination must contain enough space for the resulting index buffer (vertex_count elements) size_t generateIndexBuffer(unsigned int* destination, const void* vertices, size_t vertex_count, size_t vertex_size); // Vertex buffer generator // Generates vertex buffer from the unindexed vertex stream and index buffer generated by generateIndexBuffer // destination must contain enough space for the resulting vertex buffer (max index + 1 elements) void generateVertexBuffer(void* destination, const unsigned int* indices, const void* vertices, size_t vertex_count, size_t vertex_size); // Vertex transform cache optimizer using the Tipsify algorithm by Sander et al // http://gfx.cs.princeton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf // Reorders indices to reduce the number of GPU vertex shader invocations // // destination must contain enough space for the resulting index buffer (index_count elements) // cache_size should be less than the actual GPU cache size to avoid cache thrashing // clusters is an optional output for the overdraw optimizer (below) void optimizePostTransform(unsigned short* destination, const unsigned short* indices, size_t index_count, size_t vertex_count, unsigned int cache_size = 16, std::vector<unsigned int>* clusters = 0); void optimizePostTransform(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size = 16, std::vector<unsigned int>* clusters = 0); // Overdraw optimizer using the Tipsify algorithm // Reorders indices to reduce the number of GPU vertex shader invocations and the pixel overdraw // // destination must contain enough space for the resulting index buffer (index_count elements) // indices must contain index data that is the result of optimizePostTransform (*not* the original mesh indices!) // clusters must contain cluster data that is the result of optimizePostTransform // vertex_positions should have float3 position in the first 12 bytes of each vertex - similar to glVertexPointer // cache_size should be less than the actual GPU cache size to avoid cache thrashing // threshold indicates how much the overdraw optimizer can degrade vertex cache efficiency (1.05 = up to 5%) to reduce overdraw more efficiently void optimizeOverdraw(unsigned short* destination, const unsigned short* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count, const std::vector<unsigned int>& clusters, unsigned int cache_size = 16, float threshold = 1); void optimizeOverdraw(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count, const std::vector<unsigned int>& clusters, unsigned int cache_size = 16, float threshold = 1); // Vertex fetch cache optimizer // Reorders vertices and changes indices to reduce the amount of GPU memory fetches during vertex processing // // desination must contain enough space for the resulting vertex buffer (vertex_count elements) // indices is used both as an input and as an output index buffer void optimizePreTransform(void* destination, const void* vertices, unsigned short* indices, size_t index_count, size_t vertex_count, size_t vertex_size); void optimizePreTransform(void* destination, const void* vertices, unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size); struct PostTransformCacheStatistics { unsigned int vertices_transformed; float acmr; // transformed vertices / triangle count; best case 0.5, worst case 3.0, optimum depends on topology float atvr; // transformed vertices / vertex count; best case 1.0, worse case 6.0, optimum is 1.0 (each vertex is transformed once) }; // Vertex transform cache analyzer // Returns cache hit statistics using a simplified FIFO model // Results will not match actual GPU performance PostTransformCacheStatistics analyzePostTransform(const unsigned short* indices, size_t index_count, size_t vertex_count, unsigned int cache_size = 32); PostTransformCacheStatistics analyzePostTransform(const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size = 32); struct OverdrawStatistics { unsigned int pixels_covered; unsigned int pixels_shaded; float overdraw; // shaded pixels / covered pixels; best case 1.0 }; // Overdraw analyzer // Returns overdraw statistics using a software rasterizer // Results will not match actual GPU performance // // vertex_positions should have float3 position in the first 12 bytes of each vertex - similar to glVertexPointer OverdrawStatistics analyzeOverdraw(const unsigned short* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count); OverdrawStatistics analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count); struct PreTransformCacheStatistics { unsigned int bytes_fetched; float overfetch; // fetched bytes / vertex buffer size; best case 1.0 (each byte is fetched once) }; // Vertex fetch cache analyzer // Returns cache hit statistics using a simplified direct mapped model // Results will not match actual GPU performance PreTransformCacheStatistics analyzePreTransform(const unsigned short* indices, size_t index_count, size_t vertex_count, size_t vertex_size); PreTransformCacheStatistics analyzePreTransform(const unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size); // Quantization into commonly supported data formats // Quantize a float in [0..1] range into an N-bit fixed point unorm value // Assumes reconstruction function (q / (2^bits-1)), which is the case for fixed-function normalized fixed point conversion // Maximum reconstruction error: 1/2^(bits+1) inline int quantizeUnorm(float v, int bits) { const float scale = (1 << bits) - 1; v = (v > 0) ? v : 0; v = (v < 1) ? v : 1; return int(v * scale + 0.5f); } // Quantize a float in [-1..1] range into an N-bit fixed point snorm value // Assumes reconstruction function (q / (2^(bits-1)-1)), which is the case for fixed-function normalized fixed point conversion (except OpenGL) // Maximum reconstruction error: 1/2^bits // Warning: OpenGL fixed function reconstruction function can't represent 0 exactly; when using OpenGL, use this function and have the shader reconstruct by dividing by 2^(bits-1)-1. inline int quantizeSnorm(float v, int bits) { const float scale = (1 << (bits - 1)) - 1; v = (v > -1) ? v : -1; v = (v < +1) ? v : +1; return int(v * scale + (v >= 0 ? 0.5f : -0.5f)); }
#pragma once #include <cstddef> #include <vector> // Index buffer generator // Generates index buffer from the unindexed vertex stream and returns number of unique vertices (max index + 1) // destination must contain enough space for the resulting index buffer (vertex_count elements) size_t generateIndexBuffer(unsigned int* destination, const void* vertices, size_t vertex_count, size_t vertex_size); // Vertex buffer generator // Generates vertex buffer from the unindexed vertex stream and index buffer generated by generateIndexBuffer // destination must contain enough space for the resulting vertex buffer (max index + 1 elements) void generateVertexBuffer(void* destination, const unsigned int* indices, const void* vertices, size_t vertex_count, size_t vertex_size); // Vertex transform cache optimizer using the Tipsify algorithm by Sander et al // http://gfx.cs.princeton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf // Reorders indices to reduce the number of GPU vertex shader invocations // // destination must contain enough space for the resulting index buffer (index_count elements) // cache_size should be less than the actual GPU cache size to avoid cache thrashing // clusters is an optional output for the overdraw optimizer (below) void optimizePostTransform(unsigned short* destination, const unsigned short* indices, size_t index_count, size_t vertex_count, unsigned int cache_size = 16, std::vector<unsigned int>* clusters = 0); void optimizePostTransform(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size = 16, std::vector<unsigned int>* clusters = 0); // Overdraw optimizer using the Tipsify algorithm // Reorders indices to reduce the number of GPU vertex shader invocations and the pixel overdraw // // destination must contain enough space for the resulting index buffer (index_count elements) // indices must contain index data that is the result of optimizePostTransform (*not* the original mesh indices!) // clusters must contain cluster data that is the result of optimizePostTransform // vertex_positions should have float3 position in the first 12 bytes of each vertex - similar to glVertexPointer // cache_size should be less than the actual GPU cache size to avoid cache thrashing // threshold indicates how much the overdraw optimizer can degrade vertex cache efficiency (1.05 = up to 5%) to reduce overdraw more efficiently void optimizeOverdraw(unsigned short* destination, const unsigned short* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count, const std::vector<unsigned int>& clusters, unsigned int cache_size = 16, float threshold = 1); void optimizeOverdraw(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count, const std::vector<unsigned int>& clusters, unsigned int cache_size = 16, float threshold = 1); // Vertex fetch cache optimizer // Reorders vertices and changes indices to reduce the amount of GPU memory fetches during vertex processing // // desination must contain enough space for the resulting vertex buffer (vertex_count elements) // indices is used both as an input and as an output index buffer void optimizePreTransform(void* destination, const void* vertices, unsigned short* indices, size_t index_count, size_t vertex_count, size_t vertex_size); void optimizePreTransform(void* destination, const void* vertices, unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size); struct PostTransformCacheStatistics { unsigned int vertices_transformed; float acmr; // transformed vertices / triangle count; best case 0.5, worst case 3.0, optimum depends on topology float atvr; // transformed vertices / vertex count; best case 1.0, worse case 6.0, optimum is 1.0 (each vertex is transformed once) }; // Vertex transform cache analyzer // Returns cache hit statistics using a simplified FIFO model // Results will not match actual GPU performance PostTransformCacheStatistics analyzePostTransform(const unsigned short* indices, size_t index_count, size_t vertex_count, unsigned int cache_size = 32); PostTransformCacheStatistics analyzePostTransform(const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size = 32); struct OverdrawStatistics { unsigned int pixels_covered; unsigned int pixels_shaded; float overdraw; // shaded pixels / covered pixels; best case 1.0 }; // Overdraw analyzer // Returns overdraw statistics using a software rasterizer // Results will not match actual GPU performance // // vertex_positions should have float3 position in the first 12 bytes of each vertex - similar to glVertexPointer OverdrawStatistics analyzeOverdraw(const unsigned short* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count); OverdrawStatistics analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, size_t vertex_count); struct PreTransformCacheStatistics { unsigned int bytes_fetched; float overfetch; // fetched bytes / vertex buffer size; best case 1.0 (each byte is fetched once) }; // Vertex fetch cache analyzer // Returns cache hit statistics using a simplified direct mapped model // Results will not match actual GPU performance PreTransformCacheStatistics analyzePreTransform(const unsigned short* indices, size_t index_count, size_t vertex_count, size_t vertex_size); PreTransformCacheStatistics analyzePreTransform(const unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size); // Quantization into commonly supported data formats // Quantize a float in [0..1] range into an N-bit fixed point unorm value // Assumes reconstruction function (q / (2^bits-1)), which is the case for fixed-function normalized fixed point conversion // Maximum reconstruction error: 1/2^(bits+1) inline int quantizeUnorm(float v, int bits) { const float scale = (1 << bits) - 1; v = (v > 0) ? v : 0; v = (v < 1) ? v : 1; return int(v * scale + 0.5f); } // Quantize a float in [-1..1] range into an N-bit fixed point snorm value // Assumes reconstruction function (q / (2^(bits-1)-1)), which is the case for fixed-function normalized fixed point conversion (except OpenGL) // Maximum reconstruction error: 1/2^bits // Warning: OpenGL fixed function reconstruction function can't represent 0 exactly; when using OpenGL, use this function and have the shader reconstruct by dividing by 2^(bits-1)-1. inline int quantizeSnorm(float v, int bits) { const float scale = (1 << (bits - 1)) - 1; v = (v > -1) ? v : -1; v = (v < +1) ? v : +1; return int(v * scale + (v >= 0 ? 0.5f : -0.5f)); } // Quantize a float into half-precision floating point value // Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest // Representable magnitude range: [6e-5; 65504] // Maximum relative reconstruction error: 5e-4 inline unsigned short quantizeHalf(float v) { union { float f; unsigned int ui; } u = {v}; unsigned int ui = u.ui; int s = (ui >> 16) & 0x8000; int em = ui & 0x7fffffff; // bias exponent and round to nearest; 112 is relative exponent bias (127-15) int h = (em - (112 << 23) + (1 << 12)) >> 13; // underflow: flush to zero; 113 encodes exponent -14 h = (em < (113 << 23)) ? 0 : h; // overflow: infinity; 143 encodes exponent 16 h = (em >= (143 << 23)) ? 0x7c00 : h; // NaN; note that we convert all types of NaN to qNaN h = (em > (255 << 23)) ? 0x7e00 : h; return (unsigned short)(s | h); }
Implement half-precision float quantization
Implement half-precision float quantization quantizeHalf handles float->half conversion, correctly preserving +-Inf/NaN, generating +-Inf on overflow, and rounding to nearest value. Denormals are flushed to zero, both to simplify the conversion and to eliminate the performance cost of handling denormals on target hardware (in case some GPUs don't support full rate fp16 denormals). The results were verified by comparing them against ISPC float->half on all 2^32 floats; the only source of difference is flush-to-zero for denormals.
C++
mit
zeux/meshoptimizer,zeux/meshoptimizer,zeux/meshoptimizer
8a27d00e00798ad6a9feb6fc160b3015484fe98d
EntityComponents/EC_HoveringText/EC_HoveringText.cpp
EntityComponents/EC_HoveringText/EC_HoveringText.cpp
/** * For conditions of distribution and use, see copyright notice in license.txt * * @file EC_HoveringText.cpp * @brief EC_HoveringText shows a hovering text attached to an entity. * @note The entity must EC_OgrePlaceable available in advance. */ #include "StableHeaders.h" //#include "DebugOperatorNew.h" #include "EC_HoveringText.h" #include "ModuleInterface.h" #include "Renderer.h" #include "EC_OgrePlaceable.h" #include "Entity.h" #include "OgreMaterialUtils.h" #include <Ogre.h> #include <OgreBillboardSet.h> #include <OgreTextureManager.h> #include <OgreResource.h> #include <QFile> #include <QPainter> #include <QTimer> #include <QTimeLine> //#include "MemoryLeakCheck.h" EC_HoveringText::EC_HoveringText(Foundation::ModuleInterface *module) : Foundation::ComponentInterface(module->GetFramework()), font_(QFont("Arial", 100)), backgroundColor_(Qt::transparent), textColor_(Qt::black), billboardSet_(0), billboard_(0), text_(""), visibility_animation_timeline_(new QTimeLine(1000, this)), visibility_timer_(new QTimer(this)), using_gradient_(false) { renderer_ = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer); visibility_animation_timeline_->setFrameRange(0,100); visibility_animation_timeline_->setEasingCurve(QEasingCurve::InOutSine); visibility_timer_->setSingleShot(true); connect(visibility_animation_timeline_, SIGNAL(frameChanged(int)), SLOT(UpdateAnimationStep(int))); connect(visibility_animation_timeline_, SIGNAL(finished()), SLOT(AnimationFinished())); } EC_HoveringText::~EC_HoveringText() { } void EC_HoveringText::SetPosition(const Vector3df& position) { if (billboard_) billboard_->setPosition(Ogre::Vector3(position.x, position.y, position.z)); } void EC_HoveringText::SetFont(const QFont &font) { font_ = font; Redraw(); } void EC_HoveringText::SetTextColor(const QColor &color) { textColor_ = color; Redraw(); } void EC_HoveringText::SetBackgroundColor(const QColor &color) { backgroundColor_ = color; using_gradient_ = false; Redraw(); } void EC_HoveringText::SetBackgroundGradient(const QColor &start_color, const QColor &end_color) { bg_grad_.setColorAt(0.0, start_color); bg_grad_.setColorAt(1.0, end_color); using_gradient_ = true; } void EC_HoveringText::Show() { if (billboardSet_) billboardSet_->setVisible(true); } void EC_HoveringText::AnimatedShow() { if (visibility_animation_timeline_->state() == QTimeLine::Running || visibility_timer_->isActive() || IsVisible()) return; UpdateAnimationStep(0); Show(); visibility_animation_timeline_->setDirection(QTimeLine::Forward); visibility_animation_timeline_->start(); } void EC_HoveringText::Clicked(int msec_to_show) { if (visibility_timer_->isActive()) visibility_timer_->stop(); else { AnimatedShow(); visibility_timer_->start(msec_to_show); } } void EC_HoveringText::Hide() { if (billboardSet_) billboardSet_->setVisible(false); } void EC_HoveringText::AnimatedHide() { if (visibility_animation_timeline_->state() == QTimeLine::Running || visibility_timer_->isActive() || !IsVisible()) return; UpdateAnimationStep(100); visibility_animation_timeline_->setDirection(QTimeLine::Backward); visibility_animation_timeline_->start(); } void EC_HoveringText::UpdateAnimationStep(int step) { if (materialName_.empty()) return; float alpha = step; alpha /= 100; Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton(); Ogre::MaterialPtr material = mgr.getByName(materialName_); assert(material.get()); material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setAlphaOperation( Ogre::LBX_BLEND_MANUAL, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1.0, 0.0, alpha); } void EC_HoveringText::AnimationFinished() { if (visibility_animation_timeline_->direction() == QTimeLine::Backward && IsVisible()) Hide(); } bool EC_HoveringText::IsVisible() const { if (billboardSet_) return billboardSet_->isVisible(); else return false; } void EC_HoveringText::ShowMessage(const QString &text) { if (renderer_.expired()) return; Ogre::SceneManager *scene = renderer_.lock()->GetSceneManager(); assert(scene); if (!scene) return; Scene::Entity *entity = GetParentEntity(); assert(entity); if (!entity) return; OgreRenderer::EC_OgrePlaceable *node = entity->GetComponent<OgreRenderer::EC_OgrePlaceable>().get(); if (!node) return; Ogre::SceneNode *sceneNode = node->GetSceneNode(); assert(sceneNode); if (!sceneNode) return; // Create billboard if it doesn't exist. if (!billboardSet_ && !billboard_) { billboardSet_ = scene->createBillboardSet(renderer_.lock()->GetUniqueObjectName(), 1); assert(billboardSet_); materialName_ = std::string("material") + renderer_.lock()->GetUniqueObjectName(); OgreRenderer::CloneMaterial("HoveringText", materialName_); billboardSet_->setMaterialName(materialName_); billboardSet_->setCastShadows(false); billboard_ = billboardSet_->createBillboard(Ogre::Vector3(0, 0, 0.7f)); assert(billboard_); billboardSet_->setDefaultDimensions(2, 1); sceneNode->attachObject(billboardSet_); } if (text.isNull() || text.isEmpty()) return; text_ = text; Redraw(); } void EC_HoveringText::Redraw() { if (renderer_.expired() || !billboardSet_ || !billboard_) return; // Get pixmap with text rendered to it. QPixmap pixmap = GetTextPixmap(); if (pixmap.isNull()) return; // Create texture QImage img = pixmap.toImage(); Ogre::DataStreamPtr stream(new Ogre::MemoryDataStream((void*)img.bits(), img.byteCount())); std::string tex_name("HoveringTextTexture" + renderer_.lock()->GetUniqueObjectName()); Ogre::TextureManager &manager = Ogre::TextureManager::getSingleton(); Ogre::Texture *tex = checked_static_cast<Ogre::Texture *>(manager.create( tex_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME).get()); assert(tex); tex->loadRawData(stream, img.width(), img.height(), Ogre::PF_A8R8G8B8); // Set new texture for the material assert(!materialName_.empty()); if (!materialName_.empty()) { Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton(); Ogre::MaterialPtr material = mgr.getByName(materialName_); assert(material.get()); OgreRenderer::SetTextureUnitOnMaterial(material, tex_name); } } QPixmap EC_HoveringText::GetTextPixmap() { ///\todo Resize the font size according to the render window size and distance /// avatar's distance from the camera // const int minWidth = // const int minHeight = // Ogre::Viewport* viewport = renderer_.lock()->GetViewport(); // const int max_width = viewport->getActualWidth()/4; // int max_height = viewport->getActualHeight()/10; if (renderer_.expired() || text_.isEmpty() || text_ == " ") return 0; QRect max_rect(0, 0, 1600, 800); // Create transparent pixmap QPixmap pixmap(max_rect.size()); pixmap.fill(Qt::transparent); // Init painter with pixmap as the paint device QPainter painter(&pixmap); // Ask painter the rect for the text painter.setFont(font_); QRect rect = painter.boundingRect(max_rect, Qt::AlignCenter | Qt::TextWordWrap, text_); // Add some padding to it QFontMetrics metric(font_); int width = metric.width(text_) + metric.averageCharWidth(); int height = metric.height() + 20; rect.setWidth(width); rect.setHeight(height); // Set background brush if (using_gradient_) { bg_grad_.setStart(QPointF(0,rect.top())); bg_grad_.setFinalStop(QPointF(0,rect.bottom())); painter.setBrush(QBrush(bg_grad_)); } else painter.setBrush(backgroundColor_); // Draw background rect painter.setPen(QColor(255,255,255,150)); painter.drawRoundedRect(rect, 20.0, 20.0); // Draw text painter.setPen(textColor_); painter.drawText(rect, Qt::AlignCenter | Qt::TextWordWrap, text_); return pixmap; }
/** * For conditions of distribution and use, see copyright notice in license.txt * * @file EC_HoveringText.cpp * @brief EC_HoveringText shows a hovering text attached to an entity. * @note The entity must EC_OgrePlaceable available in advance. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "EC_HoveringText.h" #include "ModuleInterface.h" #include "Renderer.h" #include "EC_OgrePlaceable.h" #include "Entity.h" #include "OgreMaterialUtils.h" #include <Ogre.h> #include <OgreBillboardSet.h> #include <OgreTextureManager.h> #include <OgreResource.h> #include <QFile> #include <QPainter> #include <QTimer> #include <QTimeLine> #include "MemoryLeakCheck.h" EC_HoveringText::EC_HoveringText(Foundation::ModuleInterface *module) : Foundation::ComponentInterface(module->GetFramework()), font_(QFont("Arial", 100)), backgroundColor_(Qt::transparent), textColor_(Qt::black), billboardSet_(0), billboard_(0), text_(""), visibility_animation_timeline_(new QTimeLine(1000, this)), visibility_timer_(new QTimer(this)), using_gradient_(false) { renderer_ = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer); visibility_animation_timeline_->setFrameRange(0,100); visibility_animation_timeline_->setEasingCurve(QEasingCurve::InOutSine); visibility_timer_->setSingleShot(true); connect(visibility_animation_timeline_, SIGNAL(frameChanged(int)), SLOT(UpdateAnimationStep(int))); connect(visibility_animation_timeline_, SIGNAL(finished()), SLOT(AnimationFinished())); } EC_HoveringText::~EC_HoveringText() { } void EC_HoveringText::SetPosition(const Vector3df& position) { if (billboard_) billboard_->setPosition(Ogre::Vector3(position.x, position.y, position.z)); } void EC_HoveringText::SetFont(const QFont &font) { font_ = font; Redraw(); } void EC_HoveringText::SetTextColor(const QColor &color) { textColor_ = color; Redraw(); } void EC_HoveringText::SetBackgroundColor(const QColor &color) { backgroundColor_ = color; using_gradient_ = false; Redraw(); } void EC_HoveringText::SetBackgroundGradient(const QColor &start_color, const QColor &end_color) { bg_grad_.setColorAt(0.0, start_color); bg_grad_.setColorAt(1.0, end_color); using_gradient_ = true; } void EC_HoveringText::Show() { if (billboardSet_) billboardSet_->setVisible(true); } void EC_HoveringText::AnimatedShow() { if (visibility_animation_timeline_->state() == QTimeLine::Running || visibility_timer_->isActive() || IsVisible()) return; UpdateAnimationStep(0); Show(); visibility_animation_timeline_->setDirection(QTimeLine::Forward); visibility_animation_timeline_->start(); } void EC_HoveringText::Clicked(int msec_to_show) { if (visibility_timer_->isActive()) visibility_timer_->stop(); else { AnimatedShow(); visibility_timer_->start(msec_to_show); } } void EC_HoveringText::Hide() { if (billboardSet_) billboardSet_->setVisible(false); } void EC_HoveringText::AnimatedHide() { if (visibility_animation_timeline_->state() == QTimeLine::Running || visibility_timer_->isActive() || !IsVisible()) return; UpdateAnimationStep(100); visibility_animation_timeline_->setDirection(QTimeLine::Backward); visibility_animation_timeline_->start(); } void EC_HoveringText::UpdateAnimationStep(int step) { if (materialName_.empty()) return; float alpha = step; alpha /= 100; Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton(); Ogre::MaterialPtr material = mgr.getByName(materialName_); assert(material.get()); material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setAlphaOperation( Ogre::LBX_BLEND_MANUAL, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1.0, 0.0, alpha); } void EC_HoveringText::AnimationFinished() { if (visibility_animation_timeline_->direction() == QTimeLine::Backward && IsVisible()) Hide(); } bool EC_HoveringText::IsVisible() const { if (billboardSet_) return billboardSet_->isVisible(); else return false; } void EC_HoveringText::ShowMessage(const QString &text) { if (renderer_.expired()) return; Ogre::SceneManager *scene = renderer_.lock()->GetSceneManager(); assert(scene); if (!scene) return; Scene::Entity *entity = GetParentEntity(); assert(entity); if (!entity) return; OgreRenderer::EC_OgrePlaceable *node = entity->GetComponent<OgreRenderer::EC_OgrePlaceable>().get(); if (!node) return; Ogre::SceneNode *sceneNode = node->GetSceneNode(); assert(sceneNode); if (!sceneNode) return; // Create billboard if it doesn't exist. if (!billboardSet_ && !billboard_) { billboardSet_ = scene->createBillboardSet(renderer_.lock()->GetUniqueObjectName(), 1); assert(billboardSet_); materialName_ = std::string("material") + renderer_.lock()->GetUniqueObjectName(); OgreRenderer::CloneMaterial("HoveringText", materialName_); billboardSet_->setMaterialName(materialName_); billboardSet_->setCastShadows(false); billboard_ = billboardSet_->createBillboard(Ogre::Vector3(0, 0, 0.7f)); assert(billboard_); billboardSet_->setDefaultDimensions(2, 1); sceneNode->attachObject(billboardSet_); } if (text.isNull() || text.isEmpty()) return; text_ = text; Redraw(); } void EC_HoveringText::Redraw() { if (renderer_.expired() || !billboardSet_ || !billboard_) return; // Get pixmap with text rendered to it. QPixmap pixmap = GetTextPixmap(); if (pixmap.isNull()) return; // Create texture QImage img = pixmap.toImage(); #include "DisableMemoryLeakCheck.h" Ogre::DataStreamPtr stream(new Ogre::MemoryDataStream((void*)img.bits(), img.byteCount())); #include "EnableMemoryLeakCheck.h" std::string tex_name("HoveringTextTexture" + renderer_.lock()->GetUniqueObjectName()); Ogre::TextureManager &manager = Ogre::TextureManager::getSingleton(); Ogre::Texture *tex = checked_static_cast<Ogre::Texture *>(manager.create( tex_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME).get()); assert(tex); tex->loadRawData(stream, img.width(), img.height(), Ogre::PF_A8R8G8B8); // Set new texture for the material assert(!materialName_.empty()); if (!materialName_.empty()) { Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton(); Ogre::MaterialPtr material = mgr.getByName(materialName_); assert(material.get()); OgreRenderer::SetTextureUnitOnMaterial(material, tex_name); } } QPixmap EC_HoveringText::GetTextPixmap() { ///\todo Resize the font size according to the render window size and distance /// avatar's distance from the camera // const int minWidth = // const int minHeight = // Ogre::Viewport* viewport = renderer_.lock()->GetViewport(); // const int max_width = viewport->getActualWidth()/4; // int max_height = viewport->getActualHeight()/10; if (renderer_.expired() || text_.isEmpty() || text_ == " ") return 0; QRect max_rect(0, 0, 1600, 800); // Create transparent pixmap QPixmap pixmap(max_rect.size()); pixmap.fill(Qt::transparent); // Init painter with pixmap as the paint device QPainter painter(&pixmap); // Ask painter the rect for the text painter.setFont(font_); QRect rect = painter.boundingRect(max_rect, Qt::AlignCenter | Qt::TextWordWrap, text_); // Add some padding to it QFontMetrics metric(font_); int width = metric.width(text_) + metric.averageCharWidth(); int height = metric.height() + 20; rect.setWidth(width); rect.setHeight(height); // Set background brush if (using_gradient_) { bg_grad_.setStart(QPointF(0,rect.top())); bg_grad_.setFinalStop(QPointF(0,rect.bottom())); painter.setBrush(QBrush(bg_grad_)); } else painter.setBrush(backgroundColor_); // Draw background rect painter.setPen(QColor(255,255,255,150)); painter.drawRoundedRect(rect, 20.0, 20.0); // Draw text painter.setPen(textColor_); painter.drawText(rect, Qt::AlignCenter | Qt::TextWordWrap, text_); return pixmap; }
Add memory leak check to EC_HoveringText.cpp
Add memory leak check to EC_HoveringText.cpp
C++
apache-2.0
BogusCurry/tundra,jesterKing/naali,BogusCurry/tundra,AlphaStaxLLC/tundra,jesterKing/naali,pharos3d/tundra,antont/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,antont/tundra,AlphaStaxLLC/tundra,AlphaStaxLLC/tundra,realXtend/tundra,realXtend/tundra,jesterKing/naali,AlphaStaxLLC/tundra,pharos3d/tundra,antont/tundra,pharos3d/tundra,BogusCurry/tundra,realXtend/tundra,pharos3d/tundra,antont/tundra,jesterKing/naali,BogusCurry/tundra,jesterKing/naali,antont/tundra,pharos3d/tundra,realXtend/tundra,AlphaStaxLLC/tundra,BogusCurry/tundra,realXtend/tundra,realXtend/tundra,BogusCurry/tundra,antont/tundra,jesterKing/naali,jesterKing/naali,antont/tundra
6eee408cf87fbd56e187eea73579bcff59acaf1e
Source/bindings/core/v8/ScriptProfiler.cpp
Source/bindings/core/v8/ScriptProfiler.cpp
/* * Copyright (c) 2011, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/core/v8/ScriptProfiler.h" #include "bindings/core/v8/RetainedDOMInfo.h" #include "bindings/core/v8/ScriptValue.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8Node.h" #include "bindings/core/v8/V8Window.h" #include "bindings/core/v8/WrapperTypeInfo.h" #include "core/dom/Document.h" #include "core/frame/LocalDOMWindow.h" #include "core/inspector/BindingVisitors.h" #include "wtf/ThreadSpecific.h" #include <v8-profiler.h> #include <v8.h> namespace blink { typedef HashMap<String, double> ProfileNameIdleTimeMap; void ScriptProfiler::setSamplingInterval(int intervalUs) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (profiler) profiler->SetSamplingInterval(intervalUs); } void ScriptProfiler::start(const String& title) { ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); if (profileNameIdleTimeMap->contains(title)) return; profileNameIdleTimeMap->add(title, 0); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return; v8::HandleScope handleScope(isolate); profiler->StartProfiling(v8String(isolate, title), true); } PassRefPtrWillBeRawPtr<ScriptProfile> ScriptProfiler::stop(const String& title) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return nullptr; v8::HandleScope handleScope(isolate); v8::CpuProfile* profile = profiler->StopProfiling(v8String(isolate, title)); if (!profile) return nullptr; String profileTitle = toCoreString(profile->GetTitle()); double idleTime = 0.0; ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); ProfileNameIdleTimeMap::iterator profileIdleTime = profileNameIdleTimeMap->find(profileTitle); if (profileIdleTime != profileNameIdleTimeMap->end()) { idleTime = profileIdleTime->value * 1000.0; profileNameIdleTimeMap->remove(profileIdleTime); } return ScriptProfile::create(profile, idleTime); } void ScriptProfiler::collectGarbage() { v8::Isolate::GetCurrent()->LowMemoryNotification(); } ScriptValue ScriptProfiler::objectByHeapObjectId(unsigned id) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); v8::HandleScope handleScope(isolate); v8::Local<v8::Value> value = profiler->FindObjectById(id); if (value.IsEmpty() || !value->IsObject()) return ScriptValue(); v8::Local<v8::Object> object = value.As<v8::Object>(); if (object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount) { v8::Local<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex); // Skip wrapper boilerplates which are like regular wrappers but don't have // native object. if (!wrapper.IsEmpty() && wrapper->IsUndefined()) return ScriptValue(); } ScriptState* scriptState = ScriptState::from(object->CreationContext()); return ScriptValue(scriptState, object); } unsigned ScriptProfiler::getHeapObjectId(const ScriptValue& value) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); v8::SnapshotObjectId id = profiler->GetObjectId(value.v8Value()); return id; } void ScriptProfiler::clearHeapObjectIds() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); profiler->ClearObjectIds(); } namespace { class ActivityControlAdapter final : public v8::ActivityControl { public: ActivityControlAdapter(ScriptProfiler::HeapSnapshotProgress* progress) : m_progress(progress), m_firstReport(true) { } virtual ControlOption ReportProgressValue(int done, int total) override { ControlOption result = m_progress->isCanceled() ? kAbort : kContinue; if (m_firstReport) { m_firstReport = false; m_progress->Start(total); } else { m_progress->Worked(done); } if (done >= total) m_progress->Done(); return result; } private: ScriptProfiler::HeapSnapshotProgress* m_progress; bool m_firstReport; }; class GlobalObjectNameResolver final : public v8::HeapProfiler::ObjectNameResolver { public: virtual const char* GetName(v8::Local<v8::Object> object) override { DOMWindow* window = toDOMWindow(v8::Isolate::GetCurrent(), object); if (!window) return 0; CString url = toLocalDOMWindow(window)->document()->url().string().utf8(); m_strings.append(url); return url.data(); } private: Vector<CString> m_strings; }; } // namespace void ScriptProfiler::startTrackingHeapObjects(bool trackAllocations) { v8::Isolate::GetCurrent()->GetHeapProfiler()->StartTrackingHeapObjects(trackAllocations); } namespace { class HeapStatsStream : public v8::OutputStream { public: HeapStatsStream(ScriptProfiler::OutputStream* stream) : m_stream(stream) { } virtual void EndOfStream() override { } virtual WriteResult WriteAsciiChunk(char* data, int size) override { ASSERT(false); return kAbort; } virtual WriteResult WriteHeapStatsChunk(v8::HeapStatsUpdate* updateData, int count) override { Vector<uint32_t> rawData(count * 3); for (int i = 0; i < count; ++i) { int offset = i * 3; rawData[offset] = updateData[i].index; rawData[offset + 1] = updateData[i].count; rawData[offset + 2] = updateData[i].size; } m_stream->write(rawData.data(), rawData.size()); return kContinue; } private: ScriptProfiler::OutputStream* m_stream; }; } unsigned ScriptProfiler::requestHeapStatsUpdate(ScriptProfiler::OutputStream* stream) { HeapStatsStream heapStatsStream(stream); return v8::Isolate::GetCurrent()->GetHeapProfiler()->GetHeapStats(&heapStatsStream); } void ScriptProfiler::stopTrackingHeapObjects() { v8::Isolate::GetCurrent()->GetHeapProfiler()->StopTrackingHeapObjects(); } // FIXME: This method should receive a ScriptState, from which we should retrieve an Isolate. PassRefPtr<ScriptHeapSnapshot> ScriptProfiler::takeHeapSnapshot(HeapSnapshotProgress* control) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return nullptr; v8::HandleScope handleScope(isolate); ASSERT(control); ActivityControlAdapter adapter(control); GlobalObjectNameResolver resolver; const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(&adapter, &resolver); return snapshot ? ScriptHeapSnapshot::create(snapshot) : nullptr; } static v8::RetainedObjectInfo* retainedDOMInfo(uint16_t classId, v8::Local<v8::Value> wrapper) { ASSERT(classId == WrapperTypeInfo::NodeClassId); if (!wrapper->IsObject()) return 0; Node* node = V8Node::toImpl(wrapper.As<v8::Object>()); return node ? new RetainedDOMInfo(node) : 0; } void ScriptProfiler::initialize() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (profiler) profiler->SetWrapperClassInfoProvider(WrapperTypeInfo::NodeClassId, &retainedDOMInfo); } void ScriptProfiler::visitNodeWrappers(WrappedNodeVisitor* visitor) { // visitNodeWrappers() should receive a ScriptState and retrieve an Isolate // from the ScriptState. v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handleScope(isolate); class DOMNodeWrapperVisitor : public v8::PersistentHandleVisitor { public: DOMNodeWrapperVisitor(WrappedNodeVisitor* visitor, v8::Isolate* isolate) : m_visitor(visitor) #if ENABLE(ASSERT) , m_isolate(isolate) #endif { } virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) override { if (classId != WrapperTypeInfo::NodeClassId) return; #if ENABLE(ASSERT) { v8::HandleScope scope(m_isolate); v8::Local<v8::Object> wrapper = v8::Local<v8::Object>::New(m_isolate, v8::Persistent<v8::Object>::Cast(*value)); ASSERT(V8Node::hasInstance(wrapper, m_isolate)); ASSERT(wrapper->IsObject()); } #endif m_visitor->visitNode(toScriptWrappable(v8::Persistent<v8::Object>::Cast(*value))->toImpl<Node>()); } private: WrappedNodeVisitor* m_visitor; #if ENABLE(ASSERT) v8::Isolate* m_isolate; #endif } wrapperVisitor(visitor, isolate); v8::V8::VisitHandlesWithClassIds(isolate, &wrapperVisitor); } ProfileNameIdleTimeMap* ScriptProfiler::currentProfileNameIdleTimeMap() { AtomicallyInitializedStaticReference(WTF::ThreadSpecific<ProfileNameIdleTimeMap>, map, new WTF::ThreadSpecific<ProfileNameIdleTimeMap>); return map; } void ScriptProfiler::setIdle(bool isIdle) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); if (v8::CpuProfiler* profiler = isolate->GetCpuProfiler()) profiler->SetIdle(isIdle); } namespace { class HeapXDKStream : public v8::OutputStream { public: HeapXDKStream(ScriptProfiler::OutputStream* stream) : m_stream(stream) { } virtual void EndOfStream() override { } virtual WriteResult WriteAsciiChunk(char* data, int size) override { ASSERT(false); return kAbort; } virtual WriteResult WriteHeapXDKChunk(const char* symbols, int symbolsSize, const char* frames, int framesSize, const char* types, int typesSize, const char* chunks, int chunksSize, const char* retentions, int retentionSize) override { m_stream->write(symbols, symbolsSize, frames, framesSize, types, typesSize, chunks, chunksSize, retentions, retentionSize); return kContinue; } private: ScriptProfiler::OutputStream* m_stream; }; } void ScriptProfiler::requestHeapXDKUpdate(ScriptProfiler::OutputStream* stream) { HeapXDKStream heapXDKStream(stream); v8::Isolate::GetCurrent()->GetHeapProfiler()->GetHeapXDKStats( &heapXDKStream); } void ScriptProfiler::startTrackingHeapObjectsXDK(int stackDepth, bool retentions) { v8::Isolate::GetCurrent()->GetHeapProfiler()->StartTrackingHeapObjectsXDK( stackDepth, retentions); } PassRefPtr<HeapProfileXDK> ScriptProfiler::stopTrackingHeapObjectsXDK() { return HeapProfileXDK::create( v8::Isolate::GetCurrent() ->GetHeapProfiler()->StopTrackingHeapObjectsXDK()); } } // namespace blink
/* * Copyright (c) 2011, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/core/v8/ScriptProfiler.h" #include "bindings/core/v8/RetainedDOMInfo.h" #include "bindings/core/v8/ScriptValue.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8Node.h" #include "bindings/core/v8/V8Window.h" #include "bindings/core/v8/WrapperTypeInfo.h" #include "core/dom/Document.h" #include "core/frame/LocalDOMWindow.h" #include "core/inspector/BindingVisitors.h" #include "wtf/ThreadSpecific.h" #include <v8-profiler.h> #include <v8.h> namespace blink { typedef HashMap<String, double> ProfileNameIdleTimeMap; void ScriptProfiler::setSamplingInterval(int intervalUs) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (profiler) profiler->SetSamplingInterval(intervalUs); } void ScriptProfiler::start(const String& title) { ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); if (profileNameIdleTimeMap->contains(title)) return; profileNameIdleTimeMap->add(title, 0); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return; v8::HandleScope handleScope(isolate); profiler->StartProfiling(v8String(isolate, title), true); } PassRefPtrWillBeRawPtr<ScriptProfile> ScriptProfiler::stop(const String& title) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return nullptr; v8::HandleScope handleScope(isolate); v8::CpuProfile* profile = profiler->StopProfiling(v8String(isolate, title)); if (!profile) return nullptr; String profileTitle = toCoreString(profile->GetTitle()); double idleTime = 0.0; ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); ProfileNameIdleTimeMap::iterator profileIdleTime = profileNameIdleTimeMap->find(profileTitle); if (profileIdleTime != profileNameIdleTimeMap->end()) { idleTime = profileIdleTime->value * 1000.0; profileNameIdleTimeMap->remove(profileIdleTime); } return ScriptProfile::create(profile, idleTime); } void ScriptProfiler::collectGarbage() { v8::Isolate::GetCurrent()->LowMemoryNotification(); } ScriptValue ScriptProfiler::objectByHeapObjectId(unsigned id) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); v8::HandleScope handleScope(isolate); v8::Local<v8::Value> value = profiler->FindObjectById(id); if (value.IsEmpty() || !value->IsObject()) return ScriptValue(); v8::Local<v8::Object> object = value.As<v8::Object>(); if (object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount) { v8::Local<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex); // Skip wrapper boilerplates which are like regular wrappers but don't have // native object. if (!wrapper.IsEmpty() && wrapper->IsUndefined()) return ScriptValue(); } ScriptState* scriptState = ScriptState::from(object->CreationContext()); return ScriptValue(scriptState, object); } unsigned ScriptProfiler::getHeapObjectId(const ScriptValue& value) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); v8::SnapshotObjectId id = profiler->GetObjectId(value.v8Value()); return id; } void ScriptProfiler::clearHeapObjectIds() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); profiler->ClearObjectIds(); } namespace { class ActivityControlAdapter final : public v8::ActivityControl { public: ActivityControlAdapter(ScriptProfiler::HeapSnapshotProgress* progress) : m_progress(progress), m_firstReport(true) { } virtual ControlOption ReportProgressValue(int done, int total) override { ControlOption result = m_progress->isCanceled() ? kAbort : kContinue; if (m_firstReport) { m_firstReport = false; m_progress->Start(total); } else { m_progress->Worked(done); } if (done >= total) m_progress->Done(); return result; } private: ScriptProfiler::HeapSnapshotProgress* m_progress; bool m_firstReport; }; class GlobalObjectNameResolver final : public v8::HeapProfiler::ObjectNameResolver { public: virtual const char* GetName(v8::Local<v8::Object> object) override { DOMWindow* window = toDOMWindow(v8::Isolate::GetCurrent(), object); if (!window) return 0; CString url = toLocalDOMWindow(window)->document()->url().string().utf8(); m_strings.append(url); return url.data(); } private: Vector<CString> m_strings; }; } // namespace void ScriptProfiler::startTrackingHeapObjects(bool trackAllocations) { v8::Isolate::GetCurrent()->GetHeapProfiler()->StartTrackingHeapObjects(trackAllocations); } namespace { class HeapStatsStream : public v8::OutputStream { public: HeapStatsStream(ScriptProfiler::OutputStream* stream) : m_stream(stream) { } virtual void EndOfStream() override { } virtual WriteResult WriteAsciiChunk(char* data, int size) override { ASSERT(false); return kAbort; } virtual WriteResult WriteHeapStatsChunk(v8::HeapStatsUpdate* updateData, int count) override { Vector<uint32_t> rawData(count * 3); for (int i = 0; i < count; ++i) { int offset = i * 3; rawData[offset] = updateData[i].index; rawData[offset + 1] = updateData[i].count; rawData[offset + 2] = updateData[i].size; } m_stream->write(rawData.data(), rawData.size()); return kContinue; } private: ScriptProfiler::OutputStream* m_stream; }; } unsigned ScriptProfiler::requestHeapStatsUpdate(ScriptProfiler::OutputStream* stream) { HeapStatsStream heapStatsStream(stream); return v8::Isolate::GetCurrent()->GetHeapProfiler()->GetHeapStats(&heapStatsStream); } void ScriptProfiler::stopTrackingHeapObjects() { v8::Isolate::GetCurrent()->GetHeapProfiler()->StopTrackingHeapObjects(); } // FIXME: This method should receive a ScriptState, from which we should retrieve an Isolate. PassRefPtr<ScriptHeapSnapshot> ScriptProfiler::takeHeapSnapshot(HeapSnapshotProgress* control) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return nullptr; v8::HandleScope handleScope(isolate); ASSERT(control); ActivityControlAdapter adapter(control); GlobalObjectNameResolver resolver; const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(&adapter, &resolver); return snapshot ? ScriptHeapSnapshot::create(snapshot) : nullptr; } static v8::RetainedObjectInfo* retainedDOMInfo(uint16_t classId, v8::Local<v8::Value> wrapper) { ASSERT(classId == WrapperTypeInfo::NodeClassId); if (!wrapper->IsObject()) return 0; Node* node = V8Node::toImpl(wrapper.As<v8::Object>()); return node ? new RetainedDOMInfo(node) : 0; } void ScriptProfiler::initialize() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (profiler) profiler->SetWrapperClassInfoProvider(WrapperTypeInfo::NodeClassId, &retainedDOMInfo); } void ScriptProfiler::visitNodeWrappers(WrappedNodeVisitor* visitor) { // visitNodeWrappers() should receive a ScriptState and retrieve an Isolate // from the ScriptState. v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handleScope(isolate); class DOMNodeWrapperVisitor : public v8::PersistentHandleVisitor { public: DOMNodeWrapperVisitor(WrappedNodeVisitor* visitor, v8::Isolate* isolate) : m_visitor(visitor) #if ENABLE(ASSERT) , m_isolate(isolate) #endif { } virtual void VisitPersistentHandle(v8::Persistent<v8::Value>* value, uint16_t classId) override { if (classId != WrapperTypeInfo::NodeClassId) return; #if ENABLE(ASSERT) { v8::HandleScope scope(m_isolate); v8::Local<v8::Object> wrapper = v8::Local<v8::Object>::New(m_isolate, v8::Persistent<v8::Object>::Cast(*value)); ASSERT(V8Node::hasInstance(wrapper, m_isolate)); ASSERT(wrapper->IsObject()); } #endif m_visitor->visitNode(toScriptWrappable(v8::Persistent<v8::Object>::Cast(*value))->toImpl<Node>()); } private: WrappedNodeVisitor* m_visitor; #if ENABLE(ASSERT) v8::Isolate* m_isolate; #endif } wrapperVisitor(visitor, isolate); v8::V8::VisitHandlesWithClassIds(isolate, &wrapperVisitor); } ProfileNameIdleTimeMap* ScriptProfiler::currentProfileNameIdleTimeMap() { AtomicallyInitializedStaticReference(WTF::ThreadSpecific<ProfileNameIdleTimeMap>, map, new WTF::ThreadSpecific<ProfileNameIdleTimeMap>); return map; } void ScriptProfiler::setIdle(bool isIdle) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); if (v8::CpuProfiler* profiler = isolate->GetCpuProfiler()) profiler->SetIdle(isIdle); } namespace { class HeapXDKStream : public v8::OutputStream { public: HeapXDKStream(ScriptProfiler::OutputStream* stream) : m_stream(stream) { } virtual void EndOfStream() override { } virtual WriteResult WriteAsciiChunk(char* data, int size) override { ASSERT(false); return kAbort; } virtual WriteResult WriteHeapXDKChunk(const char* symbols, size_t symbolsSize, const char* frames, size_t framesSize, const char* types, size_t typesSize, const char* chunks, size_t chunksSize, const char* retentions, size_t retentionSize) override { m_stream->write(symbols, symbolsSize, frames, framesSize, types, typesSize, chunks, chunksSize, retentions, retentionSize); return kContinue; } private: ScriptProfiler::OutputStream* m_stream; }; } void ScriptProfiler::requestHeapXDKUpdate(ScriptProfiler::OutputStream* stream) { HeapXDKStream heapXDKStream(stream); v8::Isolate::GetCurrent()->GetHeapProfiler()->GetHeapXDKStats( &heapXDKStream); } void ScriptProfiler::startTrackingHeapObjectsXDK(int stackDepth, bool retentions) { v8::Isolate::GetCurrent()->GetHeapProfiler()->StartTrackingHeapObjectsXDK( stackDepth, retentions); } PassRefPtr<HeapProfileXDK> ScriptProfiler::stopTrackingHeapObjectsXDK() { return HeapProfileXDK::create( v8::Isolate::GetCurrent() ->GetHeapProfiler()->StopTrackingHeapObjectsXDK()); } } // namespace blink
Fix XDK code so that it uses size_t instead of int.
Fix XDK code so that it uses size_t instead of int. This is useful to support 64 bits because call sites of that API usually uses std functions which returns a size_t and size_t is not going to git into an int on 64 bits. Today it triggers a warning of potential data loss.
C++
bsd-3-clause
smishenk/blink-crosswalk,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,smishenk/blink-crosswalk,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk
64c84fdca6184bfe7a6d9aee71327ad86b242ed7
InteractionBase/src/autocomplete/AutoCompleteVis.cpp
InteractionBase/src/autocomplete/AutoCompleteVis.cpp
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2012 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ /* * AutoCompleteVis.cpp * * Created on: Jul 24, 2012 * Author: Dimitar Asenov */ #include "AutoCompleteVis.h" #include "AutoComplete.h" #include "AutoCompleteEntry.h" #include "../vis/TextAndDescription.h" #include "VisualizationBase/src/cursor/Cursor.h" #include "VisualizationBase/src/items/Static.h" #include "VisualizationBase/src/CustomSceneEvent.h" namespace Interaction { ITEM_COMMON_DEFINITIONS(AutoCompleteVis, "item") AutoCompleteVis::AutoCompleteVis(const QList<AutoCompleteEntry*>& entries, const StyleType* style) : LayoutProvider<>(nullptr, style), entries_(), newEntries_(entries), newEntriesSet_(true), noProposals_(), selectionEffect_(), selectionIndex_() { setFlag(QGraphicsItem::ItemIsMovable); setFlag(QGraphicsItem::ItemClipsChildrenToShape); setZValue(LAYER_AUTOCOMPLETE_Z); } AutoCompleteVis::~AutoCompleteVis() { layout()->clear(false); SAFE_DELETE_ITEM(noProposals_); for(auto e : entries_) SAFE_DELETE(e); entries_.clear(); selectionEffect_ = nullptr; // This is deleted when it's corresponding item is deleted // Deleted by layout's destructor noProposals_ = nullptr; } void AutoCompleteVis::setEntries(const QList<AutoCompleteEntry*>& entries) { newEntries_ = entries; newEntriesSet_ = true; } void AutoCompleteVis::updateEntries() { newEntriesSet_ = false; layout()->clear(false); SAFE_DELETE_ITEM(noProposals_); for(auto e : entries_) SAFE_DELETE(e); entries_ = newEntries_; for (auto e : entries_) if (!e->visualization()) e->setVisualization( new TextAndDescription(e->text(), e->description())); if (entries_.isEmpty()) { layout()->synchronizeFirst(noProposals_, true, &style()->noProposals()); selectionIndex_ = -1; } else { selectionIndex_ = 0; selectionEffect_ = new QGraphicsColorizeEffect(); // Note we must renew this every time since it will be // automatically deleted by the item that owns it. entries_.at(selectionIndex_)->visualization()->setGraphicsEffect(selectionEffect_); for (auto e : entries_) layout()->append(e->visualization()); } // Install event handler if (scene() && scene()->mainCursor() && !this->isAncestorOf(scene()->mainCursor()->owner())) scene()->mainCursor()->owner()->installSceneEventFilter(this); } void AutoCompleteVis::determineChildren() { if (newEntriesSet_) updateEntries(); layout()->setStyle(&style()->layout()); if (noProposals_) noProposals_->setStyle(&style()->noProposals()); } void AutoCompleteVis::updateGeometry(int /*availableWidth*/, int /*availableHeight*/) { // Set position if (scene() && scene()->mainCursor() && !this->isAncestorOf(scene()->mainCursor()->owner())) { auto owner = scene()->mainCursor()->owner(); setPos(owner->scenePos().toPoint() + QPoint(0, owner->height() + style()->distanceToCursor())); } // Set size if (hasShape()) { getShape()->setOffset(0, 0); QSize s = layout()->size().toSize(); if (s.height() > style()->heightLimit()) s.setHeight(style()->heightLimit()); getShape()->setInnerSize(s.width(), s.height()); layout()->setPos(getShape()->contentLeft(), getShape()->contentTop()); } else { layout()->setPos(0,0); QSize s = layout()->size().toSize(); if (s.height() > style()->heightLimit()) s.setHeight(style()->heightLimit()); setSize(s); } } Visualization::Item::UpdateType AutoCompleteVis::needsUpdate() { auto upd = Visualization::LayoutProvider<>::needsUpdate(); if ( upd == NoUpdate) return StandardUpdate; else return upd; } bool AutoCompleteVis::sceneEventFilter(QGraphicsItem* watched, QEvent* event) { Visualization::Item* cursorOwner = nullptr; if (scene()->mainCursor() && !this->isAncestorOf(scene()->mainCursor()->owner())) cursorOwner = scene()->mainCursor()->owner(); if (event->type() == QEvent::FocusOut) AutoComplete::delayedHide(); if (cursorOwner != watched) { watched->removeSceneEventFilter(this); return false; } if (event->type() == QEvent::KeyPress) { auto e = dynamic_cast<QKeyEvent*>(event); switch (e->key()) { case Qt::Key_Down: { if (selectionIndex_ < entries_.size() - 1) { ++selectionIndex_; entries_.at(selectionIndex_)->visualization()->setGraphicsEffect(selectionEffect_); } return true; } break; case Qt::Key_Up: { if (selectionIndex_ > 0) { --selectionIndex_; entries_.at(selectionIndex_)->visualization()->setGraphicsEffect(selectionEffect_); } return true; } break; case Qt::Key_Return: case Qt::Key_Enter: { if (selectionIndex_ < 0 && entries_.size() == 1) selectionIndex_ = 0; if (entries_.size() > 0) entries_.at(selectionIndex_)->execute(); scene()->addPostEventAction(new Visualization::CustomSceneEvent( AutoComplete::hide )); return true; } break; } } return false; } } /* namespace Interaction */
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2012 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ /* * AutoCompleteVis.cpp * * Created on: Jul 24, 2012 * Author: Dimitar Asenov */ #include "AutoCompleteVis.h" #include "AutoComplete.h" #include "AutoCompleteEntry.h" #include "../vis/TextAndDescription.h" #include "VisualizationBase/src/cursor/Cursor.h" #include "VisualizationBase/src/items/Static.h" #include "VisualizationBase/src/CustomSceneEvent.h" namespace Interaction { ITEM_COMMON_DEFINITIONS(AutoCompleteVis, "item") AutoCompleteVis::AutoCompleteVis(const QList<AutoCompleteEntry*>& entries, const StyleType* style) : LayoutProvider<>(nullptr, style), entries_(), newEntries_(entries), newEntriesSet_(true), noProposals_(), selectionEffect_(), selectionIndex_() { setFlag(QGraphicsItem::ItemIsMovable); setFlag(QGraphicsItem::ItemClipsChildrenToShape); setZValue(LAYER_AUTOCOMPLETE_Z); } AutoCompleteVis::~AutoCompleteVis() { layout()->clear(false); SAFE_DELETE_ITEM(noProposals_); for(auto e : entries_) SAFE_DELETE(e); entries_.clear(); selectionEffect_ = nullptr; // This is deleted when it's corresponding item is deleted // Deleted by layout's destructor noProposals_ = nullptr; } void AutoCompleteVis::setEntries(const QList<AutoCompleteEntry*>& entries) { newEntries_ = entries; newEntriesSet_ = true; } void AutoCompleteVis::updateEntries() { newEntriesSet_ = false; layout()->clear(false); SAFE_DELETE_ITEM(noProposals_); for(auto e : entries_) SAFE_DELETE(e); entries_ = newEntries_; for (auto e : entries_) if (!e->visualization()) e->setVisualization( new TextAndDescription(e->text(), e->description())); if (entries_.isEmpty()) { layout()->synchronizeFirst(noProposals_, true, &style()->noProposals()); selectionIndex_ = -1; } else { selectionIndex_ = 0; selectionEffect_ = new QGraphicsColorizeEffect(); // Note we must renew this every time since it will be // automatically deleted by the item that owns it. entries_.at(selectionIndex_)->visualization()->setGraphicsEffect(selectionEffect_); for (auto e : entries_) layout()->append(e->visualization()); } // Install event handler if (scene() && scene()->mainCursor() && !this->isAncestorOf(scene()->mainCursor()->owner())) scene()->mainCursor()->owner()->installSceneEventFilter(this); } void AutoCompleteVis::determineChildren() { if (newEntriesSet_) updateEntries(); layout()->setStyle(&style()->layout()); if (noProposals_) noProposals_->setStyle(&style()->noProposals()); } void AutoCompleteVis::updateGeometry(int /*availableWidth*/, int /*availableHeight*/) { // Set position if (scene() && scene()->mainCursor() && !this->isAncestorOf(scene()->mainCursor()->owner())) { auto owner = scene()->mainCursor()->owner(); setPos(owner->scenePos().toPoint() + QPoint(0, owner->height() + style()->distanceToCursor())); } // Set size if (hasShape()) { getShape()->setOffset(0, 0); QSize s = layout()->size().toSize(); if (s.height() > style()->heightLimit()) s.setHeight(style()->heightLimit()); getShape()->setInnerSize(s.width(), s.height()); layout()->setPos(getShape()->contentLeft(), getShape()->contentTop()); } else { layout()->setPos(0,0); QSize s = layout()->size().toSize(); if (s.height() > style()->heightLimit()) s.setHeight(style()->heightLimit()); setSize(s); } } Visualization::Item::UpdateType AutoCompleteVis::needsUpdate() { auto upd = Visualization::LayoutProvider<>::needsUpdate(); if ( upd == NoUpdate) return StandardUpdate; else return upd; } bool AutoCompleteVis::sceneEventFilter(QGraphicsItem* watched, QEvent* event) { Visualization::Item* cursorOwner = nullptr; if (scene()->mainCursor() && !this->isAncestorOf(scene()->mainCursor()->owner())) cursorOwner = scene()->mainCursor()->owner(); if (event->type() == QEvent::FocusOut) AutoComplete::delayedHide(); if (cursorOwner != watched) { watched->removeSceneEventFilter(this); return false; } if (event->type() == QEvent::KeyPress && !entries_.isEmpty()) { auto e = dynamic_cast<QKeyEvent*>(event); switch (e->key()) { case Qt::Key_Down: { if (selectionIndex_ < entries_.size() - 1) { ++selectionIndex_; entries_.at(selectionIndex_)->visualization()->setGraphicsEffect(selectionEffect_); } return true; } break; case Qt::Key_Up: { if (selectionIndex_ > 0) { --selectionIndex_; entries_.at(selectionIndex_)->visualization()->setGraphicsEffect(selectionEffect_); } return true; } break; case Qt::Key_Return: case Qt::Key_Enter: { if (selectionIndex_ < 0 && entries_.size() == 1) selectionIndex_ = 0; entries_.at(selectionIndex_)->execute(); scene()->addPostEventAction(new Visualization::CustomSceneEvent( AutoComplete::hide )); return true; } break; } } return false; } } /* namespace Interaction */
Make the auto completion ignore key presses when there are no entries
Make the auto completion ignore key presses when there are no entries
C++
bsd-3-clause
mgalbier/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,patrick-luethi/Envision,Vaishal-shah/Envision,BalzGuenat/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,BalzGuenat/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,mgalbier/Envision,mgalbier/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,patrick-luethi/Envision,dimitar-asenov/Envision,mgalbier/Envision,mgalbier/Envision,lukedirtwalker/Envision,patrick-luethi/Envision,mgalbier/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,patrick-luethi/Envision,BalzGuenat/Envision,BalzGuenat/Envision,Vaishal-shah/Envision,BalzGuenat/Envision,Vaishal-shah/Envision,BalzGuenat/Envision
67804910e567a4a878b9347c0a7bdc13ca4dee18
SurgSim/Math/UnitTests/PolynomialTests.cpp
SurgSim/Math/UnitTests/PolynomialTests.cpp
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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. /// \file /// Tests for the Polynomial functions. #include <array> #include <gtest/gtest.h> #include "SurgSim/Math/Polynomial.h" namespace SurgSim { namespace Math { namespace { double epsilon = 1.0e-10; } class PolynomialUtilityTests : public ::testing::Test { }; template <typename T> class PolynomialTests : public ::testing::Test { public: void initializeConstructor(Polynomial<double, 0>* poly) { typedef Polynomial<double, 0> PolynomialType; EXPECT_NO_THROW(PolynomialType polyNew); EXPECT_NO_THROW(PolynomialType polyNew(7.0)); PolynomialType polyNew(1.0); *poly = polyNew; } void initializeConstructor(Polynomial<double, 1>* poly) { typedef Polynomial<double, 1> PolynomialType; EXPECT_NO_THROW(PolynomialType polyNew); EXPECT_NO_THROW(PolynomialType polyNew(7.0, 8)); PolynomialType polyNew(1.0, 2.0); *poly = polyNew; } void initializeConstructor(Polynomial<double, 2>* poly) { typedef Polynomial<double, 2> PolynomialType; EXPECT_NO_THROW(PolynomialType polyNew); EXPECT_NO_THROW(PolynomialType polyNew(7.0, 8.0, 9.0)); PolynomialType polyNew(1.0, 2.0, 3.0); *poly = polyNew; } void initializeConstructor(Polynomial<double, 3>* poly) { typedef Polynomial<double, 3> PolynomialType; EXPECT_NO_THROW(PolynomialType polyNew); EXPECT_NO_THROW(PolynomialType polyNew(7.0, 8.0, 9.0, 10.0)); PolynomialType polyNew(1.0, 2.0, 3.0, 4.0); *poly = polyNew; } template <int degree> void setPolynomialFromOffset(int offset, Polynomial<double, degree>* poly) { for (size_t counter = 0; counter <= degree; ++counter) { (*poly)[counter] = static_cast<double>(counter + offset); } } template <int degree> void setPolynomialToSmallValue(Polynomial<double, degree>* poly) { for (size_t counter = 0; counter <= degree; ++counter) { (*poly)[counter] = epsilon / 2.0; } } template <int degree> void checkPolynomialConstructor(Polynomial<double, degree>* poly) { // Check get ... up to degree for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(counter + 1.0, poly->getCoefficient(counter)); EXPECT_DOUBLE_EQ(counter + 1.0, (*poly)[counter]); } // Check get ... beyond degree for (size_t counter = degree + 1; counter < 5; ++counter) { EXPECT_DOUBLE_EQ(0.0, poly->getCoefficient(counter)); EXPECT_THROW((*poly)[counter], SurgSim::Framework::AssertionFailure); } // Check set up to degree for (size_t counter = 0; counter <= degree; ++counter) { poly->setCoefficient(counter, static_cast<double>(counter)); EXPECT_DOUBLE_EQ(static_cast<double>(counter), poly->getCoefficient(counter)); (*poly)[counter] = static_cast<double>(counter + 1); EXPECT_DOUBLE_EQ(static_cast<double>(counter + 1), poly->getCoefficient(counter)); } // Check set beyond degree EXPECT_THROW(poly->setCoefficient(degree + 1, 12.0), SurgSim::Framework::AssertionFailure); EXPECT_THROW((*poly)[degree + 1] = 12, SurgSim::Framework::AssertionFailure); } template <int degree> void checkPolynomialArithmetic(const Polynomial<double, degree>& poly1, const Polynomial<double, degree>& poly2) { Polynomial<double, degree> scratch; // Check evaluate ... double evaluate = static_cast<double>(degree + 1); for (int counter = degree - 1; counter >= 0; --counter) { evaluate = (0.5 * evaluate) + counter + 1; } EXPECT_NEAR(evaluate, poly1.evaluate(0.5), epsilon); // Check negation ... scratch = -poly1; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(-1 * (static_cast<double>(counter) + 1.0), scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(-1 * (static_cast<double>(counter) + 1.0), scratch[counter]); } // Check add ... scratch = poly1 + poly2; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(2 * static_cast<double>(counter) + 3.0, scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(2 * static_cast<double>(counter) + 3.0, scratch[counter]); } scratch = poly1; scratch += poly2; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(2 * static_cast<double>(counter) + 3.0, scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(2 * static_cast<double>(counter) + 3.0, scratch[counter]); } // Check subtract ... scratch = poly1 - poly2; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(-1.0, scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(-1.0, scratch[counter]); } scratch = poly1; scratch -= poly2; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(-1.0, scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(-1.0, scratch[counter]); } // Check isApprox ... scratch = poly1; for (size_t counter = 0; counter <= degree; ++counter) { scratch[counter] += epsilon / 2.0; } EXPECT_TRUE(scratch.isApprox(poly1, epsilon)); scratch[0] = poly1[0] + 2.0 * epsilon; for (size_t counter = 0; counter < degree; ++counter) { EXPECT_FALSE(scratch.isApprox(poly1, epsilon)); scratch[counter] = poly1[counter] + epsilon / 2.0; scratch[counter + 1] = poly1[counter + 1] + 2.0 * epsilon; } EXPECT_FALSE(scratch.isApprox(poly1, epsilon)); } template <int degree> void checkPolynomialDerivative(const Polynomial<double, degree>& poly1) { if (degree != 0) { // Check derivative ... auto smallScratch = poly1.derivative(); for (size_t counter = 0; counter < degree; ++counter) { EXPECT_DOUBLE_EQ((counter + 2.0) * (counter + 1.0), smallScratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ((counter + 2.0) * (counter + 1.0), smallScratch[counter]); } EXPECT_DOUBLE_EQ(0.0, smallScratch.getCoefficient(degree)); EXPECT_THROW(smallScratch[degree], SurgSim::Framework::AssertionFailure); } } template <int degree> void checkIsNearZero(Polynomial<double, degree>* poly1) { EXPECT_TRUE(poly1->isNearZero(epsilon)); for (size_t counter = 0; counter <= degree; counter++) { poly1->setCoefficient(counter, 2 * epsilon); EXPECT_FALSE(poly1->isNearZero(epsilon)); poly1->setCoefficient(counter, epsilon / 2.0); EXPECT_TRUE(poly1->isNearZero(epsilon)); (*poly1)[counter] = 2 * epsilon; EXPECT_FALSE(poly1->isNearZero(epsilon)); (*poly1)[counter] = epsilon / 2.0; EXPECT_TRUE(poly1->isNearZero(epsilon)); } } template <int degree> void checkDiscriminant(Polynomial<double, degree>* poly, double expected) { } template <> void checkDiscriminant(Polynomial<double, 2>* poly, double expected) { EXPECT_DOUBLE_EQ(expected, poly->discriminant()); } }; template <typename T> class PolynomialDerivativeTests : public PolynomialTests<T> { }; typedef ::testing::Types<Polynomial<double, 0>, Polynomial<double, 1>, Polynomial<double, 2>, Polynomial<double, 3>> PolynomialTypes; typedef ::testing::Types < Polynomial<double, 1>, Polynomial<double, 2>, Polynomial<double, 3 >> PolynomialDerivativeTypes; TYPED_TEST_CASE(PolynomialTests, PolynomialTypes); TYPED_TEST_CASE(PolynomialDerivativeTests, PolynomialDerivativeTypes); TYPED_TEST(PolynomialTests, InitializationTests) { EXPECT_NO_THROW(TypeParam poly); TypeParam poly; this->initializeConstructor(&poly); this->checkPolynomialConstructor(&poly); }; TYPED_TEST(PolynomialTests, ArithmeticTests) { TypeParam poly1; this->setPolynomialFromOffset(1, &poly1); TypeParam poly2; this->setPolynomialFromOffset(2, &poly2); this->checkPolynomialArithmetic(poly1, poly2); }; TYPED_TEST(PolynomialDerivativeTests, DerivativeTests) { TypeParam poly1; this->setPolynomialFromOffset(1, &poly1); this->checkPolynomialDerivative(poly1); }; TYPED_TEST(PolynomialTests, NearZeroTests) { TypeParam poly1; this->setPolynomialToSmallValue(&poly1); this->checkIsNearZero(&poly1); }; TYPED_TEST(PolynomialTests, DiscriminantTests) { TypeParam poly1; { SCOPED_TRACE("0 + 1x + 2x^2"); this->setPolynomialFromOffset(0, &poly1); // discriminant = 1 - 4*0 = 1 this->checkDiscriminant(&poly1, 1.0); } { SCOPED_TRACE("1 + 2x + 3x^2"); this->setPolynomialFromOffset(1, &poly1); // discriminant = 4 - 4*3 = -8 this->checkDiscriminant(&poly1, -8.0); } { SCOPED_TRACE("2 + 3x + 4x^2"); this->setPolynomialFromOffset(2, &poly1); // discriminant = 9 - 4*8 = -23 this->checkDiscriminant(&poly1, -23.0); } }; TEST_F(PolynomialUtilityTests, UtilityTests) { Polynomial<double, 0> p0_1(1.0); Polynomial<double, 0> p0_2(2.0); Polynomial<double, 1> p1_1(1.0, 2.0); Polynomial<double, 1> p1_2(2.0, 3.0); Polynomial<double, 2> p2_1(1.0, 2.0, 3.0); Polynomial<double, 2> p2_2(2.0, 3.0, 4.0); Polynomial<double, 3> p3_1(1.0, 2.0, 3.0, 4.0); Polynomial<double, 3> p3_2(2.0, 3.0, 4.0, 5.0); // degree n * degree m { auto result = p0_2 * p3_2; EXPECT_TRUE(result.isApprox(Polynomial<double, 3>(4.0, 6.0, 8.0, 10.0), epsilon)); } // degree 1 * degree 1 { auto result = p1_1 * p1_2; EXPECT_TRUE(result.isApprox(Polynomial<double, 2>(2.0, 7.0, 6.0), epsilon)); } // degree 2 * degree 1 { auto result = p2_1 * p1_2; EXPECT_TRUE(result.isApprox(Polynomial<double, 3>(2.0, 7.0, 12.0, 9.0), epsilon)); } // degree 1 * degree 2 { auto result = p1_1 * p2_2; EXPECT_TRUE(result.isApprox(Polynomial<double, 3>(2.0, 7.0, 10.0, 8.0), epsilon)); } // degree 0^2 { auto result_p0_1 = square(p0_1); EXPECT_TRUE(result_p0_1.isApprox(Polynomial<double, 0>(1.0), epsilon)); auto result_p0_2 = square(p0_2); EXPECT_TRUE(result_p0_2.isApprox(Polynomial<double, 0>(4.0), epsilon)); } // degree 1^2 { auto result = square(p1_2); EXPECT_TRUE(result.isApprox(Polynomial<double, 2>(4.0, 12.0, 9.0), epsilon)); } // Output { // Output std::ostringstream intervalOutput; intervalOutput << p3_1; EXPECT_EQ("(4*x^3 + 3*x^2 + 2*x + 1)", intervalOutput.str()); } }; }; // namespace Math }; // namespace SurgSim
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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. /// \file /// Tests for the Polynomial functions. #include <array> #include <gtest/gtest.h> #include "SurgSim/Math/Polynomial.h" namespace SurgSim { namespace Math { namespace { double epsilon = 1.0e-10; template <int degree> void checkDiscriminant(Polynomial<double, degree>* poly, double expected) { } template <> void checkDiscriminant(Polynomial<double, 2>* poly, double expected) { EXPECT_DOUBLE_EQ(expected, poly->discriminant()); } } class PolynomialUtilityTests : public ::testing::Test { }; template <typename T> class PolynomialTests : public ::testing::Test { public: void initializeConstructor(Polynomial<double, 0>* poly) { typedef Polynomial<double, 0> PolynomialType; EXPECT_NO_THROW(PolynomialType polyNew); EXPECT_NO_THROW(PolynomialType polyNew(7.0)); PolynomialType polyNew(1.0); *poly = polyNew; } void initializeConstructor(Polynomial<double, 1>* poly) { typedef Polynomial<double, 1> PolynomialType; EXPECT_NO_THROW(PolynomialType polyNew); EXPECT_NO_THROW(PolynomialType polyNew(7.0, 8)); PolynomialType polyNew(1.0, 2.0); *poly = polyNew; } void initializeConstructor(Polynomial<double, 2>* poly) { typedef Polynomial<double, 2> PolynomialType; EXPECT_NO_THROW(PolynomialType polyNew); EXPECT_NO_THROW(PolynomialType polyNew(7.0, 8.0, 9.0)); PolynomialType polyNew(1.0, 2.0, 3.0); *poly = polyNew; } void initializeConstructor(Polynomial<double, 3>* poly) { typedef Polynomial<double, 3> PolynomialType; EXPECT_NO_THROW(PolynomialType polyNew); EXPECT_NO_THROW(PolynomialType polyNew(7.0, 8.0, 9.0, 10.0)); PolynomialType polyNew(1.0, 2.0, 3.0, 4.0); *poly = polyNew; } template <int degree> void setPolynomialFromOffset(int offset, Polynomial<double, degree>* poly) { for (size_t counter = 0; counter <= degree; ++counter) { (*poly)[counter] = static_cast<double>(counter + offset); } } template <int degree> void setPolynomialToSmallValue(Polynomial<double, degree>* poly) { for (size_t counter = 0; counter <= degree; ++counter) { (*poly)[counter] = epsilon / 2.0; } } template <int degree> void checkPolynomialConstructor(Polynomial<double, degree>* poly) { // Check get ... up to degree for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(counter + 1.0, poly->getCoefficient(counter)); EXPECT_DOUBLE_EQ(counter + 1.0, (*poly)[counter]); } // Check get ... beyond degree for (size_t counter = degree + 1; counter < 5; ++counter) { EXPECT_DOUBLE_EQ(0.0, poly->getCoefficient(counter)); EXPECT_THROW((*poly)[counter], SurgSim::Framework::AssertionFailure); } // Check set up to degree for (size_t counter = 0; counter <= degree; ++counter) { poly->setCoefficient(counter, static_cast<double>(counter)); EXPECT_DOUBLE_EQ(static_cast<double>(counter), poly->getCoefficient(counter)); (*poly)[counter] = static_cast<double>(counter + 1); EXPECT_DOUBLE_EQ(static_cast<double>(counter + 1), poly->getCoefficient(counter)); } // Check set beyond degree EXPECT_THROW(poly->setCoefficient(degree + 1, 12.0), SurgSim::Framework::AssertionFailure); EXPECT_THROW((*poly)[degree + 1] = 12, SurgSim::Framework::AssertionFailure); } template <int degree> void checkPolynomialArithmetic(const Polynomial<double, degree>& poly1, const Polynomial<double, degree>& poly2) { Polynomial<double, degree> scratch; // Check evaluate ... double evaluate = static_cast<double>(degree + 1); for (int counter = degree - 1; counter >= 0; --counter) { evaluate = (0.5 * evaluate) + counter + 1; } EXPECT_NEAR(evaluate, poly1.evaluate(0.5), epsilon); // Check negation ... scratch = -poly1; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(-1 * (static_cast<double>(counter) + 1.0), scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(-1 * (static_cast<double>(counter) + 1.0), scratch[counter]); } // Check add ... scratch = poly1 + poly2; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(2 * static_cast<double>(counter) + 3.0, scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(2 * static_cast<double>(counter) + 3.0, scratch[counter]); } scratch = poly1; scratch += poly2; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(2 * static_cast<double>(counter) + 3.0, scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(2 * static_cast<double>(counter) + 3.0, scratch[counter]); } // Check subtract ... scratch = poly1 - poly2; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(-1.0, scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(-1.0, scratch[counter]); } scratch = poly1; scratch -= poly2; for (size_t counter = 0; counter <= degree; ++counter) { EXPECT_DOUBLE_EQ(-1.0, scratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ(-1.0, scratch[counter]); } // Check isApprox ... scratch = poly1; for (size_t counter = 0; counter <= degree; ++counter) { scratch[counter] += epsilon / 2.0; } EXPECT_TRUE(scratch.isApprox(poly1, epsilon)); scratch[0] = poly1[0] + 2.0 * epsilon; for (size_t counter = 0; counter < degree; ++counter) { EXPECT_FALSE(scratch.isApprox(poly1, epsilon)); scratch[counter] = poly1[counter] + epsilon / 2.0; scratch[counter + 1] = poly1[counter + 1] + 2.0 * epsilon; } EXPECT_FALSE(scratch.isApprox(poly1, epsilon)); } template <int degree> void checkPolynomialDerivative(const Polynomial<double, degree>& poly1) { if (degree != 0) { // Check derivative ... auto smallScratch = poly1.derivative(); for (size_t counter = 0; counter < degree; ++counter) { EXPECT_DOUBLE_EQ((counter + 2.0) * (counter + 1.0), smallScratch.getCoefficient(counter)); EXPECT_DOUBLE_EQ((counter + 2.0) * (counter + 1.0), smallScratch[counter]); } EXPECT_DOUBLE_EQ(0.0, smallScratch.getCoefficient(degree)); EXPECT_THROW(smallScratch[degree], SurgSim::Framework::AssertionFailure); } } template <int degree> void checkIsNearZero(Polynomial<double, degree>* poly1) { EXPECT_TRUE(poly1->isNearZero(epsilon)); for (size_t counter = 0; counter <= degree; counter++) { poly1->setCoefficient(counter, 2 * epsilon); EXPECT_FALSE(poly1->isNearZero(epsilon)); poly1->setCoefficient(counter, epsilon / 2.0); EXPECT_TRUE(poly1->isNearZero(epsilon)); (*poly1)[counter] = 2 * epsilon; EXPECT_FALSE(poly1->isNearZero(epsilon)); (*poly1)[counter] = epsilon / 2.0; EXPECT_TRUE(poly1->isNearZero(epsilon)); } } }; template <typename T> class PolynomialDerivativeTests : public PolynomialTests<T> { }; typedef ::testing::Types<Polynomial<double, 0>, Polynomial<double, 1>, Polynomial<double, 2>, Polynomial<double, 3>> PolynomialTypes; typedef ::testing::Types < Polynomial<double, 1>, Polynomial<double, 2>, Polynomial<double, 3 >> PolynomialDerivativeTypes; TYPED_TEST_CASE(PolynomialTests, PolynomialTypes); TYPED_TEST_CASE(PolynomialDerivativeTests, PolynomialDerivativeTypes); TYPED_TEST(PolynomialTests, InitializationTests) { EXPECT_NO_THROW(TypeParam poly); TypeParam poly; this->initializeConstructor(&poly); this->checkPolynomialConstructor(&poly); }; TYPED_TEST(PolynomialTests, ArithmeticTests) { TypeParam poly1; this->setPolynomialFromOffset(1, &poly1); TypeParam poly2; this->setPolynomialFromOffset(2, &poly2); this->checkPolynomialArithmetic(poly1, poly2); }; TYPED_TEST(PolynomialDerivativeTests, DerivativeTests) { TypeParam poly1; this->setPolynomialFromOffset(1, &poly1); this->checkPolynomialDerivative(poly1); }; TYPED_TEST(PolynomialTests, NearZeroTests) { TypeParam poly1; this->setPolynomialToSmallValue(&poly1); this->checkIsNearZero(&poly1); }; TYPED_TEST(PolynomialTests, DiscriminantTests) { TypeParam poly1; { SCOPED_TRACE("0 + 1x + 2x^2"); this->setPolynomialFromOffset(0, &poly1); // discriminant = 1 - 4*0 = 1 checkDiscriminant(&poly1, 1.0); } { SCOPED_TRACE("1 + 2x + 3x^2"); this->setPolynomialFromOffset(1, &poly1); // discriminant = 4 - 4*3 = -8 checkDiscriminant(&poly1, -8.0); } { SCOPED_TRACE("2 + 3x + 4x^2"); this->setPolynomialFromOffset(2, &poly1); // discriminant = 9 - 4*8 = -23 checkDiscriminant(&poly1, -23.0); } }; TEST_F(PolynomialUtilityTests, UtilityTests) { Polynomial<double, 0> p0_1(1.0); Polynomial<double, 0> p0_2(2.0); Polynomial<double, 1> p1_1(1.0, 2.0); Polynomial<double, 1> p1_2(2.0, 3.0); Polynomial<double, 2> p2_1(1.0, 2.0, 3.0); Polynomial<double, 2> p2_2(2.0, 3.0, 4.0); Polynomial<double, 3> p3_1(1.0, 2.0, 3.0, 4.0); Polynomial<double, 3> p3_2(2.0, 3.0, 4.0, 5.0); // degree n * degree m { auto result = p0_2 * p3_2; EXPECT_TRUE(result.isApprox(Polynomial<double, 3>(4.0, 6.0, 8.0, 10.0), epsilon)); } // degree 1 * degree 1 { auto result = p1_1 * p1_2; EXPECT_TRUE(result.isApprox(Polynomial<double, 2>(2.0, 7.0, 6.0), epsilon)); } // degree 2 * degree 1 { auto result = p2_1 * p1_2; EXPECT_TRUE(result.isApprox(Polynomial<double, 3>(2.0, 7.0, 12.0, 9.0), epsilon)); } // degree 1 * degree 2 { auto result = p1_1 * p2_2; EXPECT_TRUE(result.isApprox(Polynomial<double, 3>(2.0, 7.0, 10.0, 8.0), epsilon)); } // degree 0^2 { auto result_p0_1 = square(p0_1); EXPECT_TRUE(result_p0_1.isApprox(Polynomial<double, 0>(1.0), epsilon)); auto result_p0_2 = square(p0_2); EXPECT_TRUE(result_p0_2.isApprox(Polynomial<double, 0>(4.0), epsilon)); } // degree 1^2 { auto result = square(p1_2); EXPECT_TRUE(result.isApprox(Polynomial<double, 2>(4.0, 12.0, 9.0), epsilon)); } // Output { // Output std::ostringstream intervalOutput; intervalOutput << p3_1; EXPECT_EQ("(4*x^3 + 3*x^2 + 2*x + 1)", intervalOutput.str()); } }; }; // namespace Math }; // namespace SurgSim
Fix Linux error "Explicit specialization in non-namespace scope"
Fix Linux error "Explicit specialization in non-namespace scope"
C++
apache-2.0
simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim
4cea709322c0306247ad9beab72e65580203bd18
examples/viennacl/solvers.cpp
examples/viennacl/solvers.cpp
#include <iostream> #include <vector> #include <vexcl/vexcl.hpp> #include <vexcl/external/viennacl.hpp> #include <viennacl/linalg/cg.hpp> #include <viennacl/linalg/bicgstab.hpp> typedef double real; template <class Tag> void do_solve(const vex::SpMat<real> &A, vex::vector<real> f, const Tag &tag) { vex::vector<real> x = viennacl::linalg::solve(A, f, tag); std::cout << " Iterations: " << tag.iters() << std::endl << " Error: " << tag.error() << std::endl; // Test for convergence. f -= A * x; static vex::Reductor<real, vex::MAX> max(vex::current_context().queue()); std::cout << " max(residual) = " << max(fabs(f)) << std::endl; } int main() { try { size_t n = 1024; real h2i = (n - 1) * (n - 1); std::vector<size_t> row; std::vector<size_t> col; std::vector<real> val; std::vector<real> rhs; // Prepare problem (1D Poisson equation). row.reserve(n + 1); col.reserve(2 + (n - 2) * 3); val.reserve(2 + (n - 2) * 3); rhs.reserve(n); row.push_back(0); for(size_t i = 0; i < n; i++) { if (i == 0 || i == n - 1) { col.push_back(i); val.push_back(1); rhs.push_back(0); row.push_back(row.back() + 1); } else { col.push_back(i-1); val.push_back(-h2i); col.push_back(i); val.push_back(2 * h2i); col.push_back(i+1); val.push_back(-h2i); rhs.push_back(2); row.push_back(row.back() + 3); } } // Move data to GPU(s). vex::Context ctx( vex::Filter::Type(CL_DEVICE_TYPE_GPU) && vex::Filter::DoublePrecision, CL_QUEUE_PROFILING_ENABLE ); std::cout << ctx << std::endl; vex::SpMat <real> A(ctx.queue(), n, n, row.data(), col.data(), val.data()); vex::vector<real> f(ctx.queue(), rhs); vex::profiler prof(ctx.queue()); // Solve problem with ViennaCL's solvers: std::cout << "CG" << std::endl; prof.tic_cl("CG"); do_solve(A, f, viennacl::linalg::cg_tag(1e-8, n)); prof.toc("CG"); std::cout << "BiCGStab" << std::endl; prof.tic_cl("BiCGStab"); do_solve(A, f, viennacl::linalg::bicgstab_tag(1e-8, n)); prof.toc("BiCGStab"); std::cout << prof << std::endl; } catch(const cl::Error &err) { std::cerr << "OpenCL Error: " << err << std::endl; } catch(const std::exception &err) { std::cerr << "Error: " << err.what() << std::endl; } } // vim: et
#include <iostream> #include <vector> #include <vexcl/vexcl.hpp> #include <vexcl/external/viennacl.hpp> #include <viennacl/linalg/cg.hpp> #include <viennacl/linalg/bicgstab.hpp> typedef double real; template <class Tag> void do_solve(const vex::SpMat<real> &A, vex::vector<real> f, const Tag &tag) { vex::vector<real> x = viennacl::linalg::solve(A, f, tag); std::cout << " Iterations: " << tag.iters() << std::endl << " Error: " << tag.error() << std::endl; // Test for convergence. f -= A * x; static vex::Reductor<real, vex::MAX> max(vex::current_context().queue()); std::cout << " max(residual) = " << max(fabs(f)) << std::endl; } int main() { try { size_t n = 1024; real h2i = (n - 1) * (n - 1); std::vector<size_t> row; std::vector<size_t> col; std::vector<real> val; std::vector<real> rhs; // Prepare problem (1D Poisson equation). row.reserve(n + 1); col.reserve(2 + (n - 2) * 3); val.reserve(2 + (n - 2) * 3); rhs.reserve(n); row.push_back(0); for(size_t i = 0; i < n; i++) { if (i == 0 || i == n - 1) { col.push_back(i); val.push_back(1); rhs.push_back(0); row.push_back(row.back() + 1); } else { col.push_back(i-1); val.push_back(-h2i); col.push_back(i); val.push_back(2 * h2i); col.push_back(i+1); val.push_back(-h2i); rhs.push_back(2); row.push_back(row.back() + 3); } } // Move data to GPU(s). vex::Context ctx( vex::Filter::Type(CL_DEVICE_TYPE_GPU) && vex::Filter::DoublePrecision, CL_QUEUE_PROFILING_ENABLE ); if (!ctx) throw std::runtime_error("No GPUs with double precision found"); std::cout << ctx << std::endl; vex::SpMat <real> A(ctx.queue(), n, n, row.data(), col.data(), val.data()); vex::vector<real> f(ctx.queue(), rhs); vex::profiler prof(ctx.queue()); // Solve problem with ViennaCL's solvers: std::cout << "CG" << std::endl; prof.tic_cl("CG"); do_solve(A, f, viennacl::linalg::cg_tag(1e-8, n)); prof.toc("CG"); std::cout << "BiCGStab" << std::endl; prof.tic_cl("BiCGStab"); do_solve(A, f, viennacl::linalg::bicgstab_tag(1e-8, n)); prof.toc("BiCGStab"); std::cout << prof << std::endl; } catch(const cl::Error &err) { std::cerr << "OpenCL Error: " << err << std::endl; } catch(const std::exception &err) { std::cerr << "Error: " << err.what() << std::endl; } } // vim: et
check for empty context in viennacl example
check for empty context in viennacl example
C++
mit
Poulpy21/vexcl,Poulpy21/vexcl,ddemidov/vexcl,kapadia/vexcl,Poulpy21/vexcl,kapadia/vexcl,ddemidov/vexcl
955a00a601ce40e1142c264f61f52cc757f19378
examples/viewer/viewerhud.cpp
examples/viewer/viewerhud.cpp
#include "viewerhud.h" #include "common/settings.h" #include <glm/gtc/matrix_transform.hpp> #include <sstream> #include <SDL.h> /// HL1 BSP Hl1BspHud::Hl1BspHud(Hl1BspInstance *instance, ViewerHud& mainHud) : _instance(instance), _mainHud(mainHud) { } void Hl1BspHud::Render(const glm::mat4 &proj, const glm::mat4 &view) { } /// HL1 MDL Hl1MdlHud::Hl1MdlHud(Hl1MdlInstance *instance, ViewerHud& mainHud) : _instance(instance), _mainHud(mainHud) { } void Hl1MdlHud::Render(const glm::mat4 &proj, const glm::mat4 &view) { if (Setting("Hud.ShowInfo").AsBool()) { std::stringstream ss; ss << "[ INFO ]" << std::endl << "Sequence count : " << this->_instance->Asset()->SequenceCount() << std::endl << "Bodypart count : " << this->_instance->Asset()->BodypartCount() << std::endl; this->_mainHud.Fonts.Info.DrawTextA(proj, view, this->_mainHud.Size().x - 300.0f, 20.0f, ss.str()); } } /// HL1 SPR Hl1SprHud::Hl1SprHud(Hl1SprInstance *instance, ViewerHud& mainHud) : _instance(instance), _mainHud(mainHud) { } void Hl1SprHud::Render(const glm::mat4 &proj, const glm::mat4 &view) { if (Setting("Hud.ShowInfo").AsBool()) { std::stringstream ss; ss << "[ INFO ]" << std::endl << " Frame count : " << this->_instance->Asset()->FrameCount(); this->_mainHud.Fonts.Info.DrawTextA(proj, view, this->_mainHud.Size().x - 300.0f, 20.0f, ss.str()); } } /// HL2 BSP Hl2BspHud::Hl2BspHud(Hl2BspInstance *instance, ViewerHud& mainHud) : _instance(instance), _mainHud(mainHud) { } void Hl2BspHud::Render(const glm::mat4 &proj, const glm::mat4 &view) { } ViewerHud::ViewerHud() : _hl1Bsp(nullptr), _hl1Mdl(nullptr), _hl1Spr(nullptr), _hl2Bsp(nullptr), _hud(nullptr) { Setting("Hud.ShowHelp").Register(true); Setting("Hud.ShowInfo").Register(false); } ViewerHud::~ViewerHud() { } void ViewerHud::Resize(int w, int h) { this->_size = glm::vec2(float(w), float(h)); this->_proj = glm::ortho(0.0f, this->_size.x, this->_size.y, 0.0f); } void ViewerHud::KeyAction(int key, int action) { if (key == SDLK_i && action) Setting("Hud.ShowInfo") = !Setting("Hud.ShowInfo").AsBool(); else if (key == SDLK_h && action) Setting("Hud.ShowHelp") = !Setting("Hud.ShowHelp").AsBool(); else if (this->_hud != nullptr) this->_hud->KeyAction(key, action); } void ViewerHud::InitHud(const std::string& filename, Hl1Instance* instance) { this->Fonts.Regular.InitializeFont("c:\\windows\\fonts\\verdana.ttf"); this->Fonts.Info.InitializeFont("c:\\windows\\fonts\\cour.ttf", 18.0f); this->_filename = filename; this->_hl1Bsp = dynamic_cast<Hl1BspInstance*>(instance); if (this->_hl1Bsp != nullptr) { this->_hud = new Hl1BspHud(this->_hl1Bsp, *this); return; } this->_hl1Mdl = dynamic_cast<Hl1MdlInstance*>(instance); if (this->_hl1Mdl != nullptr) { this->_hud = new Hl1MdlHud(this->_hl1Mdl, *this); return; } this->_hl1Spr = dynamic_cast<Hl1SprInstance*>(instance); if (this->_hl1Spr != nullptr) { this->_hud = new Hl1SprHud(this->_hl1Spr, *this); return; } this->_hl2Bsp = dynamic_cast<Hl2BspInstance*>(instance); if (this->_hl2Bsp != nullptr) { this->_hud = new Hl2BspHud(this->_hl2Bsp, *this); return; } } void ViewerHud::Render() { if (this->_hud != nullptr) { this->Fonts.Regular.DrawTextA(this->_proj, glm::mat4(1.0f), 5.0f, this->_size.y - 5.0f, (std::string("Loaded file : ") + this->_filename)); std::stringstream speed; speed << "Camera speed : " << Setting("Viewer.Camera.Speed").AsFloat(); this->Fonts.Regular.DrawTextA(this->_proj, glm::mat4(1.0f), this->_size.x - 130.0f, this->_size.y - 5.0f, speed.str()); if (Setting("Hud.ShowHelp").AsBool()) { std::stringstream ss; ss << "[ HELP ]" << std::endl << " <SPACE> - Pause/unpause animation" << std::endl << " h - Toggle this help on/off" << std::endl << " i - Toggle asset info on/off" << std::endl << " <KP_PLUS> - Increase camera speed" << std::endl << " <KP_MINUS> - Decrease camera speed" << std::endl << this->_hud->AdditionalHelp(); this->Fonts.Info.DrawTextA(this->_proj, glm::mat4(1.0f), 10.0f, 20.0f, ss.str()); } this->_hud->Render(this->_proj, glm::mat4(1.0f)); } else { this->Fonts.Regular.DrawTextA(this->_proj, glm::mat4(1.0f), 5.0f, this->_size.y - 5.0f, (std::string("Nothing loaded"))); } }
#include "viewerhud.h" #include "common/settings.h" #include <glm/gtc/matrix_transform.hpp> #include <sstream> #include <SDL.h> /// HL1 BSP Hl1BspHud::Hl1BspHud(Hl1BspInstance *instance, ViewerHud& mainHud) : _instance(instance), _mainHud(mainHud) { } void Hl1BspHud::Render(const glm::mat4 &proj, const glm::mat4 &view) { } /// HL1 MDL Hl1MdlHud::Hl1MdlHud(Hl1MdlInstance *instance, ViewerHud& mainHud) : _instance(instance), _mainHud(mainHud) { } void Hl1MdlHud::Render(const glm::mat4 &proj, const glm::mat4 &view) { if (Setting("Hud.ShowInfo").AsBool()) { std::stringstream ss; ss << "[ INFO ]" << std::endl << "Sequence count : " << this->_instance->Asset()->SequenceCount() << std::endl << "Bodypart count : " << this->_instance->Asset()->BodypartCount() << std::endl; this->_mainHud.Fonts.Info.DrawTextA(proj, view, this->_mainHud.Size().x - 300.0f, 20.0f, ss.str()); } } /// HL1 SPR Hl1SprHud::Hl1SprHud(Hl1SprInstance *instance, ViewerHud& mainHud) : _instance(instance), _mainHud(mainHud) { } void Hl1SprHud::Render(const glm::mat4 &proj, const glm::mat4 &view) { if (Setting("Hud.ShowInfo").AsBool()) { std::stringstream ss; ss << "[ INFO ]" << std::endl << " Frame count : " << this->_instance->Asset()->FrameCount(); this->_mainHud.Fonts.Info.DrawTextA(proj, view, this->_mainHud.Size().x - 300.0f, 20.0f, ss.str()); } } /// HL2 BSP Hl2BspHud::Hl2BspHud(Hl2BspInstance *instance, ViewerHud& mainHud) : _instance(instance), _mainHud(mainHud) { } void Hl2BspHud::Render(const glm::mat4 &proj, const glm::mat4 &view) { } ViewerHud::ViewerHud() : _hl1Bsp(nullptr), _hl1Mdl(nullptr), _hl1Spr(nullptr), _hl2Bsp(nullptr), _hud(nullptr) { Setting("Hud.ShowHelp").Register(true); Setting("Hud.ShowInfo").Register(false); } ViewerHud::~ViewerHud() { } void ViewerHud::Resize(int w, int h) { this->_size = glm::vec2(float(w), float(h)); this->_proj = glm::ortho(0.0f, this->_size.x, this->_size.y, 0.0f); } void ViewerHud::KeyAction(int key, int action) { if (key == SDLK_i && action) Setting("Hud.ShowInfo") = !Setting("Hud.ShowInfo").AsBool(); else if (key == SDLK_h && action) Setting("Hud.ShowHelp") = !Setting("Hud.ShowHelp").AsBool(); else if (this->_hud != nullptr) this->_hud->KeyAction(key, action); } void ViewerHud::InitHud(const std::string& filename, Hl1Instance* instance) { this->Fonts.Regular.InitializeFont("c:\\windows\\fonts\\verdana.ttf"); this->Fonts.Info.InitializeFont("c:\\windows\\fonts\\cour.ttf", 18.0f); this->_filename = filename; this->_hl1Bsp = dynamic_cast<Hl1BspInstance*>(instance); if (this->_hl1Bsp != nullptr) { this->_hud = new Hl1BspHud(this->_hl1Bsp, *this); return; } this->_hl1Mdl = dynamic_cast<Hl1MdlInstance*>(instance); if (this->_hl1Mdl != nullptr) { this->_hud = new Hl1MdlHud(this->_hl1Mdl, *this); return; } this->_hl1Spr = dynamic_cast<Hl1SprInstance*>(instance); if (this->_hl1Spr != nullptr) { this->_hud = new Hl1SprHud(this->_hl1Spr, *this); return; } this->_hl2Bsp = dynamic_cast<Hl2BspInstance*>(instance); if (this->_hl2Bsp != nullptr) { this->_hud = new Hl2BspHud(this->_hl2Bsp, *this); return; } } void ViewerHud::Render() { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glActiveTexture(GL_TEXTURE0); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_ALPHA_TEST); if (this->_hud != nullptr) { this->Fonts.Regular.DrawTextA(this->_proj, glm::mat4(1.0f), 5.0f, this->_size.y - 5.0f, (std::string("Loaded file : ") + this->_filename)); std::stringstream speed; speed << "Camera speed : " << Setting("Viewer.Camera.Speed").AsFloat(); this->Fonts.Regular.DrawTextA(this->_proj, glm::mat4(1.0f), this->_size.x - 130.0f, this->_size.y - 5.0f, speed.str()); if (Setting("Hud.ShowHelp").AsBool()) { std::stringstream ss; ss << "[ HELP ]" << std::endl << " <SPACE> - Pause/unpause animation" << std::endl << " h - Toggle this help on/off" << std::endl << " i - Toggle asset info on/off" << std::endl << " <KP_PLUS> - Increase camera speed" << std::endl << " <KP_MINUS> - Decrease camera speed" << std::endl << this->_hud->AdditionalHelp(); this->Fonts.Info.DrawTextA(this->_proj, glm::mat4(1.0f), 10.0f, 20.0f, ss.str()); } this->_hud->Render(this->_proj, glm::mat4(1.0f)); } else { this->Fonts.Regular.DrawTextA(this->_proj, glm::mat4(1.0f), 5.0f, this->_size.y - 5.0f, (std::string("Nothing loaded"))); } }
Fix font rendering aftfer alpha test added
Fix font rendering aftfer alpha test added
C++
mit
wtrsltnk/game-assets,wtrsltnk/game-assets
700b993b79959fcccac260eed77bf9b205747e92
include/abaclade/collections/detail/xor_list.hxx
include/abaclade/collections/detail/xor_list.hxx
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2015 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_HXX_INTERNAL #error "Please #include <abaclade.hxx> instead of this file" #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::collections::detail::xor_list namespace abc { namespace collections { namespace detail { //! Defines classes useful to implement XOR-linked list classes. class xor_list { public: //! Node for XOR doubly-linked list classes. class node { public: //! Constructor. node() { } node(node const &) { // Skip copying the source’s links. } /*! Assignment operator. @return *this. */ node & operator=(node const &) { // Skip copying the source’s links. return *this; } /*! Returns a pointer to the next node. @param pnPrev Pointer to the previous node. */ node * get_next(node * pnPrev) { return reinterpret_cast<node *>(m_iPrevXorNext ^ reinterpret_cast<std::uintptr_t>(pnPrev)); } /*! Returns a pointer to the previous node. @param pnNext Pointer to the next node. */ node * get_prev(node * pnNext) { return reinterpret_cast<node *>(m_iPrevXorNext ^ reinterpret_cast<std::uintptr_t>(pnNext)); } /*! Updates the previous/next pointer. @param pnPrev Pointer to the previous node. @param pnNext Pointer to the next node. */ void set_prev_next(node * pnPrev, node * pnNext) { m_iPrevXorNext = reinterpret_cast<std::uintptr_t>(pnPrev) ^ reinterpret_cast<std::uintptr_t>(pnNext); } private: //! Pointer to the previous node XOR pointer to the next node. std::uintptr_t m_iPrevXorNext; }; protected: //! Non-template base for iterator. class ABACLADE_SYM iterator_base { public: /*! Equality relational operator. @param it Object to compare to *this. @return true if *this refers to the same element as it, or false otherwise. */ bool operator==(iterator_base const & it) const { return m_pnCurr == it.m_pnCurr; } /*! Inequality relational operator. @param it Object to compare to *this. @return true if *this refers to a different element than it, or false otherwise. */ bool operator!=(iterator_base const & it) const { return !operator==(it); } protected: /*! Constructor. @param pnPrev Pointer to the node preceding *pnCurr. @param pnCurr Pointer to the current node. @param pnNext Pointer to the node following *pnCurr. */ iterator_base(node * pnPrev, node * pnCurr, node * pnNext) : m_pnPrev(pnPrev), m_pnCurr(pnCurr), m_pnNext(pnNext) { } /*! Moves the iterator by the specified signed amount. @param i Count of positions by which to advance the iterator. */ void advance(std::ptrdiff_t i); //! Throws an iterator_error if the iterator is at the end of the container. void throw_if_end() const; protected: //! Pointer to the previous node. node * m_pnPrev; //! Pointer to the current node. node * m_pnCurr; //! Pointer to the next node. node * m_pnNext; }; public: //! Iterator for XOR doubly-linked list node classes. template <typename TNode, typename TValue, bool t_bConst = std::is_const<TValue>::value> class iterator; // Partial specialization for const TValue. template <typename TNode, typename TValue> class iterator<TNode, TValue, true> : public iterator_base, public std::iterator<std::bidirectional_iterator_tag, TValue> { public: //! See iterator_base::iterator_base(). iterator(node * pnPrev, node * pnCurr, node * pnNext) : iterator_base(pnPrev, pnCurr, pnNext) { } /*! Dereferencing operator. @return Reference to the current node. */ TValue & operator*() const { throw_if_end(); return *static_cast<TNode *>(m_pnCurr)->value_ptr(); } /*! Dereferencing member access operator. @return Pointer to the current node. */ TValue * operator->() const { throw_if_end(); return static_cast<TNode *>(m_pnCurr)->value_ptr(); } /*! Addition-assignment operator. @param i Count of positions by which to advance the iterator. @return *this. */ iterator & operator+=(std::ptrdiff_t i) { advance(i); return *this; } /*! Subtraction-assignment operator. @param i Count of positions by which to rewind the iterator. @return *this. */ iterator & operator-=(std::ptrdiff_t i) { advance(-i); return *this; } /*! Addition operator. @param i Count of positions by which to advance the iterator. @return Resulting iterator. */ iterator operator+(std::ptrdiff_t i) const { iterator it(*this); it.advance(i); return std::move(it); } /*! Subtraction operator. @param i Count of positions by which to rewind the iterator. @return Resulting iterator. */ iterator operator-(std::ptrdiff_t i) const { iterator it(*this); it.advance(-i); return std::move(it); } /*! Preincrement operator. @return *this. */ iterator & operator++() { advance(1); return *this; } /*! Postincrement operator. @return Iterator pointing to the node following the one referenced by this iterator. */ iterator operator++(int) { node * pnPrevPrev = m_pnPrev; advance(1); return iterator(pnPrevPrev, m_pnPrev, m_pnCurr); } /*! Predecrement operator. @return *this. */ iterator & operator--() { advance(-1); return *this; } /*! Postdecrement operator. @return Iterator pointing to the node preceding the one referenced by this iterator. */ iterator operator--(int) { node * pnNextNext = m_pnNext; advance(-1); return iterator(m_pnCurr, m_pnNext, pnNextNext); } /*! Returns the underlying pointer to the node. @return Pointer to the current node. */ TNode const * base() const { return static_cast<TNode *>(m_pnCurr); } /*! Returns a pointer to the next node. @return Pointer to the next node. */ TNode const * next_base() const { return static_cast<TNode *>(m_pnNext); } /*! Returns a pointer to the previous node. @return Pointer to the previous node. */ TNode const * prev_base() const { return static_cast<TNode *>(m_pnPrev); } }; // Partial specialization for non-const TValue. template <typename TNode, typename TValue> class iterator<TNode, TValue, false> : public iterator<TNode, typename std::add_const<TValue>::type, true>, public std::iterator<std::bidirectional_iterator_tag, TValue> { private: // Shortcuts. typedef iterator<TNode, typename std::add_const<TValue>::type, true> const_iterator; typedef std::iterator<std::bidirectional_iterator_tag, TValue> std_iterator; public: // These are inherited from both base classes, so resolve the ambiguity. using typename std_iterator::difference_type; using typename std_iterator::iterator_category; using typename std_iterator::pointer; using typename std_iterator::reference; using typename std_iterator::value_type; public: //! See const_iterator::const_iterator(). iterator(node * pnPrev, node * pnCurr, node * pnNext) : const_iterator(pnPrev, pnCurr, pnNext) { } //! See const_iterator::operator*(). TValue & operator*() const { return const_cast<TValue &>(const_iterator::operator*()); } //! See const_iterator::operator->(). TValue * operator->() const { return const_cast<TValue *>(const_iterator::operator->()); } //! See const_iterator::operator+=(). iterator & operator+=(std::ptrdiff_t i) { return static_cast<iterator &>(const_iterator::operator+=(i)); } //! See const_iterator::operator-=(). iterator & operator-=(std::ptrdiff_t i) { return static_cast<iterator &>(const_iterator::operator-=(i)); } //! See const_iterator::operator+(). iterator operator+(std::ptrdiff_t i) const { return iterator(const_iterator::operator+(i)); } //! See const_iterator::operator-(). iterator operator-(std::ptrdiff_t i) const { return iterator(const_iterator::operator-(i)); } //! See const_iterator.operator++(). iterator & operator++() { return static_cast<iterator &>(const_iterator::operator++()); } //! See const_iterator::operator++(int). iterator operator++(int) { return iterator(const_iterator::operator++()); } //! See const_iterator::operator--(). iterator & operator--() { return static_cast<iterator &>(const_iterator::operator--()); } //! See const_iterator::operator--(). iterator operator--(int) { return iterator(const_iterator::operator--()); } private: /*! Constructor used for cv-removing promotions from const_iterator to iterator. @param it Source object. */ iterator(const_iterator const & it) : const_iterator(it) { } }; public: /*! Inserts a node to the end of the list. @param pn Pointer to the node to become the last in the list. @param ppnFirst Address of the pointer to the first node. @param ppnLast Address of the pointer to the last node. */ static void link_back(node * pn, node ** ppnFirst, node ** ppnLast); /*! Inserts a node to the start of the list. @param pn Pointer to the node to become the first in the list. @param ppnFirst Address of the pointer to the first node. @param ppnLast Address of the pointer to the last node. */ static void link_front(node * pn, node ** ppnFirst, node ** ppnLast); /*! Unlinks a node from the list. @param pn Pointer to the node to unlink. @param pnPrev Pointer to the node preceding *pn. @param pnNext Pointer to the node following *pn. @param ppnFirst Address of the pointer to the first node. @param ppnLast Address of the pointer to the last node. */ static void unlink(node * pn, node * pnPrev, node * pnNext, node ** ppnFirst, node ** ppnLast); }; } //namespace detail } //namespace collections } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2015 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_HXX_INTERNAL #error "Please #include <abaclade.hxx> instead of this file" #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::collections::detail::xor_list namespace abc { namespace collections { namespace detail { //! Defines classes useful to implement XOR-linked list classes. class ABACLADE_SYM xor_list { public: //! Node for XOR doubly-linked list classes. class node { public: //! Constructor. node() { } node(node const &) { // Skip copying the source’s links. } /*! Assignment operator. @return *this. */ node & operator=(node const &) { // Skip copying the source’s links. return *this; } /*! Returns a pointer to the next node. @param pnPrev Pointer to the previous node. */ node * get_next(node * pnPrev) { return reinterpret_cast<node *>(m_iPrevXorNext ^ reinterpret_cast<std::uintptr_t>(pnPrev)); } /*! Returns a pointer to the previous node. @param pnNext Pointer to the next node. */ node * get_prev(node * pnNext) { return reinterpret_cast<node *>(m_iPrevXorNext ^ reinterpret_cast<std::uintptr_t>(pnNext)); } /*! Updates the previous/next pointer. @param pnPrev Pointer to the previous node. @param pnNext Pointer to the next node. */ void set_prev_next(node * pnPrev, node * pnNext) { m_iPrevXorNext = reinterpret_cast<std::uintptr_t>(pnPrev) ^ reinterpret_cast<std::uintptr_t>(pnNext); } private: //! Pointer to the previous node XOR pointer to the next node. std::uintptr_t m_iPrevXorNext; }; protected: //! Non-template base for iterator. class ABACLADE_SYM iterator_base { public: /*! Equality relational operator. @param it Object to compare to *this. @return true if *this refers to the same element as it, or false otherwise. */ bool operator==(iterator_base const & it) const { return m_pnCurr == it.m_pnCurr; } /*! Inequality relational operator. @param it Object to compare to *this. @return true if *this refers to a different element than it, or false otherwise. */ bool operator!=(iterator_base const & it) const { return !operator==(it); } protected: /*! Constructor. @param pnPrev Pointer to the node preceding *pnCurr. @param pnCurr Pointer to the current node. @param pnNext Pointer to the node following *pnCurr. */ iterator_base(node * pnPrev, node * pnCurr, node * pnNext) : m_pnPrev(pnPrev), m_pnCurr(pnCurr), m_pnNext(pnNext) { } /*! Moves the iterator by the specified signed amount. @param i Count of positions by which to advance the iterator. */ void advance(std::ptrdiff_t i); //! Throws an iterator_error if the iterator is at the end of the container. void throw_if_end() const; protected: //! Pointer to the previous node. node * m_pnPrev; //! Pointer to the current node. node * m_pnCurr; //! Pointer to the next node. node * m_pnNext; }; public: //! Iterator for XOR doubly-linked list node classes. template <typename TNode, typename TValue, bool t_bConst = std::is_const<TValue>::value> class iterator; // Partial specialization for const TValue. template <typename TNode, typename TValue> class iterator<TNode, TValue, true> : public iterator_base, public std::iterator<std::bidirectional_iterator_tag, TValue> { public: //! See iterator_base::iterator_base(). iterator(node * pnPrev, node * pnCurr, node * pnNext) : iterator_base(pnPrev, pnCurr, pnNext) { } /*! Dereferencing operator. @return Reference to the current node. */ TValue & operator*() const { throw_if_end(); return *static_cast<TNode *>(m_pnCurr)->value_ptr(); } /*! Dereferencing member access operator. @return Pointer to the current node. */ TValue * operator->() const { throw_if_end(); return static_cast<TNode *>(m_pnCurr)->value_ptr(); } /*! Addition-assignment operator. @param i Count of positions by which to advance the iterator. @return *this. */ iterator & operator+=(std::ptrdiff_t i) { advance(i); return *this; } /*! Subtraction-assignment operator. @param i Count of positions by which to rewind the iterator. @return *this. */ iterator & operator-=(std::ptrdiff_t i) { advance(-i); return *this; } /*! Addition operator. @param i Count of positions by which to advance the iterator. @return Resulting iterator. */ iterator operator+(std::ptrdiff_t i) const { iterator it(*this); it.advance(i); return std::move(it); } /*! Subtraction operator. @param i Count of positions by which to rewind the iterator. @return Resulting iterator. */ iterator operator-(std::ptrdiff_t i) const { iterator it(*this); it.advance(-i); return std::move(it); } /*! Preincrement operator. @return *this. */ iterator & operator++() { advance(1); return *this; } /*! Postincrement operator. @return Iterator pointing to the node following the one referenced by this iterator. */ iterator operator++(int) { node * pnPrevPrev = m_pnPrev; advance(1); return iterator(pnPrevPrev, m_pnPrev, m_pnCurr); } /*! Predecrement operator. @return *this. */ iterator & operator--() { advance(-1); return *this; } /*! Postdecrement operator. @return Iterator pointing to the node preceding the one referenced by this iterator. */ iterator operator--(int) { node * pnNextNext = m_pnNext; advance(-1); return iterator(m_pnCurr, m_pnNext, pnNextNext); } /*! Returns the underlying pointer to the node. @return Pointer to the current node. */ TNode const * base() const { return static_cast<TNode *>(m_pnCurr); } /*! Returns a pointer to the next node. @return Pointer to the next node. */ TNode const * next_base() const { return static_cast<TNode *>(m_pnNext); } /*! Returns a pointer to the previous node. @return Pointer to the previous node. */ TNode const * prev_base() const { return static_cast<TNode *>(m_pnPrev); } }; // Partial specialization for non-const TValue. template <typename TNode, typename TValue> class iterator<TNode, TValue, false> : public iterator<TNode, typename std::add_const<TValue>::type, true>, public std::iterator<std::bidirectional_iterator_tag, TValue> { private: // Shortcuts. typedef iterator<TNode, typename std::add_const<TValue>::type, true> const_iterator; typedef std::iterator<std::bidirectional_iterator_tag, TValue> std_iterator; public: // These are inherited from both base classes, so resolve the ambiguity. using typename std_iterator::difference_type; using typename std_iterator::iterator_category; using typename std_iterator::pointer; using typename std_iterator::reference; using typename std_iterator::value_type; public: //! See const_iterator::const_iterator(). iterator(node * pnPrev, node * pnCurr, node * pnNext) : const_iterator(pnPrev, pnCurr, pnNext) { } //! See const_iterator::operator*(). TValue & operator*() const { return const_cast<TValue &>(const_iterator::operator*()); } //! See const_iterator::operator->(). TValue * operator->() const { return const_cast<TValue *>(const_iterator::operator->()); } //! See const_iterator::operator+=(). iterator & operator+=(std::ptrdiff_t i) { return static_cast<iterator &>(const_iterator::operator+=(i)); } //! See const_iterator::operator-=(). iterator & operator-=(std::ptrdiff_t i) { return static_cast<iterator &>(const_iterator::operator-=(i)); } //! See const_iterator::operator+(). iterator operator+(std::ptrdiff_t i) const { return iterator(const_iterator::operator+(i)); } //! See const_iterator::operator-(). iterator operator-(std::ptrdiff_t i) const { return iterator(const_iterator::operator-(i)); } //! See const_iterator.operator++(). iterator & operator++() { return static_cast<iterator &>(const_iterator::operator++()); } //! See const_iterator::operator++(int). iterator operator++(int) { return iterator(const_iterator::operator++()); } //! See const_iterator::operator--(). iterator & operator--() { return static_cast<iterator &>(const_iterator::operator--()); } //! See const_iterator::operator--(). iterator operator--(int) { return iterator(const_iterator::operator--()); } private: /*! Constructor used for cv-removing promotions from const_iterator to iterator. @param it Source object. */ iterator(const_iterator const & it) : const_iterator(it) { } }; public: /*! Inserts a node to the end of the list. @param pn Pointer to the node to become the last in the list. @param ppnFirst Address of the pointer to the first node. @param ppnLast Address of the pointer to the last node. */ static void link_back(node * pn, node ** ppnFirst, node ** ppnLast); /*! Inserts a node to the start of the list. @param pn Pointer to the node to become the first in the list. @param ppnFirst Address of the pointer to the first node. @param ppnLast Address of the pointer to the last node. */ static void link_front(node * pn, node ** ppnFirst, node ** ppnLast); /*! Unlinks a node from the list. @param pn Pointer to the node to unlink. @param pnPrev Pointer to the node preceding *pn. @param pnNext Pointer to the node following *pn. @param ppnFirst Address of the pointer to the first node. @param ppnLast Address of the pointer to the last node. */ static void unlink(node * pn, node * pnPrev, node * pnNext, node ** ppnFirst, node ** ppnLast); }; } //namespace detail } //namespace collections } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
Add missing ABACLADE_SYM qualifier to xor_list
Add missing ABACLADE_SYM qualifier to xor_list
C++
lgpl-2.1
raffaellod/lofty,raffaellod/lofty
59eb1e8eeb5cac3f6fa7ee127cdeb81e7e9125b5
cuttlefish/src/input.cpp
cuttlefish/src/input.cpp
// Copyright 2008 Paul Hodge #include "SDL.h" #include "circa.h" #include "input.h" #include "main.h" using namespace circa; namespace input { bool KEY_DOWN[SDLK_LAST]; std::set<int> KEY_JUST_PRESSED; int MOUSE_X = 0; int MOUSE_Y = 0; bool MOUSE_JUST_CLICKED = false; void key_down(circa::Term* caller) { int i = caller->input(0)->asInt(); caller->asBool() = KEY_DOWN[i]; } void key_pressed(circa::Term* caller) { int i = caller->input(0)->asInt(); caller->asBool() = KEY_JUST_PRESSED.find(i) != KEY_JUST_PRESSED.end(); } void mouse_pressed(circa::Term* caller) { as_bool(caller) = MOUSE_JUST_CLICKED; } void capture_events() { KEY_JUST_PRESSED.clear(); MOUSE_JUST_CLICKED = false; // Consume all events SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { CONTINUE_MAIN_LOOP = false; } else if (event.type == SDL_KEYDOWN) { if (!KEY_DOWN[event.key.keysym.sym]) { KEY_JUST_PRESSED.insert(event.key.keysym.sym); handle_key_press(event, event.key.keysym.sym); } KEY_DOWN[event.key.keysym.sym] = true; } else if (event.type == SDL_KEYUP) { KEY_DOWN[event.key.keysym.sym] = false; } else if (event.type == SDL_MOUSEBUTTONDOWN) { MOUSE_JUST_CLICKED = true; } else if (event.type == SDL_MOUSEBUTTONUP) { } else if (event.type == SDL_MOUSEMOTION) { MOUSE_X = event.motion.x; MOUSE_Y = event.motion.y; } } // finish event loop } void handle_key_press(SDL_Event &event, int key) { // Unmodified keys switch (key) { case SDLK_ESCAPE: CONTINUE_MAIN_LOOP = false; } // Control keys if (event.key.keysym.mod & KMOD_CTRL) { switch (event.key.keysym.sym) { case SDLK_s: circa::persist_branch_to_file(*USERS_BRANCH); std::cout << "Saved" << std::endl; break; case SDLK_e: circa::reset_state(*USERS_BRANCH); std::cout << "State has been reset" << std::endl; break; case SDLK_p: std::cout << branch_to_string_raw(*USERS_BRANCH); break; case SDLK_r: circa::reload_branch_from_file(*USERS_BRANCH); break; default: break; } } } void region_clicked(Term* caller) { //int& id = caller->input(0)->asInt(); Branch& region = caller->input(0)->asBranch(); float x1 = region[0]->toFloat(); float y1 = region[1]->toFloat(); float x2 = region[2]->toFloat(); float y2 = region[3]->toFloat(); #if 0 if (id == 0) { static next_id = 1; id = next_id++; } #endif as_bool(caller) = (MOUSE_JUST_CLICKED && x1 <= MOUSE_X && y1 <= MOUSE_Y && x2 >= MOUSE_X && y2 >= MOUSE_Y); } void initialize(Branch& branch) { for (int i=0; i < SDLK_LAST; i++) { KEY_DOWN[i] = false; } expose_value(&branch, &MOUSE_X, "mouse_x"); expose_value(&branch, &MOUSE_Y, "mouse_y"); import_function(branch, key_down, "key_down(int) : bool"); import_function(branch, key_pressed, "key_pressed(int) : bool"); import_function(branch, mouse_pressed, "mouse_pressed() : bool"); int_value(&branch, SDLK_UP, "KEY_UP"); int_value(&branch, SDLK_DOWN, "KEY_DOWN"); int_value(&branch, SDLK_LEFT, "KEY_LEFT"); int_value(&branch, SDLK_RIGHT, "KEY_RIGHT"); int_value(&branch, SDLK_SPACE, "KEY_SPACE"); import_function(branch, region_clicked, "region_clicked(List region) : bool"); } } // namespace input
// Copyright 2008 Paul Hodge #include "SDL.h" #include "circa.h" #include "input.h" #include "main.h" using namespace circa; namespace input { bool KEY_DOWN[SDLK_LAST]; std::set<int> KEY_JUST_PRESSED; int MOUSE_X = 0; int MOUSE_Y = 0; bool MOUSE_JUST_CLICKED = false; void key_down(circa::Term* caller) { int i = caller->input(0)->asInt(); caller->asBool() = KEY_DOWN[i]; } void key_pressed(circa::Term* caller) { int i = caller->input(0)->asInt(); caller->asBool() = KEY_JUST_PRESSED.find(i) != KEY_JUST_PRESSED.end(); } void mouse_pressed(circa::Term* caller) { as_bool(caller) = MOUSE_JUST_CLICKED; } void capture_events() { KEY_JUST_PRESSED.clear(); MOUSE_JUST_CLICKED = false; // Consume all events SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { CONTINUE_MAIN_LOOP = false; } else if (event.type == SDL_KEYDOWN) { if (!KEY_DOWN[event.key.keysym.sym]) { KEY_JUST_PRESSED.insert(event.key.keysym.sym); handle_key_press(event, event.key.keysym.sym); } KEY_DOWN[event.key.keysym.sym] = true; } else if (event.type == SDL_KEYUP) { KEY_DOWN[event.key.keysym.sym] = false; } else if (event.type == SDL_MOUSEBUTTONDOWN) { MOUSE_JUST_CLICKED = true; } else if (event.type == SDL_MOUSEBUTTONUP) { } else if (event.type == SDL_MOUSEMOTION) { MOUSE_X = event.motion.x; MOUSE_Y = event.motion.y; } } // finish event loop } void handle_key_press(SDL_Event &event, int key) { // Unmodified keys switch (key) { case SDLK_ESCAPE: CONTINUE_MAIN_LOOP = false; case SDLK_e: circa::reset_state(*USERS_BRANCH); break; case SDLK_r: circa::reload_branch_from_file(*USERS_BRANCH); break; } // Control keys if (event.key.keysym.mod & KMOD_CTRL) { switch (event.key.keysym.sym) { case SDLK_s: circa::persist_branch_to_file(*USERS_BRANCH); std::cout << "Saved" << std::endl; break; case SDLK_p: std::cout << branch_to_string_raw(*USERS_BRANCH); break; default: break; } } } void region_clicked(Term* caller) { //int& id = caller->input(0)->asInt(); Branch& region = caller->input(0)->asBranch(); float x1 = region[0]->toFloat(); float y1 = region[1]->toFloat(); float x2 = region[2]->toFloat(); float y2 = region[3]->toFloat(); #if 0 if (id == 0) { static next_id = 1; id = next_id++; } #endif as_bool(caller) = (MOUSE_JUST_CLICKED && x1 <= MOUSE_X && y1 <= MOUSE_Y && x2 >= MOUSE_X && y2 >= MOUSE_Y); } void initialize(Branch& branch) { for (int i=0; i < SDLK_LAST; i++) { KEY_DOWN[i] = false; } expose_value(&branch, &MOUSE_X, "mouse_x"); expose_value(&branch, &MOUSE_Y, "mouse_y"); import_function(branch, key_down, "key_down(int) : bool"); import_function(branch, key_pressed, "key_pressed(int) : bool"); import_function(branch, mouse_pressed, "mouse_pressed() : bool"); int_value(&branch, SDLK_UP, "KEY_UP"); int_value(&branch, SDLK_DOWN, "KEY_DOWN"); int_value(&branch, SDLK_LEFT, "KEY_LEFT"); int_value(&branch, SDLK_RIGHT, "KEY_RIGHT"); int_value(&branch, SDLK_SPACE, "KEY_SPACE"); import_function(branch, region_clicked, "region_clicked(List region) : bool"); } } // namespace input
change reload key to just R instead of ctrl-r
Cuttlefish: change reload key to just R instead of ctrl-r
C++
mit
andyfischer/circa,andyfischer/circa,andyfischer/circa,andyfischer/circa
5207690064125b155c39f1be67d3899f7f0fc7de
cvmfs/receiver/params.cc
cvmfs/receiver/params.cc
/** * This file is part of the CernVM File System. */ #include "params.h" #include <vector> #include "options.h" #include "util/string.h" namespace receiver { bool GetParamsFromFile(const std::string& repo_name, Params* params) { const std::string repo_config_file = "/etc/cvmfs/repositories.d/" + repo_name + "/server.conf"; SimpleOptionsParser parser; if (!parser.TryParsePath(repo_config_file)) { return false; } bool ret = true; ret &= parser.GetValue("CVMFS_UPSTREAM_STORAGE", &params->spooler_configuration); // Note: if upstream is gateway, we change it to local. This should be made to // abort, but it's useful for testing on a single machine if (HasPrefix(params->spooler_configuration, "gw", false)) { std::vector<std::string> tokens = SplitString(repo_name, '/'); const std::string rname = tokens.back(); params->spooler_configuration = "local,/srv/cvmfs/" + rname + "/data/txn,/srv/cvmfs/" + rname; } std::string hash_algorithm_str; ret &= parser.GetValue("CVMFS_HASH_ALGORITHM", &hash_algorithm_str); params->hash_alg = shash::ParseHashAlgorithm(hash_algorithm_str); std::string compression_algorithm_str; ret &= parser.GetValue("CVMFS_COMPRESSION_ALGORITHM", &compression_algorithm_str); params->compression_alg = zlib::ParseCompressionAlgorithm(compression_algorithm_str); /** * The receiver does not store files, only catalogs. We can safely disable * this option. */ params->generate_legacy_bulk_chunks = false; std::string use_chunking_str; ret &= parser.GetValue("CVMFS_USE_FILE_CHUNKING", &use_chunking_str); if (use_chunking_str == "true") { params->use_file_chunking = true; } else if (use_chunking_str == "false") { params->use_file_chunking = false; } else { return false; } std::string min_chunk_size_str; ret &= parser.GetValue("CVMFS_MIN_CHUNK_SIZE", &min_chunk_size_str); params->min_chunk_size = String2Uint64(min_chunk_size_str); std::string avg_chunk_size_str; ret &= parser.GetValue("CVMFS_AVG_CHUNK_SIZE", &avg_chunk_size_str); params->avg_chunk_size = String2Uint64(avg_chunk_size_str); std::string max_chunk_size_str; ret &= parser.GetValue("CVMFS_MAX_CHUNK_SIZE", &max_chunk_size_str); params->max_chunk_size = String2Uint64(max_chunk_size_str); std::string use_autocatalogs_str; ret &= parser.GetValue("CVMFS_AUTOCATALOGS", &use_autocatalogs_str); if (use_autocatalogs_str == "true") { params->use_autocatalogs = true; } else if (use_autocatalogs_str == "false") { params->use_autocatalogs = false; } else { return false; } std::string max_weight_str; if (parser.GetValue("CVMFS_AUTOCATALOGS_MAX_WEIGHT", &max_weight_str)) { params->max_weight = String2Uint64(max_weight_str); } std::string min_weight_str; if (parser.GetValue("CVMFS_AUTOCATALOGS_MIN_WEIGHT", &min_weight_str)) { params->min_weight = String2Uint64(min_weight_str); } std::string enforce_limits_str; ret &= parser.GetValue("CVMFS_ENFORCE_LIMITS", &enforce_limits_str); if (enforce_limits_str == "true") { params->enforce_limits = true; } else if (enforce_limits_str == "false") { params->enforce_limits = false; } else { return false; } // TODO(dwd): the next 3 limit variables should take defaults from // SyncParameters std::string nested_kcatalog_limit_str; if (parser.GetValue("CVMFS_NESTED_KCATALOG_LIMIT", &nested_kcatalog_limit_str)) { params->nested_kcatalog_limit = String2Uint64(nested_kcatalog_limit_str); } std::string root_kcatalog_limit_str; if (parser.GetValue("CVMFS_ROOT_KCATALOG_LIMIT", &root_kcatalog_limit_str)) { params->root_kcatalog_limit = String2Uint64(root_kcatalog_limit_str); } std::string file_mbyte_limit_str; if (parser.GetValue("CVMFS_FILE_MBYTE_LIMIT", &file_mbyte_limit_str)) { params->file_mbyte_limit = String2Uint64(file_mbyte_limit_str); } return ret; } } // namespace receiver
/** * This file is part of the CernVM File System. */ #include "params.h" #include <vector> #include "options.h" #include "util/string.h" namespace receiver { bool GetParamsFromFile(const std::string& repo_name, Params* params) { const std::string repo_config_file = "/etc/cvmfs/repositories.d/" + repo_name + "/server.conf"; SimpleOptionsParser parser; if (!parser.TryParsePath(repo_config_file)) { return false; } bool ret = true; ret &= parser.GetValue("CVMFS_UPSTREAM_STORAGE", &params->spooler_configuration); // Note: if upstream is gateway, we change it to local. This should be made to // abort, but it's useful for testing on a single machine if (HasPrefix(params->spooler_configuration, "gw", false)) { std::vector<std::string> tokens = SplitString(repo_name, '/'); const std::string rname = tokens.back(); params->spooler_configuration = "local,/srv/cvmfs/" + rname + "/data/txn,/srv/cvmfs/" + rname; } std::string hash_algorithm_str; ret &= parser.GetValue("CVMFS_HASH_ALGORITHM", &hash_algorithm_str); params->hash_alg = shash::ParseHashAlgorithm(hash_algorithm_str); std::string compression_algorithm_str; ret &= parser.GetValue("CVMFS_COMPRESSION_ALGORITHM", &compression_algorithm_str); params->compression_alg = zlib::ParseCompressionAlgorithm(compression_algorithm_str); /** * The receiver does not store files, only catalogs. We can safely disable * this option. */ params->generate_legacy_bulk_chunks = false; std::string use_chunking_str; ret &= parser.GetValue("CVMFS_USE_FILE_CHUNKING", &use_chunking_str); if (use_chunking_str == "true") { params->use_file_chunking = true; } else if (use_chunking_str == "false") { params->use_file_chunking = false; } else { return false; } std::string min_chunk_size_str; ret &= parser.GetValue("CVMFS_MIN_CHUNK_SIZE", &min_chunk_size_str); params->min_chunk_size = String2Uint64(min_chunk_size_str); std::string avg_chunk_size_str; ret &= parser.GetValue("CVMFS_AVG_CHUNK_SIZE", &avg_chunk_size_str); params->avg_chunk_size = String2Uint64(avg_chunk_size_str); std::string max_chunk_size_str; ret &= parser.GetValue("CVMFS_MAX_CHUNK_SIZE", &max_chunk_size_str); params->max_chunk_size = String2Uint64(max_chunk_size_str); std::string use_autocatalogs_str; ret &= parser.GetValue("CVMFS_AUTOCATALOGS", &use_autocatalogs_str); if (use_autocatalogs_str == "true") { params->use_autocatalogs = true; } else if (use_autocatalogs_str == "false") { params->use_autocatalogs = false; } else { return false; } std::string max_weight_str; if (parser.GetValue("CVMFS_AUTOCATALOGS_MAX_WEIGHT", &max_weight_str)) { params->max_weight = String2Uint64(max_weight_str); } std::string min_weight_str; if (parser.GetValue("CVMFS_AUTOCATALOGS_MIN_WEIGHT", &min_weight_str)) { params->min_weight = String2Uint64(min_weight_str); } params->enforce_limits = false; std::string enforce_limits_str; ret &= parser.GetValue("CVMFS_ENFORCE_LIMITS", &enforce_limits_str); if (enforce_limits_str == "true") { params->enforce_limits = true; } // TODO(dwd): the next 3 limit variables should take defaults from // SyncParameters std::string nested_kcatalog_limit_str; if (parser.GetValue("CVMFS_NESTED_KCATALOG_LIMIT", &nested_kcatalog_limit_str)) { params->nested_kcatalog_limit = String2Uint64(nested_kcatalog_limit_str); } std::string root_kcatalog_limit_str; if (parser.GetValue("CVMFS_ROOT_KCATALOG_LIMIT", &root_kcatalog_limit_str)) { params->root_kcatalog_limit = String2Uint64(root_kcatalog_limit_str); } std::string file_mbyte_limit_str; if (parser.GetValue("CVMFS_FILE_MBYTE_LIMIT", &file_mbyte_limit_str)) { params->file_mbyte_limit = String2Uint64(file_mbyte_limit_str); } return ret; } } // namespace receiver
fix up parameter handling for the receiver
fix up parameter handling for the receiver
C++
bsd-3-clause
cvmfs/cvmfs,DrDaveD/cvmfs,DrDaveD/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,djw8605/cvmfs,Gangbiao/cvmfs,djw8605/cvmfs,DrDaveD/cvmfs,djw8605/cvmfs,Gangbiao/cvmfs,djw8605/cvmfs,djw8605/cvmfs,DrDaveD/cvmfs,Gangbiao/cvmfs,Gangbiao/cvmfs,DrDaveD/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,Gangbiao/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs
f658b079b418a127d4c41e75d8e7e0fdeb261660
src/odbus/Message.hxx
src/odbus/Message.hxx
// -*- mode: c++; indent-tabs-mode: t; c-basic-offset: 8; -*- /* * author: Max Kellermann <[email protected]> */ #ifndef ODBUS_MESSAGE_HXX #define ODBUS_MESSAGE_HXX #include <dbus/dbus.h> #include <algorithm> #include <stdexcept> namespace ODBus { class Message { DBusMessage *msg = nullptr; explicit Message(DBusMessage *_msg) :msg(_msg) {} public: Message() = default; Message(Message &&src) :msg(src.msg) { src.msg = nullptr; } ~Message() { if (msg != nullptr) dbus_message_unref(msg); } DBusMessage *Get() { return msg; } Message &operator=(Message &&src) { std::swap(msg, src.msg); return *this; } static Message NewMethodCall(const char *destination, const char *path, const char *iface, const char *method); static Message StealReply(DBusPendingCall &pending); static Message Pop(DBusConnection &connection); bool IsDefined() const { return msg != nullptr; } int GetType() { return dbus_message_get_type(msg); } const char *GetPath() { return dbus_message_get_path(msg); } bool HasPath(const char *object_path) { return dbus_message_has_path(msg, object_path); } const char *GetInterface() { return dbus_message_get_interface(msg); } bool HasInterface(const char *iface) { return dbus_message_has_interface(msg, iface); } const char *GetMember() { return dbus_message_get_member(msg); } bool HasMember(const char *member) { return dbus_message_has_member(msg, member); } void CheckThrowError(); template<typename... Args> bool GetArgs(DBusError &error, Args... args) { return dbus_message_get_args(msg, &error, std::forward<Args>(args)..., DBUS_TYPE_INVALID); } }; } #endif
// -*- mode: c++; indent-tabs-mode: t; c-basic-offset: 8; -*- /* * author: Max Kellermann <[email protected]> */ #ifndef ODBUS_MESSAGE_HXX #define ODBUS_MESSAGE_HXX #include <dbus/dbus.h> #include <algorithm> #include <stdexcept> namespace ODBus { class Message { DBusMessage *msg = nullptr; explicit Message(DBusMessage *_msg) :msg(_msg) {} public: Message() = default; Message(Message &&src) :msg(src.msg) { src.msg = nullptr; } ~Message() { if (msg != nullptr) dbus_message_unref(msg); } DBusMessage *Get() { return msg; } Message &operator=(Message &&src) { std::swap(msg, src.msg); return *this; } static Message NewMethodCall(const char *destination, const char *path, const char *iface, const char *method); static Message StealReply(DBusPendingCall &pending); static Message Pop(DBusConnection &connection); bool IsDefined() const { return msg != nullptr; } int GetType() { return dbus_message_get_type(msg); } const char *GetPath() { return dbus_message_get_path(msg); } bool HasPath(const char *object_path) { return dbus_message_has_path(msg, object_path); } const char *GetInterface() { return dbus_message_get_interface(msg); } bool HasInterface(const char *iface) { return dbus_message_has_interface(msg, iface); } const char *GetMember() { return dbus_message_get_member(msg); } bool HasMember(const char *member) { return dbus_message_has_member(msg, member); } bool IsError(const char *error_name) const { return dbus_message_is_error(msg, error_name); } const char *GetErrorName() const { return dbus_message_get_error_name(msg); } const char *GetDestination() const { return dbus_message_get_destination(msg); } const char *GetSender() const { return dbus_message_get_sender(msg); } const char *GetSignature() const { return dbus_message_get_signature(msg); } bool GetNoReply() const { return dbus_message_get_no_reply(msg); } bool IsMethodCall(const char *iface, const char *method) const { return dbus_message_is_method_call(msg, iface, method); } bool IsSignal(const char *iface, const char *signal_name) const { return dbus_message_is_signal(msg, iface, signal_name); } void CheckThrowError(); template<typename... Args> bool GetArgs(DBusError &error, Args... args) { return dbus_message_get_args(msg, &error, std::forward<Args>(args)..., DBUS_TYPE_INVALID); } }; } #endif
add more getter methods
odbus/Message: add more getter methods
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
ce528ee99aadb239b6cb44a72269e07bdc9fc2d0
net/server/web_socket.cc
net/server/web_socket.cc
// 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/server/web_socket.h" #include "base/base64.h" #include "base/rand_util.h" #include "base/logging.h" #include "base/md5.h" #include "base/sha1.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "net/server/http_connection.h" #include "net/server/http_server_request_info.h" #if defined(OS_WIN) #include <winsock2.h> #else #include <arpa/inet.h> #endif #include <limits> namespace net { namespace { static uint32 WebSocketKeyFingerprint(const std::string& str) { std::string result; const char* p_char = str.c_str(); int length = str.length(); int spaces = 0; for (int i = 0; i < length; ++i) { if (p_char[i] >= '0' && p_char[i] <= '9') result.append(&p_char[i], 1); else if (p_char[i] == ' ') spaces++; } if (spaces == 0) return 0; int64 number = 0; if (!base::StringToInt64(result, &number)) return 0; return htonl(static_cast<uint32>(number / spaces)); } class WebSocketHixie76 : public net::WebSocket { public: static net::WebSocket* Create(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) { if (connection->recv_data().length() < *pos + kWebSocketHandshakeBodyLen) return NULL; return new WebSocketHixie76(connection, request, pos); } virtual void Accept(const HttpServerRequestInfo& request) { std::string key1 = request.GetHeaderValue("Sec-WebSocket-Key1"); std::string key2 = request.GetHeaderValue("Sec-WebSocket-Key2"); uint32 fp1 = WebSocketKeyFingerprint(key1); uint32 fp2 = WebSocketKeyFingerprint(key2); char data[16]; memcpy(data, &fp1, 4); memcpy(data + 4, &fp2, 4); memcpy(data + 8, &key3_[0], 8); base::MD5Digest digest; base::MD5Sum(data, 16, &digest); std::string origin = request.GetHeaderValue("Origin"); std::string host = request.GetHeaderValue("Host"); std::string location = "ws://" + host + request.path; connection_->Send(base::StringPrintf( "HTTP/1.1 101 WebSocket Protocol Handshake\r\n" "Upgrade: WebSocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Origin: %s\r\n" "Sec-WebSocket-Location: %s\r\n" "\r\n", origin.c_str(), location.c_str())); connection_->Send(reinterpret_cast<char*>(digest.a), 16); } virtual ParseResult Read(std::string* message) { DCHECK(message); const std::string& data = connection_->recv_data(); if (data[0]) return FRAME_ERROR; size_t pos = data.find('\377', 1); if (pos == std::string::npos) return FRAME_INCOMPLETE; std::string buffer(data.begin() + 1, data.begin() + pos); message->swap(buffer); connection_->Shift(pos + 1); return FRAME_OK; } virtual void Send(const std::string& message) { char message_start = 0; char message_end = -1; connection_->Send(&message_start, 1); connection_->Send(message); connection_->Send(&message_end, 1); } private: static const int kWebSocketHandshakeBodyLen; WebSocketHixie76(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) : WebSocket(connection) { std::string key1 = request.GetHeaderValue("Sec-WebSocket-Key1"); std::string key2 = request.GetHeaderValue("Sec-WebSocket-Key2"); if (key1.empty()) { connection->Send500("Invalid request format. " "Sec-WebSocket-Key1 is empty or isn't specified."); return; } if (key2.empty()) { connection->Send500("Invalid request format. " "Sec-WebSocket-Key2 is empty or isn't specified."); return; } key3_ = connection->recv_data().substr( *pos, *pos + kWebSocketHandshakeBodyLen); *pos += kWebSocketHandshakeBodyLen; } std::string key3_; DISALLOW_COPY_AND_ASSIGN(WebSocketHixie76); }; const int WebSocketHixie76::kWebSocketHandshakeBodyLen = 8; // Constants for hybi-10 frame format. typedef int OpCode; const OpCode kOpCodeContinuation = 0x0; const OpCode kOpCodeText = 0x1; const OpCode kOpCodeBinary = 0x2; const OpCode kOpCodeClose = 0x8; const OpCode kOpCodePing = 0x9; const OpCode kOpCodePong = 0xA; const unsigned char kFinalBit = 0x80; const unsigned char kReserved1Bit = 0x40; const unsigned char kReserved2Bit = 0x20; const unsigned char kReserved3Bit = 0x10; const unsigned char kOpCodeMask = 0xF; const unsigned char kMaskBit = 0x80; const unsigned char kPayloadLengthMask = 0x7F; const size_t kMaxSingleBytePayloadLength = 125; const size_t kTwoBytePayloadLengthField = 126; const size_t kEightBytePayloadLengthField = 127; const size_t kMaskingKeyWidthInBytes = 4; class WebSocketHybi17 : public WebSocket { public: static WebSocket* Create(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) { std::string version = request.GetHeaderValue("Sec-WebSocket-Version"); if (version != "8" && version != "13") return NULL; std::string key = request.GetHeaderValue("Sec-WebSocket-Key"); if (key.empty()) { connection->Send500("Invalid request format. " "Sec-WebSocket-Key is empty or isn't specified."); return NULL; } return new WebSocketHybi17(connection, request, pos); } virtual void Accept(const HttpServerRequestInfo& request) { static const char* const kWebSocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; std::string key = request.GetHeaderValue("Sec-WebSocket-Key"); std::string data = base::StringPrintf("%s%s", key.c_str(), kWebSocketGuid); std::string encoded_hash; base::Base64Encode(base::SHA1HashString(data), &encoded_hash); std::string response = base::StringPrintf( "HTTP/1.1 101 WebSocket Protocol Handshake\r\n" "Upgrade: WebSocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: %s\r\n" "\r\n", encoded_hash.c_str()); connection_->Send(response); } virtual ParseResult Read(std::string* message) { size_t data_length = connection_->recv_data().length(); if (data_length < 2) return FRAME_INCOMPLETE; const char* p = connection_->recv_data().c_str(); const char* buffer_end = p + data_length; unsigned char first_byte = *p++; unsigned char second_byte = *p++; final_ = first_byte & kFinalBit; reserved1_ = first_byte & kReserved1Bit; reserved2_ = first_byte & kReserved2Bit; reserved3_ = first_byte & kReserved3Bit; op_code_ = first_byte & kOpCodeMask; masked_ = second_byte & kMaskBit; switch (op_code_) { case kOpCodeClose: closed_ = true; break; case kOpCodeText: break; case kOpCodeBinary: // We don't support binary frames yet. case kOpCodeContinuation: // We don't support binary frames yet. case kOpCodePing: // We don't support binary frames yet. case kOpCodePong: // We don't support binary frames yet. default: return FRAME_ERROR; } if (!masked_) // According to Hybi-17 spec client MUST mask his frame. return FRAME_ERROR; uint64 payload_length64 = second_byte & kPayloadLengthMask; if (payload_length64 > kMaxSingleBytePayloadLength) { int extended_payload_length_size; if (payload_length64 == kTwoBytePayloadLengthField) extended_payload_length_size = 2; else { DCHECK(payload_length64 == kEightBytePayloadLengthField); extended_payload_length_size = 8; } if (buffer_end - p < extended_payload_length_size) return FRAME_INCOMPLETE; payload_length64 = 0; for (int i = 0; i < extended_payload_length_size; ++i) { payload_length64 <<= 8; payload_length64 |= static_cast<unsigned char>(*p++); } } static const uint64 max_payload_length = 0x7FFFFFFFFFFFFFFFull; static size_t max_length = std::numeric_limits<size_t>::max(); if (payload_length64 > max_payload_length || payload_length64 + kMaskingKeyWidthInBytes > max_length) { // WebSocket frame length too large. return FRAME_ERROR; } payload_length_ = static_cast<size_t>(payload_length64); size_t total_length = kMaskingKeyWidthInBytes + payload_length_; if (static_cast<size_t>(buffer_end - p) < total_length) return FRAME_INCOMPLETE; if (masked_) { message->resize(payload_length_); const char* masking_key = p; char* payload = const_cast<char*>(p + kMaskingKeyWidthInBytes); for (size_t i = 0; i < payload_length_; ++i) // Unmask the payload. (*message)[i] = payload[i] ^ masking_key[i % kMaskingKeyWidthInBytes]; } else { std::string buffer(p, p + payload_length_); message->swap(buffer); } size_t pos = p + kMaskingKeyWidthInBytes + payload_length_ - connection_->recv_data().c_str(); connection_->Shift(pos); return closed_ ? FRAME_CLOSE : FRAME_OK; } virtual void Send(const std::string& message) { if (closed_) return; std::vector<char> frame; OpCode op_code = kOpCodeText; size_t data_length = message.length(); frame.push_back(kFinalBit | op_code); if (data_length <= kMaxSingleBytePayloadLength) frame.push_back(data_length); else if (data_length <= 0xFFFF) { frame.push_back(kTwoBytePayloadLengthField); frame.push_back((data_length & 0xFF00) >> 8); frame.push_back(data_length & 0xFF); } else { frame.push_back(kEightBytePayloadLengthField); char extended_payload_length[8]; size_t remaining = data_length; // Fill the length into extended_payload_length in the network byte order. for (int i = 0; i < 8; ++i) { extended_payload_length[7 - i] = remaining & 0xFF; remaining >>= 8; } frame.insert(frame.end(), extended_payload_length, extended_payload_length + 8); DCHECK(!remaining); } const char* data = message.c_str(); frame.insert(frame.end(), data, data + data_length); connection_->Send(&frame[0], frame.size()); } private: WebSocketHybi17(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) : WebSocket(connection), op_code_(0), final_(false), reserved1_(false), reserved2_(false), reserved3_(false), masked_(false), payload_(0), payload_length_(0), frame_end_(0), closed_(false) { } OpCode op_code_; bool final_; bool reserved1_; bool reserved2_; bool reserved3_; bool masked_; const char* payload_; size_t payload_length_; const char* frame_end_; bool closed_; DISALLOW_COPY_AND_ASSIGN(WebSocketHybi17); }; } // anonymous namespace WebSocket* WebSocket::CreateWebSocket(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) { WebSocket* socket = WebSocketHybi17::Create(connection, request, pos); if (socket) return socket; return WebSocketHixie76::Create(connection, request, pos); } WebSocket::WebSocket(HttpConnection* connection) : connection_(connection) { } } // namespace net
// 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/server/web_socket.h" #include "base/base64.h" #include "base/rand_util.h" #include "base/logging.h" #include "base/md5.h" #include "base/sha1.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "net/server/http_connection.h" #include "net/server/http_server_request_info.h" #if defined(OS_WIN) #include <winsock2.h> #else #include <arpa/inet.h> #endif #include <limits> namespace net { namespace { static uint32 WebSocketKeyFingerprint(const std::string& str) { std::string result; const char* p_char = str.c_str(); int length = str.length(); int spaces = 0; for (int i = 0; i < length; ++i) { if (p_char[i] >= '0' && p_char[i] <= '9') result.append(&p_char[i], 1); else if (p_char[i] == ' ') spaces++; } if (spaces == 0) return 0; int64 number = 0; if (!base::StringToInt64(result, &number)) return 0; return htonl(static_cast<uint32>(number / spaces)); } class WebSocketHixie76 : public net::WebSocket { public: static net::WebSocket* Create(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) { if (connection->recv_data().length() < *pos + kWebSocketHandshakeBodyLen) return NULL; return new WebSocketHixie76(connection, request, pos); } virtual void Accept(const HttpServerRequestInfo& request) { std::string key1 = request.GetHeaderValue("Sec-WebSocket-Key1"); std::string key2 = request.GetHeaderValue("Sec-WebSocket-Key2"); uint32 fp1 = WebSocketKeyFingerprint(key1); uint32 fp2 = WebSocketKeyFingerprint(key2); char data[16]; memcpy(data, &fp1, 4); memcpy(data + 4, &fp2, 4); memcpy(data + 8, &key3_[0], 8); base::MD5Digest digest; base::MD5Sum(data, 16, &digest); std::string origin = request.GetHeaderValue("Origin"); std::string host = request.GetHeaderValue("Host"); std::string location = "ws://" + host + request.path; connection_->Send(base::StringPrintf( "HTTP/1.1 101 WebSocket Protocol Handshake\r\n" "Upgrade: WebSocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Origin: %s\r\n" "Sec-WebSocket-Location: %s\r\n" "\r\n", origin.c_str(), location.c_str())); connection_->Send(reinterpret_cast<char*>(digest.a), 16); } virtual ParseResult Read(std::string* message) { DCHECK(message); const std::string& data = connection_->recv_data(); if (data[0]) return FRAME_ERROR; size_t pos = data.find('\377', 1); if (pos == std::string::npos) return FRAME_INCOMPLETE; std::string buffer(data.begin() + 1, data.begin() + pos); message->swap(buffer); connection_->Shift(pos + 1); return FRAME_OK; } virtual void Send(const std::string& message) { char message_start = 0; char message_end = -1; connection_->Send(&message_start, 1); connection_->Send(message); connection_->Send(&message_end, 1); } private: static const int kWebSocketHandshakeBodyLen; WebSocketHixie76(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) : WebSocket(connection) { std::string key1 = request.GetHeaderValue("Sec-WebSocket-Key1"); std::string key2 = request.GetHeaderValue("Sec-WebSocket-Key2"); if (key1.empty()) { connection->Send500("Invalid request format. " "Sec-WebSocket-Key1 is empty or isn't specified."); return; } if (key2.empty()) { connection->Send500("Invalid request format. " "Sec-WebSocket-Key2 is empty or isn't specified."); return; } key3_ = connection->recv_data().substr( *pos, *pos + kWebSocketHandshakeBodyLen); *pos += kWebSocketHandshakeBodyLen; } std::string key3_; DISALLOW_COPY_AND_ASSIGN(WebSocketHixie76); }; const int WebSocketHixie76::kWebSocketHandshakeBodyLen = 8; // Constants for hybi-10 frame format. typedef int OpCode; const OpCode kOpCodeContinuation = 0x0; const OpCode kOpCodeText = 0x1; const OpCode kOpCodeBinary = 0x2; const OpCode kOpCodeClose = 0x8; const OpCode kOpCodePing = 0x9; const OpCode kOpCodePong = 0xA; const unsigned char kFinalBit = 0x80; const unsigned char kReserved1Bit = 0x40; const unsigned char kReserved2Bit = 0x20; const unsigned char kReserved3Bit = 0x10; const unsigned char kOpCodeMask = 0xF; const unsigned char kMaskBit = 0x80; const unsigned char kPayloadLengthMask = 0x7F; const size_t kMaxSingleBytePayloadLength = 125; const size_t kTwoBytePayloadLengthField = 126; const size_t kEightBytePayloadLengthField = 127; const size_t kMaskingKeyWidthInBytes = 4; class WebSocketHybi17 : public WebSocket { public: static WebSocket* Create(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) { std::string version = request.GetHeaderValue("Sec-WebSocket-Version"); if (version != "8" && version != "13") return NULL; std::string key = request.GetHeaderValue("Sec-WebSocket-Key"); if (key.empty()) { connection->Send500("Invalid request format. " "Sec-WebSocket-Key is empty or isn't specified."); return NULL; } return new WebSocketHybi17(connection, request, pos); } virtual void Accept(const HttpServerRequestInfo& request) { static const char* const kWebSocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; std::string key = request.GetHeaderValue("Sec-WebSocket-Key"); std::string data = base::StringPrintf("%s%s", key.c_str(), kWebSocketGuid); std::string encoded_hash; base::Base64Encode(base::SHA1HashString(data), &encoded_hash); std::string response = base::StringPrintf( "HTTP/1.1 101 WebSocket Protocol Handshake\r\n" "Upgrade: WebSocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: %s\r\n" "\r\n", encoded_hash.c_str()); connection_->Send(response); } virtual ParseResult Read(std::string* message) { size_t data_length = connection_->recv_data().length(); if (data_length < 2) return FRAME_INCOMPLETE; const char* p = connection_->recv_data().c_str(); const char* buffer_end = p + data_length; unsigned char first_byte = *p++; unsigned char second_byte = *p++; final_ = (first_byte & kFinalBit) != 0; reserved1_ = (first_byte & kReserved1Bit) != 0; reserved2_ = (first_byte & kReserved2Bit) != 0; reserved3_ = (first_byte & kReserved3Bit) != 0; op_code_ = first_byte & kOpCodeMask; masked_ = (second_byte & kMaskBit) != 0; switch (op_code_) { case kOpCodeClose: closed_ = true; break; case kOpCodeText: break; case kOpCodeBinary: // We don't support binary frames yet. case kOpCodeContinuation: // We don't support binary frames yet. case kOpCodePing: // We don't support binary frames yet. case kOpCodePong: // We don't support binary frames yet. default: return FRAME_ERROR; } if (!masked_) // According to Hybi-17 spec client MUST mask his frame. return FRAME_ERROR; uint64 payload_length64 = second_byte & kPayloadLengthMask; if (payload_length64 > kMaxSingleBytePayloadLength) { int extended_payload_length_size; if (payload_length64 == kTwoBytePayloadLengthField) extended_payload_length_size = 2; else { DCHECK(payload_length64 == kEightBytePayloadLengthField); extended_payload_length_size = 8; } if (buffer_end - p < extended_payload_length_size) return FRAME_INCOMPLETE; payload_length64 = 0; for (int i = 0; i < extended_payload_length_size; ++i) { payload_length64 <<= 8; payload_length64 |= static_cast<unsigned char>(*p++); } } static const uint64 max_payload_length = 0x7FFFFFFFFFFFFFFFull; static size_t max_length = std::numeric_limits<size_t>::max(); if (payload_length64 > max_payload_length || payload_length64 + kMaskingKeyWidthInBytes > max_length) { // WebSocket frame length too large. return FRAME_ERROR; } payload_length_ = static_cast<size_t>(payload_length64); size_t total_length = kMaskingKeyWidthInBytes + payload_length_; if (static_cast<size_t>(buffer_end - p) < total_length) return FRAME_INCOMPLETE; if (masked_) { message->resize(payload_length_); const char* masking_key = p; char* payload = const_cast<char*>(p + kMaskingKeyWidthInBytes); for (size_t i = 0; i < payload_length_; ++i) // Unmask the payload. (*message)[i] = payload[i] ^ masking_key[i % kMaskingKeyWidthInBytes]; } else { std::string buffer(p, p + payload_length_); message->swap(buffer); } size_t pos = p + kMaskingKeyWidthInBytes + payload_length_ - connection_->recv_data().c_str(); connection_->Shift(pos); return closed_ ? FRAME_CLOSE : FRAME_OK; } virtual void Send(const std::string& message) { if (closed_) return; std::vector<char> frame; OpCode op_code = kOpCodeText; size_t data_length = message.length(); frame.push_back(kFinalBit | op_code); if (data_length <= kMaxSingleBytePayloadLength) frame.push_back(data_length); else if (data_length <= 0xFFFF) { frame.push_back(kTwoBytePayloadLengthField); frame.push_back((data_length & 0xFF00) >> 8); frame.push_back(data_length & 0xFF); } else { frame.push_back(kEightBytePayloadLengthField); char extended_payload_length[8]; size_t remaining = data_length; // Fill the length into extended_payload_length in the network byte order. for (int i = 0; i < 8; ++i) { extended_payload_length[7 - i] = remaining & 0xFF; remaining >>= 8; } frame.insert(frame.end(), extended_payload_length, extended_payload_length + 8); DCHECK(!remaining); } const char* data = message.c_str(); frame.insert(frame.end(), data, data + data_length); connection_->Send(&frame[0], frame.size()); } private: WebSocketHybi17(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) : WebSocket(connection), op_code_(0), final_(false), reserved1_(false), reserved2_(false), reserved3_(false), masked_(false), payload_(0), payload_length_(0), frame_end_(0), closed_(false) { } OpCode op_code_; bool final_; bool reserved1_; bool reserved2_; bool reserved3_; bool masked_; const char* payload_; size_t payload_length_; const char* frame_end_; bool closed_; DISALLOW_COPY_AND_ASSIGN(WebSocketHybi17); }; } // anonymous namespace WebSocket* WebSocket::CreateWebSocket(HttpConnection* connection, const HttpServerRequestInfo& request, size_t* pos) { WebSocket* socket = WebSocketHybi17::Create(connection, request, pos); if (socket) return socket; return WebSocketHixie76::Create(connection, request, pos); } WebSocket::WebSocket(HttpConnection* connection) : connection_(connection) { } } // namespace net
Fix Win builder following r111314
Fix Win builder following r111314 BUG=none [email protected] Review URL: http://codereview.chromium.org/8677002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@111322 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Chilledheart/chromium,dednal/chromium.src,jaruba/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,ltilve/chromium,anirudhSK/chromium,robclark/chromium,robclark/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,keishi/chromium,Just-D/chromium-1,ChromiumWebApps/chromium,hujiajie/pa-chromium,rogerwang/chromium,Jonekee/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,patrickm/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,keishi/chromium,Pluto-tv/chromium-crosswalk,robclark/chromium,nacl-webkit/chrome_deps,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,hgl888/chromium-crosswalk,Chilledheart/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,robclark/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,robclark/chromium,ondra-novak/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,dednal/chromium.src,zcbenz/cefode-chromium,ltilve/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,dednal/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,keishi/chromium,M4sse/chromium.src,hujiajie/pa-chromium,anirudhSK/chromium,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,keishi/chromium,littlstar/chromium.src,Chilledheart/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,keishi/chromium,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,Just-D/chromium-1,markYoungH/chromium.src,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,Chilledheart/chromium,robclark/chromium,patrickm/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,dednal/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,keishi/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,dednal/chromium.src,patrickm/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,patrickm/chromium.src,ondra-novak/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,jaruba/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,hujiajie/pa-chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,dushu1203/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,patrickm/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,keishi/chromium,zcbenz/cefode-chromium,rogerwang/chromium,nacl-webkit/chrome_deps,anirudhSK/chromium,nacl-webkit/chrome_deps,jaruba/chromium.src,rogerwang/chromium,junmin-zhu/chromium-rivertrail,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,keishi/chromium,rogerwang/chromium,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,robclark/chromium,patrickm/chromium.src,robclark/chromium,markYoungH/chromium.src,markYoungH/chromium.src,timopulkkinen/BubbleFish,ltilve/chromium,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,M4sse/chromium.src,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,robclark/chromium,Just-D/chromium-1,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,rogerwang/chromium,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,zcbenz/cefode-chromium,rogerwang/chromium,patrickm/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,robclark/chromium,zcbenz/cefode-chromium,ltilve/chromium,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,anirudhSK/chromium,rogerwang/chromium,axinging/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,jaruba/chromium.src,keishi/chromium,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk
37c08b5a00ebcb4bc20518d25b345b3dfbc9ace3
broker.cc
broker.cc
#include "broker.h" #include "frame.h" #include <sstream> Broker::Broker() { topicRoot = new TopicNode("", ""); } Broker::~Broker() { delete topicRoot; } MQTT_ERROR Broker::Start() { return NO_ERROR; } std::string Broker::ApplyDummyClientID() { std::stringstream ss; ss << "DummyClientID" << clients.size() + 1; return ss.str(); } BrokerSideClient::BrokerSideClient(Transport* ct, Broker* b) : broker(b), Terminal("", NULL, 0, NULL) { this->ct = ct; } BrokerSideClient::~BrokerSideClient() {} void BrokerSideClient::setPreviousSession(BrokerSideClient* ps) { subTopics = ps->subTopics; packetIDMap = ps->packetIDMap; cleanSession = ps->cleanSession; will = ps->will; user = ps->user; keepAlive = ps->keepAlive; } MQTT_ERROR BrokerSideClient::recvConnectMessage(ConnectMessage* m) {return NO_ERROR;} MQTT_ERROR BrokerSideClient::recvConnackMessage(ConnackMessage* m) {return INVALID_MESSAGE_CAME;} MQTT_ERROR BrokerSideClient::recvPublishMessage(PublishMessage* m) {return NO_ERROR;} MQTT_ERROR BrokerSideClient::recvPubackMessage(PubackMessage* m) { if (m->fh->PacketID > 0) { return ackMessage(m->fh->PacketID); } return NO_ERROR; } MQTT_ERROR BrokerSideClient::recvPubrecMessage(PubrecMessage* m) { MQTT_ERROR err = ackMessage(m->fh->PacketID); if (err < 0) { return err; } err = sendMessage(new PubrelMessage(m->fh->PacketID)); return err; } MQTT_ERROR BrokerSideClient::recvPubrelMessage(PubrelMessage* m) { MQTT_ERROR err = ackMessage(m->fh->PacketID); if (err < 0) { return err; } err = sendMessage(new PubcompMessage(m->fh->PacketID)); return err; } MQTT_ERROR BrokerSideClient::recvPubcompMessage(PubcompMessage* m) { return ackMessage(m->fh->PacketID); } MQTT_ERROR BrokerSideClient::recvSubscribeMessage(SubscribeMessage* m) { std::vector<SubackCode> returnCodes; MQTT_ERROR err; // this sould be duplicate? for (std::vector<SubscribeTopic*>::iterator it = m->subTopics.begin(); it != m->subTopics.end(); it++) { std::vector<TopicNode*> nodes = broker->topicRoot->getTopicNode((*it)->topic, true, err); if (err != NO_ERROR) { for (std::vector<TopicNode*>::iterator nIt = nodes.begin(); nIt != nodes.end(); nIt++) { returnCodes.push_back(FAILURE); } } else { for (std::vector<TopicNode*>::iterator nIt = nodes.begin(); nIt != nodes.end(); nIt++) { (*nIt)->subscribers[ID] = (*it)->qos; returnCodes.push_back((SubackCode)(*it)->qos); subTopics[(*it)->topic] = (*it)->qos; if ((*nIt)->retainMessage.size() > 0) { uint16_t pID = 0; if ((*nIt)->retainQoS > 0) { err = getUsablePacketID(&pID); if (err != NO_ERROR) { return err; } } err = sendMessage(new PublishMessage(false, (*nIt)->retainQoS, true, pID, (*nIt)->fullPath, (*nIt)->retainMessage)); if (err != NO_ERROR) { return err; } } } } } return sendMessage(new SubackMessage(m->fh->PacketID, returnCodes)); } MQTT_ERROR BrokerSideClient::recvSubackMessage(SubackMessage* m) {return INVALID_MESSAGE_CAME;} MQTT_ERROR BrokerSideClient::recvUnsubscribeMessage(UnsubscribeMessage* m) { if (m->topics.size() == 0) { return PROTOCOL_VIOLATION; } MQTT_ERROR err = NO_ERROR; for (std::vector<std::string>::iterator it = m->topics.begin(); it != m->topics.end(); it++) { this->broker->topicRoot->deleteSubscriber(this->ID, *it, err); this->subTopics.erase(*it); } this->sendMessage(new UnsubackMessage(m->fh->PacketID)); return err; } MQTT_ERROR BrokerSideClient::recvUnsubackMessage(UnsubackMessage* m) {return INVALID_MESSAGE_CAME;} MQTT_ERROR BrokerSideClient::recvPingreqMessage(PingreqMessage* m) {return NO_ERROR;} MQTT_ERROR BrokerSideClient::recvPingrespMessage(PingrespMessage* m) {return INVALID_MESSAGE_CAME;} MQTT_ERROR BrokerSideClient::recvDisconnectMessage(DisconnectMessage* m) {return NO_ERROR;}
#include "broker.h" #include "frame.h" #include <sstream> Broker::Broker() { topicRoot = new TopicNode("", ""); } Broker::~Broker() { delete topicRoot; } MQTT_ERROR Broker::Start() { return NO_ERROR; } std::string Broker::ApplyDummyClientID() { std::stringstream ss; ss << "DummyClientID" << clients.size() + 1; return ss.str(); } BrokerSideClient::BrokerSideClient(Transport* ct, Broker* b) : broker(b), Terminal("", NULL, 0, NULL) { this->ct = ct; } BrokerSideClient::~BrokerSideClient() {} void BrokerSideClient::setPreviousSession(BrokerSideClient* ps) { subTopics = ps->subTopics; packetIDMap = ps->packetIDMap; cleanSession = ps->cleanSession; will = ps->will; user = ps->user; keepAlive = ps->keepAlive; } MQTT_ERROR BrokerSideClient::recvConnectMessage(ConnectMessage* m) {return NO_ERROR;} MQTT_ERROR BrokerSideClient::recvConnackMessage(ConnackMessage* m) {return INVALID_MESSAGE_CAME;} MQTT_ERROR BrokerSideClient::recvPublishMessage(PublishMessage* m) {return NO_ERROR;} MQTT_ERROR BrokerSideClient::recvPubackMessage(PubackMessage* m) { if (m->fh->PacketID > 0) { return ackMessage(m->fh->PacketID); } return NO_ERROR; } MQTT_ERROR BrokerSideClient::recvPubrecMessage(PubrecMessage* m) { MQTT_ERROR err = ackMessage(m->fh->PacketID); if (err < 0) { return err; } err = sendMessage(new PubrelMessage(m->fh->PacketID)); return err; } MQTT_ERROR BrokerSideClient::recvPubrelMessage(PubrelMessage* m) { MQTT_ERROR err = ackMessage(m->fh->PacketID); if (err < 0) { return err; } err = sendMessage(new PubcompMessage(m->fh->PacketID)); return err; } MQTT_ERROR BrokerSideClient::recvPubcompMessage(PubcompMessage* m) { return ackMessage(m->fh->PacketID); } MQTT_ERROR BrokerSideClient::recvSubscribeMessage(SubscribeMessage* m) { std::vector<SubackCode> returnCodes; MQTT_ERROR err; // this sould be duplicate? for (std::vector<SubscribeTopic*>::iterator it = m->subTopics.begin(); it != m->subTopics.end(); it++) { std::vector<TopicNode*> nodes = broker->topicRoot->getTopicNode((*it)->topic, true, err); SubackCode code = (SubackCode)(*it)->qos; if (err != NO_ERROR) { code = FAILURE; } else { for (std::vector<TopicNode*>::iterator nIt = nodes.begin(); nIt != nodes.end(); nIt++) { (*nIt)->subscribers[ID] = (*it)->qos; subTopics[(*it)->topic] = (*it)->qos; if ((*nIt)->retainMessage.size() > 0) { uint16_t pID = 0; if ((*nIt)->retainQoS > 0) { err = getUsablePacketID(&pID); if (err != NO_ERROR) { return err; } } err = sendMessage(new PublishMessage(false, (*nIt)->retainQoS, true, pID, (*nIt)->fullPath, (*nIt)->retainMessage)); if (err != NO_ERROR) { return err; } } } } returnCodes.push_back(code); } return sendMessage(new SubackMessage(m->fh->PacketID, returnCodes)); } MQTT_ERROR BrokerSideClient::recvSubackMessage(SubackMessage* m) {return INVALID_MESSAGE_CAME;} MQTT_ERROR BrokerSideClient::recvUnsubscribeMessage(UnsubscribeMessage* m) { if (m->topics.size() == 0) { return PROTOCOL_VIOLATION; } MQTT_ERROR err = NO_ERROR; for (std::vector<std::string>::iterator it = m->topics.begin(); it != m->topics.end(); it++) { this->broker->topicRoot->deleteSubscriber(this->ID, *it, err); this->subTopics.erase(*it); } this->sendMessage(new UnsubackMessage(m->fh->PacketID)); return err; } MQTT_ERROR BrokerSideClient::recvUnsubackMessage(UnsubackMessage* m) {return INVALID_MESSAGE_CAME;} MQTT_ERROR BrokerSideClient::recvPingreqMessage(PingreqMessage* m) {return NO_ERROR;} MQTT_ERROR BrokerSideClient::recvPingrespMessage(PingrespMessage* m) {return INVALID_MESSAGE_CAME;} MQTT_ERROR BrokerSideClient::recvDisconnectMessage(DisconnectMessage* m) {return NO_ERROR;}
fix the number of returned suback code
fix the number of returned suback code
C++
mit
ami-GS/MQTTcc
558f32d2d55907a85e8a2d4351817902a335463c
src/option_manager.cc
src/option_manager.cc
#include "option_manager.hh" #include "assert.hh" #include <sstream> namespace Kakoune { namespace { String option_to_string(const String& opt) { return opt; } void option_from_string(const String& str, String& opt) { opt = str; } String option_to_string(int opt) { return int_to_str(opt); } void option_from_string(const String& str, int& opt) { opt = str_to_int(str); } String option_to_string(bool opt) { return opt ? "true" : "false"; } void option_from_string(const String& str, bool& opt) { if (str == "true" or str == "yes") opt = true; else if (str == "false" or str == "no") opt = false; else throw runtime_error("boolean values are either true, yes, false or no"); } template<typename T> String option_to_string(const std::vector<T>& opt) { String res; for (size_t i = 0; i < opt.size(); ++i) { res += option_to_string(opt[i]); if (i != opt.size() - 1) res += ","; } return res; } template<typename T> void option_from_string(const String& str, std::vector<T>& opt) { opt.clear(); std::vector<String> elems = split(str, ','); for (auto& elem: elems) { T opt_elem; option_from_string(elem, opt_elem); opt.push_back(opt_elem); } } } template<typename T> class TypedOption : public Option { public: TypedOption(OptionManager& manager, String name, const T& value) : Option(manager, std::move(name)), m_value(value) {} void set(const T& value) { if (m_value != value) { m_value = value; m_manager.on_option_changed(*this); } } const T& get() const { return m_value; } String get_as_string() const override { return option_to_string(m_value); } void set_from_string(const String& str) override { T val; option_from_string(str, val); set(val); } Option* clone(OptionManager& manager) const override { return new TypedOption{manager, name(), m_value}; } private: T m_value; }; Option::Option(OptionManager& manager, String name) : m_manager(manager), m_name(std::move(name)) {} template<typename T> const T& Option::get() const { return dynamic_cast<const TypedOption<T>*>(this)->get(); } template<typename T> void Option::set(const T& val) { return dynamic_cast<TypedOption<T>*>(this)->set(val); } template const String& Option::get<String>() const; template void Option::set<String>(const String&); template const int& Option::get<int>() const; template void Option::set<int>(const int&); template const bool& Option::get<bool>() const; template void Option::set<bool>(const bool&); template const std::vector<int>& Option::get<std::vector<int>>() const; template void Option::set<std::vector<int>>(const std::vector<int>&); OptionManager::OptionManager(OptionManager& parent) : m_parent(&parent) { parent.register_watcher(*this); } OptionManager::~OptionManager() { if (m_parent) m_parent->unregister_watcher(*this); assert(m_watchers.empty()); } void OptionManager::register_watcher(OptionManagerWatcher& watcher) { assert(not contains(m_watchers, &watcher)); m_watchers.push_back(&watcher); } void OptionManager::unregister_watcher(OptionManagerWatcher& watcher) { auto it = find(m_watchers.begin(), m_watchers.end(), &watcher); assert(it != m_watchers.end()); m_watchers.erase(it); } template<typename T> auto find_option(T& container, const String& name) -> decltype(container.begin()) { using ptr_type = decltype(*container.begin()); return find_if(container, [&name](const ptr_type& opt) { return opt->name() == name; }); } Option& OptionManager::get_local_option(const String& name) { auto it = find_option(m_options, name); if (it != m_options.end()) return **it; else if (m_parent) { m_options.emplace_back((*m_parent)[name].clone(*this)); return *m_options.back(); } else throw option_not_found(name); } const Option& OptionManager::operator[](const String& name) const { auto it = find_option(m_options, name); if (it != m_options.end()) return **it; else if (m_parent) return (*m_parent)[name]; else throw option_not_found(name); } CandidateList OptionManager::complete_option_name(const String& prefix, ByteCount cursor_pos) { String real_prefix = prefix.substr(0, cursor_pos); CandidateList result; if (m_parent) result = m_parent->complete_option_name(prefix, cursor_pos); for (auto& option : m_options) { const auto& name = option->name(); if (name.substr(0, real_prefix.length()) == real_prefix and not contains(result, name)) result.push_back(name); } return result; } OptionManager::OptionList OptionManager::flatten_options() const { OptionList res = m_parent ? m_parent->flatten_options() : OptionList{}; for (auto& option : m_options) { auto it = find_option(res, option->name()); if (it != res.end()) *it = option.get(); else res.emplace_back(option.get()); } return res; } void OptionManager::on_option_changed(const Option& option) { // if parent option changed, but we overrided it, it's like nothing happened if (&option.manager() != this and find_option(m_options, option.name()) != m_options.end()) return; for (auto watcher : m_watchers) watcher->on_option_changed(option); } GlobalOptions::GlobalOptions() : OptionManager() { declare_option<int>("tabstop", 8); declare_option<int>("indentwidth", 4); declare_option<String>("eolformat", "lf"); declare_option<String>("BOM", "no"); declare_option<String>("shell", "sh"); declare_option<bool>("complete_prefix", true); declare_option<bool>("incsearch", true); declare_option<String>("ignored_files", R"(^(\..*|.*\.(o|so|a))$)"); declare_option<String>("filetype", ""); } template<typename T> Option& GlobalOptions::declare_option(const String& name, const T& value) { if (find_option(m_options, name) != m_options.end()) throw runtime_error("option " + name + " already declared"); m_options.emplace_back(new TypedOption<T>{*this, name, value}); return *m_options.back(); } template Option& GlobalOptions::declare_option<>(const String&, const std::vector<int>&); }
#include "option_manager.hh" #include "assert.hh" #include <sstream> namespace Kakoune { namespace { String option_to_string(const String& opt) { return opt; } void option_from_string(const String& str, String& opt) { opt = str; } String option_to_string(int opt) { return int_to_str(opt); } void option_from_string(const String& str, int& opt) { opt = str_to_int(str); } String option_to_string(bool opt) { return opt ? "true" : "false"; } void option_from_string(const String& str, bool& opt) { if (str == "true" or str == "yes") opt = true; else if (str == "false" or str == "no") opt = false; else throw runtime_error("boolean values are either true, yes, false or no"); } template<typename T> String option_to_string(const std::vector<T>& opt) { String res; for (size_t i = 0; i < opt.size(); ++i) { res += option_to_string(opt[i]); if (i != opt.size() - 1) res += ","; } return res; } template<typename T> void option_from_string(const String& str, std::vector<T>& opt) { opt.clear(); std::vector<String> elems = split(str, ','); for (auto& elem: elems) { T opt_elem; option_from_string(elem, opt_elem); opt.push_back(opt_elem); } } } template<typename T> class TypedOption : public Option { public: TypedOption(OptionManager& manager, String name, const T& value) : Option(manager, std::move(name)), m_value(value) {} void set(const T& value) { if (m_value != value) { m_value = value; m_manager.on_option_changed(*this); } } const T& get() const { return m_value; } String get_as_string() const override { return option_to_string(m_value); } void set_from_string(const String& str) override { T val; option_from_string(str, val); set(val); } Option* clone(OptionManager& manager) const override { return new TypedOption{manager, name(), m_value}; } private: T m_value; }; Option::Option(OptionManager& manager, String name) : m_manager(manager), m_name(std::move(name)) {} template<typename T> const T& Option::get() const { auto* typed_opt = dynamic_cast<const TypedOption<T>*>(this); if (not typed_opt) throw runtime_error("option " + name() + " is not of type " + typeid(T).name()); return typed_opt->get(); } template<typename T> void Option::set(const T& val) { auto* typed_opt = dynamic_cast<TypedOption<T>*>(this); if (not typed_opt) throw runtime_error("option " + name() + " is not of type " + typeid(T).name()); return typed_opt->set(val); } template const String& Option::get<String>() const; template void Option::set<String>(const String&); template const int& Option::get<int>() const; template void Option::set<int>(const int&); template const bool& Option::get<bool>() const; template void Option::set<bool>(const bool&); template const std::vector<int>& Option::get<std::vector<int>>() const; template void Option::set<std::vector<int>>(const std::vector<int>&); OptionManager::OptionManager(OptionManager& parent) : m_parent(&parent) { parent.register_watcher(*this); } OptionManager::~OptionManager() { if (m_parent) m_parent->unregister_watcher(*this); assert(m_watchers.empty()); } void OptionManager::register_watcher(OptionManagerWatcher& watcher) { assert(not contains(m_watchers, &watcher)); m_watchers.push_back(&watcher); } void OptionManager::unregister_watcher(OptionManagerWatcher& watcher) { auto it = find(m_watchers.begin(), m_watchers.end(), &watcher); assert(it != m_watchers.end()); m_watchers.erase(it); } template<typename T> auto find_option(T& container, const String& name) -> decltype(container.begin()) { using ptr_type = decltype(*container.begin()); return find_if(container, [&name](const ptr_type& opt) { return opt->name() == name; }); } Option& OptionManager::get_local_option(const String& name) { auto it = find_option(m_options, name); if (it != m_options.end()) return **it; else if (m_parent) { m_options.emplace_back((*m_parent)[name].clone(*this)); return *m_options.back(); } else throw option_not_found(name); } const Option& OptionManager::operator[](const String& name) const { auto it = find_option(m_options, name); if (it != m_options.end()) return **it; else if (m_parent) return (*m_parent)[name]; else throw option_not_found(name); } CandidateList OptionManager::complete_option_name(const String& prefix, ByteCount cursor_pos) { String real_prefix = prefix.substr(0, cursor_pos); CandidateList result; if (m_parent) result = m_parent->complete_option_name(prefix, cursor_pos); for (auto& option : m_options) { const auto& name = option->name(); if (name.substr(0, real_prefix.length()) == real_prefix and not contains(result, name)) result.push_back(name); } return result; } OptionManager::OptionList OptionManager::flatten_options() const { OptionList res = m_parent ? m_parent->flatten_options() : OptionList{}; for (auto& option : m_options) { auto it = find_option(res, option->name()); if (it != res.end()) *it = option.get(); else res.emplace_back(option.get()); } return res; } void OptionManager::on_option_changed(const Option& option) { // if parent option changed, but we overrided it, it's like nothing happened if (&option.manager() != this and find_option(m_options, option.name()) != m_options.end()) return; for (auto watcher : m_watchers) watcher->on_option_changed(option); } GlobalOptions::GlobalOptions() : OptionManager() { declare_option<int>("tabstop", 8); declare_option<int>("indentwidth", 4); declare_option<String>("eolformat", "lf"); declare_option<String>("BOM", "no"); declare_option<String>("shell", "sh"); declare_option<bool>("complete_prefix", true); declare_option<bool>("incsearch", true); declare_option<String>("ignored_files", R"(^(\..*|.*\.(o|so|a))$)"); declare_option<String>("filetype", ""); } template<typename T> Option& GlobalOptions::declare_option(const String& name, const T& value) { if (find_option(m_options, name) != m_options.end()) throw runtime_error("option " + name + " already declared"); m_options.emplace_back(new TypedOption<T>{*this, name, value}); return *m_options.back(); } template Option& GlobalOptions::declare_option<>(const String&, const std::vector<int>&); }
throw a runtime error when a wrong type is requested for an option
throw a runtime error when a wrong type is requested for an option
C++
unlicense
ekie/kakoune,zakgreant/kakoune,alpha123/kakoune,danielma/kakoune,Asenar/kakoune,lenormf/kakoune,jkonecny12/kakoune,occivink/kakoune,alpha123/kakoune,casimir/kakoune,jjthrash/kakoune,Somasis/kakoune,alexherbo2/kakoune,elegios/kakoune,elegios/kakoune,mawww/kakoune,elegios/kakoune,danielma/kakoune,casimir/kakoune,mawww/kakoune,ekie/kakoune,Asenar/kakoune,occivink/kakoune,alexherbo2/kakoune,jkonecny12/kakoune,occivink/kakoune,jjthrash/kakoune,alexherbo2/kakoune,zakgreant/kakoune,casimir/kakoune,ekie/kakoune,danr/kakoune,Somasis/kakoune,zakgreant/kakoune,jkonecny12/kakoune,Asenar/kakoune,rstacruz/kakoune,danr/kakoune,xificurC/kakoune,casimir/kakoune,xificurC/kakoune,danielma/kakoune,mawww/kakoune,danielma/kakoune,rstacruz/kakoune,danr/kakoune,occivink/kakoune,elegios/kakoune,lenormf/kakoune,jkonecny12/kakoune,Somasis/kakoune,flavius/kakoune,xificurC/kakoune,rstacruz/kakoune,alpha123/kakoune,lenormf/kakoune,jjthrash/kakoune,alexherbo2/kakoune,zakgreant/kakoune,jjthrash/kakoune,lenormf/kakoune,ekie/kakoune,flavius/kakoune,danr/kakoune,Asenar/kakoune,rstacruz/kakoune,flavius/kakoune,flavius/kakoune,Somasis/kakoune,mawww/kakoune,alpha123/kakoune,xificurC/kakoune
b4d565b7b9dc2262213e5bd08601737694d6bfb5
src/lib/client.cc
src/lib/client.cc
/* * ***************************************************************************** * Copyright 2014 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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 <stdlib.h> #include <string.h> #include <QFileInfo> #include <QHash> #include "lib/client.h" #include "lib/logger.h" #include "models/session.h" Client::Client(const Session* session) { m_creds = ds3_create_creds(session->GetAccessId().toUtf8().constData(), session->GetSecretKey().toUtf8().constData()); QString protocol = session->GetProtocolName(); m_endpoint = protocol + "://" + session->GetHost(); QString port = session->GetPort(); if (!port.isEmpty() && port != "80" && port != "443") { m_endpoint += ":" + port; } m_client = ds3_create_client(m_endpoint.toUtf8().constData(), m_creds); } Client::~Client() { ds3_free_creds(m_creds); ds3_free_client(m_client); ds3_cleanup(); } ds3_get_service_response* Client::GetService() { ds3_get_service_response *response; ds3_request* request = ds3_init_get_service(); LOG_INFO("Get Buckets (GET " + m_endpoint + ")"); ds3_error* error = ds3_get_service(m_client, request, &response); ds3_free_request(request); if (error) { // TODO Handle the error ds3_free_error(error); } return response; } ds3_get_bucket_response* Client::GetBucket(const std::string& bucketName, const std::string& prefix, const std::string& delimiter, const std::string& marker, uint32_t maxKeys) { ds3_get_bucket_response *response; ds3_request* request = ds3_init_get_bucket(bucketName.c_str()); QString logMsg = "List Objects (GET " + m_endpoint + "/"; logMsg += QString::fromStdString(bucketName); QStringList logQueryParams; if (!prefix.empty()) { ds3_request_set_prefix(request, prefix.c_str()); logQueryParams << "prefix=" + QString::fromStdString(prefix); } if (!delimiter.empty()) { ds3_request_set_delimiter(request, delimiter.c_str()); logQueryParams << "delimiter=" + QString::fromStdString(delimiter); } if (!marker.empty()) { ds3_request_set_marker(request, marker.c_str()); logQueryParams << "marker=" + QString::fromStdString(marker); } if (maxKeys > 0) { ds3_request_set_max_keys(request, maxKeys); logQueryParams << "max-keys=" + QString::number(maxKeys); } if (!logQueryParams.isEmpty()) { logMsg += "&" + logQueryParams.join("&"); } logMsg += ")"; LOG_INFO(logMsg); ds3_error* error = ds3_get_bucket(m_client, request, &response); ds3_free_request(request); if (error) { // TODO Handle the error ds3_free_error(error); } return response; } void Client::CreateBucket(const std::string& name) { ds3_request* request = ds3_init_put_bucket(name.c_str()); QString qname = QString::fromStdString(name); LOG_INFO("Create Bucket " + qname + " (PUT " + m_endpoint + "/" + \ qname + ")"); ds3_error* error = ds3_put_bucket(m_client, request); ds3_free_request(request); if (error) { // TODO Handle the error ds3_free_error(error); } } void Client::BulkPut(const QString& bucketName, const QString& prefix, const QList<QUrl> urls) { uint64_t numFiles = urls.count(); ds3_bulk_object_list *bulkObjList = (ds3_bulk_object_list*)calloc(1, sizeof(ds3_bulk_object_list)); bulkObjList->list = (ds3_bulk_object*)malloc(numFiles * sizeof(ds3_bulk_object)); bulkObjList->size = numFiles; QHash<QString, QString> objMap; QString normPrefix = prefix; if (!normPrefix.isEmpty()) { normPrefix.replace(QRegExp("/$"), ""); normPrefix += "/"; } for (uint64_t i = 0; i < numFiles; i++) { QString filePath = urls[i].path(); QFileInfo fileInfo(filePath); QString fileName = fileInfo.fileName(); QString objName = normPrefix + fileName; uint64_t fileSize = 0; if (fileInfo.isDir()) { objName.replace(QRegExp("/$"), ""); objName += "/"; // TODO Recursively get all files in dir } else { fileSize = fileInfo.size(); } objMap.insert(objName, filePath); ds3_bulk_object* bulkObj = &bulkObjList->list[i]; bulkObj->name = ds3_str_init(objName.toUtf8().constData()); bulkObj->length = fileSize; bulkObj->offset = 0; } ds3_request* request = ds3_init_put_bulk(bucketName.toLocal8Bit().constData(), bulkObjList); ds3_bulk_response *response; ds3_error* error = ds3_bulk(m_client, request, &response); ds3_free_request(request); ds3_free_bulk_object_list(bulkObjList); if (error) { // TODO Handle the error ds3_free_error(error); } for (size_t i = 0; i < response->list_size; i++) { ds3_bulk_object_list* list = response->list[i]; for (uint64_t j = 0; j < list->size; j++) { ds3_bulk_object* bulkObj = &list->list[j]; QString objName = QString(bulkObj->name->value); // TODO objMap only holds objects for URLs that were // passed in and not files that were discovered // underneath directories. Account for that. QString filePath = objMap[objName]; PutObject(bucketName, objName, filePath); } } ds3_free_bulk_response(response); } void Client::PutObject(const QString& bucket, const QString& object, const QString& fileName) { LOG_DEBUG("PUT OBJECT: " + object + ", FILE: " + fileName); QFileInfo fileInfo(fileName); ds3_request* request = ds3_init_put_object(bucket.toUtf8().constData(), object.toUtf8().constData(), fileInfo.size()); ds3_error* error = NULL; if (fileInfo.isDir()) { // "folder" objects don't have a size nor do they have any // data associated with them error = ds3_put_object(m_client, request, NULL, NULL); } else { FILE* file = fopen(fileName.toUtf8().constData(), "r"); if (file == NULL) { LOG_ERROR("PUT object failed: unable to open file " + fileName); } else { error = ds3_put_object(m_client, request, file, ds3_read_from_file); fclose(file); } } ds3_free_request(request); if (error) { // TODO Handle the error ds3_free_error(error); } }
/* * ***************************************************************************** * Copyright 2014 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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 <stdlib.h> #include <string.h> #include <QFileInfo> #include <QHash> #include "lib/client.h" #include "lib/logger.h" #include "models/session.h" Client::Client(const Session* session) { m_creds = ds3_create_creds(session->GetAccessId().toUtf8().constData(), session->GetSecretKey().toUtf8().constData()); QString protocol = session->GetProtocolName(); m_endpoint = protocol + "://" + session->GetHost(); QString port = session->GetPort(); if (!port.isEmpty() && port != "80" && port != "443") { m_endpoint += ":" + port; } m_client = ds3_create_client(m_endpoint.toUtf8().constData(), m_creds); } Client::~Client() { ds3_free_creds(m_creds); ds3_free_client(m_client); ds3_cleanup(); } ds3_get_service_response* Client::GetService() { ds3_get_service_response *response; ds3_request* request = ds3_init_get_service(); LOG_INFO("Get Buckets (GET " + m_endpoint + ")"); ds3_error* error = ds3_get_service(m_client, request, &response); ds3_free_request(request); if (error) { // TODO Handle the error ds3_free_error(error); } return response; } ds3_get_bucket_response* Client::GetBucket(const std::string& bucketName, const std::string& prefix, const std::string& delimiter, const std::string& marker, uint32_t maxKeys) { ds3_get_bucket_response *response; ds3_request* request = ds3_init_get_bucket(bucketName.c_str()); QString logMsg = "List Objects (GET " + m_endpoint + "/"; logMsg += QString::fromStdString(bucketName); QStringList logQueryParams; if (!prefix.empty()) { ds3_request_set_prefix(request, prefix.c_str()); logQueryParams << "prefix=" + QString::fromStdString(prefix); } if (!delimiter.empty()) { ds3_request_set_delimiter(request, delimiter.c_str()); logQueryParams << "delimiter=" + QString::fromStdString(delimiter); } if (!marker.empty()) { ds3_request_set_marker(request, marker.c_str()); logQueryParams << "marker=" + QString::fromStdString(marker); } if (maxKeys > 0) { ds3_request_set_max_keys(request, maxKeys); logQueryParams << "max-keys=" + QString::number(maxKeys); } if (!logQueryParams.isEmpty()) { logMsg += "&" + logQueryParams.join("&"); } logMsg += ")"; LOG_INFO(logMsg); ds3_error* error = ds3_get_bucket(m_client, request, &response); ds3_free_request(request); if (error) { // TODO Handle the error ds3_free_error(error); } return response; } void Client::CreateBucket(const std::string& name) { ds3_request* request = ds3_init_put_bucket(name.c_str()); QString qname = QString::fromStdString(name); LOG_INFO("Create Bucket " + qname + " (PUT " + m_endpoint + "/" + \ qname + ")"); ds3_error* error = ds3_put_bucket(m_client, request); ds3_free_request(request); if (error) { // TODO Handle the error ds3_free_error(error); } } void Client::BulkPut(const QString& bucketName, const QString& prefix, const QList<QUrl> urls) { uint64_t numFiles = urls.count(); ds3_bulk_object_list *bulkObjList = (ds3_bulk_object_list*)calloc(1, sizeof(ds3_bulk_object_list)); bulkObjList->list = (ds3_bulk_object*)malloc(numFiles * sizeof(ds3_bulk_object)); bulkObjList->size = numFiles; QHash<QString, QString> objMap; QString normPrefix = prefix; if (!normPrefix.isEmpty()) { normPrefix.replace(QRegExp("/$"), ""); normPrefix += "/"; } for (uint64_t i = 0; i < numFiles; i++) { QString filePath = urls[i].path(); QFileInfo fileInfo(filePath); QString fileName = fileInfo.fileName(); QString objName = normPrefix + fileName; uint64_t fileSize = 0; if (fileInfo.isDir()) { objName.replace(QRegExp("/$"), ""); objName += "/"; // TODO Recursively get all files in dir } else { fileSize = fileInfo.size(); } objMap.insert(objName, filePath); ds3_bulk_object* bulkObj = &bulkObjList->list[i]; bulkObj->name = ds3_str_init(objName.toUtf8().constData()); bulkObj->length = fileSize; bulkObj->offset = 0; } ds3_request* request = ds3_init_put_bulk(bucketName.toLocal8Bit().constData(), bulkObjList); ds3_bulk_response *response = NULL; ds3_error* error = ds3_bulk(m_client, request, &response); ds3_free_request(request); ds3_free_bulk_object_list(bulkObjList); if (error) { // TODO Handle the error ds3_free_error(error); } if (response == NULL) { // Bulk putting only empty folders will result in a 204 // response (no content) indicating there's nothing else to do. return; } for (size_t i = 0; i < response->list_size; i++) { ds3_bulk_object_list* list = response->list[i]; for (uint64_t j = 0; j < list->size; j++) { ds3_bulk_object* bulkObj = &list->list[j]; QString objName = QString(bulkObj->name->value); // TODO objMap only holds objects for URLs that were // passed in and not files that were discovered // underneath directories. Account for that. QString filePath = objMap[objName]; PutObject(bucketName, objName, filePath); } } ds3_free_bulk_response(response); } void Client::PutObject(const QString& bucket, const QString& object, const QString& fileName) { LOG_DEBUG("PUT OBJECT: " + object + ", FILE: " + fileName); QFileInfo fileInfo(fileName); ds3_request* request = ds3_init_put_object(bucket.toUtf8().constData(), object.toUtf8().constData(), fileInfo.size()); ds3_error* error = NULL; if (fileInfo.isDir()) { // "folder" objects don't have a size nor do they have any // data associated with them error = ds3_put_object(m_client, request, NULL, NULL); } else { FILE* file = fopen(fileName.toUtf8().constData(), "r"); if (file == NULL) { LOG_ERROR("PUT object failed: unable to open file " + fileName); } else { error = ds3_put_object(m_client, request, file, ds3_read_from_file); fclose(file); } } ds3_free_request(request); if (error) { // TODO Handle the error ds3_free_error(error); } }
Fix to allow dragging/dropping only empty folders.
Fix to allow dragging/dropping only empty folders. lib/client.cc: Fix Client::BulkPut to tolerate responses that don't have a body, which is the case when bulk putting one or more empty folders (and no actual objects).
C++
apache-2.0
Klopsch/ds3_browser,Klopsch/ds3_browser,SpectraLogic/ds3_browser,Klopsch/ds3_browser,SpectraLogic/ds3_browser,SpectraLogic/ds3_browser
8ca464705f01a289ec31c728e3b2953b62236346
Modules/Core/Common/src/itkMultiThreaderPThreads.cxx
Modules/Core/Common/src/itkMultiThreaderPThreads.cxx
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkMultiThreader.h" #include "itkObjectFactory.h" #include "itksys/SystemTools.hxx" #include <stdlib.h> #ifdef __APPLE__ #include <sys/types.h> #include <sys/sysctl.h> #endif namespace itk { extern "C" { typedef void *( *c_void_cast )(void *); } ThreadIdType MultiThreader::GetGlobalDefaultNumberOfThreadsByPlatform() { ThreadIdType num; // Default the number of threads to be the number of available // processors if we are using pthreads() #ifdef _SC_NPROCESSORS_ONLN num = sysconf(_SC_NPROCESSORS_ONLN); #elif defined( _SC_NPROC_ONLN ) num = sysconf(_SC_NPROC_ONLN); #else num = 1; #endif #if defined( __SVR4 ) && defined( sun ) && defined( PTHREAD_MUTEX_NORMAL ) pthread_setconcurrency(num); #endif #ifdef __APPLE__ // Determine the number of CPU cores. Prefer sysctlbyname() // over MPProcessors() because it doesn't require CoreServices // (which is only available in 32bit on Mac OS X 10.4). // hw.logicalcpu takes into account cores/CPUs that are // disabled because of power management. size_t dataLen = sizeof( int ); // 'num' is an 'int' int result = sysctlbyname ("hw.logicalcpu", &num, &dataLen, NULL, 0); if ( result == -1 ) { num = 1; } #endif return num; } void MultiThreader::MultipleMethodExecute() { ThreadIdType thread_loop; pthread_t process_id[ITK_MAX_THREADS]; // obey the global maximum number of threads limit if ( m_NumberOfThreads > m_GlobalMaximumNumberOfThreads ) { m_NumberOfThreads = m_GlobalMaximumNumberOfThreads; } for ( thread_loop = 0; thread_loop < m_NumberOfThreads; thread_loop++ ) { if ( m_MultipleMethod[thread_loop] == (ThreadFunctionType)0 ) { itkExceptionMacro(<< "No multiple method set for: " << thread_loop); return; } } // Using POSIX threads // // We want to use pthread_create to start m_NumberOfThreads - 1 // additional // threads which will be used to call the NumberOfThreads-1 methods // defined in m_MultipleMethods[](). The parent thread // will call m_MultipleMethods[NumberOfThreads-1](). When it is done, // it will wait for all the children to finish. // // First, start up the m_NumberOfThreads-1 processes. Keep track // of their process ids for use later in the pthread_join call pthread_attr_t attr; pthread_attr_init(&attr); #ifndef __CYGWIN__ pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); #endif for ( thread_loop = 1; thread_loop < m_NumberOfThreads; thread_loop++ ) { m_ThreadInfoArray[thread_loop].UserData = m_MultipleData[thread_loop]; m_ThreadInfoArray[thread_loop].NumberOfThreads = m_NumberOfThreads; pthread_create( &( process_id[thread_loop] ), &attr, reinterpret_cast< c_void_cast >( m_MultipleMethod[thread_loop] ), ( (void *)( &m_ThreadInfoArray[thread_loop] ) ) ); } // Now, the parent thread calls the last method itself m_ThreadInfoArray[0].UserData = m_MultipleData[0]; m_ThreadInfoArray[0].NumberOfThreads = m_NumberOfThreads; ( m_MultipleMethod[0] )( (void *)( &m_ThreadInfoArray[0] ) ); // The parent thread has finished its method - so now it // waits for each of the other processes to exit for ( thread_loop = 1; thread_loop < m_NumberOfThreads; thread_loop++ ) { pthread_join(process_id[thread_loop], 0); } } int MultiThreader::SpawnThread(ThreadFunctionType f, void *UserData) { int id = 0; while ( id < ITK_MAX_THREADS ) { if ( !m_SpawnedThreadActiveFlagLock[id] ) { m_SpawnedThreadActiveFlagLock[id] = MutexLock::New(); } m_SpawnedThreadActiveFlagLock[id]->Lock(); if ( m_SpawnedThreadActiveFlag[id] == 0 ) { // We've got a useable thread id, so grab it m_SpawnedThreadActiveFlag[id] = 1; m_SpawnedThreadActiveFlagLock[id]->Unlock(); break; } m_SpawnedThreadActiveFlagLock[id]->Unlock(); id++; } if ( id >= ITK_MAX_THREADS ) { itkExceptionMacro(<< "You have too many active threads!"); } m_SpawnedThreadInfoArray[id].UserData = UserData; m_SpawnedThreadInfoArray[id].NumberOfThreads = 1; m_SpawnedThreadInfoArray[id].ActiveFlag = &m_SpawnedThreadActiveFlag[id]; m_SpawnedThreadInfoArray[id].ActiveFlagLock = m_SpawnedThreadActiveFlagLock[id]; pthread_attr_t attr; pthread_attr_init(&attr); #ifndef __CYGWIN__ pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); #endif pthread_create( &( m_SpawnedThreadProcessID[id] ), &attr, reinterpret_cast< c_void_cast >( f ), ( (void *)( &m_SpawnedThreadInfoArray[id] ) ) ); return id; } void MultiThreader::TerminateThread(ThreadIdType ThreadID) { if ( !m_SpawnedThreadActiveFlag[ThreadID] ) { return; } m_SpawnedThreadActiveFlagLock[ThreadID]->Lock(); m_SpawnedThreadActiveFlag[ThreadID] = 0; m_SpawnedThreadActiveFlagLock[ThreadID]->Unlock(); pthread_join(m_SpawnedThreadProcessID[ThreadID], 0); m_SpawnedThreadActiveFlagLock[ThreadID] = 0; m_SpawnedThreadActiveFlagLock[ThreadID] = 0; } void MultiThreader ::WaitForSingleMethodThread(ThreadProcessIDType threadHandle) { // Using POSIX threads if ( pthread_join(threadHandle, 0) ) { itkExceptionMacro(<< "Unable to join thread."); } } ThreadProcessIDType MultiThreader ::DispatchSingleMethodThread(MultiThreader::ThreadInfoStruct *threadInfo) { // Using POSIX threads pthread_attr_t attr; pthread_t threadHandle; pthread_attr_init(&attr); #if !defined( __CYGWIN__ ) pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); #endif int threadError; threadError = pthread_create( &threadHandle, &attr, reinterpret_cast< c_void_cast >( this->SingleMethodProxy ), reinterpret_cast< void * >( threadInfo ) ); if ( threadError != 0 ) { itkExceptionMacro(<< "Unable to create a thread. pthread_create() returned " << threadError); } return threadHandle; } } // end namespace itk
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkMultiThreader.h" #include "itkObjectFactory.h" #include "itksys/SystemTools.hxx" #include <stdlib.h> #ifdef __APPLE__ #include <sys/types.h> #include <sys/sysctl.h> #endif namespace itk { extern "C" { typedef void *( *c_void_cast )(void *); } ThreadIdType MultiThreader::GetGlobalDefaultNumberOfThreadsByPlatform() { ThreadIdType num; // Default the number of threads to be the number of available // processors if we are using pthreads() #ifdef _SC_NPROCESSORS_ONLN num = sysconf(_SC_NPROCESSORS_ONLN); #elif defined( _SC_NPROC_ONLN ) num = sysconf(_SC_NPROC_ONLN); #else num = 1; #endif #if defined( __SVR4 ) && defined( sun ) && defined( PTHREAD_MUTEX_NORMAL ) pthread_setconcurrency(num); #endif #ifdef __APPLE__ // Determine the number of CPU cores. Prefer sysctlbyname() // over MPProcessors() because it doesn't require CoreServices // (which is only available in 32bit on Mac OS X 10.4). // hw.logicalcpu takes into account cores/CPUs that are // disabled because of power management. size_t dataLen = sizeof( int ); // 'num' is an 'int' int result = sysctlbyname ("hw.logicalcpu", &num, &dataLen, NULL, 0); if ( result == -1 ) { num = 1; } #endif return num; } void MultiThreader::MultipleMethodExecute() { ThreadIdType thread_loop; pthread_t process_id[ITK_MAX_THREADS]; // obey the global maximum number of threads limit if ( m_NumberOfThreads > m_GlobalMaximumNumberOfThreads ) { m_NumberOfThreads = m_GlobalMaximumNumberOfThreads; } for ( thread_loop = 0; thread_loop < m_NumberOfThreads; thread_loop++ ) { if ( m_MultipleMethod[thread_loop] == (ThreadFunctionType)0 ) { itkExceptionMacro(<< "No multiple method set for: " << thread_loop); return; } } // Using POSIX threads // // We want to use pthread_create to start m_NumberOfThreads - 1 // additional // threads which will be used to call the NumberOfThreads-1 methods // defined in m_MultipleMethods[](). The parent thread // will call m_MultipleMethods[NumberOfThreads-1](). When it is done, // it will wait for all the children to finish. // // First, start up the m_NumberOfThreads-1 processes. Keep track // of their process ids for use later in the pthread_join call pthread_attr_t attr; pthread_attr_init(&attr); #ifndef __CYGWIN__ pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); #endif for ( thread_loop = 1; thread_loop < m_NumberOfThreads; thread_loop++ ) { m_ThreadInfoArray[thread_loop].UserData = m_MultipleData[thread_loop]; m_ThreadInfoArray[thread_loop].NumberOfThreads = m_NumberOfThreads; int threadError = pthread_create( &( process_id[thread_loop] ), &attr, reinterpret_cast< c_void_cast >( m_MultipleMethod[thread_loop] ), ( (void *)( &m_ThreadInfoArray[thread_loop] ) ) ); if ( threadError != 0 ) { itkExceptionMacro(<< "Unable to create a thread. pthread_create() returned " << threadError); } } // Now, the parent thread calls the last method itself m_ThreadInfoArray[0].UserData = m_MultipleData[0]; m_ThreadInfoArray[0].NumberOfThreads = m_NumberOfThreads; ( m_MultipleMethod[0] )( (void *)( &m_ThreadInfoArray[0] ) ); // The parent thread has finished its method - so now it // waits for each of the other processes to exit for ( thread_loop = 1; thread_loop < m_NumberOfThreads; thread_loop++ ) { pthread_join(process_id[thread_loop], 0); } } int MultiThreader::SpawnThread(ThreadFunctionType f, void *UserData) { int id = 0; while ( id < ITK_MAX_THREADS ) { if ( !m_SpawnedThreadActiveFlagLock[id] ) { m_SpawnedThreadActiveFlagLock[id] = MutexLock::New(); } m_SpawnedThreadActiveFlagLock[id]->Lock(); if ( m_SpawnedThreadActiveFlag[id] == 0 ) { // We've got a useable thread id, so grab it m_SpawnedThreadActiveFlag[id] = 1; m_SpawnedThreadActiveFlagLock[id]->Unlock(); break; } m_SpawnedThreadActiveFlagLock[id]->Unlock(); id++; } if ( id >= ITK_MAX_THREADS ) { itkExceptionMacro(<< "You have too many active threads!"); } m_SpawnedThreadInfoArray[id].UserData = UserData; m_SpawnedThreadInfoArray[id].NumberOfThreads = 1; m_SpawnedThreadInfoArray[id].ActiveFlag = &m_SpawnedThreadActiveFlag[id]; m_SpawnedThreadInfoArray[id].ActiveFlagLock = m_SpawnedThreadActiveFlagLock[id]; pthread_attr_t attr; pthread_attr_init(&attr); #ifndef __CYGWIN__ pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); #endif int threadError = pthread_create( &( m_SpawnedThreadProcessID[id] ), &attr, reinterpret_cast< c_void_cast >( f ), ( (void *)( &m_SpawnedThreadInfoArray[id] ) ) ); if ( threadError != 0 ) { itkExceptionMacro(<< "Unable to create a thread. pthread_create() returned " << threadError); } return id; } void MultiThreader::TerminateThread(ThreadIdType ThreadID) { if ( !m_SpawnedThreadActiveFlag[ThreadID] ) { return; } m_SpawnedThreadActiveFlagLock[ThreadID]->Lock(); m_SpawnedThreadActiveFlag[ThreadID] = 0; m_SpawnedThreadActiveFlagLock[ThreadID]->Unlock(); pthread_join(m_SpawnedThreadProcessID[ThreadID], 0); m_SpawnedThreadActiveFlagLock[ThreadID] = 0; m_SpawnedThreadActiveFlagLock[ThreadID] = 0; } void MultiThreader ::WaitForSingleMethodThread(ThreadProcessIDType threadHandle) { // Using POSIX threads if ( pthread_join(threadHandle, 0) ) { itkExceptionMacro(<< "Unable to join thread."); } } ThreadProcessIDType MultiThreader ::DispatchSingleMethodThread(MultiThreader::ThreadInfoStruct *threadInfo) { // Using POSIX threads pthread_attr_t attr; pthread_t threadHandle; pthread_attr_init(&attr); #if !defined( __CYGWIN__ ) pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); #endif int threadError; threadError = pthread_create( &threadHandle, &attr, reinterpret_cast< c_void_cast >( this->SingleMethodProxy ), reinterpret_cast< void * >( threadInfo ) ); if ( threadError != 0 ) { itkExceptionMacro(<< "Unable to create a thread. pthread_create() returned " << threadError); } return threadHandle; } } // end namespace itk
Check pthread_create return value.
BUG: Check pthread_create return value. In some cases, the pthread_create() call was not checking its return value, which can cause segmentation faults under certain circumstances. Change-Id: I784e8c5bb38235dfc51aa31e84a67535907a6bbc
C++
apache-2.0
hendradarwin/ITK,GEHC-Surgery/ITK,InsightSoftwareConsortium/ITK,msmolens/ITK,biotrump/ITK,fbudin69500/ITK,paulnovo/ITK,biotrump/ITK,thewtex/ITK,biotrump/ITK,fuentesdt/InsightToolkit-dev,eile/ITK,jmerkow/ITK,atsnyder/ITK,PlutoniumHeart/ITK,LucasGandel/ITK,BlueBrain/ITK,rhgong/itk-with-dom,richardbeare/ITK,BRAINSia/ITK,stnava/ITK,richardbeare/ITK,Kitware/ITK,GEHC-Surgery/ITK,Kitware/ITK,hinerm/ITK,hjmjohnson/ITK,vfonov/ITK,jmerkow/ITK,spinicist/ITK,heimdali/ITK,BlueBrain/ITK,PlutoniumHeart/ITK,heimdali/ITK,atsnyder/ITK,LucHermitte/ITK,atsnyder/ITK,vfonov/ITK,stnava/ITK,jmerkow/ITK,hendradarwin/ITK,thewtex/ITK,heimdali/ITK,PlutoniumHeart/ITK,zachary-williamson/ITK,InsightSoftwareConsortium/ITK,fbudin69500/ITK,Kitware/ITK,ajjl/ITK,hinerm/ITK,BRAINSia/ITK,vfonov/ITK,fuentesdt/InsightToolkit-dev,LucHermitte/ITK,spinicist/ITK,fedral/ITK,paulnovo/ITK,msmolens/ITK,zachary-williamson/ITK,malaterre/ITK,Kitware/ITK,LucHermitte/ITK,GEHC-Surgery/ITK,ajjl/ITK,BRAINSia/ITK,rhgong/itk-with-dom,stnava/ITK,blowekamp/ITK,paulnovo/ITK,Kitware/ITK,msmolens/ITK,ajjl/ITK,malaterre/ITK,jcfr/ITK,heimdali/ITK,fedral/ITK,BRAINSia/ITK,eile/ITK,ajjl/ITK,jmerkow/ITK,msmolens/ITK,BlueBrain/ITK,fuentesdt/InsightToolkit-dev,blowekamp/ITK,vfonov/ITK,zachary-williamson/ITK,fbudin69500/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,hjmjohnson/ITK,fedral/ITK,malaterre/ITK,fuentesdt/InsightToolkit-dev,msmolens/ITK,jmerkow/ITK,LucasGandel/ITK,LucHermitte/ITK,stnava/ITK,malaterre/ITK,spinicist/ITK,BlueBrain/ITK,fuentesdt/InsightToolkit-dev,hendradarwin/ITK,blowekamp/ITK,Kitware/ITK,vfonov/ITK,eile/ITK,atsnyder/ITK,jmerkow/ITK,thewtex/ITK,zachary-williamson/ITK,paulnovo/ITK,paulnovo/ITK,vfonov/ITK,jcfr/ITK,BRAINSia/ITK,stnava/ITK,fedral/ITK,zachary-williamson/ITK,atsnyder/ITK,blowekamp/ITK,msmolens/ITK,LucasGandel/ITK,hjmjohnson/ITK,BlueBrain/ITK,paulnovo/ITK,GEHC-Surgery/ITK,rhgong/itk-with-dom,InsightSoftwareConsortium/ITK,thewtex/ITK,blowekamp/ITK,fbudin69500/ITK,ajjl/ITK,biotrump/ITK,thewtex/ITK,spinicist/ITK,malaterre/ITK,thewtex/ITK,LucasGandel/ITK,richardbeare/ITK,BlueBrain/ITK,rhgong/itk-with-dom,hinerm/ITK,jmerkow/ITK,jcfr/ITK,paulnovo/ITK,heimdali/ITK,spinicist/ITK,LucHermitte/ITK,hjmjohnson/ITK,biotrump/ITK,fuentesdt/InsightToolkit-dev,biotrump/ITK,jcfr/ITK,LucHermitte/ITK,GEHC-Surgery/ITK,PlutoniumHeart/ITK,spinicist/ITK,hendradarwin/ITK,stnava/ITK,fedral/ITK,atsnyder/ITK,msmolens/ITK,stnava/ITK,jcfr/ITK,fuentesdt/InsightToolkit-dev,hendradarwin/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,jcfr/ITK,GEHC-Surgery/ITK,jcfr/ITK,eile/ITK,malaterre/ITK,PlutoniumHeart/ITK,zachary-williamson/ITK,hjmjohnson/ITK,hinerm/ITK,hinerm/ITK,LucasGandel/ITK,PlutoniumHeart/ITK,atsnyder/ITK,fbudin69500/ITK,eile/ITK,hendradarwin/ITK,InsightSoftwareConsortium/ITK,BlueBrain/ITK,fedral/ITK,zachary-williamson/ITK,jcfr/ITK,hendradarwin/ITK,eile/ITK,paulnovo/ITK,jmerkow/ITK,ajjl/ITK,BlueBrain/ITK,heimdali/ITK,blowekamp/ITK,hinerm/ITK,zachary-williamson/ITK,hinerm/ITK,spinicist/ITK,blowekamp/ITK,fuentesdt/InsightToolkit-dev,atsnyder/ITK,biotrump/ITK,LucHermitte/ITK,vfonov/ITK,fedral/ITK,vfonov/ITK,BRAINSia/ITK,spinicist/ITK,malaterre/ITK,richardbeare/ITK,ajjl/ITK,eile/ITK,spinicist/ITK,fbudin69500/ITK,rhgong/itk-with-dom,rhgong/itk-with-dom,Kitware/ITK,fuentesdt/InsightToolkit-dev,fbudin69500/ITK,GEHC-Surgery/ITK,thewtex/ITK,heimdali/ITK,blowekamp/ITK,BRAINSia/ITK,hjmjohnson/ITK,biotrump/ITK,ajjl/ITK,fedral/ITK,eile/ITK,hjmjohnson/ITK,heimdali/ITK,PlutoniumHeart/ITK,PlutoniumHeart/ITK,richardbeare/ITK,hinerm/ITK,hendradarwin/ITK,InsightSoftwareConsortium/ITK,eile/ITK,LucasGandel/ITK,malaterre/ITK,richardbeare/ITK,LucHermitte/ITK,GEHC-Surgery/ITK,stnava/ITK,vfonov/ITK,rhgong/itk-with-dom,hinerm/ITK,rhgong/itk-with-dom,LucasGandel/ITK,fbudin69500/ITK,atsnyder/ITK,LucasGandel/ITK,zachary-williamson/ITK,malaterre/ITK,msmolens/ITK
bec4c85601a5ca356daa320327425f915d142152
content/common/fileapi/file_system_dispatcher.cc
content/common/fileapi/file_system_dispatcher.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/fileapi/file_system_dispatcher.h" #include "base/file_util.h" #include "base/process.h" #include "content/common/child_thread.h" #include "content/common/fileapi/file_system_messages.h" namespace content { FileSystemDispatcher::FileSystemDispatcher() { } FileSystemDispatcher::~FileSystemDispatcher() { // Make sure we fire all the remaining callbacks. for (IDMap<fileapi::FileSystemCallbackDispatcher, IDMapOwnPointer>::iterator iter(&dispatchers_); !iter.IsAtEnd(); iter.Advance()) { int request_id = iter.GetCurrentKey(); fileapi::FileSystemCallbackDispatcher* dispatcher = iter.GetCurrentValue(); DCHECK(dispatcher); dispatcher->DidFail(base::PLATFORM_FILE_ERROR_ABORT); dispatchers_.Remove(request_id); } } bool FileSystemDispatcher::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(FileSystemDispatcher, msg) IPC_MESSAGE_HANDLER(FileSystemMsg_DidOpenFileSystem, OnDidOpenFileSystem) IPC_MESSAGE_HANDLER(FileSystemMsg_DidSucceed, OnDidSucceed) IPC_MESSAGE_HANDLER(FileSystemMsg_DidReadDirectory, OnDidReadDirectory) IPC_MESSAGE_HANDLER(FileSystemMsg_DidReadMetadata, OnDidReadMetadata) IPC_MESSAGE_HANDLER(FileSystemMsg_DidFail, OnDidFail) IPC_MESSAGE_HANDLER(FileSystemMsg_DidWrite, OnDidWrite) IPC_MESSAGE_HANDLER(FileSystemMsg_DidOpenFile, OnDidOpenFile) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } bool FileSystemDispatcher::OpenFileSystem( const GURL& origin_url, fileapi::FileSystemType type, long long size, bool create, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_Open( request_id, origin_url, type, size, create))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::DeleteFileSystem( const GURL& origin_url, fileapi::FileSystemType type, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_DeleteFileSystem( request_id, origin_url, type))) { dispatchers_.Remove(request_id); return false; } return true; } bool FileSystemDispatcher::Move( const GURL& src_path, const GURL& dest_path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_Move( request_id, src_path, dest_path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Copy( const GURL& src_path, const GURL& dest_path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_Copy( request_id, src_path, dest_path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Remove( const GURL& path, bool recursive, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemMsg_Remove(request_id, path, recursive))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::ReadMetadata( const GURL& path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_ReadMetadata(request_id, path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Create( const GURL& path, bool exclusive, bool is_directory, bool recursive, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_Create( request_id, path, exclusive, is_directory, recursive))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Exists( const GURL& path, bool is_directory, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_Exists(request_id, path, is_directory))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::ReadDirectory( const GURL& path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_ReadDirectory(request_id, path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Truncate( const GURL& path, int64 offset, int* request_id_out, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_Truncate(request_id, path, offset))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } if (request_id_out) *request_id_out = request_id; return true; } bool FileSystemDispatcher::Write( const GURL& path, const GURL& blob_url, int64 offset, int* request_id_out, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_Write(request_id, path, blob_url, offset))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } if (request_id_out) *request_id_out = request_id; return true; } bool FileSystemDispatcher::Cancel( int request_id_to_cancel, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_CancelWrite( request_id, request_id_to_cancel))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::TouchFile( const GURL& path, const base::Time& last_access_time, const base::Time& last_modified_time, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_TouchFile( request_id, path, last_access_time, last_modified_time))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::OpenFile( const GURL& file_path, int file_flags, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_OpenFile( request_id, file_path, file_flags))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::NotifyCloseFile(const GURL& file_path) { return ChildThread::current()->Send( new FileSystemHostMsg_NotifyCloseFile(file_path)); } bool FileSystemDispatcher::CreateSnapshotFile( const GURL& file_path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_CreateSnapshotFile( request_id, file_path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::CreateSnapshotFile_Deprecated( const GURL& blob_url, const GURL& file_path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_CreateSnapshotFile_Deprecated( request_id, blob_url, file_path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } void FileSystemDispatcher::OnDidOpenFileSystem(int request_id, const std::string& name, const GURL& root) { DCHECK(root.is_valid()); fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidOpenFileSystem(name, root); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidSucceed(int request_id) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidSucceed(); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidReadMetadata( int request_id, const base::PlatformFileInfo& file_info, const base::FilePath& platform_path) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidReadMetadata(file_info, platform_path); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidCreateSnapshotFile( int request_id, const base::PlatformFileInfo& file_info, const base::FilePath& platform_path) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidCreateSnapshotFile(file_info, platform_path); dispatchers_.Remove(request_id); ChildThread::current()->Send( new FileSystemHostMsg_DidReceiveSnapshotFile(request_id)); } void FileSystemDispatcher::OnDidReadDirectory( int request_id, const std::vector<base::FileUtilProxy::Entry>& entries, bool has_more) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidReadDirectory(entries, has_more); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidFail( int request_id, base::PlatformFileError error_code) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidFail(error_code); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidWrite( int request_id, int64 bytes, bool complete) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidWrite(bytes, complete); if (complete) dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidOpenFile( int request_id, IPC::PlatformFileForTransit file) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidOpenFile(IPC::PlatformFileForTransitToPlatformFile(file)); dispatchers_.Remove(request_id); } } // namespace content
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/fileapi/file_system_dispatcher.h" #include "base/file_util.h" #include "base/process.h" #include "content/common/child_thread.h" #include "content/common/fileapi/file_system_messages.h" namespace content { FileSystemDispatcher::FileSystemDispatcher() { } FileSystemDispatcher::~FileSystemDispatcher() { // Make sure we fire all the remaining callbacks. for (IDMap<fileapi::FileSystemCallbackDispatcher, IDMapOwnPointer>::iterator iter(&dispatchers_); !iter.IsAtEnd(); iter.Advance()) { int request_id = iter.GetCurrentKey(); fileapi::FileSystemCallbackDispatcher* dispatcher = iter.GetCurrentValue(); DCHECK(dispatcher); dispatcher->DidFail(base::PLATFORM_FILE_ERROR_ABORT); dispatchers_.Remove(request_id); } } bool FileSystemDispatcher::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(FileSystemDispatcher, msg) IPC_MESSAGE_HANDLER(FileSystemMsg_DidOpenFileSystem, OnDidOpenFileSystem) IPC_MESSAGE_HANDLER(FileSystemMsg_DidSucceed, OnDidSucceed) IPC_MESSAGE_HANDLER(FileSystemMsg_DidReadDirectory, OnDidReadDirectory) IPC_MESSAGE_HANDLER(FileSystemMsg_DidReadMetadata, OnDidReadMetadata) IPC_MESSAGE_HANDLER(FileSystemMsg_DidCreateSnapshotFile, OnDidCreateSnapshotFile) IPC_MESSAGE_HANDLER(FileSystemMsg_DidFail, OnDidFail) IPC_MESSAGE_HANDLER(FileSystemMsg_DidWrite, OnDidWrite) IPC_MESSAGE_HANDLER(FileSystemMsg_DidOpenFile, OnDidOpenFile) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } bool FileSystemDispatcher::OpenFileSystem( const GURL& origin_url, fileapi::FileSystemType type, long long size, bool create, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_Open( request_id, origin_url, type, size, create))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::DeleteFileSystem( const GURL& origin_url, fileapi::FileSystemType type, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_DeleteFileSystem( request_id, origin_url, type))) { dispatchers_.Remove(request_id); return false; } return true; } bool FileSystemDispatcher::Move( const GURL& src_path, const GURL& dest_path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_Move( request_id, src_path, dest_path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Copy( const GURL& src_path, const GURL& dest_path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_Copy( request_id, src_path, dest_path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Remove( const GURL& path, bool recursive, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemMsg_Remove(request_id, path, recursive))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::ReadMetadata( const GURL& path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_ReadMetadata(request_id, path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Create( const GURL& path, bool exclusive, bool is_directory, bool recursive, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_Create( request_id, path, exclusive, is_directory, recursive))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Exists( const GURL& path, bool is_directory, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_Exists(request_id, path, is_directory))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::ReadDirectory( const GURL& path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_ReadDirectory(request_id, path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::Truncate( const GURL& path, int64 offset, int* request_id_out, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_Truncate(request_id, path, offset))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } if (request_id_out) *request_id_out = request_id; return true; } bool FileSystemDispatcher::Write( const GURL& path, const GURL& blob_url, int64 offset, int* request_id_out, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_Write(request_id, path, blob_url, offset))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } if (request_id_out) *request_id_out = request_id; return true; } bool FileSystemDispatcher::Cancel( int request_id_to_cancel, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send(new FileSystemHostMsg_CancelWrite( request_id, request_id_to_cancel))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::TouchFile( const GURL& path, const base::Time& last_access_time, const base::Time& last_modified_time, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_TouchFile( request_id, path, last_access_time, last_modified_time))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::OpenFile( const GURL& file_path, int file_flags, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_OpenFile( request_id, file_path, file_flags))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::NotifyCloseFile(const GURL& file_path) { return ChildThread::current()->Send( new FileSystemHostMsg_NotifyCloseFile(file_path)); } bool FileSystemDispatcher::CreateSnapshotFile( const GURL& file_path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_CreateSnapshotFile( request_id, file_path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } bool FileSystemDispatcher::CreateSnapshotFile_Deprecated( const GURL& blob_url, const GURL& file_path, fileapi::FileSystemCallbackDispatcher* dispatcher) { int request_id = dispatchers_.Add(dispatcher); if (!ChildThread::current()->Send( new FileSystemHostMsg_CreateSnapshotFile_Deprecated( request_id, blob_url, file_path))) { dispatchers_.Remove(request_id); // destroys |dispatcher| return false; } return true; } void FileSystemDispatcher::OnDidOpenFileSystem(int request_id, const std::string& name, const GURL& root) { DCHECK(root.is_valid()); fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidOpenFileSystem(name, root); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidSucceed(int request_id) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidSucceed(); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidReadMetadata( int request_id, const base::PlatformFileInfo& file_info, const base::FilePath& platform_path) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidReadMetadata(file_info, platform_path); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidCreateSnapshotFile( int request_id, const base::PlatformFileInfo& file_info, const base::FilePath& platform_path) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidCreateSnapshotFile(file_info, platform_path); dispatchers_.Remove(request_id); ChildThread::current()->Send( new FileSystemHostMsg_DidReceiveSnapshotFile(request_id)); } void FileSystemDispatcher::OnDidReadDirectory( int request_id, const std::vector<base::FileUtilProxy::Entry>& entries, bool has_more) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidReadDirectory(entries, has_more); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidFail( int request_id, base::PlatformFileError error_code) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidFail(error_code); dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidWrite( int request_id, int64 bytes, bool complete) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidWrite(bytes, complete); if (complete) dispatchers_.Remove(request_id); } void FileSystemDispatcher::OnDidOpenFile( int request_id, IPC::PlatformFileForTransit file) { fileapi::FileSystemCallbackDispatcher* dispatcher = dispatchers_.Lookup(request_id); DCHECK(dispatcher); dispatcher->DidOpenFile(IPC::PlatformFileForTransitToPlatformFile(file)); dispatchers_.Remove(request_id); } } // namespace content
Fix a boneheaded problem introduced in r182822. Review URL: https://codereview.chromium.org/12388058
Fix a boneheaded problem introduced in r182822. Review URL: https://codereview.chromium.org/12388058 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@185974 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,hujiajie/pa-chromium,littlstar/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,hujiajie/pa-chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,patrickm/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk,littlstar/chromium.src,fujunwei/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,ltilve/chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,patrickm/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,jaruba/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,hujiajie/pa-chromium,timopulkkinen/BubbleFish,markYoungH/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,Just-D/chromium-1,ltilve/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,Chilledheart/chromium,Fireblend/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,ondra-novak/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,dednal/chromium.src,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,hgl888/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,anirudhSK/chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,Jonekee/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,M4sse/chromium.src
f635caa3a1b4e6f07040d48328d110cb16e8f2ff
vespalib/src/vespa/vespalib/net/tls/policy_checking_certificate_verifier.cpp
vespalib/src/vespa/vespalib/net/tls/policy_checking_certificate_verifier.cpp
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "policy_checking_certificate_verifier.h" namespace vespalib::net::tls { namespace { bool matches_single_san_requirement(const PeerCredentials& peer_creds, const RequiredPeerCredential& requirement) { for (auto& provided_cred : peer_creds.dns_sans) { if (requirement.matches(provided_cred)) { return true; } } return false; } bool matches_cn_requirement(const PeerCredentials& peer_creds, const RequiredPeerCredential& requirement) { return requirement.matches(peer_creds.common_name); } bool matches_all_policy_requirements(const PeerCredentials& peer_creds, const PeerPolicy& policy) { for (auto& required_cred : policy.required_peer_credentials()) { switch (required_cred.field()) { case RequiredPeerCredential::Field::SAN_DNS: if (!matches_single_san_requirement(peer_creds, required_cred)) { return false; } continue; case RequiredPeerCredential::Field::CN: if (!matches_cn_requirement(peer_creds, required_cred)) { return false; } continue; } abort(); } return true; } } // anon ns class PolicyConfiguredCertificateVerifier : public CertificateVerificationCallback { AllowedPeers _allowed_peers; public: explicit PolicyConfiguredCertificateVerifier(AllowedPeers allowed_peers); ~PolicyConfiguredCertificateVerifier() override; bool verify(const PeerCredentials& peer_creds) const override; }; PolicyConfiguredCertificateVerifier::PolicyConfiguredCertificateVerifier(AllowedPeers allowed_peers) : _allowed_peers(std::move(allowed_peers)) {} PolicyConfiguredCertificateVerifier::~PolicyConfiguredCertificateVerifier() = default; bool PolicyConfiguredCertificateVerifier::verify(const PeerCredentials& peer_creds) const { if (_allowed_peers.allows_all_authenticated()) { return true; } for (auto& policy : _allowed_peers.peer_policies()) { if (matches_all_policy_requirements(peer_creds, policy)) { return true; } } return false; } std::shared_ptr<CertificateVerificationCallback> create_verify_callback_from(AllowedPeers allowed_peers) { return std::make_shared<PolicyConfiguredCertificateVerifier>(std::move(allowed_peers)); } } // vespalib::net::tls
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "policy_checking_certificate_verifier.h" namespace vespalib::net::tls { namespace { bool matches_single_san_requirement(const PeerCredentials& peer_creds, const RequiredPeerCredential& requirement) { for (const auto& provided_cred : peer_creds.dns_sans) { if (requirement.matches(provided_cred)) { return true; } } return false; } bool matches_cn_requirement(const PeerCredentials& peer_creds, const RequiredPeerCredential& requirement) { return requirement.matches(peer_creds.common_name); } bool matches_all_policy_requirements(const PeerCredentials& peer_creds, const PeerPolicy& policy) { for (const auto& required_cred : policy.required_peer_credentials()) { switch (required_cred.field()) { case RequiredPeerCredential::Field::SAN_DNS: if (!matches_single_san_requirement(peer_creds, required_cred)) { return false; } continue; case RequiredPeerCredential::Field::CN: if (!matches_cn_requirement(peer_creds, required_cred)) { return false; } continue; } abort(); } return true; } } // anon ns class PolicyConfiguredCertificateVerifier : public CertificateVerificationCallback { AllowedPeers _allowed_peers; public: explicit PolicyConfiguredCertificateVerifier(AllowedPeers allowed_peers); ~PolicyConfiguredCertificateVerifier() override; bool verify(const PeerCredentials& peer_creds) const override; }; PolicyConfiguredCertificateVerifier::PolicyConfiguredCertificateVerifier(AllowedPeers allowed_peers) : _allowed_peers(std::move(allowed_peers)) {} PolicyConfiguredCertificateVerifier::~PolicyConfiguredCertificateVerifier() = default; bool PolicyConfiguredCertificateVerifier::verify(const PeerCredentials& peer_creds) const { if (_allowed_peers.allows_all_authenticated()) { return true; } for (const auto& policy : _allowed_peers.peer_policies()) { if (matches_all_policy_requirements(peer_creds, policy)) { return true; } } return false; } std::shared_ptr<CertificateVerificationCallback> create_verify_callback_from(AllowedPeers allowed_peers) { return std::make_shared<PolicyConfiguredCertificateVerifier>(std::move(allowed_peers)); } } // vespalib::net::tls
Use explicit `const` for `auto`
Use explicit `const` for `auto`
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
683f77e0334bec67246d84ec05618fbf31e19559
utils/image.cc
utils/image.cc
#include "utils.hpp" #include "image.hpp" #include <cerrno> #include <cstdio> #include <cassert> const Color Image::red(1, 0, 0); const Color Image::green(0, 1, 0); const Color Image::blue(0, 0, 1); const Color Image::black(0, 0, 0); const Color Image::white(1, 1, 1); const Color somecolors[] = { Color(0.0, 0.6, 0.0), // Dark green Color(0.0, 0.0, 0.6), // Dark blue Color(0.5, 0.0, 0.5), // Purple Color(1.0, 0.54, 0.0), // Dark orange Color(0.28, 0.24, 0.55), // Slate blue Color(0.42, 0.56, 0.14), // Olive drab Color(0.25, 0.80, 0.80), // "Skyish" Color(0.80, 0.80, 0.20), // Mustard }; const unsigned int Nsomecolors = sizeof(somecolors) / sizeof(somecolors[0]); Image::Image(unsigned int width, unsigned int height, const char *t) : w(width), h(height), title(t), data(NULL) { } Image::~Image(void) { while (!comps.empty()) { delete comps.back(); comps.pop_back(); } if (data) delete[] data; } void Image::save(const char *path, bool usletter, int marginpt) const { FILE *f = fopen(path, "w"); if (!f) fatalx(errno, "Failed to open %s for writing\n", path); output(f, usletter, marginpt); fclose(f); } void Image::output(FILE *out, bool usletter, int marginpt) const { if (marginpt < 0) marginpt = usletter ? 72/2 : 0; /* 72/2 pt == ½ in */ if (usletter) outputhdr_usletter(out, marginpt); else outputhdr(out, marginpt); if (data) outputdata(out); for (unsigned int i = 0; i < comps.size(); i++) { fputc('\n', out); comps[i]->write(out); } fprintf(out, "showpage\n"); } enum { Widthpt = 612, /* pts == 8.5 in */ Heightpt = 792, /* pts = 11 in */ }; void Image::outputhdr_usletter(FILE *out, unsigned int marginpt) const { fprintf(out, "%%!PS-Adobe-3.0\n"); fprintf(out, "%%%%Creator: UNH-AI C++ Search Framework\n"); fprintf(out, "%%%%Title: %s\n", title.c_str()); fprintf(out, "%%%%BoundingBox: 0 0 %u %u\n", Widthpt, Heightpt); fprintf(out, "%%%%EndComments\n"); double maxw = Widthpt - marginpt * 2, maxh = Heightpt - marginpt * 2; double scalex = maxw / w, scaley = maxh / h; double transx = marginpt, transy = -(Heightpt - h * scalex) / 2; double scale = scalex; if (scaley < scalex) { scale = scaley; transx = (Widthpt - w * scaley) / 2; } fprintf(out, "%g %g translate\n", transx, transy); fprintf(out, "%g %g scale\n", scale, scale); } void Image::outputhdr(FILE *out, unsigned int marginpt) const { fprintf(out, "%%!PS-Adobe-3.0\n"); fprintf(out, "%%%%Creator: UNH-AI C++ Search Framework\n"); fprintf(out, "%%%%Title: %s\n", title.c_str()); fprintf(out, "%%%%BoundingBox: 0 0 %u %u\n", w + 2 * marginpt, h + 2 * marginpt); fprintf(out, "%%%%EndComments\n"); fprintf(out, "%u %u translate\n", marginpt, marginpt); } void Image::outputdata(FILE *out) const { fprintf(out, "\n%% Image data\n"); fprintf(out, "gsave\n"); fprintf(out, "%u %u scale %% scale pixels to points\n", w, h); fprintf(out, "%u %u 8 [%u 0 0 %u 0 0] ", w, h, w, h); fprintf(out, "%% width height colordepth transform\n"); fprintf(out, "/datasource currentfile "); fprintf(out, "/ASCII85Decode filter /RunLengthDecode filter def\n"); fprintf(out, "/datastring %u string def ", w * 3); fprintf(out, "%% %u = width * color components\n", w * 3); fprintf(out, "{datasource datastring readstring pop}\n"); fprintf(out, "false %% false == single data source (rgb)\n"); fprintf(out, "3 %% number of color components\n"); fprintf(out, "colorimage\n"); std::string encoded; encodedata(encoded); fprintf(out, "%s\n", encoded.c_str()); fprintf(out, "grestore\n"); } void Image::encodedata(std::string &dst) const { std::string cs; for (unsigned int i = 0; i < w * h; i++) { cs.push_back(data[i].getred255()); cs.push_back(data[i].getgreen255()); cs.push_back(data[i].getblue255()); } std::string rlenc; runlenenc(rlenc, cs); ascii85enc(dst, rlenc); dst.push_back('~'); dst.push_back('>'); } Image::Path::~Path(void) { while (!segs.empty()) { delete segs.back(); segs.pop_back(); } } void Image::Path::write(FILE *out) const { fprintf(out, "%% Path\n"); fprintf(out, "newpath\n"); for (unsigned int i = 0; i < segs.size(); i++) segs[i]->write(out); if (_closepath) fprintf(out, "closepath\n"); if (!_fill) fprintf(out, "stroke\n"); else fprintf(out, "fill\n"); } void Image::Path::LineJoin::write(FILE *out) const { fprintf(out, "%d setlinejoin\n", type); } void Image::Path::MoveTo::write(FILE *out) const { fprintf(out, "%g %g moveto\n", x, y); } Image::Path::Loc Image::Path::MoveTo::move(Loc p) const { return Loc(std::pair<double,double>(x, y)); } void Image::Path::LineTo::write(FILE *out) const { fprintf(out, "%g %g lineto\n", x, y); } Image::Path::Loc Image::Path::LineTo::move(Loc p) const { return Loc(std::pair<double,double>(x, y)); } void Image::Path::SetLineWidth::write(FILE *out) const { fprintf(out, "%g setlinewidth\n", w); } void Image::Path::SetColor::write(FILE *out) const { fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); } void Image::Path::Arc::write(FILE *out) const { const char *fun = "arc"; if (dt < 0) fun = "arcn"; fprintf(out, "%g %g %g %g %g %s\n", x, y, r, t, t + dt, fun); } Image::Path::Loc Image::Path::Arc::move(Loc p) const { double x1 = x + r * cos((t + dt) * M_PI / 180); double y1 = y + r * sin((t + dt) * M_PI / 180); return Loc(std::pair<double,double>(x1, y1)); } static bool dbleq(double a, double b) { static const double Epsilon = 0.01; return fabs(a - b) < Epsilon; } void Image::Path::line(double x0, double y0, double x1, double y1) { if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(new LineTo(x1, y1)); } void Image::Path::nauticalcurve(double xc, double yc, double r, double t, double dt) { NauticalArc *a = new NauticalArc(xc, yc, r, t, dt); double x0 = xc + a->r * cos(a->t * M_PI / 180); double y0 = yc + a->r * sin(a->t * M_PI / 180); if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(a); } void Image::Path::curve(double xc, double yc, double r, double t, double dt) { Arc *a = new Arc(xc, yc, r, t, dt); double x0 = xc + a->r * cos(a->t * M_PI / 180); double y0 = yc + a->r * sin(a->t * M_PI / 180); if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(a); } void Image::Text::write(FILE *out) const { fprintf(out, "%% Text\n"); fprintf(out, "/%s findfont %g scalefont setfont\n", font.c_str(), sz); fprintf(out, "%u %u moveto\n", x, y); fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fprintf(out, "(%s) ", text.c_str()); switch (pos) { case Left: fprintf(out, "show\n"); break; case Right: fprintf(out, "dup stringwidth pop neg 0 rmoveto show\n"); break; case Centered: fprintf(out, "dup stringwidth pop 2 div neg 0 rmoveto show\n"); break; default: fatal("Unknown text position: %d\n", pos); } } void Image::Triangle::write(FILE *out) const { double wrad = w * M_PI / 180; double rotrad = rot * M_PI / 180; double side = ht / cos(wrad / 2); double xtop = ht / 2; double xbot = -ht / 2; double y1 = side * sin(wrad / 2); double y2 = -side * sin(wrad / 2); double x0r = xtop * cos(rotrad); double y0r = xtop * sin(rotrad); double x1r = xbot * cos(rotrad) - y1 * sin(rotrad); double y1r = xbot * sin(rotrad) + y1 * cos(rotrad); double x2r = xbot * cos(rotrad) - y2 * sin(rotrad); double y2r = xbot * sin(rotrad) + y2 * cos(rotrad); fprintf(out, "%% Triangle\n"); fprintf(out, "newpath\n"); fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); if (linewidth >= 0) fprintf(out, "%g setlinewidth\n", linewidth); else fprintf(out, "0.1 setlinewidth\n"); fprintf(out, "%g %g moveto\n", x0r + x, y0r + y); fprintf(out, "%g %g lineto\n", x1r + x, y1r + y); fprintf(out, "%g %g lineto\n", x2r + x, y2r + y); fprintf(out, "closepath\n"); if (linewidth < 0) fprintf(out, "fill\n"); else fprintf(out, "stroke\n"); } void Image::Circle::write(FILE *out) const { fprintf(out, "%% Circle\n"); const char *finish = "stroke"; if (lwidth <= 0) { finish = "fill"; fprintf(out, "0.1 setlinewidth\n"); } else { fprintf(out, "%g setlinewidth\n", lwidth); } fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fprintf(out, "newpath %g %g %g 0 360 arc %s\n", x, y, r, finish); } void Image::Rect::write(FILE *out) const { fprintf(out, "%% Rect\n"); const char *finish = "stroke"; if (lwidth <= 0) { finish = "fill"; fprintf(out, "0.1 setlinewidth\n"); } else { fprintf(out, "%g setlinewidth\n", lwidth); } fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fputs("0 setlinejoin\n", out); fputs("newpath\n", out); fprintf(out, "%g %g moveto\n", x, y); fprintf(out, "%g %g lineto\n", x + w, y); fprintf(out, "%g %g lineto\n", x + w, y + h); fprintf(out, "%g %g lineto\n", x, y + h); fprintf(out, "closepath\n%s\n", finish); }
#include "utils.hpp" #include "image.hpp" #include <cerrno> #include <cstdio> #include <cassert> const Color Image::red(1, 0, 0); const Color Image::green(0, 1, 0); const Color Image::blue(0, 0, 1); const Color Image::black(0, 0, 0); const Color Image::white(1, 1, 1); const Color somecolors[] = { Color(0.0, 0.6, 0.0), // Dark green Color(0.0, 0.0, 0.6), // Dark blue Color(0.5, 0.0, 0.5), // Purple Color(1.0, 0.54, 0.0), // Dark orange Color(0.28, 0.24, 0.55), // Slate blue Color(0.42, 0.56, 0.14), // Olive drab Color(0.25, 0.80, 0.80), // "Skyish" Color(0.80, 0.80, 0.20), // Mustard }; const unsigned int Nsomecolors = sizeof(somecolors) / sizeof(somecolors[0]); Image::Image(unsigned int width, unsigned int height, const char *t) : w(width), h(height), title(t), data(NULL) { } Image::~Image(void) { while (!comps.empty()) { delete comps.back(); comps.pop_back(); } if (data) delete[] data; } void Image::save(const char *path, bool usletter, int marginpt) const { FILE *f = fopen(path, "w"); if (!f) fatalx(errno, "Failed to open %s for writing\n", path); output(f, usletter, marginpt); fclose(f); } void Image::output(FILE *out, bool usletter, int marginpt) const { if (marginpt < 0) marginpt = usletter ? 72/2 : 0; /* 72/2 pt == ½ in */ if (usletter) outputhdr_usletter(out, marginpt); else outputhdr(out, marginpt); if (data) outputdata(out); for (unsigned int i = 0; i < comps.size(); i++) { fputc('\n', out); comps[i]->write(out); } fprintf(out, "showpage\n"); } enum { Widthpt = 612, /* pts == 8.5 in */ Heightpt = 792, /* pts = 11 in */ }; void Image::outputhdr_usletter(FILE *out, unsigned int marginpt) const { fprintf(out, "%%!PS-Adobe-3.0\n"); fprintf(out, "%%%%Creator: UNH-AI C++ Search Framework\n"); fprintf(out, "%%%%Title: %s\n", title.c_str()); fprintf(out, "%%%%BoundingBox: 0 0 %u %u\n", Widthpt, Heightpt); fprintf(out, "%%%%EndComments\n"); double maxw = Widthpt - marginpt * 2, maxh = Heightpt - marginpt * 2; double scalex = maxw / w, scaley = maxh / h; double transx = marginpt, transy = (Heightpt - h * scalex) / 2; double scale = scalex; if (scaley < scalex) { scale = scaley; transx = (Widthpt - w * scaley) / 2; } fprintf(out, "%g %g translate\n", transx, transy); fprintf(out, "%g %g scale\n", scale, scale); } void Image::outputhdr(FILE *out, unsigned int marginpt) const { fprintf(out, "%%!PS-Adobe-3.0\n"); fprintf(out, "%%%%Creator: UNH-AI C++ Search Framework\n"); fprintf(out, "%%%%Title: %s\n", title.c_str()); fprintf(out, "%%%%BoundingBox: 0 0 %u %u\n", w + 2 * marginpt, h + 2 * marginpt); fprintf(out, "%%%%EndComments\n"); fprintf(out, "%u %u translate\n", marginpt, marginpt); } void Image::outputdata(FILE *out) const { fprintf(out, "\n%% Image data\n"); fprintf(out, "gsave\n"); fprintf(out, "%u %u scale %% scale pixels to points\n", w, h); fprintf(out, "%u %u 8 [%u 0 0 %u 0 0] ", w, h, w, h); fprintf(out, "%% width height colordepth transform\n"); fprintf(out, "/datasource currentfile "); fprintf(out, "/ASCII85Decode filter /RunLengthDecode filter def\n"); fprintf(out, "/datastring %u string def ", w * 3); fprintf(out, "%% %u = width * color components\n", w * 3); fprintf(out, "{datasource datastring readstring pop}\n"); fprintf(out, "false %% false == single data source (rgb)\n"); fprintf(out, "3 %% number of color components\n"); fprintf(out, "colorimage\n"); std::string encoded; encodedata(encoded); fprintf(out, "%s\n", encoded.c_str()); fprintf(out, "grestore\n"); } void Image::encodedata(std::string &dst) const { std::string cs; for (unsigned int i = 0; i < w * h; i++) { cs.push_back(data[i].getred255()); cs.push_back(data[i].getgreen255()); cs.push_back(data[i].getblue255()); } std::string rlenc; runlenenc(rlenc, cs); ascii85enc(dst, rlenc); dst.push_back('~'); dst.push_back('>'); } Image::Path::~Path(void) { while (!segs.empty()) { delete segs.back(); segs.pop_back(); } } void Image::Path::write(FILE *out) const { fprintf(out, "%% Path\n"); fprintf(out, "newpath\n"); for (unsigned int i = 0; i < segs.size(); i++) segs[i]->write(out); if (_closepath) fprintf(out, "closepath\n"); if (!_fill) fprintf(out, "stroke\n"); else fprintf(out, "fill\n"); } void Image::Path::LineJoin::write(FILE *out) const { fprintf(out, "%d setlinejoin\n", type); } void Image::Path::MoveTo::write(FILE *out) const { fprintf(out, "%g %g moveto\n", x, y); } Image::Path::Loc Image::Path::MoveTo::move(Loc p) const { return Loc(std::pair<double,double>(x, y)); } void Image::Path::LineTo::write(FILE *out) const { fprintf(out, "%g %g lineto\n", x, y); } Image::Path::Loc Image::Path::LineTo::move(Loc p) const { return Loc(std::pair<double,double>(x, y)); } void Image::Path::SetLineWidth::write(FILE *out) const { fprintf(out, "%g setlinewidth\n", w); } void Image::Path::SetColor::write(FILE *out) const { fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); } void Image::Path::Arc::write(FILE *out) const { const char *fun = "arc"; if (dt < 0) fun = "arcn"; fprintf(out, "%g %g %g %g %g %s\n", x, y, r, t, t + dt, fun); } Image::Path::Loc Image::Path::Arc::move(Loc p) const { double x1 = x + r * cos((t + dt) * M_PI / 180); double y1 = y + r * sin((t + dt) * M_PI / 180); return Loc(std::pair<double,double>(x1, y1)); } static bool dbleq(double a, double b) { static const double Epsilon = 0.01; return fabs(a - b) < Epsilon; } void Image::Path::line(double x0, double y0, double x1, double y1) { if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(new LineTo(x1, y1)); } void Image::Path::nauticalcurve(double xc, double yc, double r, double t, double dt) { NauticalArc *a = new NauticalArc(xc, yc, r, t, dt); double x0 = xc + a->r * cos(a->t * M_PI / 180); double y0 = yc + a->r * sin(a->t * M_PI / 180); if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(a); } void Image::Path::curve(double xc, double yc, double r, double t, double dt) { Arc *a = new Arc(xc, yc, r, t, dt); double x0 = xc + a->r * cos(a->t * M_PI / 180); double y0 = yc + a->r * sin(a->t * M_PI / 180); if (!cur || !dbleq(cur->first, x0) || !dbleq(cur->second, y0)) addseg(new MoveTo(x0, y0)); addseg(a); } void Image::Text::write(FILE *out) const { fprintf(out, "%% Text\n"); fprintf(out, "/%s findfont %g scalefont setfont\n", font.c_str(), sz); fprintf(out, "%u %u moveto\n", x, y); fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fprintf(out, "(%s) ", text.c_str()); switch (pos) { case Left: fprintf(out, "show\n"); break; case Right: fprintf(out, "dup stringwidth pop neg 0 rmoveto show\n"); break; case Centered: fprintf(out, "dup stringwidth pop 2 div neg 0 rmoveto show\n"); break; default: fatal("Unknown text position: %d\n", pos); } } void Image::Triangle::write(FILE *out) const { double wrad = w * M_PI / 180; double rotrad = rot * M_PI / 180; double side = ht / cos(wrad / 2); double xtop = ht / 2; double xbot = -ht / 2; double y1 = side * sin(wrad / 2); double y2 = -side * sin(wrad / 2); double x0r = xtop * cos(rotrad); double y0r = xtop * sin(rotrad); double x1r = xbot * cos(rotrad) - y1 * sin(rotrad); double y1r = xbot * sin(rotrad) + y1 * cos(rotrad); double x2r = xbot * cos(rotrad) - y2 * sin(rotrad); double y2r = xbot * sin(rotrad) + y2 * cos(rotrad); fprintf(out, "%% Triangle\n"); fprintf(out, "newpath\n"); fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); if (linewidth >= 0) fprintf(out, "%g setlinewidth\n", linewidth); else fprintf(out, "0.1 setlinewidth\n"); fprintf(out, "%g %g moveto\n", x0r + x, y0r + y); fprintf(out, "%g %g lineto\n", x1r + x, y1r + y); fprintf(out, "%g %g lineto\n", x2r + x, y2r + y); fprintf(out, "closepath\n"); if (linewidth < 0) fprintf(out, "fill\n"); else fprintf(out, "stroke\n"); } void Image::Circle::write(FILE *out) const { fprintf(out, "%% Circle\n"); const char *finish = "stroke"; if (lwidth <= 0) { finish = "fill"; fprintf(out, "0.1 setlinewidth\n"); } else { fprintf(out, "%g setlinewidth\n", lwidth); } fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fprintf(out, "newpath %g %g %g 0 360 arc %s\n", x, y, r, finish); } void Image::Rect::write(FILE *out) const { fprintf(out, "%% Rect\n"); const char *finish = "stroke"; if (lwidth <= 0) { finish = "fill"; fprintf(out, "0.1 setlinewidth\n"); } else { fprintf(out, "%g setlinewidth\n", lwidth); } fprintf(out, "%g %g %g setrgbcolor\n", c.getred(), c.getgreen(), c.getblue()); fputs("0 setlinejoin\n", out); fputs("newpath\n", out); fprintf(out, "%g %g moveto\n", x, y); fprintf(out, "%g %g lineto\n", x + w, y); fprintf(out, "%g %g lineto\n", x + w, y + h); fprintf(out, "%g %g lineto\n", x, y + h); fprintf(out, "closepath\n%s\n", finish); }
revert an unintentional change to translation.
image: revert an unintentional change to translation.
C++
mit
skiesel/search,skiesel/search,skiesel/search,eaburns/search,eaburns/search,eaburns/search
7bfee3bd643d6de72cc24fe12daff22d45af7fd4
map/map_tests/countries_names_tests.cpp
map/map_tests/countries_names_tests.cpp
#include "testing/testing.hpp" #include "map/framework.hpp" #include "search/categories_cache.hpp" #include "search/downloader_search_callback.hpp" #include "search/mwm_context.hpp" #include "storage/storage.hpp" #include "indexer/data_source.hpp" #include "indexer/ftypes_matcher.hpp" #include "indexer/mwm_set.hpp" #include "indexer/utils.hpp" #include "coding/string_utf8_multilang.hpp" #include "base/cancellable.hpp" #include "base/checked_cast.hpp" #include <algorithm> #include <set> #include <string> #include <utility> #include <vector> using namespace platform; using namespace storage; using namespace std; UNIT_TEST(CountriesNamesTest) { Framework f(FrameworkParams(false /* m_enableLocalAds */, false /* m_enableDiffs */)); auto & storage = f.GetStorage(); auto const & synonyms = storage.GetCountryNameSynonyms(); auto handle = indexer::FindWorld(f.GetDataSource()); TEST(handle.IsAlive(), ()); FeaturesLoaderGuard g(f.GetDataSource(), handle.GetId()); auto & value = *handle.GetValue(); TEST(value.HasSearchIndex(), ()); search::MwmContext const mwmContext(move(handle)); base::Cancellable const cancellable; search::CategoriesCache cache(ftypes::IsLocalityChecker::Instance(), cancellable); vector<int8_t> const langIndices = {StringUtf8Multilang::kEnglishCode, StringUtf8Multilang::kDefaultCode, StringUtf8Multilang::kInternationalCode}; set<string> const kIgnoreList = {"Turkish Republic Of Northern Cyprus", "Transnistria", "Nagorno-Karabakh Republic", "Republic of Artsakh", // MAPSME-10611 "Mayorca Residencial", "Magnolias Residencial", "Residencial Magnolias", }; auto const features = cache.Get(mwmContext); features.ForEach([&](uint64_t fid) { auto ft = g.GetFeatureByIndex(base::asserted_cast<uint32_t>(fid)); TEST(ft, ()); ftypes::LocalityType const type = ftypes::IsLocalityChecker::Instance().GetType(*ft); if (type != ftypes::LocalityType::Country) return; TEST(any_of(langIndices.begin(), langIndices.end(), [&](uint8_t langIndex) { string name; if (!ft->GetName(langIndex, name)) return false; auto const it = synonyms.find(name); if (it == synonyms.end()) return storage.IsNode(name) || kIgnoreList.count(name) != 0; return storage.IsNode(it->second); }), ("Cannot find countries.txt record for country feature:", ft->DebugString(FeatureType::BEST_GEOMETRY))); }); }
#include "testing/testing.hpp" #include "map/framework.hpp" #include "search/categories_cache.hpp" #include "search/downloader_search_callback.hpp" #include "search/mwm_context.hpp" #include "storage/storage.hpp" #include "indexer/data_source.hpp" #include "indexer/ftypes_matcher.hpp" #include "indexer/mwm_set.hpp" #include "indexer/utils.hpp" #include "coding/string_utf8_multilang.hpp" #include "base/cancellable.hpp" #include "base/checked_cast.hpp" #include <algorithm> #include <set> #include <string> #include <utility> #include <vector> using namespace platform; using namespace storage; using namespace std; UNIT_TEST(CountriesNamesTest) { Framework f(FrameworkParams(false /* m_enableLocalAds */, false /* m_enableDiffs */)); auto & storage = f.GetStorage(); auto const & synonyms = storage.GetCountryNameSynonyms(); auto handle = indexer::FindWorld(f.GetDataSource()); TEST(handle.IsAlive(), ()); FeaturesLoaderGuard g(f.GetDataSource(), handle.GetId()); auto & value = *handle.GetValue(); TEST(value.HasSearchIndex(), ()); search::MwmContext const mwmContext(move(handle)); base::Cancellable const cancellable; search::CategoriesCache cache(ftypes::IsLocalityChecker::Instance(), cancellable); vector<int8_t> const langIndices = {StringUtf8Multilang::kEnglishCode, StringUtf8Multilang::kDefaultCode, StringUtf8Multilang::kInternationalCode}; set<string> const kIgnoreList = {"Turkish Republic Of Northern Cyprus", "Transnistria", "Nagorno-Karabakh Republic", "Republic of Artsakh", }; auto const features = cache.Get(mwmContext); features.ForEach([&](uint64_t fid) { auto ft = g.GetFeatureByIndex(base::asserted_cast<uint32_t>(fid)); TEST(ft, ()); ftypes::LocalityType const type = ftypes::IsLocalityChecker::Instance().GetType(*ft); if (type != ftypes::LocalityType::Country) return; TEST(any_of(langIndices.begin(), langIndices.end(), [&](uint8_t langIndex) { string name; if (!ft->GetName(langIndex, name)) return false; auto const it = synonyms.find(name); if (it == synonyms.end()) return storage.IsNode(name) || kIgnoreList.count(name) != 0; return storage.IsNode(it->second); }), ("Cannot find countries.txt record for country feature:", ft->DebugString(FeatureType::BEST_GEOMETRY))); }); }
Remove CountriesNamesTest exceptions after MAPSME-10611 fix.
[data] Remove CountriesNamesTest exceptions after MAPSME-10611 fix.
C++
apache-2.0
milchakov/omim,mapsme/omim,mpimenov/omim,darina/omim,mapsme/omim,darina/omim,matsprea/omim,milchakov/omim,mpimenov/omim,matsprea/omim,mpimenov/omim,milchakov/omim,milchakov/omim,darina/omim,darina/omim,matsprea/omim,matsprea/omim,milchakov/omim,mapsme/omim,mpimenov/omim,mpimenov/omim,mapsme/omim,matsprea/omim,matsprea/omim,milchakov/omim,matsprea/omim,mpimenov/omim,darina/omim,milchakov/omim,matsprea/omim,milchakov/omim,milchakov/omim,mapsme/omim,mpimenov/omim,darina/omim,darina/omim,darina/omim,mpimenov/omim,mapsme/omim,darina/omim,mpimenov/omim,mpimenov/omim,milchakov/omim,darina/omim,matsprea/omim,mapsme/omim,milchakov/omim,mpimenov/omim,mapsme/omim,darina/omim,darina/omim,mapsme/omim,mpimenov/omim,mapsme/omim,mapsme/omim,darina/omim,milchakov/omim,mapsme/omim,mpimenov/omim,mapsme/omim,milchakov/omim,matsprea/omim
1cb0efd6b05b8e6f929a3de9863ed0aef8bf630a
o3d/plugin/cross/main.cc
o3d/plugin/cross/main.cc
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "plugin/cross/main.h" #include "base/at_exit.h" #include "base/command_line.h" #include "base/file_util.h" #include "plugin/cross/config.h" #include "plugin/cross/out_of_memory.h" #include "plugin/cross/whitelist.h" #ifdef OS_WIN #include "breakpad/win/bluescreen_detector.h" #endif using glue::_o3d::PluginObject; using glue::StreamManager; #if !defined(O3D_INTERNAL_PLUGIN) #ifdef OS_WIN #define O3D_DEBUG_LOG_FILENAME L"debug.log" #else #define O3D_DEBUG_LOG_FILENAME "debug.log" #endif #if defined(OS_WIN) || defined(OS_MACOSX) o3d::PluginLogging *g_logger = NULL; static bool g_logging_initialized = false; #ifdef OS_WIN static o3d::BluescreenDetector *g_bluescreen_detector = NULL; #endif // OS_WIN #endif // OS_WIN || OS_MACOSX // We would normally make this a stack variable in main(), but in a // plugin, that's not possible, so we make it a global. When the DLL is loaded // this it gets constructed and when it is unlooaded it is destructed. Note // that this cannot be done in NP_Initialize and NP_Shutdown because those // calls do not necessarily signify the DLL being loaded and unloaded. If the // DLL is not unloaded then the values of global variables are preserved. static base::AtExitManager g_at_exit_manager; int BreakpadEnabler::scope_count_ = 0; #endif // O3D_INTERNAL_PLUGIN namespace o3d { NPError NP_GetValue(NPPVariable variable, void *value) { switch (variable) { case NPPVpluginNameString: *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_NAME); break; case NPPVpluginDescriptionString: *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_DESCRIPTION); break; default: return NPERR_INVALID_PARAM; break; } return NPERR_NO_ERROR; } int16 NPP_HandleEvent(NPP instance, void *event) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } return PlatformNPPHandleEvent(instance, obj, event); } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, uint16 *stype) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_INVALID_PARAM; } StreamManager *stream_manager = obj->stream_manager(); if (stream_manager->NewStream(stream, stype)) { return NPERR_NO_ERROR; } else { // TODO: find out which error we should return return NPERR_INVALID_PARAM; } } NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } StreamManager *stream_manager = obj->stream_manager(); if (stream_manager->DestroyStream(stream, reason)) { return NPERR_NO_ERROR; } else { // TODO: find out which error we should return return NPERR_INVALID_PARAM; } } int32 NPP_WriteReady(NPP instance, NPStream *stream) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } StreamManager *stream_manager = obj->stream_manager(); return stream_manager->WriteReady(stream); } int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } StreamManager *stream_manager = obj->stream_manager(); return stream_manager->Write(stream, offset, len, buffer); } void NPP_Print(NPP instance, NPPrint *platformPrint) { HANDLE_CRASHES; } void NPP_URLNotify(NPP instance, const char *url, NPReason reason, void *notifyData) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return; } StreamManager *stream_manager = obj->stream_manager(); stream_manager->URLNotify(url, reason, notifyData); } NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { HANDLE_CRASHES; if (!instance) { // Our ActiveX wrapper calls us like this as a way of saying that what it // really wants to call is NP_GetValue(). :/ return o3d::NP_GetValue(variable, value); } PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_INVALID_PARAM; } switch (variable) { case NPPVpluginScriptableNPObject: { void **v = static_cast<void **>(value); // Return value is expected to be retained GLUE_PROFILE_START(instance, "retainobject"); NPN_RetainObject(obj); GLUE_PROFILE_STOP(instance, "retainobject"); *v = obj; break; } default: { NPError ret = PlatformNPPGetValue(obj, variable, value); if (ret == NPERR_INVALID_PARAM) // TODO(tschmelcher): Do we still need to fall back to this now that we // have the ActiveX special case above? ret = o3d::NP_GetValue(variable, value); return ret; } } return NPERR_NO_ERROR; } NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { HANDLE_CRASHES; #if !defined(O3D_INTERNAL_PLUGIN) && (defined(OS_WIN) || defined(OS_MACOSX)) // TODO(tschmelcher): Support this on Linux? if (!g_logging_initialized) { // Get user config metrics. These won't be stored though unless the user // opts-in for usagestats logging GetUserAgentMetrics(instance); GetUserConfigMetrics(); // Create usage stats logs object g_logger = o3d::PluginLogging::InitializeUsageStatsLogging(); #ifdef OS_WIN if (g_logger) { // Setup blue-screen detection g_bluescreen_detector = new o3d::BluescreenDetector(); g_bluescreen_detector->Start(); } #endif g_logging_initialized = true; } #endif if (!IsDomainAuthorized(instance)) { return NPERR_INVALID_URL; } PluginObject *obj = glue::_o3d::PluginObject::Create(instance); instance->pdata = obj; glue::_o3d::InitializeGlue(instance); obj->Init(argc, argn, argv); return PlatformNPPNew(instance, obj); } NPError NPP_Destroy(NPP instance, NPSavedData **save) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } NPError err = PlatformNPPDestroy(instance, obj); NPN_ReleaseObject(obj); instance->pdata = NULL; return err; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { HANDLE_CRASHES; return NPERR_GENERIC_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* window) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } return PlatformNPPSetWindow(instance, obj, window); } // Called when the browser has finished attempting to stream data to // a file as requested. If fname == NULL the attempt was not successful. void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return; } StreamManager *stream_manager = obj->stream_manager(); PlatformNPPStreamAsFile(stream_manager, stream, fname); } } // namespace o3d #if defined(O3D_INTERNAL_PLUGIN) namespace o3d { #else extern "C" { #endif NPError EXPORT_SYMBOL OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs #ifdef OS_LINUX , NPPluginFuncs *pluginFuncs #endif ) { HANDLE_CRASHES; NPError err = InitializeNPNApi(browserFuncs); if (err != NPERR_NO_ERROR) { return err; } #ifdef OS_LINUX NP_GetEntryPoints(pluginFuncs); #endif // OS_LINUX #if !defined(O3D_INTERNAL_PLUGIN) if (!o3d::SetupOutOfMemoryHandler()) return NPERR_MODULE_LOAD_FAILED_ERROR; #endif // O3D_INTERNAL_PLUGIN err = o3d::PlatformPreNPInitialize(); if (err != NPERR_NO_ERROR) { return err; } #if !defined(O3D_INTERNAL_PLUGIN) // Turn on the logging. CommandLine::Init(0, NULL); FilePath log; file_util::GetTempDir(&log); log.Append(O3D_DEBUG_LOG_FILENAME); InitLogging(log.value().c_str(), logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG, logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE); #endif // O3D_INTERNAL_PLUGIN DLOG(INFO) << "NP_Initialize"; return o3d::PlatformPostNPInitialize(); } NPError EXPORT_SYMBOL OSCALL NP_Shutdown(void) { HANDLE_CRASHES; DLOG(INFO) << "NP_Shutdown"; NPError err = o3d::PlatformPreNPShutdown(); if (err != NPERR_NO_ERROR) { return err; } #if !defined(O3D_INTERNAL_PLUGIN) #if defined(OS_WIN) || defined(OS_MACOSX) if (g_logger) { // Do a last sweep to aggregate metrics before we shut down g_logger->ProcessMetrics(true, false, false); delete g_logger; g_logger = NULL; g_logging_initialized = false; stats_report::g_global_metrics.Uninitialize(); } #endif // OS_WIN || OS_MACOSX CommandLine::Reset(); #ifdef OS_WIN // Strictly speaking, on windows, it's not really necessary to call // Stop(), but we do so for completeness if (g_bluescreen_detector) { g_bluescreen_detector->Stop(); delete g_bluescreen_detector; g_bluescreen_detector = NULL; } #endif // OS_WIN #endif // O3D_INTERNAL_PLUGIN return o3d::PlatformPostNPShutdown(); } NPError EXPORT_SYMBOL OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) { HANDLE_CRASHES; pluginFuncs->version = 11; pluginFuncs->size = sizeof(*pluginFuncs); pluginFuncs->newp = o3d::NPP_New; pluginFuncs->destroy = o3d::NPP_Destroy; pluginFuncs->setwindow = o3d::NPP_SetWindow; pluginFuncs->newstream = o3d::NPP_NewStream; pluginFuncs->destroystream = o3d::NPP_DestroyStream; pluginFuncs->asfile = o3d::NPP_StreamAsFile; pluginFuncs->writeready = o3d::NPP_WriteReady; pluginFuncs->write = o3d::NPP_Write; pluginFuncs->print = o3d::NPP_Print; pluginFuncs->event = o3d::NPP_HandleEvent; pluginFuncs->urlnotify = o3d::NPP_URLNotify; pluginFuncs->getvalue = o3d::NPP_GetValue; pluginFuncs->setvalue = o3d::NPP_SetValue; return NPERR_NO_ERROR; } char* NP_GetMIMEDescription(void) { return const_cast<char*>(O3D_PLUGIN_NPAPI_MIMETYPE "::O3D MIME"); } } // namespace o3d / extern "C" #if !defined(O3D_INTERNAL_PLUGIN) extern "C" { NPError EXPORT_SYMBOL NP_GetValue(void *instance, NPPVariable variable, void *value) { return o3d::NP_GetValue(variable, value); } } #endif
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "plugin/cross/main.h" #include "base/at_exit.h" #include "base/command_line.h" #include "base/file_util.h" #include "plugin/cross/config.h" #include "plugin/cross/out_of_memory.h" #include "plugin/cross/whitelist.h" #ifdef OS_WIN #include "breakpad/win/bluescreen_detector.h" #endif using glue::_o3d::PluginObject; using glue::StreamManager; #if !defined(O3D_INTERNAL_PLUGIN) #ifdef OS_WIN #define O3D_DEBUG_LOG_FILENAME L"debug.log" #else #define O3D_DEBUG_LOG_FILENAME "debug.log" #endif #if defined(OS_WIN) || defined(OS_MACOSX) o3d::PluginLogging *g_logger = NULL; static bool g_logging_initialized = false; #ifdef OS_WIN static o3d::BluescreenDetector *g_bluescreen_detector = NULL; #endif // OS_WIN #endif // OS_WIN || OS_MACOSX // We would normally make this a stack variable in main(), but in a // plugin, that's not possible, so we make it a global. When the DLL is loaded // this it gets constructed and when it is unlooaded it is destructed. Note // that this cannot be done in NP_Initialize and NP_Shutdown because those // calls do not necessarily signify the DLL being loaded and unloaded. If the // DLL is not unloaded then the values of global variables are preserved. static base::AtExitManager g_at_exit_manager; int BreakpadEnabler::scope_count_ = 0; #endif // O3D_INTERNAL_PLUGIN namespace o3d { NPError NP_GetValue(NPPVariable variable, void *value) { switch (variable) { case NPPVpluginNameString: *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_NAME); break; case NPPVpluginDescriptionString: *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_DESCRIPTION); break; default: return NPERR_INVALID_PARAM; break; } return NPERR_NO_ERROR; } int16 NPP_HandleEvent(NPP instance, void *event) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } return PlatformNPPHandleEvent(instance, obj, event); } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, uint16 *stype) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_INVALID_PARAM; } StreamManager *stream_manager = obj->stream_manager(); if (stream_manager->NewStream(stream, stype)) { return NPERR_NO_ERROR; } else { // TODO: find out which error we should return return NPERR_INVALID_PARAM; } } NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } StreamManager *stream_manager = obj->stream_manager(); if (stream_manager->DestroyStream(stream, reason)) { return NPERR_NO_ERROR; } else { // TODO: find out which error we should return return NPERR_INVALID_PARAM; } } int32 NPP_WriteReady(NPP instance, NPStream *stream) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } StreamManager *stream_manager = obj->stream_manager(); return stream_manager->WriteReady(stream); } int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } StreamManager *stream_manager = obj->stream_manager(); return stream_manager->Write(stream, offset, len, buffer); } void NPP_Print(NPP instance, NPPrint *platformPrint) { HANDLE_CRASHES; } void NPP_URLNotify(NPP instance, const char *url, NPReason reason, void *notifyData) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return; } StreamManager *stream_manager = obj->stream_manager(); stream_manager->URLNotify(url, reason, notifyData); } NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { HANDLE_CRASHES; if (!instance) { // Our ActiveX wrapper calls us like this as a way of saying that what it // really wants to call is NP_GetValue(). :/ return o3d::NP_GetValue(variable, value); } PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_INVALID_PARAM; } switch (variable) { case NPPVpluginScriptableNPObject: { void **v = static_cast<void **>(value); // Return value is expected to be retained GLUE_PROFILE_START(instance, "retainobject"); NPN_RetainObject(obj); GLUE_PROFILE_STOP(instance, "retainobject"); *v = obj; break; } default: { NPError ret = PlatformNPPGetValue(obj, variable, value); if (ret == NPERR_INVALID_PARAM) // TODO(tschmelcher): Do we still need to fall back to this now that we // have the ActiveX special case above? ret = o3d::NP_GetValue(variable, value); return ret; } } return NPERR_NO_ERROR; } NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { HANDLE_CRASHES; #if !defined(O3D_INTERNAL_PLUGIN) && (defined(OS_WIN) || defined(OS_MACOSX)) // TODO(tschmelcher): Support this on Linux? if (!g_logging_initialized) { // Get user config metrics. These won't be stored though unless the user // opts-in for usagestats logging GetUserAgentMetrics(instance); GetUserConfigMetrics(); // Create usage stats logs object g_logger = o3d::PluginLogging::InitializeUsageStatsLogging(); #ifdef OS_WIN if (g_logger) { // Setup blue-screen detection g_bluescreen_detector = new o3d::BluescreenDetector(); g_bluescreen_detector->Start(); } #endif g_logging_initialized = true; } #endif if (!IsDomainAuthorized(instance)) { return NPERR_INVALID_URL; } PluginObject *obj = glue::_o3d::PluginObject::Create(instance); instance->pdata = obj; glue::_o3d::InitializeGlue(instance); obj->Init(argc, argn, argv); return PlatformNPPNew(instance, obj); } NPError NPP_Destroy(NPP instance, NPSavedData **save) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } NPError err = PlatformNPPDestroy(instance, obj); NPN_ReleaseObject(obj); instance->pdata = NULL; return err; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { HANDLE_CRASHES; return NPERR_GENERIC_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* window) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } return PlatformNPPSetWindow(instance, obj, window); } // Called when the browser has finished attempting to stream data to // a file as requested. If fname == NULL the attempt was not successful. void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return; } StreamManager *stream_manager = obj->stream_manager(); PlatformNPPStreamAsFile(stream_manager, stream, fname); } } // namespace o3d #if defined(O3D_INTERNAL_PLUGIN) namespace o3d { #else extern "C" { #endif NPError EXPORT_SYMBOL OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs #ifdef OS_LINUX , NPPluginFuncs *pluginFuncs #endif ) { HANDLE_CRASHES; NPError err = InitializeNPNApi(browserFuncs); if (err != NPERR_NO_ERROR) { return err; } #ifdef OS_LINUX NP_GetEntryPoints(pluginFuncs); #endif // OS_LINUX #if !defined(O3D_INTERNAL_PLUGIN) if (!o3d::SetupOutOfMemoryHandler()) return NPERR_MODULE_LOAD_FAILED_ERROR; #endif // O3D_INTERNAL_PLUGIN err = o3d::PlatformPreNPInitialize(); if (err != NPERR_NO_ERROR) { return err; } #if !defined(O3D_INTERNAL_PLUGIN) // Turn on the logging. CommandLine::Init(0, NULL); FilePath log; file_util::GetTempDir(&log); log = log.Append(O3D_DEBUG_LOG_FILENAME); InitLogging(log.value().c_str(), logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG, logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE); #endif // O3D_INTERNAL_PLUGIN DLOG(INFO) << "NP_Initialize"; return o3d::PlatformPostNPInitialize(); } NPError EXPORT_SYMBOL OSCALL NP_Shutdown(void) { HANDLE_CRASHES; DLOG(INFO) << "NP_Shutdown"; NPError err = o3d::PlatformPreNPShutdown(); if (err != NPERR_NO_ERROR) { return err; } #if !defined(O3D_INTERNAL_PLUGIN) #if defined(OS_WIN) || defined(OS_MACOSX) if (g_logger) { // Do a last sweep to aggregate metrics before we shut down g_logger->ProcessMetrics(true, false, false); delete g_logger; g_logger = NULL; g_logging_initialized = false; stats_report::g_global_metrics.Uninitialize(); } #endif // OS_WIN || OS_MACOSX CommandLine::Reset(); #ifdef OS_WIN // Strictly speaking, on windows, it's not really necessary to call // Stop(), but we do so for completeness if (g_bluescreen_detector) { g_bluescreen_detector->Stop(); delete g_bluescreen_detector; g_bluescreen_detector = NULL; } #endif // OS_WIN #endif // O3D_INTERNAL_PLUGIN return o3d::PlatformPostNPShutdown(); } NPError EXPORT_SYMBOL OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) { HANDLE_CRASHES; pluginFuncs->version = 11; pluginFuncs->size = sizeof(*pluginFuncs); pluginFuncs->newp = o3d::NPP_New; pluginFuncs->destroy = o3d::NPP_Destroy; pluginFuncs->setwindow = o3d::NPP_SetWindow; pluginFuncs->newstream = o3d::NPP_NewStream; pluginFuncs->destroystream = o3d::NPP_DestroyStream; pluginFuncs->asfile = o3d::NPP_StreamAsFile; pluginFuncs->writeready = o3d::NPP_WriteReady; pluginFuncs->write = o3d::NPP_Write; pluginFuncs->print = o3d::NPP_Print; pluginFuncs->event = o3d::NPP_HandleEvent; pluginFuncs->urlnotify = o3d::NPP_URLNotify; pluginFuncs->getvalue = o3d::NPP_GetValue; pluginFuncs->setvalue = o3d::NPP_SetValue; return NPERR_NO_ERROR; } char* NP_GetMIMEDescription(void) { return const_cast<char*>(O3D_PLUGIN_NPAPI_MIMETYPE "::O3D MIME"); } } // namespace o3d / extern "C" #if !defined(O3D_INTERNAL_PLUGIN) extern "C" { NPError EXPORT_SYMBOL NP_GetValue(void *instance, NPPVariable variable, void *value) { return o3d::NP_GetValue(variable, value); } } #endif
Fix debug.log creation, which has been broken since r58501.
Fix debug.log creation, which has been broken since r58501. TEST=loaded O3D in Safari on Mac and verified that debug.log is created and used BUG=none Review URL: http://codereview.chromium.org/5651002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@68520 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium
16ffe0c2ffa67a107df065faa91c332dc3f59012
RenderSystems/GL3Plus/src/OgreGL3PlusDepthBuffer.cpp
RenderSystems/GL3Plus/src/OgreGL3PlusDepthBuffer.cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreGL3PlusDepthBuffer.h" #include "OgreGL3PlusHardwarePixelBuffer.h" #include "OgreGL3PlusRenderSystem.h" #include "OgreGL3PlusFrameBufferObject.h" namespace Ogre { GL3PlusDepthBuffer::GL3PlusDepthBuffer( uint16 poolId, GL3PlusRenderSystem *renderSystem, GL3PlusContext *creatorContext, GL3PlusRenderBuffer *depth, GL3PlusRenderBuffer *stencil, uint32 width, uint32 height, uint32 fsaa, uint32 multiSampleQuality, bool manual ) : DepthBuffer( poolId, 0, width, height, fsaa, "", manual ), mMultiSampleQuality( multiSampleQuality ), mCreatorContext( creatorContext ), mDepthBuffer( depth ), mStencilBuffer( stencil ), mRenderSystem( renderSystem ) { if( mDepthBuffer ) { switch( mDepthBuffer->getGLFormat() ) { case GL_DEPTH_COMPONENT16: mBitDepth = 16; break; case GL_DEPTH_COMPONENT24: case GL_DEPTH24_STENCIL8: // Packed depth / stencil mBitDepth = 24; case GL_DEPTH_COMPONENT32: case GL_DEPTH_COMPONENT32F: case GL_DEPTH32F_STENCIL8: mBitDepth = 32; break; } } } GL3PlusDepthBuffer::~GL3PlusDepthBuffer() { if( mStencilBuffer && mStencilBuffer != mDepthBuffer ) { delete mStencilBuffer; mStencilBuffer = 0; } if( mDepthBuffer ) { delete mDepthBuffer; mDepthBuffer = 0; } } bool GL3PlusDepthBuffer::isCompatible( RenderTarget *renderTarget ) const { bool retVal = false; //Check standard stuff first. if( mRenderSystem->getCapabilities()->hasCapability( RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL ) ) { if( !DepthBuffer::isCompatible( renderTarget ) ) return false; } else { if( this->getWidth() != renderTarget->getWidth() || this->getHeight() != renderTarget->getHeight() || this->getFsaa() != renderTarget->getFSAA() ) return false; } //Now check this is the appropriate format GL3PlusFrameBufferObject *fbo = 0; renderTarget->getCustomAttribute(GLRenderTexture::CustomAttributeString_FBO, &fbo); if( !fbo ) { GL3PlusContext *windowContext = 0; renderTarget->getCustomAttribute( GLRenderTexture::CustomAttributeString_GLCONTEXT, &windowContext ); //Non-FBO targets and FBO depth surfaces don't play along, only dummies which match the same //context if( !mDepthBuffer && !mStencilBuffer && mCreatorContext == windowContext ) retVal = true; } else { //Check this isn't a dummy non-FBO depth buffer with an FBO target, don't mix them. //If you don't want depth buffer, use a Null Depth Buffer, not a dummy one. if( mDepthBuffer || mStencilBuffer ) { PixelFormat internalFormat = fbo->getFormat(); GLenum depthFormat, stencilFormat; mRenderSystem->_getDepthStencilFormatFor( internalFormat, &depthFormat, &stencilFormat ); bool bSameDepth = false; if( mDepthBuffer ) bSameDepth |= mDepthBuffer->getGLFormat() == depthFormat; bool bSameStencil = false; if( !mStencilBuffer || mStencilBuffer == mDepthBuffer ) bSameStencil = stencilFormat == GL_NONE; else { if( mStencilBuffer ) bSameStencil = stencilFormat == mStencilBuffer->getGLFormat(); } if(internalFormat == PF_DEPTH) retVal = bSameDepth; else retVal = bSameDepth && bSameStencil; } } return retVal; } }
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreGL3PlusDepthBuffer.h" #include "OgreGL3PlusHardwarePixelBuffer.h" #include "OgreGL3PlusRenderSystem.h" #include "OgreGL3PlusFrameBufferObject.h" namespace Ogre { GL3PlusDepthBuffer::GL3PlusDepthBuffer( uint16 poolId, GL3PlusRenderSystem *renderSystem, GL3PlusContext *creatorContext, GL3PlusRenderBuffer *depth, GL3PlusRenderBuffer *stencil, uint32 width, uint32 height, uint32 fsaa, uint32 multiSampleQuality, bool manual ) : DepthBuffer( poolId, 0, width, height, fsaa, "", manual ), mMultiSampleQuality( multiSampleQuality ), mCreatorContext( creatorContext ), mDepthBuffer( depth ), mStencilBuffer( stencil ), mRenderSystem( renderSystem ) { if( mDepthBuffer ) { switch( mDepthBuffer->getGLFormat() ) { case GL_DEPTH_COMPONENT16: mBitDepth = 16; break; case GL_DEPTH_COMPONENT24: case GL_DEPTH24_STENCIL8: // Packed depth / stencil mBitDepth = 24; break; case GL_DEPTH_COMPONENT32: case GL_DEPTH_COMPONENT32F: case GL_DEPTH32F_STENCIL8: mBitDepth = 32; break; } } } GL3PlusDepthBuffer::~GL3PlusDepthBuffer() { if( mStencilBuffer && mStencilBuffer != mDepthBuffer ) { delete mStencilBuffer; mStencilBuffer = 0; } if( mDepthBuffer ) { delete mDepthBuffer; mDepthBuffer = 0; } } bool GL3PlusDepthBuffer::isCompatible( RenderTarget *renderTarget ) const { bool retVal = false; //Check standard stuff first. if( mRenderSystem->getCapabilities()->hasCapability( RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL ) ) { if( !DepthBuffer::isCompatible( renderTarget ) ) return false; } else { if( this->getWidth() != renderTarget->getWidth() || this->getHeight() != renderTarget->getHeight() || this->getFsaa() != renderTarget->getFSAA() ) return false; } //Now check this is the appropriate format GL3PlusFrameBufferObject *fbo = 0; renderTarget->getCustomAttribute(GLRenderTexture::CustomAttributeString_FBO, &fbo); if( !fbo ) { GL3PlusContext *windowContext = 0; renderTarget->getCustomAttribute( GLRenderTexture::CustomAttributeString_GLCONTEXT, &windowContext ); //Non-FBO targets and FBO depth surfaces don't play along, only dummies which match the same //context if( !mDepthBuffer && !mStencilBuffer && mCreatorContext == windowContext ) retVal = true; } else { //Check this isn't a dummy non-FBO depth buffer with an FBO target, don't mix them. //If you don't want depth buffer, use a Null Depth Buffer, not a dummy one. if( mDepthBuffer || mStencilBuffer ) { PixelFormat internalFormat = fbo->getFormat(); GLenum depthFormat, stencilFormat; mRenderSystem->_getDepthStencilFormatFor( internalFormat, &depthFormat, &stencilFormat ); bool bSameDepth = false; if( mDepthBuffer ) bSameDepth |= mDepthBuffer->getGLFormat() == depthFormat; bool bSameStencil = false; if( !mStencilBuffer || mStencilBuffer == mDepthBuffer ) bSameStencil = stencilFormat == GL_NONE; else { if( mStencilBuffer ) bSameStencil = stencilFormat == mStencilBuffer->getGLFormat(); } if(internalFormat == PF_DEPTH) retVal = bSameDepth; else retVal = bSameDepth && bSameStencil; } } return retVal; } }
add missing break
GL3PlusDepthBuffer: add missing break
C++
mit
RealityFactory/ogre,RealityFactory/ogre,RealityFactory/ogre,RealityFactory/ogre,RealityFactory/ogre
53a8876984c7593bab28a31e19ccdc904638c19e
media/base/android/video_decoder_job.cc
media/base/android/video_decoder_job.cc
// Copyright 2013 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 "media/base/android/video_decoder_job.h" #include "base/bind.h" #include "base/lazy_instance.h" #include "base/threading/thread.h" #include "media/base/android/media_codec_bridge.h" #include "media/base/android/media_drm_bridge.h" namespace media { class VideoDecoderThread : public base::Thread { public: VideoDecoderThread() : base::Thread("MediaSource_VideoDecoderThread") { Start(); } }; // TODO(qinmin): Check if it is tolerable to use worker pool to handle all the // decoding tasks so that we don't need a global thread here. // http://crbug.com/245750 base::LazyInstance<VideoDecoderThread>::Leaky g_video_decoder_thread = LAZY_INSTANCE_INITIALIZER; VideoDecoderJob::VideoDecoderJob( const base::Closure& request_data_cb, const base::Closure& request_resources_cb, const base::Closure& on_demuxer_config_changed_cb) : MediaDecoderJob(g_video_decoder_thread.Pointer()->message_loop_proxy(), request_data_cb, on_demuxer_config_changed_cb), video_codec_(kUnknownVideoCodec), config_width_(0), config_height_(0), output_width_(0), output_height_(0), request_resources_cb_(request_resources_cb), next_video_data_is_iframe_(true) { } VideoDecoderJob::~VideoDecoderJob() {} bool VideoDecoderJob::SetVideoSurface(gfx::ScopedJavaSurface surface) { // For an empty surface, always pass it to the |media_codec_bridge_| job so // that it can detach from the current one. Otherwise, don't pass an // unprotected surface if the video content requires a protected one. if (!surface.IsEmpty() && IsProtectedSurfaceRequired() && !surface.is_protected()) { return false; } surface_ = surface.Pass(); need_to_reconfig_decoder_job_ = true; return true; } bool VideoDecoderJob::HasStream() const { return video_codec_ != kUnknownVideoCodec; } void VideoDecoderJob::Flush() { MediaDecoderJob::Flush(); next_video_data_is_iframe_ = true; } void VideoDecoderJob::ReleaseDecoderResources() { MediaDecoderJob::ReleaseDecoderResources(); surface_ = gfx::ScopedJavaSurface(); } void VideoDecoderJob::SetDemuxerConfigs(const DemuxerConfigs& configs) { video_codec_ = configs.video_codec; config_width_ = configs.video_size.width(); config_height_ = configs.video_size.height(); set_is_content_encrypted(configs.is_video_encrypted); if (!media_codec_bridge_) { output_width_ = config_width_; output_height_ = config_height_; } } void VideoDecoderJob::ReleaseOutputBuffer( int output_buffer_index, size_t size, bool render_output, base::TimeDelta current_presentation_timestamp, const ReleaseOutputCompletionCallback& callback) { media_codec_bridge_->ReleaseOutputBuffer(output_buffer_index, render_output); callback.Run(current_presentation_timestamp, current_presentation_timestamp); } bool VideoDecoderJob::ComputeTimeToRender() const { return true; } bool VideoDecoderJob::IsCodecReconfigureNeeded( const DemuxerConfigs& configs) const { if (!media_codec_bridge_) return true; if (!AreDemuxerConfigsChanged(configs)) return false; bool only_size_changed = false; if (video_codec_ == configs.video_codec && is_content_encrypted() == configs.is_video_encrypted) { only_size_changed = true; } return !only_size_changed || !static_cast<VideoCodecBridge*>(media_codec_bridge_.get())-> IsAdaptivePlaybackSupported(configs.video_size.width(), configs.video_size.height()); } bool VideoDecoderJob::AreDemuxerConfigsChanged( const DemuxerConfigs& configs) const { return video_codec_ != configs.video_codec || is_content_encrypted() != configs.is_video_encrypted || config_width_ != configs.video_size.width() || config_height_ != configs.video_size.height(); } bool VideoDecoderJob::CreateMediaCodecBridgeInternal() { if (surface_.IsEmpty()) { ReleaseMediaCodecBridge(); return false; } // If the next data is not iframe, return false so that the player need to // perform a browser seek. if (!next_video_data_is_iframe_) return false; bool is_secure = is_content_encrypted() && drm_bridge() && drm_bridge()->IsProtectedSurfaceRequired(); media_codec_bridge_.reset(VideoCodecBridge::CreateDecoder( video_codec_, is_secure, gfx::Size(config_width_, config_height_), surface_.j_surface().obj(), GetMediaCrypto().obj())); if (!media_codec_bridge_) return false; request_resources_cb_.Run(); return true; } void VideoDecoderJob::CurrentDataConsumed(bool is_config_change) { next_video_data_is_iframe_ = is_config_change; } bool VideoDecoderJob::UpdateOutputFormat() { if (!media_codec_bridge_) return false; int prev_output_width = output_width_; int prev_output_height = output_height_; media_codec_bridge_->GetOutputFormat(&output_width_, &output_height_); return (output_width_ != prev_output_width) || (output_height_ != prev_output_height); } bool VideoDecoderJob::IsProtectedSurfaceRequired() { return is_content_encrypted() && drm_bridge() && drm_bridge()->IsProtectedSurfaceRequired(); } } // namespace media
// Copyright 2013 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 "media/base/android/video_decoder_job.h" #include "base/bind.h" #include "base/lazy_instance.h" #include "base/threading/thread.h" #include "media/base/android/media_codec_bridge.h" #include "media/base/android/media_drm_bridge.h" namespace media { class VideoDecoderThread : public base::Thread { public: VideoDecoderThread() : base::Thread("MediaSource_VideoDecoderThread") { Start(); } }; // TODO(qinmin): Check if it is tolerable to use worker pool to handle all the // decoding tasks so that we don't need a global thread here. // http://crbug.com/245750 base::LazyInstance<VideoDecoderThread>::Leaky g_video_decoder_thread = LAZY_INSTANCE_INITIALIZER; VideoDecoderJob::VideoDecoderJob( const base::Closure& request_data_cb, const base::Closure& request_resources_cb, const base::Closure& on_demuxer_config_changed_cb) : MediaDecoderJob(g_video_decoder_thread.Pointer()->message_loop_proxy(), request_data_cb, on_demuxer_config_changed_cb), video_codec_(kUnknownVideoCodec), config_width_(0), config_height_(0), output_width_(0), output_height_(0), request_resources_cb_(request_resources_cb), next_video_data_is_iframe_(true) { } VideoDecoderJob::~VideoDecoderJob() {} bool VideoDecoderJob::SetVideoSurface(gfx::ScopedJavaSurface surface) { // For an empty surface, always pass it to the |media_codec_bridge_| job so // that it can detach from the current one. Otherwise, don't pass an // unprotected surface if the video content requires a protected one. if (!surface.IsEmpty() && IsProtectedSurfaceRequired() && !surface.is_protected()) { return false; } surface_ = surface.Pass(); need_to_reconfig_decoder_job_ = true; return true; } bool VideoDecoderJob::HasStream() const { return video_codec_ != kUnknownVideoCodec; } void VideoDecoderJob::Flush() { MediaDecoderJob::Flush(); next_video_data_is_iframe_ = true; } void VideoDecoderJob::ReleaseDecoderResources() { MediaDecoderJob::ReleaseDecoderResources(); surface_ = gfx::ScopedJavaSurface(); } void VideoDecoderJob::SetDemuxerConfigs(const DemuxerConfigs& configs) { video_codec_ = configs.video_codec; config_width_ = configs.video_size.width(); config_height_ = configs.video_size.height(); set_is_content_encrypted(configs.is_video_encrypted); if (!media_codec_bridge_) { output_width_ = config_width_; output_height_ = config_height_; } } void VideoDecoderJob::ReleaseOutputBuffer( int output_buffer_index, size_t size, bool render_output, base::TimeDelta current_presentation_timestamp, const ReleaseOutputCompletionCallback& callback) { media_codec_bridge_->ReleaseOutputBuffer(output_buffer_index, render_output); callback.Run(current_presentation_timestamp, current_presentation_timestamp); } bool VideoDecoderJob::ComputeTimeToRender() const { return true; } bool VideoDecoderJob::IsCodecReconfigureNeeded( const DemuxerConfigs& configs) const { if (!media_codec_bridge_) return true; if (!AreDemuxerConfigsChanged(configs)) return false; bool only_size_changed = false; if (video_codec_ == configs.video_codec && is_content_encrypted() == configs.is_video_encrypted) { only_size_changed = true; } return !only_size_changed || !static_cast<VideoCodecBridge*>(media_codec_bridge_.get())-> IsAdaptivePlaybackSupported(configs.video_size.width(), configs.video_size.height()); } bool VideoDecoderJob::AreDemuxerConfigsChanged( const DemuxerConfigs& configs) const { return video_codec_ != configs.video_codec || is_content_encrypted() != configs.is_video_encrypted || config_width_ != configs.video_size.width() || config_height_ != configs.video_size.height(); } bool VideoDecoderJob::CreateMediaCodecBridgeInternal() { if (surface_.IsEmpty()) { ReleaseMediaCodecBridge(); return false; } // If the next data is not iframe, return false so that the player need to // perform a browser seek. if (!next_video_data_is_iframe_) return false; bool is_secure = is_content_encrypted() && drm_bridge() && drm_bridge()->IsProtectedSurfaceRequired(); media_codec_bridge_.reset(VideoCodecBridge::CreateDecoder( video_codec_, is_secure, gfx::Size(config_width_, config_height_), surface_.j_surface().obj(), GetMediaCrypto().obj())); if (!media_codec_bridge_) return false; request_resources_cb_.Run(); return true; } void VideoDecoderJob::CurrentDataConsumed(bool is_config_change) { next_video_data_is_iframe_ = is_config_change; } bool VideoDecoderJob::UpdateOutputFormat() { if (!media_codec_bridge_) return false; int prev_output_width = output_width_; int prev_output_height = output_height_; // See b/18224769. The values reported from MediaCodecBridge::GetOutputFormat // correspond to the actual video frame size, but this is not necessarily the // size that should be output. output_width_ = config_width_; output_height_ = config_height_; return (output_width_ != prev_output_width) || (output_height_ != prev_output_height); } bool VideoDecoderJob::IsProtectedSurfaceRequired() { return is_content_encrypted() && drm_bridge() && drm_bridge()->IsProtectedSurfaceRequired(); } } // namespace media
use demuxer configs for video output size.
Android: use demuxer configs for video output size. The values reported from MediaCodec.GetOutputFormat (once the crop rectangle is accounted for) correspond to the actual video size, but not necessarily the size that should be outputted. Some videos appear to report a different aspect ratio in their config than the actual video data, but the reported aspect ratio is what it should be displayed at. [email protected] BUG=internal b/18224769 Review URL: https://codereview.chromium.org/730133003 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#304477}
C++
bsd-3-clause
krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,Chilledheart/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ltilve/chromium,M4sse/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,dushu1203/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,ltilve/chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,Chilledheart/chromium,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk
236c8221af8dbd58e7523b7c03752051e074c4b1
src/miniz_png.cpp
src/miniz_png.cpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 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 * *****************************************************************************/ // mapnik #include <mapnik/palette.hpp> #include <mapnik/miniz_png.hpp> #include <mapnik/image_data.hpp> #include <mapnik/image_view.hpp> // miniz #define MINIZ_NO_ARCHIVE_APIS #define MINIZ_NO_STDIO #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES #include "miniz.c" // zlib #include <zlib.h> // stl #include <vector> #include <iostream> #include <stdexcept> namespace mapnik { namespace MiniZ { PNGWriter::PNGWriter(int level, int strategy) { buffer = NULL; compressor = NULL; if (level == -1) { level = MZ_DEFAULT_LEVEL; // 6 } else if (level < 0 || level > 10) { throw std::runtime_error("compression level must be between 0 and 10"); } mz_uint flags = s_tdefl_num_probes[level] | (level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0 | TDEFL_WRITE_ZLIB_HEADER; if (strategy == Z_FILTERED) flags |= TDEFL_FILTER_MATCHES; else if (strategy == Z_HUFFMAN_ONLY) flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == Z_RLE) flags |= TDEFL_RLE_MATCHES; else if (strategy == Z_FIXED) flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; buffer = (tdefl_output_buffer *)MZ_MALLOC(sizeof(tdefl_output_buffer)); if (buffer == NULL) { throw std::bad_alloc(); } buffer->m_pBuf = NULL; buffer->m_capacity = 8192; buffer->m_expandable = MZ_TRUE; buffer->m_pBuf = (mz_uint8 *)MZ_MALLOC(buffer->m_capacity); if (buffer->m_pBuf == NULL) { throw std::bad_alloc(); } compressor = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (compressor == NULL) { throw std::bad_alloc(); } // Reset output buffer. buffer->m_size = 0; tdefl_status tdstatus = tdefl_init(compressor, tdefl_output_buffer_putter, buffer, flags); if (tdstatus != TDEFL_STATUS_OKAY) { throw std::runtime_error("tdefl_init failed"); } // Write preamble. mz_bool status = tdefl_output_buffer_putter(preamble, 8, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } } PNGWriter::~PNGWriter() { if (compressor) { MZ_FREE(compressor); } if (buffer) { if (buffer->m_pBuf) { MZ_FREE(buffer->m_pBuf); } MZ_FREE(buffer); } } inline void PNGWriter::writeUInt32BE(mz_uint8 *target, mz_uint32 value) { target[0] = (value >> 24) & 0xFF; target[1] = (value >> 16) & 0xFF; target[2] = (value >> 8) & 0xFF; target[3] = value & 0xFF; } size_t PNGWriter::startChunk(const mz_uint8 header[], size_t length) { size_t start = buffer->m_size; mz_bool status = tdefl_output_buffer_putter(header, length, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } return start; } void PNGWriter::finishChunk(size_t start) { // Write chunk length at the beginning of the chunk. size_t payloadLength = buffer->m_size - start - 4 - 4; writeUInt32BE(buffer->m_pBuf + start, payloadLength); // Write CRC32 checksum. Don't include the 4-byte length, but /do/ include // the 4-byte chunk name. mz_uint32 crc = mz_crc32(MZ_CRC32_INIT, buffer->m_pBuf + start + 4, payloadLength + 4); mz_uint8 checksum[] = { crc >> 24, crc >> 16, crc >> 8, crc }; mz_bool status = tdefl_output_buffer_putter(checksum, 4, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } } void PNGWriter::writeIHDR(mz_uint32 width, mz_uint32 height, mz_uint8 pixel_depth) { // Write IHDR chunk. size_t IHDR = startChunk(IHDR_tpl, 21); writeUInt32BE(buffer->m_pBuf + IHDR + 8, width); writeUInt32BE(buffer->m_pBuf + IHDR + 12, height); if (pixel_depth == 32) { // Alpha full color image. buffer->m_pBuf[IHDR + 16] = 8; // bit depth buffer->m_pBuf[IHDR + 17] = 6; // color type (6 == true color with alpha) } else if (pixel_depth == 24) { // Full color image. buffer->m_pBuf[IHDR + 16] = 8; // bit depth buffer->m_pBuf[IHDR + 17] = 2; // color type (2 == true color without alpha) } else { // Paletted image. buffer->m_pBuf[IHDR + 16] = pixel_depth; // bit depth buffer->m_pBuf[IHDR + 17] = 3; // color type (3 == indexed color) } buffer->m_pBuf[IHDR + 18] = 0; // compression method buffer->m_pBuf[IHDR + 19] = 0; // filter method buffer->m_pBuf[IHDR + 20] = 0; // interlace method finishChunk(IHDR); } void PNGWriter::writePLTE(std::vector<rgb> const& palette) { // Write PLTE chunk. size_t PLTE = startChunk(PLTE_tpl, 8); const mz_uint8 *colors = reinterpret_cast<const mz_uint8 *>(&palette[0]); mz_bool status = tdefl_output_buffer_putter(colors, palette.size() * 3, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } finishChunk(PLTE); } void PNGWriter::writetRNS(std::vector<unsigned> const& alpha) { if (alpha.size() == 0) { return; } std::vector<unsigned char> transparency(alpha.size()); unsigned char transparencySize = 0; // Stores position of biggest to nonopaque value. for(unsigned i = 0; i < alpha.size(); i++) { transparency[i] = alpha[i]; if (alpha[i] < 255) { transparencySize = i + 1; } } if (transparencySize > 0) { // Write tRNS chunk. size_t tRNS = startChunk(tRNS_tpl, 8); mz_bool status = tdefl_output_buffer_putter(&transparency[0], transparencySize, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } finishChunk(tRNS); } } template<typename T> void PNGWriter::writeIDAT(T const& image) { // Write IDAT chunk. size_t IDAT = startChunk(IDAT_tpl, 8); mz_uint8 filter_type = 0; tdefl_status status; int bytes_per_pixel = sizeof(typename T::pixel_type); int stride = image.width() * bytes_per_pixel; for (unsigned int y = 0; y < image.height(); y++) { // Write filter_type status = tdefl_compress_buffer(compressor, &filter_type, 1, TDEFL_NO_FLUSH); if (status != TDEFL_STATUS_OKAY) { throw std::runtime_error("failed to compress image"); } // Write scanline status = tdefl_compress_buffer(compressor, (mz_uint8 *)image.getRow(y), stride, TDEFL_NO_FLUSH); if (status != TDEFL_STATUS_OKAY) { throw std::runtime_error("failed to compress image"); } } status = tdefl_compress_buffer(compressor, NULL, 0, TDEFL_FINISH); if (status != TDEFL_STATUS_DONE) { throw std::runtime_error("failed to compress image"); } finishChunk(IDAT); } template<typename T> void PNGWriter::writeIDATStripAlpha(T const& image) { // Write IDAT chunk. size_t IDAT = startChunk(IDAT_tpl, 8); mz_uint8 filter_type = 0; tdefl_status status; size_t stride = image.width() * 3; size_t i, j; mz_uint8 *scanline = (mz_uint8 *)MZ_MALLOC(stride); for (unsigned int y = 0; y < image.height(); y++) { // Write filter_type status = tdefl_compress_buffer(compressor, &filter_type, 1, TDEFL_NO_FLUSH); if (status != TDEFL_STATUS_OKAY) { MZ_FREE(scanline); throw std::runtime_error("failed to compress image"); } // Strip alpha bytes from scanline mz_uint8 *row = (mz_uint8 *)image.getRow(y); for (i = 0, j = 0; j < stride; i += 4, j += 3) { scanline[j] = row[i]; scanline[j+1] = row[i+1]; scanline[j+2] = row[i+2]; } // Write scanline status = tdefl_compress_buffer(compressor, scanline, stride, TDEFL_NO_FLUSH); if (status != TDEFL_STATUS_OKAY) { MZ_FREE(scanline); throw std::runtime_error("failed to compress image"); } } MZ_FREE(scanline); status = tdefl_compress_buffer(compressor, NULL, 0, TDEFL_FINISH); if (status != TDEFL_STATUS_DONE) throw std::runtime_error("failed to compress image"); finishChunk(IDAT); } void PNGWriter::writeIEND() { // Write IEND chunk. size_t IEND = startChunk(IEND_tpl, 8); finishChunk(IEND); } void PNGWriter::toStream(std::ostream& stream) { stream.write((char *)buffer->m_pBuf, buffer->m_size); } const mz_uint8 PNGWriter::preamble[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }; const mz_uint8 PNGWriter::IHDR_tpl[] = { 0x00, 0x00, 0x00, 0x0D, // chunk length 'I', 'H', 'D', 'R', // "IHDR" 0x00, 0x00, 0x00, 0x00, // image width (4 bytes) 0x00, 0x00, 0x00, 0x00, // image height (4 bytes) 0x00, // bit depth (1 byte) 0x00, // color type (1 byte) 0x00, // compression method (1 byte), has to be 0 0x00, // filter method (1 byte) 0x00 // interlace method (1 byte) }; const mz_uint8 PNGWriter::PLTE_tpl[] = { 0x00, 0x00, 0x00, 0x00, // chunk length 'P', 'L', 'T', 'E' // "IDAT" }; const mz_uint8 PNGWriter::tRNS_tpl[] = { 0x00, 0x00, 0x00, 0x00, // chunk length 't', 'R', 'N', 'S' // "IDAT" }; const mz_uint8 PNGWriter::IDAT_tpl[] = { 0x00, 0x00, 0x00, 0x00, // chunk length 'I', 'D', 'A', 'T' // "IDAT" }; const mz_uint8 PNGWriter::IEND_tpl[] = { 0x00, 0x00, 0x00, 0x00, // chunk length 'I', 'E', 'N', 'D' // "IEND" }; template void PNGWriter::writeIDAT<image_data_8>(image_data_8 const& image); template void PNGWriter::writeIDAT<image_view<image_data_8> >(image_view<image_data_8> const& image); template void PNGWriter::writeIDAT<image_data_32>(image_data_32 const& image); template void PNGWriter::writeIDAT<image_view<image_data_32> >(image_view<image_data_32> const& image); template void PNGWriter::writeIDATStripAlpha<image_data_32>(image_data_32 const& image); template void PNGWriter::writeIDATStripAlpha<image_view<image_data_32> >(image_view<image_data_32> const& image); }}
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 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 * *****************************************************************************/ // mapnik #include <mapnik/palette.hpp> #include <mapnik/miniz_png.hpp> #include <mapnik/image_data.hpp> #include <mapnik/image_view.hpp> // miniz #define MINIZ_NO_ARCHIVE_APIS #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES #include "miniz.c" // zlib #include <zlib.h> // stl #include <vector> #include <iostream> #include <stdexcept> namespace mapnik { namespace MiniZ { PNGWriter::PNGWriter(int level, int strategy) { buffer = NULL; compressor = NULL; if (level == -1) { level = MZ_DEFAULT_LEVEL; // 6 } else if (level < 0 || level > 10) { throw std::runtime_error("compression level must be between 0 and 10"); } mz_uint flags = s_tdefl_num_probes[level] | (level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0 | TDEFL_WRITE_ZLIB_HEADER; if (strategy == Z_FILTERED) flags |= TDEFL_FILTER_MATCHES; else if (strategy == Z_HUFFMAN_ONLY) flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == Z_RLE) flags |= TDEFL_RLE_MATCHES; else if (strategy == Z_FIXED) flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; buffer = (tdefl_output_buffer *)MZ_MALLOC(sizeof(tdefl_output_buffer)); if (buffer == NULL) { throw std::bad_alloc(); } buffer->m_pBuf = NULL; buffer->m_capacity = 8192; buffer->m_expandable = MZ_TRUE; buffer->m_pBuf = (mz_uint8 *)MZ_MALLOC(buffer->m_capacity); if (buffer->m_pBuf == NULL) { throw std::bad_alloc(); } compressor = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (compressor == NULL) { throw std::bad_alloc(); } // Reset output buffer. buffer->m_size = 0; tdefl_status tdstatus = tdefl_init(compressor, tdefl_output_buffer_putter, buffer, flags); if (tdstatus != TDEFL_STATUS_OKAY) { throw std::runtime_error("tdefl_init failed"); } // Write preamble. mz_bool status = tdefl_output_buffer_putter(preamble, 8, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } } PNGWriter::~PNGWriter() { if (compressor) { MZ_FREE(compressor); } if (buffer) { if (buffer->m_pBuf) { MZ_FREE(buffer->m_pBuf); } MZ_FREE(buffer); } } inline void PNGWriter::writeUInt32BE(mz_uint8 *target, mz_uint32 value) { target[0] = (value >> 24) & 0xFF; target[1] = (value >> 16) & 0xFF; target[2] = (value >> 8) & 0xFF; target[3] = value & 0xFF; } size_t PNGWriter::startChunk(const mz_uint8 header[], size_t length) { size_t start = buffer->m_size; mz_bool status = tdefl_output_buffer_putter(header, length, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } return start; } void PNGWriter::finishChunk(size_t start) { // Write chunk length at the beginning of the chunk. size_t payloadLength = buffer->m_size - start - 4 - 4; writeUInt32BE(buffer->m_pBuf + start, payloadLength); // Write CRC32 checksum. Don't include the 4-byte length, but /do/ include // the 4-byte chunk name. mz_uint32 crc = mz_crc32(MZ_CRC32_INIT, buffer->m_pBuf + start + 4, payloadLength + 4); mz_uint8 checksum[] = { crc >> 24, crc >> 16, crc >> 8, crc }; mz_bool status = tdefl_output_buffer_putter(checksum, 4, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } } void PNGWriter::writeIHDR(mz_uint32 width, mz_uint32 height, mz_uint8 pixel_depth) { // Write IHDR chunk. size_t IHDR = startChunk(IHDR_tpl, 21); writeUInt32BE(buffer->m_pBuf + IHDR + 8, width); writeUInt32BE(buffer->m_pBuf + IHDR + 12, height); if (pixel_depth == 32) { // Alpha full color image. buffer->m_pBuf[IHDR + 16] = 8; // bit depth buffer->m_pBuf[IHDR + 17] = 6; // color type (6 == true color with alpha) } else if (pixel_depth == 24) { // Full color image. buffer->m_pBuf[IHDR + 16] = 8; // bit depth buffer->m_pBuf[IHDR + 17] = 2; // color type (2 == true color without alpha) } else { // Paletted image. buffer->m_pBuf[IHDR + 16] = pixel_depth; // bit depth buffer->m_pBuf[IHDR + 17] = 3; // color type (3 == indexed color) } buffer->m_pBuf[IHDR + 18] = 0; // compression method buffer->m_pBuf[IHDR + 19] = 0; // filter method buffer->m_pBuf[IHDR + 20] = 0; // interlace method finishChunk(IHDR); } void PNGWriter::writePLTE(std::vector<rgb> const& palette) { // Write PLTE chunk. size_t PLTE = startChunk(PLTE_tpl, 8); const mz_uint8 *colors = reinterpret_cast<const mz_uint8 *>(&palette[0]); mz_bool status = tdefl_output_buffer_putter(colors, palette.size() * 3, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } finishChunk(PLTE); } void PNGWriter::writetRNS(std::vector<unsigned> const& alpha) { if (alpha.size() == 0) { return; } std::vector<unsigned char> transparency(alpha.size()); unsigned char transparencySize = 0; // Stores position of biggest to nonopaque value. for(unsigned i = 0; i < alpha.size(); i++) { transparency[i] = alpha[i]; if (alpha[i] < 255) { transparencySize = i + 1; } } if (transparencySize > 0) { // Write tRNS chunk. size_t tRNS = startChunk(tRNS_tpl, 8); mz_bool status = tdefl_output_buffer_putter(&transparency[0], transparencySize, buffer); if (status != MZ_TRUE) { throw std::bad_alloc(); } finishChunk(tRNS); } } template<typename T> void PNGWriter::writeIDAT(T const& image) { // Write IDAT chunk. size_t IDAT = startChunk(IDAT_tpl, 8); mz_uint8 filter_type = 0; tdefl_status status; int bytes_per_pixel = sizeof(typename T::pixel_type); int stride = image.width() * bytes_per_pixel; for (unsigned int y = 0; y < image.height(); y++) { // Write filter_type status = tdefl_compress_buffer(compressor, &filter_type, 1, TDEFL_NO_FLUSH); if (status != TDEFL_STATUS_OKAY) { throw std::runtime_error("failed to compress image"); } // Write scanline status = tdefl_compress_buffer(compressor, (mz_uint8 *)image.getRow(y), stride, TDEFL_NO_FLUSH); if (status != TDEFL_STATUS_OKAY) { throw std::runtime_error("failed to compress image"); } } status = tdefl_compress_buffer(compressor, NULL, 0, TDEFL_FINISH); if (status != TDEFL_STATUS_DONE) { throw std::runtime_error("failed to compress image"); } finishChunk(IDAT); } template<typename T> void PNGWriter::writeIDATStripAlpha(T const& image) { // Write IDAT chunk. size_t IDAT = startChunk(IDAT_tpl, 8); mz_uint8 filter_type = 0; tdefl_status status; size_t stride = image.width() * 3; size_t i, j; mz_uint8 *scanline = (mz_uint8 *)MZ_MALLOC(stride); for (unsigned int y = 0; y < image.height(); y++) { // Write filter_type status = tdefl_compress_buffer(compressor, &filter_type, 1, TDEFL_NO_FLUSH); if (status != TDEFL_STATUS_OKAY) { MZ_FREE(scanline); throw std::runtime_error("failed to compress image"); } // Strip alpha bytes from scanline mz_uint8 *row = (mz_uint8 *)image.getRow(y); for (i = 0, j = 0; j < stride; i += 4, j += 3) { scanline[j] = row[i]; scanline[j+1] = row[i+1]; scanline[j+2] = row[i+2]; } // Write scanline status = tdefl_compress_buffer(compressor, scanline, stride, TDEFL_NO_FLUSH); if (status != TDEFL_STATUS_OKAY) { MZ_FREE(scanline); throw std::runtime_error("failed to compress image"); } } MZ_FREE(scanline); status = tdefl_compress_buffer(compressor, NULL, 0, TDEFL_FINISH); if (status != TDEFL_STATUS_DONE) throw std::runtime_error("failed to compress image"); finishChunk(IDAT); } void PNGWriter::writeIEND() { // Write IEND chunk. size_t IEND = startChunk(IEND_tpl, 8); finishChunk(IEND); } void PNGWriter::toStream(std::ostream& stream) { stream.write((char *)buffer->m_pBuf, buffer->m_size); } const mz_uint8 PNGWriter::preamble[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }; const mz_uint8 PNGWriter::IHDR_tpl[] = { 0x00, 0x00, 0x00, 0x0D, // chunk length 'I', 'H', 'D', 'R', // "IHDR" 0x00, 0x00, 0x00, 0x00, // image width (4 bytes) 0x00, 0x00, 0x00, 0x00, // image height (4 bytes) 0x00, // bit depth (1 byte) 0x00, // color type (1 byte) 0x00, // compression method (1 byte), has to be 0 0x00, // filter method (1 byte) 0x00 // interlace method (1 byte) }; const mz_uint8 PNGWriter::PLTE_tpl[] = { 0x00, 0x00, 0x00, 0x00, // chunk length 'P', 'L', 'T', 'E' // "IDAT" }; const mz_uint8 PNGWriter::tRNS_tpl[] = { 0x00, 0x00, 0x00, 0x00, // chunk length 't', 'R', 'N', 'S' // "IDAT" }; const mz_uint8 PNGWriter::IDAT_tpl[] = { 0x00, 0x00, 0x00, 0x00, // chunk length 'I', 'D', 'A', 'T' // "IDAT" }; const mz_uint8 PNGWriter::IEND_tpl[] = { 0x00, 0x00, 0x00, 0x00, // chunk length 'I', 'E', 'N', 'D' // "IEND" }; template void PNGWriter::writeIDAT<image_data_8>(image_data_8 const& image); template void PNGWriter::writeIDAT<image_view<image_data_8> >(image_view<image_data_8> const& image); template void PNGWriter::writeIDAT<image_data_32>(image_data_32 const& image); template void PNGWriter::writeIDAT<image_view<image_data_32> >(image_view<image_data_32> const& image); template void PNGWriter::writeIDATStripAlpha<image_data_32>(image_data_32 const& image); template void PNGWriter::writeIDATStripAlpha<image_view<image_data_32> >(image_view<image_data_32> const& image); }}
remove MINIZ_NO_STDIO as it is uneeded since it is covered by catchall MINIZ_NO_ARCHIVE_APIS
miniz: remove MINIZ_NO_STDIO as it is uneeded since it is covered by catchall MINIZ_NO_ARCHIVE_APIS
C++
lgpl-2.1
mapnik/mapnik,kapouer/mapnik,mapnik/mapnik,cjmayo/mapnik,yiqingj/work,Airphrame/mapnik,Uli1/mapnik,mapnik/python-mapnik,tomhughes/python-mapnik,davenquinn/python-mapnik,mapnik/python-mapnik,yiqingj/work,yohanboniface/python-mapnik,mbrukman/mapnik,zerebubuth/mapnik,stefanklug/mapnik,kapouer/mapnik,CartoDB/mapnik,davenquinn/python-mapnik,naturalatlas/mapnik,tomhughes/python-mapnik,rouault/mapnik,garnertb/python-mapnik,pnorman/mapnik,garnertb/python-mapnik,Airphrame/mapnik,Uli1/mapnik,CartoDB/mapnik,kapouer/mapnik,mbrukman/mapnik,yohanboniface/python-mapnik,naturalatlas/mapnik,pnorman/mapnik,manz/python-mapnik,tomhughes/mapnik,garnertb/python-mapnik,yohanboniface/python-mapnik,lightmare/mapnik,rouault/mapnik,whuaegeanse/mapnik,mapycz/python-mapnik,jwomeara/mapnik,jwomeara/mapnik,naturalatlas/mapnik,yiqingj/work,sebastic/python-mapnik,Mappy/mapnik,mapnik/python-mapnik,naturalatlas/mapnik,Mappy/mapnik,jwomeara/mapnik,pramsey/mapnik,pramsey/mapnik,tomhughes/mapnik,mbrukman/mapnik,tomhughes/python-mapnik,kapouer/mapnik,cjmayo/mapnik,mapycz/mapnik,sebastic/python-mapnik,pnorman/mapnik,rouault/mapnik,rouault/mapnik,zerebubuth/mapnik,cjmayo/mapnik,stefanklug/mapnik,whuaegeanse/mapnik,Mappy/mapnik,Airphrame/mapnik,whuaegeanse/mapnik,pramsey/mapnik,qianwenming/mapnik,Uli1/mapnik,cjmayo/mapnik,Uli1/mapnik,qianwenming/mapnik,lightmare/mapnik,mapycz/mapnik,tomhughes/mapnik,manz/python-mapnik,lightmare/mapnik,Airphrame/mapnik,mapycz/python-mapnik,pnorman/mapnik,Mappy/mapnik,qianwenming/mapnik,tomhughes/mapnik,mapycz/mapnik,stefanklug/mapnik,mbrukman/mapnik,davenquinn/python-mapnik,yiqingj/work,qianwenming/mapnik,mapnik/mapnik,whuaegeanse/mapnik,jwomeara/mapnik,zerebubuth/mapnik,sebastic/python-mapnik,qianwenming/mapnik,lightmare/mapnik,mapnik/mapnik,manz/python-mapnik,stefanklug/mapnik,pramsey/mapnik,CartoDB/mapnik
3c3b915dbd8991383ebd9515de46b2f9a77d7f81
filterfalse.hpp
filterfalse.hpp
#ifndef FILTERFALSE__H__ #define FILTERFALSE__H__ #include "filter.hpp" namespace iter { //Forward declarations of FilterFalse and filterfalse template <typename FilterFunc, typename Container> class FilterFalse; template <typename FilterFunc, typename Container> FilterFalse<FilterFunc, Container> filterfalse(FilterFunc, Container &); template <typename FilterFunc, typename Container> class FilterFalse : public Filter<FilterFunc, Container> { // The filterfalse function is the only thing allowed to // create a FilterFalse friend FilterFalse filterfalse<FilterFunc, Container>( FilterFunc, Container &); using Base = Filter<FilterFunc, Container>; public: using Filter<FilterFunc, Container>::Filter; class Iterator { protected: typename Base::contained_iter_type sub_iter; const typename Base::contained_iter_type sub_end; FilterFunc filter_func; // skip every element that is true ender the predicate void skip_passes() { while (this->sub_iter != this->sub_end && this->filter_func(*this->sub_iter)) { ++this->sub_iter; } } public: Iterator (typename Base::contained_iter_type iter, typename Base::contained_iter_type end, FilterFunc filter_func) : sub_iter(iter), sub_end(end), filter_func(filter_func) { this->skip_passes(); } typename Base::contained_iter_ret operator*() const { return *this->sub_iter; } Iterator & operator++() { ++this->sub_iter; this->skip_passes(); return *this; } bool operator!=(const Iterator & other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() const { return Iterator( this->container.begin(), this->container.end(), this->filter_func); } Iterator end() const { return Iterator( this->container.end(), this->container.end(), this->filter_func); } }; template <typename FilterFunc, typename Container> FilterFalse<FilterFunc, Container> filterfalse(FilterFunc filter_func, Container & container) { return FilterFalse<FilterFunc, Container>(filter_func, container); } //Forward declarations of filterfalseFalseDefault and filterfalse template <typename Container> class filterfalseFalseDefault; template <typename Container> filterfalseFalseDefault<Container> filterfalse(Container &); template <typename Container> class filterfalseFalseDefault { protected: Container & container; // The filterfalse function is the only thing allowed to create a // filterfalseFalseDefault friend filterfalseFalseDefault filterfalse<Container>(Container &); // Type of the Container::Iterator, but since the name of that // iterator can be anything, we have to grab it with this using contained_iter_type = decltype(container.begin()); // The type returned when dereferencing the Container::Iterator using contained_iter_ret = decltype(container.begin().operator*()); // Value constructor for use only in the filterfalse function filterfalseFalseDefault(Container & container) : container(container) { } filterfalseFalseDefault () = delete; filterfalseFalseDefault & operator=(const filterfalseFalseDefault &) = delete; public: filterfalseFalseDefault(const filterfalseFalseDefault &) = default; class Iterator { protected: contained_iter_type sub_iter; const contained_iter_type sub_end; void skip_passes() { while (this->sub_iter != this->sub_end && *this->sub_iter) { ++this->sub_iter; } } public: Iterator (contained_iter_type iter, contained_iter_type end) : sub_iter(iter), sub_end(end) { this->skip_passes(); } contained_iter_ret operator*() const { return *this->sub_iter; } Iterator & operator++() { ++this->sub_iter; this->skip_passes(); return *this; } bool operator!=(const Iterator & other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() const { return Iterator( this->container.begin(), this->container.end()); } Iterator end() const { return Iterator( this->container.end(), this->container.end()); } }; // Helper function to instantiate a filterfalseFalseDefault template <typename Container> filterfalseFalseDefault<Container> filterfalse(Container & container) { return filterfalseFalseDefault<Container>(container); } } #endif //ifndef FILTERFALSE__H__
#ifndef FILTER_FALSE__HPP__ #define FILTER_FALSE__HPP__ #include "filter.hpp" namespace iter { namespace detail { // Callable object that reverses the boolean result of another // callable, taking the object in a Container's iterator template <typename FilterFunc, typename Container> class PredicateFlipper { private: FilterFunc filter_func; using contained_iter_type = decltype(std::declval<Container>().begin()); using contained_iter_ret = decltype(std::declval<contained_iter_type>().operator*()); public: PredicateFlipper(FilterFunc filter_func) : filter_func(filter_func) { } PredicateFlipper() = delete; PredicateFlipper(const PredicateFlipper &) = default; // Calls the filter_func bool operator() (const contained_iter_ret item) const { return !bool(filter_func(item)); } }; // Reverses the bool() conversion result of anything that supports a // bool conversion template <typename Container> class BoolFlipper { private: using contained_iter_type = decltype(std::declval<Container>().begin()); using contained_iter_ret = decltype(std::declval<contained_iter_type>().operator*()); public: BoolFlipper() = default; BoolFlipper(const BoolFlipper &) = default; bool operator() (const contained_iter_ret item) const { return !bool(item); } }; } // Creates a PredicateFlipper for the predicate function, which reverses // the bool result of the function. The PredicateFlipper is then passed // to the normal filter() function template <typename FilterFunc, typename Container> auto filterfalse(FilterFunc filter_func, Container & container) -> decltype(filter(detail::PredicateFlipper<FilterFunc, Container>( filter_func), container)) { return filter( detail::PredicateFlipper<FilterFunc, Container>(filter_func), container); } // Single argument version, uses a BoolFlipper to reverse the truthiness // of an object template <typename Container> auto filterfalse(Container & container) -> decltype(filter(detail::BoolFlipper<Container>(), container)) { return filter(detail::BoolFlipper<Container>(), container); } } #endif //#ifndef FILTER_FALSE__HPP__
Complete rewrite of filterfalse
Complete rewrite of filterfalse Tosses the new classes in favor of wrapper function and extra classes to build filterfalse() ontop of filter()
C++
bsd-2-clause
jkhoogland/cppitertools,jkhoogland/cppitertools,ryanhaining/cppitertools,tempbottle/cppitertools,tempbottle/cppitertools,ryanhaining/cppitertools,tempbottle/cppitertools,ryanhaining/cppitertools,jkhoogland/cppitertools
95a6b35c4d1ff0741fca743ccc5be0fa071f9a29
cb_info/analyze.cpp
cb_info/analyze.cpp
// cb_info allows to parse and manipulate MCell's cellblender output files // // (C) Markus Dittrich, 2015 // Licenses under a BSD license, see LICENSE file for details #include <cassert> #include <iostream> #include <limits> #include "analyze.hpp" using binArray = std::array<long long, N3>; // static helper functions static std::tuple<Vec3, Vec3> compute_bounds( const SpecMap& specMap, const std::vector<std::string>& specs); static std::tuple<binArray, long long> compute_bins( const SpecMap& specMap, const std::vector<std::string>& specs, const Vec3& llc, const Vec3& urc); static void print_results(const Vec3& v1, const Vec3& v2, double chi); // analyze_mol_positions tests if molecules are uniformly distributed std::string analyze_mol_positions(const SpecMap& specMap, const std::vector<std::string>& specs) { Vec3 llc; Vec3 urc; std::tie(llc, urc) = compute_bounds(specMap, specs); binArray bin; long long numMols; std::tie(bin, numMols) = compute_bins(specMap, specs, llc, urc); if (numMols == 0) { return "selection contains no molecules"; } double expected = numMols / static_cast<double>(N3); double chi2 = 0; for (int z = 0; z < N; ++z) { for (int y = 0; y < N; ++y) { for (int x = 0; x < N; ++x) { double val = bin[x + y * N + z * N2] - expected; chi2 += val * val; } } } chi2 /= expected; print_results(llc, urc, chi2); return ""; } // compute_bounds computes the system bounds based on the position of all // molecules std::tuple<Vec3, Vec3> compute_bounds(const SpecMap& specMap, const std::vector<std::string>& specs) { Vec3 llc = {std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max()}; Vec3 urc = {-std::numeric_limits<double>::max(), -std::numeric_limits<double>::max(), -std::numeric_limits<double>::max()}; for (const auto& s : specs) { for (const auto& p : specMap.at(s).pos) { if (p.x < llc.x) { llc.x = p.x; } if (p.y < llc.y) { llc.y = p.y; } if (p.z < llc.z) { llc.z = p.z; } if (p.x > urc.x) { urc.x = p.x; } if (p.y > urc.y) { urc.y = p.y; } if (p.z > urc.z) { urc.z = p.z; } } } return std::make_tuple(llc, urc); } // print_results outputs the results of the chi squared analysis void print_results(const Vec3& llc, const Vec3& urc, double chi2) { std::cout << "------ system dimensions ------------------\n" << "LLC: " << llc << "\n" << "URC: " << urc << "\n\n"; if (chi2 < chi2_ref_999) { std::cout << "selected molecules are uniformly distributed (p = 0.01)\n"; } else { std::cout << "selected molecules are not uniformly distributed (p = 0.01)\n"; } std::cout << "CHI^2: " << chi2 << "/" << chi2_ref_999 << " (computed/expected)\n"; } // compute_bins computes the 3D binning of all selected molecules std::tuple<binArray, long long> compute_bins( const SpecMap& specMap, const std::vector<std::string>& specs, const Vec3& llc, const Vec3& urc) { long long numMols = 0; Vec3 delta = (urc - llc) / N; binArray bin{}; for (const auto& s : specs) { for (const auto& p : specMap.at(s).pos) { auto v = p - llc; assert(v.x >= 0); size_t bin_x = static_cast<int>(v.x/delta.x); if (bin_x < 0) { bin_x = 0; } else if (bin_x >= N) { bin_x = N-1; } assert(v.y >= 0); size_t bin_y = static_cast<int>(v.y/delta.y); if (bin_y < 0) { bin_y = 0; } else if (bin_y >= N) { bin_y = N-1; } assert(v.z >= 0); size_t bin_z = static_cast<int>(v.z/delta.z); if (bin_z < 0) { bin_z = 0; } else if (bin_z >= N) { bin_z = N-1; } ++bin[bin_x + bin_y * N + bin_z*N2]; ++numMols; } } return std::make_tuple(bin, numMols); }
// cb_info allows to parse and manipulate MCell's cellblender output files // // (C) Markus Dittrich, 2015 // Licenses under a BSD license, see LICENSE file for details #include <cassert> #include <iostream> #include <limits> #include "analyze.hpp" using binArray = std::array<long long, N3>; // static helper functions static std::tuple<Vec3, Vec3> compute_bounds( const SpecMap& specMap, const std::vector<std::string>& specs); static std::tuple<binArray, long long> compute_bins( const SpecMap& specMap, const std::vector<std::string>& specs, const Vec3& llc, const Vec3& urc); static void print_results(const Vec3& v1, const Vec3& v2, double chi); // analyze_mol_positions tests if molecules are uniformly distributed std::string analyze_mol_positions(const SpecMap& specMap, const std::vector<std::string>& specs) { Vec3 llc; Vec3 urc; std::tie(llc, urc) = compute_bounds(specMap, specs); binArray bin; long long numMols; std::tie(bin, numMols) = compute_bins(specMap, specs, llc, urc); if (numMols == 0) { return "selection contains no molecules"; } double expected = numMols / static_cast<double>(N3); double chi2 = 0; for (int z = 0; z < N; ++z) { for (int y = 0; y < N; ++y) { for (int x = 0; x < N; ++x) { double val = bin[x + y * N + z * N2] - expected; chi2 += val * val; } } } chi2 /= expected; print_results(llc, urc, chi2); return ""; } // compute_bounds computes the system bounds based on the position of all // molecules std::tuple<Vec3, Vec3> compute_bounds(const SpecMap& specMap, const std::vector<std::string>& specs) { Vec3 llc = {std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max()}; Vec3 urc = {-std::numeric_limits<double>::max(), -std::numeric_limits<double>::max(), -std::numeric_limits<double>::max()}; for (const auto& s : specs) { for (const auto& p : specMap.at(s).pos) { if (p.x < llc.x) { llc.x = p.x; } if (p.y < llc.y) { llc.y = p.y; } if (p.z < llc.z) { llc.z = p.z; } if (p.x > urc.x) { urc.x = p.x; } if (p.y > urc.y) { urc.y = p.y; } if (p.z > urc.z) { urc.z = p.z; } } } return std::make_tuple(llc, urc); } // print_results outputs the results of the chi squared analysis void print_results(const Vec3& llc, const Vec3& urc, double chi2) { std::cout << "\n------ system dimensions ------------------\n" << "LLC: " << llc << "\n" << "URC: " << urc << "\n\n"; if (chi2 < chi2_ref_999) { std::cout << "selected molecules are uniformly distributed (p = 0.01)\n"; } else { std::cout << "selected molecules are not uniformly distributed (p = 0.01)\n"; } std::cout << "CHI^2: " << chi2 << "/" << chi2_ref_999 << " (computed/cutoff)\n"; } // compute_bins computes the 3D binning of all selected molecules std::tuple<binArray, long long> compute_bins( const SpecMap& specMap, const std::vector<std::string>& specs, const Vec3& llc, const Vec3& urc) { long long numMols = 0; Vec3 delta = (urc - llc) / N; binArray bin{}; for (const auto& s : specs) { for (const auto& p : specMap.at(s).pos) { auto v = p - llc; assert(v.x >= 0); size_t bin_x = static_cast<int>(v.x/delta.x); if (bin_x < 0) { bin_x = 0; } else if (bin_x >= N) { bin_x = N-1; } assert(v.y >= 0); size_t bin_y = static_cast<int>(v.y/delta.y); if (bin_y < 0) { bin_y = 0; } else if (bin_y >= N) { bin_y = N-1; } assert(v.z >= 0); size_t bin_z = static_cast<int>(v.z/delta.z); if (bin_z < 0) { bin_z = 0; } else if (bin_z >= N) { bin_z = N-1; } ++bin[bin_x + bin_y * N + bin_z*N2]; ++numMols; } } return std::make_tuple(bin, numMols); }
Add small cosmetic fix to analysis output.
Add small cosmetic fix to analysis output.
C++
bsd-3-clause
haskelladdict/mcell_tools
63c5de04edc46203d03337d497dbdfc83f883595
sc/source/ui/inc/colorformat.hxx
sc/source/ui/inc/colorformat.hxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDED_SC_SOURCE_UI_INC_COLORFORMAT_HXX #define INCLUDED_SC_SOURCE_UI_INC_COLORFORMAT_HXX #include <vcl/button.hxx> #include <vcl/dialog.hxx> #include <vcl/fixed.hxx> #include <svtools/ctrlbox.hxx> #include <svl/zforlist.hxx> #include "anyrefdg.hxx" struct ScDataBarFormatData; class ScDocument; class ScDataBarSettingsDlg : public ModalDialog { private: VclPtr<OKButton> mpBtnOk; VclPtr<CancelButton> mpBtnCancel; VclPtr<ColorListBox> mpLbPos; VclPtr<ColorListBox> mpLbNeg; VclPtr<ColorListBox> mpLbFillType; VclPtr<ColorListBox> mpLbAxisCol; VclPtr<ListBox> mpLbTypeMin; VclPtr<ListBox> mpLbTypeMax; VclPtr<ListBox> mpLbAxisPos; VclPtr<Edit> mpEdMin; VclPtr<Edit> mpEdMax; VclPtr<Edit> mpLenMin; VclPtr<Edit> mpLenMax; VclPtr<CheckBox> mpCbOnlyBar; OUString maStrWarnSameValue; SvNumberFormatter* mpNumberFormatter; ScDocument* mpDoc; ScAddress maPos; DECL_LINK(OkBtnHdl, void*); DECL_LINK(TypeSelectHdl, void*); DECL_LINK(PosSelectHdl, void*); void Init(); public: ScDataBarSettingsDlg(vcl::Window* pParent, const ScDataBarFormatData& rData, ScDocument* pDoc, const ScAddress& rPos); virtual ~ScDataBarSettingsDlg(); virtual void dispose() SAL_OVERRIDE; ScDataBarFormatData* GetData(); }; #endif // INCLUDED_SC_SOURCE_UI_INC_COLORFORMAT_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDED_SC_SOURCE_UI_INC_COLORFORMAT_HXX #define INCLUDED_SC_SOURCE_UI_INC_COLORFORMAT_HXX #include <vcl/button.hxx> #include <vcl/dialog.hxx> #include <vcl/fixed.hxx> #include <svtools/ctrlbox.hxx> #include <svl/zforlist.hxx> #include "anyrefdg.hxx" struct ScDataBarFormatData; class ScDocument; class ScDataBarSettingsDlg : public ModalDialog { private: VclPtr<OKButton> mpBtnOk; VclPtr<CancelButton> mpBtnCancel; VclPtr<ColorListBox> mpLbPos; VclPtr<ColorListBox> mpLbNeg; VclPtr<ColorListBox> mpLbAxisCol; VclPtr<ListBox> mpLbFillType; VclPtr<ListBox> mpLbTypeMin; VclPtr<ListBox> mpLbTypeMax; VclPtr<ListBox> mpLbAxisPos; VclPtr<Edit> mpEdMin; VclPtr<Edit> mpEdMax; VclPtr<Edit> mpLenMin; VclPtr<Edit> mpLenMax; VclPtr<CheckBox> mpCbOnlyBar; OUString maStrWarnSameValue; SvNumberFormatter* mpNumberFormatter; ScDocument* mpDoc; ScAddress maPos; DECL_LINK(OkBtnHdl, void*); DECL_LINK(TypeSelectHdl, void*); DECL_LINK(PosSelectHdl, void*); void Init(); public: ScDataBarSettingsDlg(vcl::Window* pParent, const ScDataBarFormatData& rData, ScDocument* pDoc, const ScAddress& rPos); virtual ~ScDataBarSettingsDlg(); virtual void dispose() SAL_OVERRIDE; ScDataBarFormatData* GetData(); }; #endif // INCLUDED_SC_SOURCE_UI_INC_COLORFORMAT_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
fix regression from 552f754ab9d9f0fedd73d5328618315ec774d3d6
fix regression from 552f754ab9d9f0fedd73d5328618315ec774d3d6 How did that ever work when testing? Change-Id: Ib8520da252c7fa11c9a0cec62a2bba6833951901 Reviewed-on: https://gerrit.libreoffice.org/15724 Tested-by: Markus Mohrhard <[email protected]> Reviewed-by: Markus Mohrhard <[email protected]>
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
25a242fea8f6df3341855526c9d8a855dfdb11ff
search/cities_boundaries_table.cpp
search/cities_boundaries_table.cpp
#include "search/cities_boundaries_table.hpp" #include "search/categories_cache.hpp" #include "search/localities_source.hpp" #include "search/mwm_context.hpp" #include "search/utils.hpp" #include "indexer/cities_boundaries_serdes.hpp" #include "indexer/mwm_set.hpp" #include "coding/reader.hpp" #include "base/assert.hpp" #include "base/cancellable.hpp" #include "base/checked_cast.hpp" #include "base/logging.hpp" #include <algorithm> using namespace indexer; using namespace std; namespace search { // CitiesBoundariesTable::Boundaries --------------------------------------------------------------- bool CitiesBoundariesTable::Boundaries::HasPoint(m2::PointD const & p) const { return any_of(m_boundaries.begin(), m_boundaries.end(), [&](CityBoundary const & b) { return b.HasPoint(p, m_eps); }); } // CitiesBoundariesTable --------------------------------------------------------------------------- bool CitiesBoundariesTable::Load() { auto handle = FindWorld(m_dataSource); if (!handle.IsAlive()) { LOG(LWARNING, ("Can't find World map file.")); return false; } // Skip if table was already loaded from this file. if (handle.GetId() == m_mwmId) return true; MwmContext context(move(handle)); base::Cancellable const cancellable; auto const localities = CategoriesCache(LocalitiesSource{}, cancellable).Get(context); auto const & cont = context.m_value.m_cont; if (!cont.IsExist(CITIES_BOUNDARIES_FILE_TAG)) { LOG(LWARNING, ("No cities boundaries table in the world map.")); return false; } vector<vector<CityBoundary>> all; double precision; try { auto reader = cont.GetReader(CITIES_BOUNDARIES_FILE_TAG); ReaderSource<ReaderPtr<ModelReader>> source(reader); CitiesBoundariesSerDes::Deserialize(source, all, precision); } catch (Reader::Exception const & e) { LOG(LERROR, ("Can't read cities boundaries table from the world map:", e.Msg())); return false; } // Disabled until World.mwm generation with new code. // ASSERT_EQUAL(all.size(), localities.PopCount(), ()); if (all.size() != localities.PopCount()) { // Disabled until World.mwm generation with new code. // LOG(LERROR, // ("Wrong number of boundaries, expected:", localities.PopCount(), "actual:", all.size())); return false; } m_mwmId = context.GetId(); m_table.clear(); m_eps = precision; size_t boundary = 0; localities.ForEach([&](uint64_t fid) { ASSERT_LESS(boundary, all.size(), ()); m_table[base::asserted_cast<uint32_t>(fid)] = move(all[boundary]); ++boundary; }); ASSERT_EQUAL(boundary, all.size(), ()); return true; } bool CitiesBoundariesTable::Get(FeatureID const & fid, Boundaries & bs) const { if (fid.m_mwmId != m_mwmId) return false; return Get(fid.m_index, bs); } bool CitiesBoundariesTable::Get(uint32_t fid, Boundaries & bs) const { auto const it = m_table.find(fid); if (it == m_table.end()) return false; bs = Boundaries(it->second, m_eps); return true; } void GetCityBoundariesInRectForTesting(CitiesBoundariesTable const & table, m2::RectD const & rect, vector<uint32_t> & featureIds) { featureIds.clear(); for (auto const & kv : table.m_table) { for (auto const & cb : kv.second) { if (rect.IsIntersect(m2::RectD(cb.m_bbox.Min(), cb.m_bbox.Max()))) { featureIds.push_back(kv.first); break; } } } } } // namespace search
#include "search/cities_boundaries_table.hpp" #include "search/categories_cache.hpp" #include "search/localities_source.hpp" #include "search/mwm_context.hpp" #include "search/utils.hpp" #include "indexer/cities_boundaries_serdes.hpp" #include "indexer/mwm_set.hpp" #include "coding/reader.hpp" #include "base/assert.hpp" #include "base/cancellable.hpp" #include "base/checked_cast.hpp" #include "base/logging.hpp" #include <algorithm> using namespace indexer; using namespace std; namespace search { // CitiesBoundariesTable::Boundaries --------------------------------------------------------------- bool CitiesBoundariesTable::Boundaries::HasPoint(m2::PointD const & p) const { return any_of(m_boundaries.begin(), m_boundaries.end(), [&](CityBoundary const & b) { return b.HasPoint(p, m_eps); }); } // CitiesBoundariesTable --------------------------------------------------------------------------- bool CitiesBoundariesTable::Load() { auto handle = FindWorld(m_dataSource); if (!handle.IsAlive()) { LOG(LWARNING, ("Can't find World map file.")); return false; } // Skip if table was already loaded from this file. if (handle.GetId() == m_mwmId) return true; MwmContext context(move(handle)); base::Cancellable const cancellable; auto const localities = CategoriesCache(LocalitiesSource{}, cancellable).Get(context); auto const & cont = context.m_value.m_cont; if (!cont.IsExist(CITIES_BOUNDARIES_FILE_TAG)) { LOG(LWARNING, ("No cities boundaries table in the world map.")); return false; } vector<vector<CityBoundary>> all; double precision; try { auto reader = cont.GetReader(CITIES_BOUNDARIES_FILE_TAG); ReaderSource<ReaderPtr<ModelReader>> source(reader); CitiesBoundariesSerDes::Deserialize(source, all, precision); } catch (Reader::Exception const & e) { LOG(LERROR, ("Can't read cities boundaries table from the world map:", e.Msg())); return false; } ASSERT_EQUAL(all.size(), localities.PopCount(), ()); if (all.size() != localities.PopCount()) { LOG(LERROR, ("Wrong number of boundaries, expected:", localities.PopCount(), "actual:", all.size())); return false; } m_mwmId = context.GetId(); m_table.clear(); m_eps = precision; size_t boundary = 0; localities.ForEach([&](uint64_t fid) { ASSERT_LESS(boundary, all.size(), ()); m_table[base::asserted_cast<uint32_t>(fid)] = move(all[boundary]); ++boundary; }); ASSERT_EQUAL(boundary, all.size(), ()); return true; } bool CitiesBoundariesTable::Get(FeatureID const & fid, Boundaries & bs) const { if (fid.m_mwmId != m_mwmId) return false; return Get(fid.m_index, bs); } bool CitiesBoundariesTable::Get(uint32_t fid, Boundaries & bs) const { auto const it = m_table.find(fid); if (it == m_table.end()) return false; bs = Boundaries(it->second, m_eps); return true; } void GetCityBoundariesInRectForTesting(CitiesBoundariesTable const & table, m2::RectD const & rect, vector<uint32_t> & featureIds) { featureIds.clear(); for (auto const & kv : table.m_table) { for (auto const & cb : kv.second) { if (rect.IsIntersect(m2::RectD(cb.m_bbox.Min(), cb.m_bbox.Max()))) { featureIds.push_back(kv.first); break; } } } } } // namespace search
Enable CitiesBoundariesTable.
[search] Enable CitiesBoundariesTable.
C++
apache-2.0
mapsme/omim,alexzatsepin/omim,VladiMihaylenko/omim,mapsme/omim,matsprea/omim,bykoianko/omim,mapsme/omim,matsprea/omim,bykoianko/omim,alexzatsepin/omim,milchakov/omim,VladiMihaylenko/omim,matsprea/omim,matsprea/omim,darina/omim,alexzatsepin/omim,mpimenov/omim,darina/omim,VladiMihaylenko/omim,milchakov/omim,mapsme/omim,rokuz/omim,bykoianko/omim,milchakov/omim,milchakov/omim,milchakov/omim,matsprea/omim,VladiMihaylenko/omim,darina/omim,bykoianko/omim,alexzatsepin/omim,mpimenov/omim,milchakov/omim,rokuz/omim,matsprea/omim,bykoianko/omim,mpimenov/omim,bykoianko/omim,VladiMihaylenko/omim,milchakov/omim,rokuz/omim,rokuz/omim,VladiMihaylenko/omim,mapsme/omim,rokuz/omim,matsprea/omim,rokuz/omim,VladiMihaylenko/omim,matsprea/omim,rokuz/omim,bykoianko/omim,mpimenov/omim,bykoianko/omim,rokuz/omim,mpimenov/omim,mpimenov/omim,mapsme/omim,alexzatsepin/omim,bykoianko/omim,mpimenov/omim,alexzatsepin/omim,rokuz/omim,mapsme/omim,darina/omim,bykoianko/omim,mpimenov/omim,mapsme/omim,matsprea/omim,milchakov/omim,darina/omim,VladiMihaylenko/omim,rokuz/omim,alexzatsepin/omim,VladiMihaylenko/omim,mpimenov/omim,alexzatsepin/omim,milchakov/omim,bykoianko/omim,VladiMihaylenko/omim,milchakov/omim,alexzatsepin/omim,mapsme/omim,alexzatsepin/omim,alexzatsepin/omim,matsprea/omim,bykoianko/omim,darina/omim,mapsme/omim,darina/omim,bykoianko/omim,darina/omim,milchakov/omim,darina/omim,alexzatsepin/omim,darina/omim,darina/omim,mpimenov/omim,alexzatsepin/omim,milchakov/omim,rokuz/omim,mapsme/omim,VladiMihaylenko/omim,mapsme/omim,rokuz/omim,mpimenov/omim,milchakov/omim,VladiMihaylenko/omim,rokuz/omim,mpimenov/omim,VladiMihaylenko/omim,darina/omim,mapsme/omim,mpimenov/omim,darina/omim
e89a170f9af1ba4e6786eb157fd75b7b67d22336
firmware/Adafruit_HDC1000.cpp
firmware/Adafruit_HDC1000.cpp
/*************************************************** This is a library for the HDC1000 Humidity & Temp Sensor Designed specifically to work with the HDC1008 sensor from Adafruit ----> https://www.adafruit.com/products/2635 These sensors use I2C to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution Modified for Photon needs application.h for types RMB ****************************************************/ #include "application.h" #include "Adafruit_HDC1000/Adafruit_HDC1000.h" Adafruit_HDC1000::Adafruit_HDC1000() { } boolean Adafruit_HDC1000::begin(uint8_t addr) { _i2caddr = addr; Wire.begin(); reset(); if (read16(HDC1000_MANUFID) != 0x5449) return false; if (read16(HDC1000_DEVICEID) != 0x1000) return false; return true; } void Adafruit_HDC1000::reset(void) { // reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14; Wire.beginTransmission(_i2caddr); Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB Wire.write(config>>8); // now write out 2 bytes MSB first RMB Wire.write(config&0xFF); Wire.endTransmission(); delay(15); } float Adafruit_HDC1000::readTemperature(void) { float temp = (read32(HDC1000_TEMP, 20) >> 16); temp /= 65536; temp *= 165; temp -= 40; return temp; } float Adafruit_HDC1000::readHumidity(void) { // original code used HDC1000_TEMP register, doesn't work with HDC1000_HUMID with 32bit read RMB float hum = (read32(HDC1000_TEMP, 20) & 0xFFFF); hum /= 65536; hum *= 100; return hum; } // Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V // Thanks to KFricke for micropython-hdc1008 on GitHub, usually called after Temp/Humid reading RMB boolean Adafruit_HDC1000::batteryLOW(void) { uint16_t battV = (read16(HDC1000_CONFIG_BATT, 20)); battV &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V if (battV > 0) return true; return false; } /*********************************************************************/ uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) { Wire.beginTransmission(_i2caddr); Wire.write(a); Wire.endTransmission(); delay(d); Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2); uint16_t r = Wire.read(); r <<= 8; r |= Wire.read(); //Serial.println(r, HEX); return r; } uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) { Wire.beginTransmission(_i2caddr); Wire.write(a); Wire.endTransmission(); delay(50); Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4); uint32_t r = Wire.read(); r <<= 8; r |= Wire.read(); r <<= 8; r |= Wire.read(); r <<= 8; r |= Wire.read(); //Serial.println(r, HEX); return r; }
/*************************************************** This is a library for the HDC1000 Humidity & Temp Sensor Designed specifically to work with the HDC1008 sensor from Adafruit ----> https://www.adafruit.com/products/2635 These sensors use I2C to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution Modified for Photon needs application.h for types RMB ****************************************************/ #include "application.h" #include "Adafruit_HDC1000/Adafruit_HDC1000.h" Adafruit_HDC1000::Adafruit_HDC1000() { } boolean Adafruit_HDC1000::begin(uint8_t addr) { _i2caddr = addr; Wire.begin(); reset(); if (read16(HDC1000_MANUFID) != 0x5449) return false; if (read16(HDC1000_DEVICEID) != 0x1000) return false; return true; } void Adafruit_HDC1000::reset(void) { // reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14; Wire.beginTransmission(_i2caddr); Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB Wire.write(config>>8); // now write out 2 bytes MSB first RMB Wire.write(config&0xFF); Wire.endTransmission(); delay(15); } float Adafruit_HDC1000::readTemperature(void) { float temp = (read32(HDC1000_TEMP, 20) >> 16); temp /= 65536; temp *= 165; temp -= 40; return temp; } float Adafruit_HDC1000::readHumidity(void) { // reads both temp and humidity, masks out temp in highest 16 bits // originally used hum but humidity declared in private section of class float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF); humidity /= 65536; humidity *= 100; return hum; } // Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V // Thanks to KFricke for micropython-hdc1008 on GitHub, usually called after Temp/Humid reading RMB boolean Adafruit_HDC1000::batteryLOW(void) { uint16_t battV = (read16(HDC1000_CONFIG_BATT, 20)); battV &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V if (battV > 0) return true; return false; } /*********************************************************************/ uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) { Wire.beginTransmission(_i2caddr); Wire.write(a); Wire.endTransmission(); delay(d); Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2); uint16_t r = Wire.read(); r <<= 8; r |= Wire.read(); //Serial.println(r, HEX); return r; } uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) { Wire.beginTransmission(_i2caddr); Wire.write(a); Wire.endTransmission(); // delay was hardcoded as 50, should be d (delay) delay(d); Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4); uint32_t r = Wire.read(); // assembles temp into highest 16 bits, humidity into lowest 16 bits r <<= 8; r |= Wire.read(); r <<= 8; r |= Wire.read(); r <<= 8; r |= Wire.read(); //Serial.println(r, HEX); return r; }
use variable d instead of hardcoded 50 in read32()
use variable d instead of hardcoded 50 in read32()
C++
bsd-2-clause
CaptIgmu/Adafruit_HDC1000,CaptIgmu/Adafruit_HDC1000
9083f456ddcf6ee9f1627471b14e255436e768f6
firmware/examples/example.cpp
firmware/examples/example.cpp
/*============================================================================== * Configuration Variables * * Change these variables to your own settings. *=============================================================================*/ String cikData = "0000000000000000000000000000000000000000"; // <-- Fill in your CIK here! (https://portals.exosite.com -> Add Device) // Use these variables to customize what datasources are read and written to. String readString = "command&uptime"; String writeString = "uptime="; String returnString; /*============================================================================== * End of Configuration Variables *=============================================================================*/ class TCPClient client; Exosite exosite(cikData, &client); /*============================================================================== * setup * * Arduino setup function. *=============================================================================*/ void setup(){ Serial.begin(115200); delay(3000); Serial.println("Boot"); } /*============================================================================== * loop * * Arduino loop function. *=============================================================================*/ void loop(){ //Write to "uptime" and read from "uptime" and "command" datasources. if ( exosite.writeRead(writeString+String(millis()), readString, returnString)){ Serial.println("OK"); Serial.println(returnString); delay(5000); }else{ Serial.println("Error"); delay(500); } }
#include "exosite/exosite.h" /*============================================================================== * Configuration Variables * * Change these variables to your own settings. *=============================================================================*/ String cikData = "0000000000000000000000000000000000000000"; // <-- Fill in your CIK here! (https://portals.exosite.com -> Add Device) // Use these variables to customize what datasources are read and written to. String readString = "command&uptime"; String writeString = "uptime="; String returnString; /*============================================================================== * End of Configuration Variables *=============================================================================*/ class TCPClient client; Exosite exosite(cikData, &client); /*============================================================================== * setup * * Arduino setup function. *=============================================================================*/ void setup(){ Serial.begin(115200); delay(3000); Serial.println("Boot"); } /*============================================================================== * loop * * Arduino loop function. *=============================================================================*/ void loop(){ //Write to "uptime" and read from "uptime" and "command" datasources. if ( exosite.writeRead(writeString+String(millis()), readString, returnString)){ Serial.println("OK"); Serial.println(returnString); delay(5000); }else{ Serial.println("Error"); delay(500); } }
Include Needed
Include Needed
C++
bsd-3-clause
exosite-garage/SparkCore-Exosite,exosite-garage/particle_exosite_library
c95ad6b51cfb9c0495d9fc8e06dfbef0f409c179
src/object/fwd.hh
src/object/fwd.hh
/** ** \file object/fwd.hh ** \brief Forward declarations of all node-classes of OBJECT ** (needed by the visitors) */ #ifndef OBJECT_FWD_HH # define OBJECT_FWD_HH # include <vector> # include "libport/fwd.hh" # include "libport/shared-ptr.hh" namespace ast { class Exp; } namespace object { // state.hh struct State; // rObject & objects_type. class Object; typedef libport::shared_ptr<Object> rObject; typedef std::vector<rObject> objects_type; /// \a Macro should be a binary macro whose first arg, \p What, is the /// lower case C++ name, and the second argument, \p Name, the /// capitalized URBI name. # define APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT_AND_PRIMITIVE(Macro) \ Macro(code, Code) \ Macro(delegate, Delegate) \ Macro(lobby, Lobby) \ Macro(float, Float) \ Macro(integer, Integer) \ Macro(list, List) \ Macro(string, String) # define APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) \ Macro(primitive, Primitive) \ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT_AND_PRIMITIVE(Macro) # define APPLY_ON_ALL_PRIMITIVES(Macro) \ Macro(object, Object) \ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) // All the atoms. template <typename Traits> class Atom; /// Define a primitive as an Atom parametrized with a traits. # define DEFINE(What, Name) \ struct What ## _traits; \ typedef Atom< What ## _traits > Name; \ typedef libport::shared_ptr < Name > r ## Name; /* You have to understand that the primitives are defined here. For * example, a Code is manipulated through a rCode (r = ref counted) and in * fact Code is just a typedef for Atom<code_traits>. If get compilation * errors about non existent members, it's most likely because you did * obj.get_value () instead of obj->get_value (). This is a side effect * of the operator-> used for the ref-counting. Keep that in mind. */ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT_AND_PRIMITIVE(DEFINE) // primitive_type. // It is because we need this typedef that we have the // previous hideous macro. typedef rObject (*primitive_type) (rLobby, objects_type); DEFINE(primitive, Primitive) # undef DEFINE // urbi-exception.hh class IDelegate; class UrbiException; class LookupError; class RedefinitionError; class PrimitiveError; class WrongArgumentType; class WrongArgumentCount; extern rObject void_class; } // namespace object #endif // !OBJECT_FWD_HH
/** ** \file object/fwd.hh ** \brief Forward declarations of all node-classes of OBJECT ** (needed by the visitors) */ #ifndef OBJECT_FWD_HH # define OBJECT_FWD_HH # include <vector> # include "libport/fwd.hh" # include "libport/shared-ptr.hh" namespace object { // state.hh struct State; // rObject & objects_type. class Object; typedef libport::shared_ptr<Object> rObject; typedef std::vector<rObject> objects_type; /// \a Macro should be a binary macro whose first arg, \p What, is the /// lower case C++ name, and the second argument, \p Name, the /// capitalized URBI name. # define APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT_AND_PRIMITIVE(Macro) \ Macro(code, Code) \ Macro(delegate, Delegate) \ Macro(lobby, Lobby) \ Macro(float, Float) \ Macro(integer, Integer) \ Macro(list, List) \ Macro(string, String) # define APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) \ Macro(primitive, Primitive) \ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT_AND_PRIMITIVE(Macro) # define APPLY_ON_ALL_PRIMITIVES(Macro) \ Macro(object, Object) \ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) // All the atoms. template <typename Traits> class Atom; /// Define a primitive as an Atom parametrized with a traits. # define DEFINE(What, Name) \ struct What ## _traits; \ typedef Atom< What ## _traits > Name; \ typedef libport::shared_ptr < Name > r ## Name; /* You have to understand that the primitives are defined here. For * example, a Code is manipulated through a rCode (r = ref counted) and in * fact Code is just a typedef for Atom<code_traits>. If get compilation * errors about non existent members, it's most likely because you did * obj.get_value () instead of obj->get_value (). This is a side effect * of the operator-> used for the ref-counting. Keep that in mind. */ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT_AND_PRIMITIVE(DEFINE) // primitive_type. // It is because we need this typedef that we have the // previous hideous macro. typedef rObject (*primitive_type) (rLobby, objects_type); DEFINE(primitive, Primitive) # undef DEFINE // urbi-exception.hh class IDelegate; class UrbiException; class LookupError; class RedefinitionError; class PrimitiveError; class WrongArgumentType; class WrongArgumentCount; extern rObject void_class; } // namespace object #endif // !OBJECT_FWD_HH
Remove unused forward declaration.
Remove unused forward declaration. * src/object/fwd.hh: Remove unused ast::Exp forward.
C++
bsd-3-clause
urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi
401390bb63e551db86a2a045d0e8e4f8f9d73ba8
kernel/src/modelingTools/FirstOrderLinearTIR.cpp
kernel/src/modelingTools/FirstOrderLinearTIR.cpp
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include "SimpleMatrix.hpp" #include "FirstOrderLinearTIR.hpp" #include "Interaction.hpp" #include "BlockVector.hpp" #include "SimulationGraphs.hpp" #include "SiconosAlgebraProd.hpp" // for matrix-vector prod // #define DEBUG_NOCOLOR // #define DEBUG_STDOUT // #define DEBUG_MESSAGES #include "debug.h" using namespace RELATION; FirstOrderLinearTIR::FirstOrderLinearTIR(): FirstOrderR(LinearTIR) { } // Minimum data (C, B as pointers) constructor FirstOrderLinearTIR::FirstOrderLinearTIR(SP::SimpleMatrix C, SP::SimpleMatrix B): FirstOrderR(LinearTIR) { _C = C; _B = B; } // Constructor from a complete set of data FirstOrderLinearTIR::FirstOrderLinearTIR(SP::SimpleMatrix C, SP::SimpleMatrix D, SP::SimpleMatrix F, SP::SiconosVector e, SP::SimpleMatrix B): FirstOrderR(LinearTIR) { _C = C; _B = B; _D = D; _F = F; _e = e; } void FirstOrderLinearTIR::initialize(Interaction& inter) { DEBUG_PRINT("FirstOrderLinearTIR::initialize(Interaction & inter)\n"); FirstOrderR::initialize(inter); // ? if(!_C) RuntimeException::selfThrow("FirstOrderLinearTIR::initialize() C is null and is a required input."); if(!_B) RuntimeException::selfThrow("FirstOrderLinearTIR::initialize() B is null and is a required input."); checkSize(inter); } void FirstOrderLinearTIR::checkSize(Interaction& inter) { DEBUG_PRINT("FirstOrderLinearTIR::checkSize(Interaction & inter)\n"); DEBUG_PRINTF("_C->size(0) = %i,\t inter.dimension() = %i\n ",_C->size(0),inter.dimension()); DEBUG_PRINTF("_C->size(1) = %i,\t inter.getSizeOfDS() = %i\n ",_C->size(1),inter.getSizeOfDS()); assert((_C->size(0) == inter.dimension() && _C->size(1) == inter.getSizeOfDS()) && "FirstOrderLinearTIR::initialize , inconsistent size between C and Interaction."); assert((_B->size(1) == inter.dimension() && _B->size(0) == inter.getSizeOfDS()) && "FirstOrderLinearTIR::initialize , inconsistent size between B and interaction."); // C and B are the minimum inputs. The others may remain null. if(_D) assert((_D->size(0) == inter.dimension() || _D->size(1) == inter.dimension()) && "FirstOrderLinearTIR::initialize , inconsistent size between C and D."); if(_F) assert(((_F->size(0) != inter.dimension()) && (_F->size(1) != (inter.linkToDSVariables())[FirstOrderR::z]->size())) && "FirstOrderLinearTIR::initialize , inconsistent size between C and F."); if(_e) assert(_e->size() == inter.dimension() && "FirstOrderLinearTIR::initialize , inconsistent size between C and e."); } void FirstOrderLinearTIR::computeh(BlockVector& x, SiconosVector& lambda, BlockVector& z, SiconosVector& y) { if(_C) prod(*_C, x, y, true); else y.zero(); if(_D) prod(*_D, lambda, y, false); if(_e) y += *_e; if(_F) prod(*_F, z, y, false); } void FirstOrderLinearTIR::computeOutput(double time, Interaction& inter, unsigned int level) { // We get y and lambda of the interaction (pointers) SiconosVector& y = *inter.y(level); SiconosVector& lambda = *inter.lambda(level); VectorOfBlockVectors& DSlink = inter.linkToDSVariables(); computeh(*DSlink[FirstOrderR::x], lambda, *DSlink[FirstOrderR::z], y); } void FirstOrderLinearTIR::computeg(SiconosVector& lambda, BlockVector& r) { prod(*_B, lambda, r, false); } void FirstOrderLinearTIR::computeInput(double time, Interaction& inter, unsigned int level) { DEBUG_BEGIN("FirstOrderLinearTIR::computeInput(double time, Interaction& inter, unsigned int level)\n") VectorOfBlockVectors& DSlink = inter.linkToDSVariables(); DEBUG_EXPR(inter.lambda(level)->display();); DEBUG_EXPR(DSlink[FirstOrderR::r]->display();); computeg(*inter.lambda(level), *DSlink[FirstOrderR::r]); DEBUG_END("FirstOrderLinearTIR::computeInput(double time, Interaction& inter, unsigned int level)\n") } void FirstOrderLinearTIR::display() const { std::cout << " ===== Linear Time Invariant relation display ===== " <<std::endl; std::cout << "| C " <<std::endl; if(_C) _C->display(); else std::cout << "->NULL" <<std::endl; std::cout << "| D " <<std::endl; if(_D) _D->display(); else std::cout << "->NULL" <<std::endl; std::cout << "| F " <<std::endl; if(_F) _F->display(); else std::cout << "->NULL" <<std::endl; std::cout << "| e " <<std::endl; if(_e) _e->display(); else std::cout << "->NULL" <<std::endl; std::cout << "| B " <<std::endl; if(_B) _B->display(); else std::cout << "->NULL" <<std::endl; std::cout << " ================================================== " <<std::endl; }
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include "SimpleMatrix.hpp" #include "FirstOrderLinearTIR.hpp" #include "Interaction.hpp" #include "BlockVector.hpp" #include "SimulationGraphs.hpp" #include "SiconosAlgebraProd.hpp" // for matrix-vector prod // #define DEBUG_NOCOLOR // #define DEBUG_STDOUT // #define DEBUG_MESSAGES #include "debug.h" using namespace RELATION; FirstOrderLinearTIR::FirstOrderLinearTIR(): FirstOrderR(LinearTIR) { } // Minimum data (C, B as pointers) constructor FirstOrderLinearTIR::FirstOrderLinearTIR(SP::SimpleMatrix C, SP::SimpleMatrix B): FirstOrderR(LinearTIR) { _C = C; _B = B; } // Constructor from a complete set of data FirstOrderLinearTIR::FirstOrderLinearTIR(SP::SimpleMatrix C, SP::SimpleMatrix D, SP::SimpleMatrix F, SP::SiconosVector e, SP::SimpleMatrix B): FirstOrderR(LinearTIR) { _C = C; _B = B; _D = D; _F = F; _e = e; } void FirstOrderLinearTIR::initialize(Interaction& inter) { DEBUG_PRINT("FirstOrderLinearTIR::initialize(Interaction & inter)\n"); FirstOrderR::initialize(inter); // ? if(!_C) RuntimeException::selfThrow("FirstOrderLinearTIR::initialize() C is null and is a required input."); if(!_B) RuntimeException::selfThrow("FirstOrderLinearTIR::initialize() B is null and is a required input."); checkSize(inter); } void FirstOrderLinearTIR::checkSize(Interaction& inter) { DEBUG_PRINT("FirstOrderLinearTIR::checkSize(Interaction & inter)\n"); DEBUG_PRINTF("_C->size(0) = %i,\t inter.dimension() = %i\n ",_C->size(0),inter.dimension()); DEBUG_PRINTF("_C->size(1) = %i,\t inter.getSizeOfDS() = %i\n ",_C->size(1),inter.getSizeOfDS()); assert((_C->size(0) == inter.dimension() && _C->size(1) == inter.getSizeOfDS()) && "FirstOrderLinearTIR::initialize , inconsistent size between C and Interaction sizes."); assert((_B->size(1) == inter.dimension() && _B->size(0) == inter.getSizeOfDS()) && "FirstOrderLinearTIR::initialize , inconsistent size between B and interaction sizes."); // C and B are the minimum inputs. The others may remain null. if(_D) assert((_D->size(0) == inter.dimension() || _D->size(1) == inter.dimension()) && "FirstOrderLinearTIR::initialize , inconsistent size between D and interaction sizes"); DEBUG_EXPR(if(_F) _F->display(); (inter.linkToDSVariables())[FirstOrderR::z]->display();); if(_F) assert(((_F->size(0) == inter.dimension()) && (_F->size(1) == (inter.linkToDSVariables())[FirstOrderR::z]->size())) && "FirstOrderLinearTIR::initialize , inconsistent size between F and z."); if(_e) assert(_e->size() == inter.dimension() && "FirstOrderLinearTIR::initialize , inconsistent size between C and e."); } void FirstOrderLinearTIR::computeh(BlockVector& x, SiconosVector& lambda, BlockVector& z, SiconosVector& y) { if(_C) prod(*_C, x, y, true); else y.zero(); if(_D) prod(*_D, lambda, y, false); if(_e) y += *_e; if(_F) prod(*_F, z, y, false); } void FirstOrderLinearTIR::computeOutput(double time, Interaction& inter, unsigned int level) { // We get y and lambda of the interaction (pointers) SiconosVector& y = *inter.y(level); SiconosVector& lambda = *inter.lambda(level); VectorOfBlockVectors& DSlink = inter.linkToDSVariables(); computeh(*DSlink[FirstOrderR::x], lambda, *DSlink[FirstOrderR::z], y); } void FirstOrderLinearTIR::computeg(SiconosVector& lambda, BlockVector& r) { prod(*_B, lambda, r, false); } void FirstOrderLinearTIR::computeInput(double time, Interaction& inter, unsigned int level) { DEBUG_BEGIN("FirstOrderLinearTIR::computeInput(double time, Interaction& inter, unsigned int level)\n") VectorOfBlockVectors& DSlink = inter.linkToDSVariables(); DEBUG_EXPR(inter.lambda(level)->display();); DEBUG_EXPR(DSlink[FirstOrderR::r]->display();); computeg(*inter.lambda(level), *DSlink[FirstOrderR::r]); DEBUG_END("FirstOrderLinearTIR::computeInput(double time, Interaction& inter, unsigned int level)\n") } void FirstOrderLinearTIR::display() const { std::cout << " ===== Linear Time Invariant relation display ===== " <<std::endl; std::cout << "| C " <<std::endl; if(_C) _C->display(); else std::cout << "->NULL" <<std::endl; std::cout << "| D " <<std::endl; if(_D) _D->display(); else std::cout << "->NULL" <<std::endl; std::cout << "| F " <<std::endl; if(_F) _F->display(); else std::cout << "->NULL" <<std::endl; std::cout << "| e " <<std::endl; if(_e) _e->display(); else std::cout << "->NULL" <<std::endl; std::cout << "| B " <<std::endl; if(_B) _B->display(); else std::cout << "->NULL" <<std::endl; std::cout << " ================================================== " <<std::endl; }
correct wrong assertion
[kernel] correct wrong assertion
C++
apache-2.0
radarsat1/siconos,siconos/siconos,radarsat1/siconos,siconos/siconos,radarsat1/siconos,radarsat1/siconos,siconos/siconos,radarsat1/siconos,siconos/siconos
435cc46041820e59d1fbcbd88a2bfcf5b8ba3f49
src/base/bitunion.hh
src/base/bitunion.hh
/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __BASE_BITUNION_HH__ #define __BASE_BITUNION_HH__ #include <inttypes.h> #include "base/bitfield.hh" // The following implements the BitUnion system of defining bitfields //on top of an underlying class. This is done through the pervasive use of //both named and unnamed unions which all contain the same actual storage. //Since they're unioned with each other, all of these storage locations //overlap. This allows all of the bitfields to manipulate the same data //without having to have access to each other. More details are provided with //the individual components. //This namespace is for classes which implement the backend of the BitUnion //stuff. Don't use any of these directly, except for the Bitfield classes in //the *BitfieldTypes class(es). namespace BitfieldBackend { //A base class for all bitfields. It instantiates the actual storage, //and provides getBits and setBits functions for manipulating it. The //Data template parameter is type of the underlying storage. template<class Data> class BitfieldBase { protected: Data __data; //This function returns a range of bits from the underlying storage. //It relies on the "bits" function above. It's the user's //responsibility to make sure that there is a properly overloaded //version of this function for whatever type they want to overlay. inline uint64_t getBits(int first, int last) const { return bits(__data, first, last); } //Similar to the above, but for settings bits with replaceBits. inline void setBits(int first, int last, uint64_t val) { replaceBits(__data, first, last, val); } }; //This class contains all the "regular" bitfield classes. It is inherited //by all BitUnions which give them access to those types. template<class Type> class RegularBitfieldTypes { protected: //This class implements ordinary bitfields, that is a span of bits //who's msb is "first", and who's lsb is "last". template<int first, int last=first> class Bitfield : public BitfieldBase<Type> { public: operator uint64_t () const { return this->getBits(first, last); } uint64_t operator=(const uint64_t _data) { this->setBits(first, last, _data); return _data; } }; //A class which specializes the above so that it can only be read //from. This is accomplished explicitly making sure the assignment //operator is blocked. The conversion operator is carried through //inheritance. This will unfortunately need to be copied into each //bitfield type due to limitations with how templates work template<int first, int last=first> class BitfieldRO : public Bitfield<first, last> { private: uint64_t operator=(const uint64_t _data); }; //Similar to the above, but only allows writing. template<int first, int last=first> class BitfieldWO : public Bitfield<first, last> { private: operator uint64_t () const; public: using Bitfield<first, last>::operator=; }; }; //This class contains all the "regular" bitfield classes. It is inherited //by all BitUnions which give them access to those types. template<class Type> class SignedBitfieldTypes { protected: //This class implements ordinary bitfields, that is a span of bits //who's msb is "first", and who's lsb is "last". template<int first, int last=first> class SignedBitfield : public BitfieldBase<Type> { public: operator int64_t () const { return sext<first - last + 1>(this->getBits(first, last)); } int64_t operator=(const int64_t _data) { this->setBits(first, last, _data); return _data; } }; //A class which specializes the above so that it can only be read //from. This is accomplished explicitly making sure the assignment //operator is blocked. The conversion operator is carried through //inheritance. This will unfortunately need to be copied into each //bitfield type due to limitations with how templates work template<int first, int last=first> class SignedBitfieldRO : public SignedBitfield<first, last> { private: int64_t operator=(const int64_t _data); }; //Similar to the above, but only allows writing. template<int first, int last=first> class SignedBitfieldWO : public SignedBitfield<first, last> { private: operator int64_t () const; public: int64_t operator=(const int64_t _data) { *((SignedBitfield<first, last> *)this) = _data; return _data; } }; }; template<class Type> class BitfieldTypes : public RegularBitfieldTypes<Type>, public SignedBitfieldTypes<Type> {}; //When a BitUnion is set up, an underlying class is created which holds //the actual union. This class then inherits from it, and provids the //implementations for various operators. Setting things up this way //prevents having to redefine these functions in every different BitUnion //type. More operators could be implemented in the future, as the need //arises. template <class Type, class Base> class BitUnionOperators : public Base { public: BitUnionOperators(Type & _data) { Base::__data = _data; } BitUnionOperators() {} operator Type () const { return Base::__data; } Type operator=(const Type & _data) { Base::__data = _data; return _data; } bool operator<(const Base & base) const { return Base::__data < base.__data; } bool operator==(const Base & base) const { return Base::__data == base.__data; } }; } //This macro is a backend for other macros that specialize it slightly. //First, it creates/extends a namespace "BitfieldUnderlyingClasses" and //sticks the class which has the actual union in it, which //BitfieldOperators above inherits from. Putting these classes in a special //namespace ensures that there will be no collisions with other names as long //as the BitUnion names themselves are all distinct and nothing else uses //the BitfieldUnderlyingClasses namespace, which is unlikely. The class itself //creates a typedef of the "type" parameter called __DataType. This allows //the type to propagate outside of the macro itself in a controlled way. //Finally, the base storage is defined which BitfieldOperators will refer to //in the operators it defines. This macro is intended to be followed by //bitfield definitions which will end up inside it's union. As explained //above, these is overlayed the __data member in its entirety by each of the //bitfields which are defined in the union, creating shared storage with no //overhead. #define __BitUnion(type, name) \ namespace BitfieldUnderlyingClasses \ { \ class name; \ } \ class BitfieldUnderlyingClasses::name : \ public BitfieldBackend::BitfieldTypes<type> \ { \ public: \ typedef type __DataType; \ union { \ type __data;\ //This closes off the class and union started by the above macro. It is //followed by a typedef which makes "name" refer to a BitfieldOperator //class inheriting from the class and union just defined, which completes //building up the type for the user. #define EndBitUnion(name) \ }; \ }; \ typedef BitfieldBackend::BitUnionOperators< \ BitfieldUnderlyingClasses::name::__DataType, \ BitfieldUnderlyingClasses::name> name; //This sets up a bitfield which has other bitfields nested inside of it. The //__data member functions like the "underlying storage" of the top level //BitUnion. Like everything else, it overlays with the top level storage, so //making it a regular bitfield type makes the entire thing function as a //regular bitfield when referred to by itself. #define __SubBitUnion(fieldType, first, last, name) \ class : public BitfieldBackend::BitfieldTypes<__DataType> \ { \ public: \ union { \ fieldType<first, last> __data; //This closes off the union created above and gives it a name. Unlike the top //level BitUnion, we're interested in creating an object instead of a type. //The operators are defined in the macro itself instead of a class for //technical reasons. If someone determines a way to move them to one, please //do so. #define EndSubBitUnion(name) \ }; \ inline operator const __DataType () \ { return __data; } \ \ inline const __DataType operator = (const __DataType & _data) \ { return __data = _data;} \ } name; //Regular bitfields //These define macros for read/write regular bitfield based subbitfields. #define SubBitUnion(name, first, last) \ __SubBitUnion(Bitfield, first, last, name) //Regular bitfields //These define macros for read/write regular bitfield based subbitfields. #define SignedSubBitUnion(name, first, last) \ __SubBitUnion(SignedBitfield, first, last, name) //Use this to define an arbitrary type overlayed with bitfields. #define BitUnion(type, name) __BitUnion(type, name) //Use this to define conveniently sized values overlayed with bitfields. #define BitUnion64(name) __BitUnion(uint64_t, name) #define BitUnion32(name) __BitUnion(uint32_t, name) #define BitUnion16(name) __BitUnion(uint16_t, name) #define BitUnion8(name) __BitUnion(uint8_t, name) #endif // __BASE_BITUNION_HH__
/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __BASE_BITUNION_HH__ #define __BASE_BITUNION_HH__ #include <inttypes.h> #include "base/bitfield.hh" // The following implements the BitUnion system of defining bitfields //on top of an underlying class. This is done through the pervasive use of //both named and unnamed unions which all contain the same actual storage. //Since they're unioned with each other, all of these storage locations //overlap. This allows all of the bitfields to manipulate the same data //without having to have access to each other. More details are provided with //the individual components. //This namespace is for classes which implement the backend of the BitUnion //stuff. Don't use any of these directly, except for the Bitfield classes in //the *BitfieldTypes class(es). namespace BitfieldBackend { //A base class for all bitfields. It instantiates the actual storage, //and provides getBits and setBits functions for manipulating it. The //Data template parameter is type of the underlying storage. template<class Data> class BitfieldBase { protected: Data __data; //This function returns a range of bits from the underlying storage. //It relies on the "bits" function above. It's the user's //responsibility to make sure that there is a properly overloaded //version of this function for whatever type they want to overlay. inline uint64_t getBits(int first, int last) const { return bits(__data, first, last); } //Similar to the above, but for settings bits with replaceBits. inline void setBits(int first, int last, uint64_t val) { replaceBits(__data, first, last, val); } }; //This class contains all the "regular" bitfield classes. It is inherited //by all BitUnions which give them access to those types. template<class Type> class RegularBitfieldTypes { protected: //This class implements ordinary bitfields, that is a span of bits //who's msb is "first", and who's lsb is "last". template<int first, int last=first> class Bitfield : public BitfieldBase<Type> { public: operator uint64_t () const { return this->getBits(first, last); } uint64_t operator=(const uint64_t _data) { this->setBits(first, last, _data); return _data; } }; //A class which specializes the above so that it can only be read //from. This is accomplished explicitly making sure the assignment //operator is blocked. The conversion operator is carried through //inheritance. This will unfortunately need to be copied into each //bitfield type due to limitations with how templates work template<int first, int last=first> class BitfieldRO : public Bitfield<first, last> { private: uint64_t operator=(const uint64_t _data); }; //Similar to the above, but only allows writing. template<int first, int last=first> class BitfieldWO : public Bitfield<first, last> { private: operator uint64_t () const; public: using Bitfield<first, last>::operator=; }; }; //This class contains all the "regular" bitfield classes. It is inherited //by all BitUnions which give them access to those types. template<class Type> class SignedBitfieldTypes { protected: //This class implements ordinary bitfields, that is a span of bits //who's msb is "first", and who's lsb is "last". template<int first, int last=first> class SignedBitfield : public BitfieldBase<Type> { public: operator int64_t () const { return sext<first - last + 1>(this->getBits(first, last)); } int64_t operator=(const int64_t _data) { this->setBits(first, last, _data); return _data; } }; //A class which specializes the above so that it can only be read //from. This is accomplished explicitly making sure the assignment //operator is blocked. The conversion operator is carried through //inheritance. This will unfortunately need to be copied into each //bitfield type due to limitations with how templates work template<int first, int last=first> class SignedBitfieldRO : public SignedBitfield<first, last> { private: int64_t operator=(const int64_t _data); }; //Similar to the above, but only allows writing. template<int first, int last=first> class SignedBitfieldWO : public SignedBitfield<first, last> { private: operator int64_t () const; public: int64_t operator=(const int64_t _data) { *((SignedBitfield<first, last> *)this) = _data; return _data; } }; }; template<class Type> class BitfieldTypes : public RegularBitfieldTypes<Type>, public SignedBitfieldTypes<Type> {}; //When a BitUnion is set up, an underlying class is created which holds //the actual union. This class then inherits from it, and provids the //implementations for various operators. Setting things up this way //prevents having to redefine these functions in every different BitUnion //type. More operators could be implemented in the future, as the need //arises. template <class Type, class Base> class BitUnionOperators : public Base { public: BitUnionOperators(Type const & _data) { Base::__data = _data; } BitUnionOperators() {} operator Type () const { return Base::__data; } Type operator=(Type const & _data) { Base::__data = _data; return _data; } bool operator<(Base const & base) const { return Base::__data < base.__data; } bool operator==(Base const & base) const { return Base::__data == base.__data; } }; } //This macro is a backend for other macros that specialize it slightly. //First, it creates/extends a namespace "BitfieldUnderlyingClasses" and //sticks the class which has the actual union in it, which //BitfieldOperators above inherits from. Putting these classes in a special //namespace ensures that there will be no collisions with other names as long //as the BitUnion names themselves are all distinct and nothing else uses //the BitfieldUnderlyingClasses namespace, which is unlikely. The class itself //creates a typedef of the "type" parameter called __DataType. This allows //the type to propagate outside of the macro itself in a controlled way. //Finally, the base storage is defined which BitfieldOperators will refer to //in the operators it defines. This macro is intended to be followed by //bitfield definitions which will end up inside it's union. As explained //above, these is overlayed the __data member in its entirety by each of the //bitfields which are defined in the union, creating shared storage with no //overhead. #define __BitUnion(type, name) \ namespace BitfieldUnderlyingClasses \ { \ class name; \ } \ class BitfieldUnderlyingClasses::name : \ public BitfieldBackend::BitfieldTypes<type> \ { \ public: \ typedef type __DataType; \ union { \ type __data;\ //This closes off the class and union started by the above macro. It is //followed by a typedef which makes "name" refer to a BitfieldOperator //class inheriting from the class and union just defined, which completes //building up the type for the user. #define EndBitUnion(name) \ }; \ }; \ typedef BitfieldBackend::BitUnionOperators< \ BitfieldUnderlyingClasses::name::__DataType, \ BitfieldUnderlyingClasses::name> name; //This sets up a bitfield which has other bitfields nested inside of it. The //__data member functions like the "underlying storage" of the top level //BitUnion. Like everything else, it overlays with the top level storage, so //making it a regular bitfield type makes the entire thing function as a //regular bitfield when referred to by itself. #define __SubBitUnion(fieldType, first, last, name) \ class : public BitfieldBackend::BitfieldTypes<__DataType> \ { \ public: \ union { \ fieldType<first, last> __data; //This closes off the union created above and gives it a name. Unlike the top //level BitUnion, we're interested in creating an object instead of a type. //The operators are defined in the macro itself instead of a class for //technical reasons. If someone determines a way to move them to one, please //do so. #define EndSubBitUnion(name) \ }; \ inline operator const __DataType () \ { return __data; } \ \ inline const __DataType operator = (const __DataType & _data) \ { return __data = _data;} \ } name; //Regular bitfields //These define macros for read/write regular bitfield based subbitfields. #define SubBitUnion(name, first, last) \ __SubBitUnion(Bitfield, first, last, name) //Regular bitfields //These define macros for read/write regular bitfield based subbitfields. #define SignedSubBitUnion(name, first, last) \ __SubBitUnion(SignedBitfield, first, last, name) //Use this to define an arbitrary type overlayed with bitfields. #define BitUnion(type, name) __BitUnion(type, name) //Use this to define conveniently sized values overlayed with bitfields. #define BitUnion64(name) __BitUnion(uint64_t, name) #define BitUnion32(name) __BitUnion(uint32_t, name) #define BitUnion16(name) __BitUnion(uint16_t, name) #define BitUnion8(name) __BitUnion(uint8_t, name) #endif // __BASE_BITUNION_HH__
Fix some types in the bitunion classes.
BitUnion: Fix some types in the bitunion classes.
C++
bsd-3-clause
haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5
5c6323c296230cffede4bd63897de64760beaa4f
Library/Sources/Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.inl
Library/Sources/Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.inl
/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ #define _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../../Memory/BlockAllocated.h" #include "../Private/IteratorImplHelper.h" #include "../Private/PatchingDataStructures/LinkedList.h" namespace Stroika { namespace Foundation { namespace Containers { namespace Concrete { using Traversal::IteratorOwnerID; /* ******************************************************************************** ******** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::IImplRepBase_ ******** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> class Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::IImplRepBase_ : public Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep { private: using inherited = typename _IRep; #if qCompilerAndStdLib_TemplateTypenameReferenceToBaseOfBaseClassMemberNotFound_Buggy protected: using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE; using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE; #endif }; /* ******************************************************************************** *********** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Rep_*************** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename KEY_EQUALS_COMPARER> class Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Rep_ : public IImplRepBase_ { private: using inherited = IImplRepBase_; public: using _IterableRepSharedPtr = typename Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::_IterableRepSharedPtr; using _MappingRepSharedPtr = typename inherited::_MappingRepSharedPtr; using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE; using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE; using KeyEqualsCompareFunctionType = typename Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::KeyEqualsCompareFunctionType; public: Rep_ (const KEY_EQUALS_COMPARER& keyEqualsComparer) : fKeyEqualsComparer_ (keyEqualsComparer) { } Rep_ (const Rep_& from) = delete; Rep_ (Rep_* from, IteratorOwnerID forIterableEnvelope) : inherited () , fKeyEqualsComparer_ (from->fKeyEqualsComparer_) , fData_ (&from->fData_, forIterableEnvelope) { RequireNotNull (from); } public: nonvirtual Rep_& operator= (const Rep_&) = delete; public: DECLARE_USE_BLOCK_ALLOCATION (Rep_); private: KEY_EQUALS_COMPARER fKeyEqualsComparer_; // Iterable<T>::_IRep overrides public: virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override { // const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists return Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope); } virtual Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> MakeIterator (IteratorOwnerID suggestedOwner) const override { Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API return Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> (Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_)); } virtual size_t GetLength () const override { return fData_.GetLength (); } virtual bool IsEmpty () const override { return fData_.IsEmpty (); } virtual void Apply (_APPLY_ARGTYPE doToElement) const override { // empirically faster (vs2k13) to lock once and apply (even calling stdfunc) than to // use iterator (which currently implies lots of locks) with this->_Apply () fData_.Apply (doToElement); } virtual Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const override { std::shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; using RESULT_TYPE = Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>; using SHARED_REP_TYPE = Traversal::IteratorBase::SharedPtrImplementationTemplate<IteratorRep_>; auto iLink = fData_.FindFirstThat (doToElement); if (iLink == nullptr) { return RESULT_TYPE::GetEmptyIterator (); } Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API SHARED_REP_TYPE resultRep = Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_); resultRep->fIterator.SetCurrentLink (iLink); // because Iterator<T> locks rep (non recursive mutex) - this CTOR needs to happen outside CONTAINER_LOCK_HELPER_START() return RESULT_TYPE (resultRep); } // Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep overrides public: virtual KeyEqualsCompareFunctionType GetKeyEqualsComparer () const override { return KeyEqualsCompareFunctionType{fKeyEqualsComparer_}; } virtual _MappingRepSharedPtr CloneEmpty (IteratorOwnerID forIterableEnvelope) const override { if (fData_.HasActiveIterators ()) { // const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists auto r = Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope); r->fData_.RemoveAll (); return r; } else { return Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<Rep_> (fKeyEqualsComparer_); } } virtual Iterable<KEY_TYPE> Keys () const override { return this->_Keys_Reference_Implementation (); } virtual Iterable<MAPPED_VALUE_TYPE> MappedValues () const override { return this->_Values_Reference_Implementation (); } virtual bool Lookup (ArgByValueType<KEY_TYPE> key, Memory::Optional<MAPPED_VALUE_TYPE>* item) const override { std::shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructures::LinkedList<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::ForwardIterator it (&fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { if (item != nullptr) { *item = it.Current ().fValue; } return true; } } if (item != nullptr) { item->clear (); } return false; } virtual void Add (ArgByValueType<KEY_TYPE> key, ArgByValueType<MAPPED_VALUE_TYPE> newElt) override { using Traversal::kUnknownIteratorOwnerID; std::lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructureImplType_::ForwardIterator it (kUnknownIteratorOwnerID, &fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { fData_.SetAt (it, KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE> (key, newElt)); return; } } fData_.Append (KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE> (key, newElt)); } virtual void Remove (ArgByValueType<KEY_TYPE> key) override { using Traversal::kUnknownIteratorOwnerID; std::lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructureImplType_::ForwardIterator it (kUnknownIteratorOwnerID, &fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { fData_.RemoveAt (it); return; } } } virtual void Remove (const Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>& i) override { std::lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; const typename Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::IRep& ir = i.GetRep (); AssertMember (&ir, IteratorRep_); auto& mir = dynamic_cast<const IteratorRep_&> (ir); fData_.RemoveAt (mir.fIterator); } #if qDebug virtual void AssertNoIteratorsReferenceOwner (IteratorOwnerID oBeingDeleted) const override { std::shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; fData_.AssertNoIteratorsReferenceOwner (oBeingDeleted); } #endif private: using DataStructureImplType_ = Private::PatchingDataStructures::LinkedList<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>; using IteratorRep_ = Private::IteratorImplHelper_<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>, DataStructureImplType_>; private: DataStructureImplType_ fData_; }; /* ******************************************************************************** *************** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE> **************** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> inline Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList () : Mapping_LinkedList (std::equal_to<KEY_TYPE>{}) { AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename KEY_EQUALS_COMPARER, typename ENABLE_IF_IS_COMPARER> Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (const KEY_EQUALS_COMPARER& keyEqualsComparer, ENABLE_IF_IS_COMPARER*) : inherited (inherited::template MakeSharedPtr<Rep_<KEY_EQUALS_COMPARER>> (keyEqualsComparer)) { AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename CONTAINER_OF_ADDABLE, typename ENABLE_IF> inline Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (const CONTAINER_OF_ADDABLE& src) : Mapping_LinkedList () { this->AddAll (src); AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename COPY_FROM_ITERATOR_KEYVALUE> Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (COPY_FROM_ITERATOR_KEYVALUE start, COPY_FROM_ITERATOR_KEYVALUE end) : Mapping_LinkedList () { this->AddAll (start, end); AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> inline void Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::AssertRepValidType_ () const { #if qDebug typename inherited::template _SafeReadRepAccessor<IImplRepBase_> tmp{this}; // for side-effect of AssertMemeber #endif } } } } } #endif /* _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ */
/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ #define _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../../Memory/BlockAllocated.h" #include "../Private/IteratorImplHelper.h" #include "../Private/PatchingDataStructures/LinkedList.h" namespace Stroika { namespace Foundation { namespace Containers { namespace Concrete { using Traversal::IteratorOwnerID; /* ******************************************************************************** ******** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::IImplRepBase_ ******** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> class Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::IImplRepBase_ : public Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep { private: using inherited = typename Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep; #if qCompilerAndStdLib_TemplateTypenameReferenceToBaseOfBaseClassMemberNotFound_Buggy protected: using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE; using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE; #endif }; /* ******************************************************************************** *********** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Rep_*************** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename KEY_EQUALS_COMPARER> class Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Rep_ : public IImplRepBase_ { private: using inherited = IImplRepBase_; public: using _IterableRepSharedPtr = typename Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::_IterableRepSharedPtr; using _MappingRepSharedPtr = typename inherited::_MappingRepSharedPtr; using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE; using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE; using KeyEqualsCompareFunctionType = typename Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::KeyEqualsCompareFunctionType; public: Rep_ (const KEY_EQUALS_COMPARER& keyEqualsComparer) : fKeyEqualsComparer_ (keyEqualsComparer) { } Rep_ (const Rep_& from) = delete; Rep_ (Rep_* from, IteratorOwnerID forIterableEnvelope) : inherited () , fKeyEqualsComparer_ (from->fKeyEqualsComparer_) , fData_ (&from->fData_, forIterableEnvelope) { RequireNotNull (from); } public: nonvirtual Rep_& operator= (const Rep_&) = delete; public: DECLARE_USE_BLOCK_ALLOCATION (Rep_); private: KEY_EQUALS_COMPARER fKeyEqualsComparer_; // Iterable<T>::_IRep overrides public: virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override { // const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists return Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope); } virtual Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> MakeIterator (IteratorOwnerID suggestedOwner) const override { Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API return Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> (Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_)); } virtual size_t GetLength () const override { return fData_.GetLength (); } virtual bool IsEmpty () const override { return fData_.IsEmpty (); } virtual void Apply (_APPLY_ARGTYPE doToElement) const override { // empirically faster (vs2k13) to lock once and apply (even calling stdfunc) than to // use iterator (which currently implies lots of locks) with this->_Apply () fData_.Apply (doToElement); } virtual Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const override { std::shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; using RESULT_TYPE = Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>; using SHARED_REP_TYPE = Traversal::IteratorBase::SharedPtrImplementationTemplate<IteratorRep_>; auto iLink = fData_.FindFirstThat (doToElement); if (iLink == nullptr) { return RESULT_TYPE::GetEmptyIterator (); } Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API SHARED_REP_TYPE resultRep = Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_); resultRep->fIterator.SetCurrentLink (iLink); // because Iterator<T> locks rep (non recursive mutex) - this CTOR needs to happen outside CONTAINER_LOCK_HELPER_START() return RESULT_TYPE (resultRep); } // Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep overrides public: virtual KeyEqualsCompareFunctionType GetKeyEqualsComparer () const override { return KeyEqualsCompareFunctionType{fKeyEqualsComparer_}; } virtual _MappingRepSharedPtr CloneEmpty (IteratorOwnerID forIterableEnvelope) const override { if (fData_.HasActiveIterators ()) { // const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists auto r = Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope); r->fData_.RemoveAll (); return r; } else { return Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSharedPtr<Rep_> (fKeyEqualsComparer_); } } virtual Iterable<KEY_TYPE> Keys () const override { return this->_Keys_Reference_Implementation (); } virtual Iterable<MAPPED_VALUE_TYPE> MappedValues () const override { return this->_Values_Reference_Implementation (); } virtual bool Lookup (ArgByValueType<KEY_TYPE> key, Memory::Optional<MAPPED_VALUE_TYPE>* item) const override { std::shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructures::LinkedList<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::ForwardIterator it (&fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { if (item != nullptr) { *item = it.Current ().fValue; } return true; } } if (item != nullptr) { item->clear (); } return false; } virtual void Add (ArgByValueType<KEY_TYPE> key, ArgByValueType<MAPPED_VALUE_TYPE> newElt) override { using Traversal::kUnknownIteratorOwnerID; std::lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructureImplType_::ForwardIterator it (kUnknownIteratorOwnerID, &fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { fData_.SetAt (it, KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE> (key, newElt)); return; } } fData_.Append (KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE> (key, newElt)); } virtual void Remove (ArgByValueType<KEY_TYPE> key) override { using Traversal::kUnknownIteratorOwnerID; std::lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructureImplType_::ForwardIterator it (kUnknownIteratorOwnerID, &fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { fData_.RemoveAt (it); return; } } } virtual void Remove (const Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>& i) override { std::lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; const typename Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::IRep& ir = i.GetRep (); AssertMember (&ir, IteratorRep_); auto& mir = dynamic_cast<const IteratorRep_&> (ir); fData_.RemoveAt (mir.fIterator); } #if qDebug virtual void AssertNoIteratorsReferenceOwner (IteratorOwnerID oBeingDeleted) const override { std::shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; fData_.AssertNoIteratorsReferenceOwner (oBeingDeleted); } #endif private: using DataStructureImplType_ = Private::PatchingDataStructures::LinkedList<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>; using IteratorRep_ = Private::IteratorImplHelper_<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>, DataStructureImplType_>; private: DataStructureImplType_ fData_; }; /* ******************************************************************************** *************** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE> **************** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> inline Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList () : Mapping_LinkedList (std::equal_to<KEY_TYPE>{}) { AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename KEY_EQUALS_COMPARER, typename ENABLE_IF_IS_COMPARER> Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (const KEY_EQUALS_COMPARER& keyEqualsComparer, ENABLE_IF_IS_COMPARER*) : inherited (inherited::template MakeSharedPtr<Rep_<KEY_EQUALS_COMPARER>> (keyEqualsComparer)) { AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename CONTAINER_OF_ADDABLE, typename ENABLE_IF> inline Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (const CONTAINER_OF_ADDABLE& src) : Mapping_LinkedList () { this->AddAll (src); AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename COPY_FROM_ITERATOR_KEYVALUE> Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (COPY_FROM_ITERATOR_KEYVALUE start, COPY_FROM_ITERATOR_KEYVALUE end) : Mapping_LinkedList () { this->AddAll (start, end); AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> inline void Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::AssertRepValidType_ () const { #if qDebug typename inherited::template _SafeReadRepAccessor<IImplRepBase_> tmp{this}; // for side-effect of AssertMemeber #endif } } } } } #endif /* _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ */
tweak for typename restrictions
tweak for typename restrictions
C++
mit
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
a74088c867505d3577dcdac25c73341be4e4433b
src/EmuCommon/KC85Emu.cc
src/EmuCommon/KC85Emu.cc
//------------------------------------------------------------------------------ // Emu/KC85Emu.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "KC85Emu.h" #include "Assets/Gfx/ShapeBuilder.h" #include "Input/Input.h" #include "yakc/roms/rom_dumps.h" #include "emu_shaders.h" using namespace YAKC; namespace Oryol { //------------------------------------------------------------------------------ void KC85Emu::Setup(const GfxSetup& gfxSetup, YAKC::system m, os_rom os) { this->model = m; this->rom = os; // initialize the emulator if (this->model == YAKC::system::kc85_3) { roms.add(rom_images::caos31, dump_caos31, sizeof(dump_caos31)); roms.add(rom_images::kc85_basic_rom, dump_basic_c0, sizeof(dump_basic_c0)); } ext_funcs sys_funcs; sys_funcs.assertmsg_func = Log::AssertMsg; sys_funcs.malloc_func = [] (size_t s) -> void* { return Memory::Alloc(int(s)); }; sys_funcs.free_func = [] (void* p) { Memory::Free(p); }; this->emu.init(sys_funcs); this->draw.Setup(gfxSetup, 5, 5); this->audio.Setup(&this->emu); this->keyboard.Setup(this->emu); this->fileLoader.Setup(this->emu); // register modules if (int(this->model) & int(YAKC::system::any_kc85)) { kc85.exp.register_none_module("NO MODULE", "Click to insert module!"); kc85.exp.register_ram_module(kc85_exp::m022_16kbyte, 0xC0, 0x4000, "nohelp"); } // setup a mesh and draw state to render a simple plane ShapeBuilder shapeBuilder; shapeBuilder.Layout .Add(VertexAttr::Position, VertexFormat::Float3) .Add(VertexAttr::TexCoord0, VertexFormat::Float2); shapeBuilder.Plane(1.0f, 1.0f, 1); this->drawState.Mesh[0] = Gfx::CreateResource(shapeBuilder.Build()); Id shd = Gfx::CreateResource(KCShader::Setup()); auto pip = PipelineSetup::FromLayoutAndShader(shapeBuilder.Layout, shd); pip.DepthStencilState.DepthWriteEnabled = true; pip.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual; pip.RasterizerState.SampleCount = gfxSetup.SampleCount; pip.BlendState.ColorFormat = gfxSetup.ColorFormat; pip.BlendState.DepthFormat = gfxSetup.DepthFormat; this->drawState.Pipeline = Gfx::CreateResource(pip); } //------------------------------------------------------------------------------ void KC85Emu::Discard() { this->fileLoader.Discard(); this->emu.poweroff(); this->keyboard.Discard(); this->audio.Discard(); this->draw.Discard(); } //------------------------------------------------------------------------------ void KC85Emu::Update(Duration frameTime) { this->frameIndex++; if (this->SwitchedOn()) { // need to start a game? if (this->startGameFrameIndex == this->frameIndex) { for (const auto& item : this->fileLoader.Items) { if ((int(item.Compat) & int(this->emu.model)) && (item.Name == this->startGameName)) { this->fileLoader.LoadAndStart(item); break; } } } // handle the normal emulator per-frame update this->keyboard.HandleInput(); int micro_secs = (int) frameTime.AsMicroSeconds(); const uint64_t audio_cycle_count = this->audio.GetProcessedCycles(); this->emu.exec(micro_secs, audio_cycle_count); this->audio.Update(); } else { // switch KC on once after a little while if (this->frameIndex == this->switchOnDelayFrames) { if (!this->SwitchedOn()) { this->TogglePower(); } } } } //------------------------------------------------------------------------------ void KC85Emu::TogglePower() { if (this->SwitchedOn()) { this->emu.poweroff(); } else { this->emu.poweron(this->model, this->rom); if (int(this->model) & int(YAKC::system::any_kc85)) { if (!kc85.exp.slot_occupied(0x08)) { kc85.exp.insert_module(0x08, kc85_exp::m022_16kbyte); } if (!kc85.exp.slot_occupied(0x0C)) { kc85.exp.insert_module(0x0C, kc85_exp::none); } } } } //------------------------------------------------------------------------------ bool KC85Emu::SwitchedOn() const { return this->emu.switchedon(); } //------------------------------------------------------------------------------ void KC85Emu::Reset() { if (this->SwitchedOn()) { this->emu.reset(); } } //------------------------------------------------------------------------------ void KC85Emu::StartGame(const char* name) { o_assert_dbg(name); // switch KC off and on, and start game after it has booted if (this->SwitchedOn()) { this->TogglePower(); } this->TogglePower(); this->startGameFrameIndex = this->frameIndex + 5 * 60; this->startGameName = name; } //------------------------------------------------------------------------------ void KC85Emu::Render(const glm::mat4& mvp, bool onlyUpdateTexture) { if (this->SwitchedOn()) { // get the emulator's framebuffer and fb size int width = 0, height = 0; const void* fb = this->emu.framebuffer(width, height); if (fb) { this->draw.validateTexture(width, height); this->draw.texUpdateAttrs.Sizes[0][0] = width*height*4; if (this->draw.texture.IsValid()) { Gfx::UpdateTexture(this->draw.texture, fb, this->draw.texUpdateAttrs); if (!onlyUpdateTexture) { this->drawState.FSTexture[KCShader::irm] = this->draw.texture; KCShader::vsParams vsParams; vsParams.mvp = mvp; Gfx::ApplyDrawState(this->drawState); Gfx::ApplyUniformBlock(vsParams); Gfx::Draw(); } } } } } } // namespace Oryol
//------------------------------------------------------------------------------ // Emu/KC85Emu.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "KC85Emu.h" #include "yakc/systems/kc85.h" #include "Assets/Gfx/ShapeBuilder.h" #include "Input/Input.h" #include "yakc/roms/rom_dumps.h" #include "emu_shaders.h" using namespace YAKC; namespace Oryol { //------------------------------------------------------------------------------ void KC85Emu::Setup(const GfxSetup& gfxSetup, YAKC::system m, os_rom os) { this->model = m; this->rom = os; // initialize the emulator if (this->model == YAKC::system::kc85_3) { roms.add(rom_images::caos31, dump_caos31, sizeof(dump_caos31)); roms.add(rom_images::kc85_basic_rom, dump_basic_c0, sizeof(dump_basic_c0)); } ext_funcs sys_funcs; sys_funcs.assertmsg_func = Log::AssertMsg; sys_funcs.malloc_func = [] (size_t s) -> void* { return Memory::Alloc(int(s)); }; sys_funcs.free_func = [] (void* p) { Memory::Free(p); }; this->emu.init(sys_funcs); this->draw.Setup(gfxSetup, 5, 5); this->audio.Setup(&this->emu); this->keyboard.Setup(this->emu); this->fileLoader.Setup(this->emu); // register modules if (int(this->model) & int(YAKC::system::any_kc85)) { kc85.exp.register_none_module("NO MODULE", "Click to insert module!"); kc85.exp.register_ram_module(kc85_exp::m022_16kbyte, 0xC0, 0x4000, "nohelp"); } // setup a mesh and draw state to render a simple plane ShapeBuilder shapeBuilder; shapeBuilder.Layout .Add(VertexAttr::Position, VertexFormat::Float3) .Add(VertexAttr::TexCoord0, VertexFormat::Float2); shapeBuilder.Plane(1.0f, 1.0f, 1); this->drawState.Mesh[0] = Gfx::CreateResource(shapeBuilder.Build()); Id shd = Gfx::CreateResource(KCShader::Setup()); auto pip = PipelineSetup::FromLayoutAndShader(shapeBuilder.Layout, shd); pip.DepthStencilState.DepthWriteEnabled = true; pip.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual; pip.RasterizerState.SampleCount = gfxSetup.SampleCount; pip.BlendState.ColorFormat = gfxSetup.ColorFormat; pip.BlendState.DepthFormat = gfxSetup.DepthFormat; this->drawState.Pipeline = Gfx::CreateResource(pip); } //------------------------------------------------------------------------------ void KC85Emu::Discard() { this->fileLoader.Discard(); this->emu.poweroff(); this->keyboard.Discard(); this->audio.Discard(); this->draw.Discard(); } //------------------------------------------------------------------------------ void KC85Emu::Update(Duration frameTime) { this->frameIndex++; if (this->SwitchedOn()) { // need to start a game? if (this->startGameFrameIndex == this->frameIndex) { for (const auto& item : this->fileLoader.Items) { if ((int(item.Compat) & int(this->emu.model)) && (item.Name == this->startGameName)) { this->fileLoader.LoadAndStart(item); break; } } } // handle the normal emulator per-frame update this->keyboard.HandleInput(); int micro_secs = (int) frameTime.AsMicroSeconds(); const uint64_t audio_cycle_count = this->audio.GetProcessedCycles(); this->emu.exec(micro_secs, audio_cycle_count); this->audio.Update(); } else { // switch KC on once after a little while if (this->frameIndex == this->switchOnDelayFrames) { if (!this->SwitchedOn()) { this->TogglePower(); } } } } //------------------------------------------------------------------------------ void KC85Emu::TogglePower() { if (this->SwitchedOn()) { this->emu.poweroff(); } else { this->emu.poweron(this->model, this->rom); if (int(this->model) & int(YAKC::system::any_kc85)) { if (!kc85.exp.slot_occupied(0x08)) { kc85.exp.insert_module(0x08, kc85_exp::m022_16kbyte); } if (!kc85.exp.slot_occupied(0x0C)) { kc85.exp.insert_module(0x0C, kc85_exp::none); } } } } //------------------------------------------------------------------------------ bool KC85Emu::SwitchedOn() const { return this->emu.switchedon(); } //------------------------------------------------------------------------------ void KC85Emu::Reset() { if (this->SwitchedOn()) { this->emu.reset(); } } //------------------------------------------------------------------------------ void KC85Emu::StartGame(const char* name) { o_assert_dbg(name); // switch KC off and on, and start game after it has booted if (this->SwitchedOn()) { this->TogglePower(); } this->TogglePower(); this->startGameFrameIndex = this->frameIndex + 5 * 60; this->startGameName = name; } //------------------------------------------------------------------------------ void KC85Emu::Render(const glm::mat4& mvp, bool onlyUpdateTexture) { if (this->SwitchedOn()) { // get the emulator's framebuffer and fb size int width = 0, height = 0; const void* fb = this->emu.framebuffer(width, height); if (fb) { this->draw.validateTexture(width, height); this->draw.texUpdateAttrs.Sizes[0][0] = width*height*4; if (this->draw.texture.IsValid()) { Gfx::UpdateTexture(this->draw.texture, fb, this->draw.texUpdateAttrs); if (!onlyUpdateTexture) { this->drawState.FSTexture[KCShader::irm] = this->draw.texture; KCShader::vsParams vsParams; vsParams.mvp = mvp; Gfx::ApplyDrawState(this->drawState); Gfx::ApplyUniformBlock(vsParams); Gfx::Draw(); } } } } } } // namespace Oryol
Fix for YAKC updates
Fix for YAKC updates
C++
mit
floooh/oryol-samples,floooh/oryol-samples,floooh/oryol-samples,floooh/oryol-samples,floooh/oryol-samples
081edb8a9f314108fe536453e916d4e84c75aa62
agency/experimental/view.hpp
agency/experimental/view.hpp
#pragma once #include <agency/detail/config.hpp> #include <agency/experimental/array.hpp> #include <agency/experimental/span.hpp> #include <type_traits> #include <iterator> namespace agency { namespace experimental { // XXX this is only valid for contiguous containers template<class Container> __AGENCY_ANNOTATION span<typename Container::value_type> all(Container& c) { return span<typename Container::value_type>(c); } // XXX this is only valid for contiguous containers template<class Container> __AGENCY_ANNOTATION span<const typename Container::value_type> all(const Container& c) { return span<const typename Container::value_type>(c); } template<class T, std::size_t N> __AGENCY_ANNOTATION span<T,N> all(array<T,N>& a) { return span<T,N>(a); } template<class T, std::size_t N> __AGENCY_ANNOTATION span<const T,N> all(const array<T,N>& a) { return span<const T,N>(a); } // spans are already views, so don't wrap them // XXX maybe should put this in span.hpp template<class ElementType, std::ptrdiff_t Extent> __AGENCY_ANNOTATION span<ElementType,Extent> all(span<ElementType,Extent> s) { return s; } template<class Iterator, class Sentinel = Iterator> class range_view { public: using iterator = Iterator; using sentinel = Sentinel; __AGENCY_ANNOTATION range_view(iterator begin, sentinel end) : begin_(begin), end_(end) {} __AGENCY_ANNOTATION iterator begin() const { return begin_; } __AGENCY_ANNOTATION sentinel end() const { return end_; } // "drops" the first n elements of the range by advancing the begin iterator n times __AGENCY_ANNOTATION void drop(typename std::iterator_traits<iterator>::difference_type n) { begin_ += n; } private: iterator begin_; sentinel end_; }; // range_views are already views, so don't wrap them template<class Iterator, class Sentinel> __AGENCY_ANNOTATION range_view<Iterator,Sentinel> all(range_view<Iterator,Sentinel> v) { return v; } namespace detail { template<class Range> using range_iterator_t = decltype(std::declval<Range*>()->begin()); template<class Range> using range_sentinel_t = decltype(std::declval<Range*>()->end()); template<class Range> using decay_range_iterator_t = range_iterator_t<typename std::decay<Range>::type>; template<class Range> using decay_range_sentinel_t = range_sentinel_t<typename std::decay<Range>::type>; template<class Range> using range_difference_t = typename std::iterator_traits<range_iterator_t<Range>>::difference_type; } // end detail template<class Range> __AGENCY_ANNOTATION range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>> make_range_view(Range&& rng) { return range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>(rng.begin(), rng.end()); } // create a view of the given range and drop the first n elements from the view template<class Range> __AGENCY_ANNOTATION range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>> drop(Range&& rng, detail::range_difference_t<typename std::decay<Range>::type> n) { auto result = make_range_view(rng); result.drop(n); return result; } } // end experimental } // end agency
#pragma once #include <agency/detail/config.hpp> #include <agency/experimental/array.hpp> #include <agency/experimental/span.hpp> #include <type_traits> #include <iterator> namespace agency { namespace experimental { // XXX this is only valid for contiguous containers template<class Container> __AGENCY_ANNOTATION span<typename Container::value_type> all(Container& c) { return span<typename Container::value_type>(c); } // XXX this is only valid for contiguous containers template<class Container> __AGENCY_ANNOTATION span<const typename Container::value_type> all(const Container& c) { return span<const typename Container::value_type>(c); } template<class T, std::size_t N> __AGENCY_ANNOTATION span<T,N> all(array<T,N>& a) { return span<T,N>(a); } template<class T, std::size_t N> __AGENCY_ANNOTATION span<const T,N> all(const array<T,N>& a) { return span<const T,N>(a); } // spans are already views, so don't wrap them // XXX maybe should put this in span.hpp template<class ElementType, std::ptrdiff_t Extent> __AGENCY_ANNOTATION span<ElementType,Extent> all(span<ElementType,Extent> s) { return s; } template<class Iterator, class Sentinel = Iterator> class range_view { public: using iterator = Iterator; using sentinel = Sentinel; __AGENCY_ANNOTATION range_view(iterator begin, sentinel end) : begin_(begin), end_(end) {} __AGENCY_ANNOTATION iterator begin() const { return begin_; } __AGENCY_ANNOTATION sentinel end() const { return end_; } // "drops" the first n elements of the range by advancing the begin iterator n times __AGENCY_ANNOTATION void drop(typename std::iterator_traits<iterator>::difference_type n) { begin_ += n; } private: iterator begin_; sentinel end_; }; // range_views are already views, so don't wrap them template<class Iterator, class Sentinel> __AGENCY_ANNOTATION range_view<Iterator,Sentinel> all(range_view<Iterator,Sentinel> v) { return v; } namespace detail { template<class Range> using range_iterator_t = decltype(std::declval<Range*>()->begin()); template<class Range> using range_sentinel_t = decltype(std::declval<Range*>()->end()); template<class Range> using decay_range_iterator_t = range_iterator_t<typename std::decay<Range>::type>; template<class Range> using decay_range_sentinel_t = range_sentinel_t<typename std::decay<Range>::type>; template<class Range> using range_difference_t = typename std::iterator_traits<range_iterator_t<Range>>::difference_type; template<class Range> using range_value_t = typename std::iterator_traits<range_iterator_t<Range>>::value_type; } // end detail template<class Range> __AGENCY_ANNOTATION range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>> make_range_view(Range&& rng) { return range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>>(rng.begin(), rng.end()); } // create a view of the given range and drop the first n elements from the view template<class Range> __AGENCY_ANNOTATION range_view<detail::decay_range_iterator_t<Range>, detail::decay_range_sentinel_t<Range>> drop(Range&& rng, detail::range_difference_t<typename std::decay<Range>::type> n) { auto result = make_range_view(rng); result.drop(n); return result; } } // end experimental } // end agency
Add experimental::detail::range_value_t
Add experimental::detail::range_value_t
C++
bsd-3-clause
egaburov/agency,egaburov/agency
fd896c899f918dffbf2459911c9f2f05a2f896ee
C++/shortest-palindrome.cpp
C++/shortest-palindrome.cpp
// Time: O(n) // Space: O(n) // KMP Algorithm class Solution { public: string shortestPalindrome(string s) { if (s.empty()) { return s; } string rev_s(s.crbegin(), s.crend()); // Assume s is (Palindrome)abc, // A would be (Palindrome)abccba(Palindrome). string A = s + rev_s; vector<int> prefix(move(getPrefix(A))); // The index prefix.back() of A would be: // (Palindrome)abccba(Palindrome) // ^ // The index prefix.back() + 1 of s would be: // (Palindrome)abc // ^ // Get non palindrome part of s. string non_palindrome = s.substr(prefix.back() + 1); reverse(non_palindrome.begin(), non_palindrome.end()); return non_palindrome + s; // cba(Palindrome)abc. } private: vector<int> getPrefix(const string& pattern) { vector<int> prefix(pattern.length(), -1); int j = -1; for (int i = 1; i < pattern.length(); ++i) { while (j > -1 && pattern[j + 1] != pattern[i]) { j = prefix[j]; } if (pattern[j + 1] == pattern[i]) { ++j; } prefix[i] = j; } return prefix; } }; // Time: O(n) // Space: O(n) // Manacher's Algorithm class Solution2 { public: string shortestPalindrome(string s) { string T = preProcess(s); int n = T.length(); vector<int> P(n); int C = 0, R = 0; for (int i = 1; i < n - 1; ++i) { int i_mirror = 2 * C - i; // equals to i' = C - (i-C) P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; // Attempt to expand palindrome centered at i while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) { ++P[i]; } // If palindrome centered at i expand past R, // adjust center based on expanded palindrome. if (i + P[i] > R) { C = i; R = i + P[i]; } } // Find the max len of palindrome which starts with the first char of s. int max_len = 0; for (int i = 1; i < n - 1; ++i) { if (i - P[i] == 1) { max_len = P[i]; } } // Assume s is (Palindrome)abc. string ans = s.substr(max_len); // abc. reverse(ans.begin(), ans.end()); // cba. ans.append(s); // cba(Palindrome)abc. return ans; } private: string preProcess(string s) { int n = s.length(); if (n == 0) { return "^$"; } string ret = "^"; for (int i = 0; i < n; ++i) { ret += "#" + s.substr(i, 1); } ret += "#$"; return ret; } };
// Time: O(n) // Space: O(n) // KMP Algorithm class Solution { public: string shortestPalindrome(string s) { if (s.empty()) { return s; } string rev_s(s.crbegin(), s.crend()); // Assume s is (Palindrome)abc, // A would be (Palindrome)abccba(Palindrome). string A = s + rev_s; auto prefix = getPrefix(A); // The index prefix.back() of A would be: // (Palindrome)abccba(Palindrome) // ^ // The index prefix.back() + 1 of s would be: // (Palindrome)abc // ^ // Get non palindrome part of s. string non_palindrome = s.substr(prefix.back() + 1); reverse(non_palindrome.begin(), non_palindrome.end()); return non_palindrome + s; // cba(Palindrome)abc. } private: vector<int> getPrefix(const string& pattern) { vector<int> prefix(pattern.length(), -1); int j = -1; for (int i = 1; i < pattern.length(); ++i) { while (j > -1 && pattern[j + 1] != pattern[i]) { j = prefix[j]; } if (pattern[j + 1] == pattern[i]) { ++j; } prefix[i] = j; } return prefix; } }; // Time: O(n) // Space: O(n) // Manacher's Algorithm class Solution2 { public: string shortestPalindrome(string s) { string T = preProcess(s); int n = T.length(); vector<int> P(n); int C = 0, R = 0; for (int i = 1; i < n - 1; ++i) { int i_mirror = 2 * C - i; // equals to i' = C - (i-C) P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; // Attempt to expand palindrome centered at i while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) { ++P[i]; } // If palindrome centered at i expand past R, // adjust center based on expanded palindrome. if (i + P[i] > R) { C = i; R = i + P[i]; } } // Find the max len of palindrome which starts with the first char of s. int max_len = 0; for (int i = 1; i < n - 1; ++i) { if (i - P[i] == 1) { max_len = P[i]; } } // Assume s is (Palindrome)abc. string ans = s.substr(max_len); // abc. reverse(ans.begin(), ans.end()); // cba. ans.append(s); // cba(Palindrome)abc. return ans; } private: string preProcess(string s) { int n = s.length(); if (n == 0) { return "^$"; } string ret = "^"; for (int i = 0; i < n; ++i) { ret += "#" + s.substr(i, 1); } ret += "#$"; return ret; } };
Update shortest-palindrome.cpp
Update shortest-palindrome.cpp
C++
mit
tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,githubutilities/LeetCode,githubutilities/LeetCode,kamyu104/LeetCode,yiwen-luo/LeetCode,yiwen-luo/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,githubutilities/LeetCode,jaredkoontz/leetcode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode,kamyu104/LeetCode,yiwen-luo/LeetCode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,jaredkoontz/leetcode
8dcb1ca58c8d14ae3f8377c927097996a54ac5d5
src/partition.cpp
src/partition.cpp
#include "partition.h" #include "vector.h" namespace { inline void swap (unsigned * index, unsigned i, unsigned j) { unsigned temp = index [j]; index [j] = index [i]; index [i] = temp; } inline bool less (unsigned * index, const float (* x) [4], unsigned i, unsigned j, unsigned dim) { return x [index [i]] [dim] < x [index [j]] [dim]; } } // Reorder index [0, count) so that {i} <= {m} for i = 0 .. m - 1, // and {m} <= {j} for j = m + 1 .. count - 1, // where {i} = x [index [i]] [dim]. // Undefined behaviour if count < 3. void partition (unsigned * index, const float (* x) [4], unsigned begin, unsigned middle, unsigned end, unsigned dim) { // Move the middle element to position 1. swap (index, begin + 1, (begin + end) / 2); // Now put elements 0, 1, count-1 in order. if (less (index, x, begin + 1, begin, dim)) swap (index, begin, begin + 1); if (less (index, x, end - 1, begin, dim)) swap (index, begin, end - 1); if (less (index, x, end - 1, begin + 1, dim)) swap (index, begin + 1, end - 1); // The element in position 1 (the median-of-three) is the pivot. // Scan i forwards for an element with {i} >= {1}, and scan j // backwards for {j} <= {1} (the elements in positions 1 and count-1 // are sentinels); if i <= j, exchange elements i and j and repeat. unsigned i = begin + 1, j = end - 1; for (;;) { while (less (index, x, ++ i, begin + 1, dim)) continue; while (less (index, x, begin + 1, -- j, dim)) continue; if (j < i) break; swap (index, i, j); } // At this point j < i, // and: {i} >= {1}, but {k} <= {1} for k = 2 .. i-1, // and: {j} <= {1}, but {k} >= {1} for k = j+1 .. count-1. // It follows that if j < k < i then {k} == {1}. swap (index, begin + 1, j); // Now, {j} == {j+1} == ... == {i-2} == {i-1}. // If j <= m < i we are done; otherwise, partition // either [0,j) or [i,count), the one that contains m. if (middle < j) i = begin; else if (middle >= i) j = end; else return; // Partition the chosen range [i,j) about m. Tail call. if (j > i + 2) partition (index, x, i, middle, j, dim); else if (j == i + 2 && less (index, x, i + 1, i, dim)) swap (index, i, i + 1); } void insertion_sort (unsigned * index, const float (* x) [4], unsigned begin, unsigned end) { const unsigned dim = 2; for (unsigned n = begin + 1; n != end; ++ n) { // Now, the range [begin, n) is sorted. unsigned item = index [n]; while (n > begin && x [item] [dim] < x [index [n - 1]] [dim]) { index [n] = index [n - 1]; n = n - 1; } index [n] = item; // Now, the range [begin, n + 1) is sorted. } // Now, the range [begin, end) is sorted. } void quicksort (unsigned * index, const float (* x) [4], unsigned count) { const unsigned dim = 2; struct task_t { unsigned begin; unsigned end; }; task_t stack [50]; unsigned sp = 0; stack [sp ++] = { 0, count, }; do { -- sp; unsigned begin = stack [sp].begin; unsigned end = stack [sp].end; if (end - begin < 7) { insertion_sort (index, x, begin, end); } else { // Move the middle element to position 1. swap (index, begin + 1, (begin + end) / 2); // Now use the median of elements 0, 1, count-1 as the pivot. if (less (index, x, begin + 1, begin, dim)) swap (index, begin, begin + 1); if (less (index, x, end - 1, begin, dim)) swap (index, begin, end - 1); if (less (index, x, end - 1, begin + 1, dim)) swap (index, begin + 1, end - 1); // Scan i forwards for an element with {i} >= {1}, and scan j // backwards for {j} <= {1} (the elements in positions 1 and count-1 // are sentinels); if i < j, exchange elements i and j and repeat. unsigned i = begin + 1, j = end - 1; for (;;) { while (less (index, x, ++ i, begin + 1, dim)) continue; while (less (index, x, begin + 1, -- j, dim)) continue; if (j < i) break; swap (index, i, j); } // At this point j < i, // and: {i} >= {1}, but {k} <= {1} for k = 2 .. i-1, // and: {j} <= {1}, but {k} >= {1} for k = j+1 .. count-1. // It follows that if j < k < i then {k} == {1}. swap (index, begin + 1, j); // Now, {j} == {j+1} == ... == {i-2} == {i-1}. // Partition the ranges [begin,j) and [i,end). stack [sp ++] = { begin, j, }; stack [sp ++] = { i, end, }; } } while (sp); }
#include "partition.h" #include "vector.h" namespace { inline void swap (unsigned * index, unsigned i, unsigned j) { unsigned temp = index [j]; index [j] = index [i]; index [i] = temp; } inline bool less (unsigned * index, const float (* x) [4], unsigned i, unsigned j, unsigned dim) { return x [index [i]] [dim] < x [index [j]] [dim]; } } // Reorder index [0, count) so that {i} <= {m} for i = 0 .. m - 1, // and {m} <= {j} for j = m + 1 .. count - 1, // where {i} = x [index [i]] [dim]. // Undefined behaviour if count < 3. void partition (unsigned * index, const float (* x) [4], unsigned begin, unsigned middle, unsigned end, unsigned dim) { // Move the middle element to position 1. swap (index, begin + 1, (begin + end) / 2); // Now put elements 0, 1, count-1 in order. if (less (index, x, begin + 1, begin, dim)) swap (index, begin, begin + 1); if (less (index, x, end - 1, begin, dim)) swap (index, begin, end - 1); if (less (index, x, end - 1, begin + 1, dim)) swap (index, begin + 1, end - 1); // The element in position 1 (the median-of-three) is the pivot. // Scan i forwards for an element with {i} >= {1}, and scan j // backwards for {j} <= {1} (the elements in positions 1 and count-1 // are sentinels); if i <= j, exchange elements i and j and repeat. unsigned i = begin + 1, j = end - 1; for (;;) { while (less (index, x, ++ i, begin + 1, dim)) continue; while (less (index, x, begin + 1, -- j, dim)) continue; if (j < i) break; swap (index, i, j); } // At this point j < i, // and: {i} >= {1}, but {k} <= {1} for k = 2 .. i-1, // and: {j} <= {1}, but {k} >= {1} for k = j+1 .. count-1. // It follows that if j < k < i then {k} == {1}. swap (index, begin + 1, j); // Now, {j} == {j+1} == ... == {i-2} == {i-1}. // If j <= m < i we are done; otherwise, partition // either [0,j) or [i,count), the one that contains m. if (middle < j) i = begin; else if (middle >= i) j = end; else return; // Partition the chosen range [i,j) about m. Tail call. if (j - i > 7) partition (index, x, i, middle, j, dim); else if (j - i > 1) insertion_sort (index, x, i, j); } void insertion_sort (unsigned * index, const float (* x) [4], unsigned begin, unsigned end) { const unsigned dim = 2; for (unsigned n = begin + 1; n != end; ++ n) { // Now, the range [begin, n) is sorted. unsigned item = index [n]; while (n > begin && x [item] [dim] < x [index [n - 1]] [dim]) { index [n] = index [n - 1]; n = n - 1; } index [n] = item; // Now, the range [begin, n + 1) is sorted. } // Now, the range [begin, end) is sorted. } void quicksort (unsigned * index, const float (* x) [4], unsigned count) { const unsigned dim = 2; struct task_t { unsigned begin; unsigned end; }; task_t stack [50]; unsigned sp = 0; stack [sp ++] = { 0, count, }; do { -- sp; unsigned begin = stack [sp].begin; unsigned end = stack [sp].end; if (end - begin < 7) { insertion_sort (index, x, begin, end); } else { // Move the middle element to position 1. swap (index, begin + 1, (begin + end) / 2); // Now use the median of elements 0, 1, count-1 as the pivot. if (less (index, x, begin + 1, begin, dim)) swap (index, begin, begin + 1); if (less (index, x, end - 1, begin, dim)) swap (index, begin, end - 1); if (less (index, x, end - 1, begin + 1, dim)) swap (index, begin + 1, end - 1); // Scan i forwards for an element with {i} >= {1}, and scan j // backwards for {j} <= {1} (the elements in positions 1 and count-1 // are sentinels); if i < j, exchange elements i and j and repeat. unsigned i = begin + 1, j = end - 1; for (;;) { while (less (index, x, ++ i, begin + 1, dim)) continue; while (less (index, x, begin + 1, -- j, dim)) continue; if (j < i) break; swap (index, i, j); } // At this point j < i, // and: {i} >= {1}, but {k} <= {1} for k = 2 .. i-1, // and: {j} <= {1}, but {k} >= {1} for k = j+1 .. count-1. // It follows that if j < k < i then {k} == {1}. swap (index, begin + 1, j); // Now, {j} == {j+1} == ... == {i-2} == {i-1}. // Partition the ranges [begin,j) and [i,end). stack [sp ++] = { begin, j, }; stack [sp ++] = { i, end, }; } } while (sp); }
Use insertion sort to partition ranges of size 7 or less.
Use insertion sort to partition ranges of size 7 or less.
C++
apache-2.0
bustercopley/polymorph,bustercopley/polymorph
6ed283946cc34d489e366cecb64142d551fc06f9
src/qt/bitcoingui.cpp
src/qt/bitcoingui.cpp
/* * Qt4 bitcoin GUI. * * W.J. van der Laan 2011 */ #include "bitcoingui.h" #include "transactiontablemodel.h" #include "addressbookdialog.h" #include "sendcoinsdialog.h" #include "optionsdialog.h" #include "aboutdialog.h" #include "clientmodel.h" #include "guiutil.h" #include "editaddressdialog.h" #include "optionsmodel.h" #include "transactiondescdialog.h" #include "addresstablemodel.h" #include "transactionview.h" #include "headers.h" #include <QApplication> #include <QMainWindow> #include <QMenuBar> #include <QMenu> #include <QIcon> #include <QTabWidget> #include <QVBoxLayout> #include <QWidget> #include <QToolBar> #include <QStatusBar> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QLocale> #include <QClipboard> #include <QMessageBox> #include <QProgressBar> #include <QDebug> #include <iostream> BitcoinGUI::BitcoinGUI(QWidget *parent): QMainWindow(parent), trayIcon(0) { resize(850, 550); setWindowTitle(tr("Bitcoin")); setWindowIcon(QIcon(":icons/bitcoin")); createActions(); // Menus QMenu *file = menuBar()->addMenu("&File"); file->addAction(sendcoins); file->addSeparator(); file->addAction(quit); QMenu *settings = menuBar()->addMenu("&Settings"); settings->addAction(receivingAddresses); settings->addAction(options); QMenu *help = menuBar()->addMenu("&Help"); help->addAction(about); // Toolbar QToolBar *toolbar = addToolBar("Main toolbar"); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(sendcoins); toolbar->addAction(addressbook); // Address: <address>: New... : Paste to clipboard QHBoxLayout *hbox_address = new QHBoxLayout(); hbox_address->addWidget(new QLabel(tr("Your Bitcoin address:"))); address = new QLineEdit(); address->setReadOnly(true); address->setFont(GUIUtil::bitcoinAddressFont()); address->setToolTip(tr("Your current default receiving address")); hbox_address->addWidget(address); QPushButton *button_new = new QPushButton(tr("&New...")); button_new->setToolTip(tr("Create new receiving address")); button_new->setIcon(QIcon(":/icons/add")); QPushButton *button_clipboard = new QPushButton(tr("&Copy to clipboard")); button_clipboard->setToolTip(tr("Copy current receiving address to the system clipboard")); button_clipboard->setIcon(QIcon(":/icons/editcopy")); hbox_address->addWidget(button_new); hbox_address->addWidget(button_clipboard); // Balance: <balance> QHBoxLayout *hbox_balance = new QHBoxLayout(); hbox_balance->addWidget(new QLabel(tr("Balance:"))); hbox_balance->addSpacing(5);/* Add some spacing between the label and the text */ labelBalance = new QLabel(); labelBalance->setFont(QFont("Monospace", -1, QFont::Bold)); labelBalance->setToolTip(tr("Your current balance")); hbox_balance->addWidget(labelBalance); hbox_balance->addStretch(1); QVBoxLayout *vbox = new QVBoxLayout(); vbox->addLayout(hbox_address); vbox->addLayout(hbox_balance); transactionView = new TransactionView(this); connect(transactionView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(transactionDetails(const QModelIndex&))); vbox->addWidget(transactionView); QWidget *centralwidget = new QWidget(this); centralwidget->setLayout(vbox); setCentralWidget(centralwidget); // Create status bar statusBar(); labelConnections = new QLabel(); labelConnections->setFrameStyle(QFrame::Panel | QFrame::Sunken); labelConnections->setMinimumWidth(150); labelConnections->setToolTip(tr("Number of connections to other clients")); labelBlocks = new QLabel(); labelBlocks->setFrameStyle(QFrame::Panel | QFrame::Sunken); labelBlocks->setMinimumWidth(130); labelBlocks->setToolTip(tr("Number of blocks in the block chain")); labelTransactions = new QLabel(); labelTransactions->setFrameStyle(QFrame::Panel | QFrame::Sunken); labelTransactions->setMinimumWidth(130); labelTransactions->setToolTip(tr("Number of transactions in your wallet")); // Progress bar for blocks download progressBarLabel = new QLabel(tr("Synchronizing with network...")); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); progressBar->setToolTip(tr("Block chain synchronization in progress")); progressBar->setVisible(false); statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(labelConnections); statusBar()->addPermanentWidget(labelBlocks); statusBar()->addPermanentWidget(labelTransactions); // Action bindings connect(button_new, SIGNAL(clicked()), this, SLOT(newAddressClicked())); connect(button_clipboard, SIGNAL(clicked()), this, SLOT(copyClipboardClicked())); createTrayIcon(); } void BitcoinGUI::createActions() { quit = new QAction(QIcon(":/icons/quit"), tr("&Exit"), this); quit->setToolTip(tr("Quit application")); sendcoins = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this); sendcoins->setToolTip(tr("Send coins to a bitcoin address")); addressbook = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this); addressbook->setToolTip(tr("Edit the list of stored addresses and labels")); about = new QAction(QIcon(":/icons/bitcoin"), tr("&About"), this); about->setToolTip(tr("Show information about Bitcoin")); receivingAddresses = new QAction(QIcon(":/icons/receiving_addresses"), tr("Your &Receiving Addresses..."), this); receivingAddresses->setToolTip(tr("Show the list of receiving addresses and edit their labels")); options = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); options->setToolTip(tr("Modify configuration options for bitcoin")); openBitcoin = new QAction(QIcon(":/icons/bitcoin"), "Open &Bitcoin", this); openBitcoin->setToolTip(tr("Show the Bitcoin window")); connect(quit, SIGNAL(triggered()), qApp, SLOT(quit())); connect(sendcoins, SIGNAL(triggered()), this, SLOT(sendcoinsClicked())); connect(addressbook, SIGNAL(triggered()), this, SLOT(addressbookClicked())); connect(receivingAddresses, SIGNAL(triggered()), this, SLOT(receivingAddressesClicked())); connect(options, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(about, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(openBitcoin, SIGNAL(triggered()), this, SLOT(show())); } void BitcoinGUI::setModel(ClientModel *model) { this->model = model; // Keep up to date with client setBalance(model->getBalance()); connect(model, SIGNAL(balanceChanged(qint64)), this, SLOT(setBalance(qint64))); setNumConnections(model->getNumConnections()); connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumTransactions(model->getNumTransactions()); connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int))); setNumBlocks(model->getNumBlocks()); connect(model, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int))); setAddress(model->getAddressTableModel()->getDefaultAddress()); connect(model->getAddressTableModel(), SIGNAL(defaultAddressChanged(QString)), this, SLOT(setAddress(QString))); // Report errors from network/worker thread connect(model, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString))); // Put transaction list in tabs transactionView->setModel(model->getTransactionTableModel()); // Balloon popup for new transaction connect(model->getTransactionTableModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(incomingTransaction(const QModelIndex &, int, int))); } void BitcoinGUI::createTrayIcon() { QMenu *trayIconMenu = new QMenu(this); trayIconMenu->addAction(openBitcoin); trayIconMenu->addAction(sendcoins); trayIconMenu->addAction(options); trayIconMenu->addSeparator(); trayIconMenu->addAction(quit); trayIcon = new QSystemTrayIcon(this); trayIcon->setContextMenu(trayIconMenu); trayIcon->setIcon(QIcon(":/icons/toolbar")); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); trayIcon->show(); } void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::DoubleClick) { // Doubleclick on system tray icon triggers "open bitcoin" openBitcoin->trigger(); } } void BitcoinGUI::sendcoinsClicked() { SendCoinsDialog dlg; dlg.setModel(model); dlg.exec(); } void BitcoinGUI::addressbookClicked() { AddressBookDialog dlg(AddressBookDialog::ForEditing); dlg.setModel(model->getAddressTableModel()); dlg.setTab(AddressBookDialog::SendingTab); dlg.exec(); } void BitcoinGUI::receivingAddressesClicked() { AddressBookDialog dlg(AddressBookDialog::ForEditing); dlg.setModel(model->getAddressTableModel()); dlg.setTab(AddressBookDialog::ReceivingTab); dlg.exec(); } void BitcoinGUI::optionsClicked() { OptionsDialog dlg; dlg.setModel(model->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { AboutDialog dlg; dlg.exec(); } void BitcoinGUI::newAddressClicked() { EditAddressDialog dlg(EditAddressDialog::NewReceivingAddress); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { QString newAddress = dlg.saveCurrentRow(); } } void BitcoinGUI::copyClipboardClicked() { // Copy text in address to clipboard QApplication::clipboard()->setText(address->text()); } void BitcoinGUI::setBalance(qint64 balance) { labelBalance->setText(QString::fromStdString(FormatMoney(balance)) + QString(" BTC")); } void BitcoinGUI::setAddress(const QString &addr) { address->setText(addr); } void BitcoinGUI::setNumConnections(int count) { QString icon; switch(count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } labelConnections->setTextFormat(Qt::RichText); labelConnections->setText("<img src=\""+icon+"\"> " + tr("%n connection(s)", "", count)); } void BitcoinGUI::setNumBlocks(int count) { int total = model->getTotalBlocksEstimate(); if(count < total) { progressBarLabel->setVisible(true); progressBar->setVisible(true); progressBar->setMaximum(total); progressBar->setValue(count); } else { progressBarLabel->setVisible(false); progressBar->setVisible(false); } labelBlocks->setText(tr("%n block(s)", "", count)); } void BitcoinGUI::setNumTransactions(int count) { labelTransactions->setText(tr("%n transaction(s)", "", count)); } void BitcoinGUI::error(const QString &title, const QString &message) { // Report errors from network/worker thread if(trayIcon->supportsMessages()) { // Show as "balloon" message if possible trayIcon->showMessage(title, message, QSystemTrayIcon::Critical); } else { // Fall back to old fashioned popup dialog if not QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok); } } void BitcoinGUI::changeEvent(QEvent *e) { if (e->type() == QEvent::WindowStateChange) { if(model->getOptionsModel()->getMinimizeToTray()) { if (isMinimized()) { hide(); e->ignore(); } else { e->accept(); } } } QMainWindow::changeEvent(e); } void BitcoinGUI::closeEvent(QCloseEvent *event) { if(!model->getOptionsModel()->getMinimizeToTray() && !model->getOptionsModel()->getMinimizeOnClose()) { qApp->quit(); } QMainWindow::closeEvent(event); } void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee) { QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, " "which goes to the nodes that process your transaction and helps to support the network. " "Do you want to pay the fee?").arg(QString::fromStdString(FormatMoney(nFeeRequired))); QMessageBox::StandardButton retval = QMessageBox::question( this, tr("Sending..."), strMessage, QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes); *payFee = (retval == QMessageBox::Yes); } void BitcoinGUI::transactionDetails(const QModelIndex& idx) { // A transaction is doubleclicked TransactionDescDialog dlg(idx); dlg.exec(); } void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end) { TransactionTableModel *ttm = model->getTransactionTableModel(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent) .data(Qt::EditRole).toULongLong(); if(amount>0 && !model->inInitialBlockDownload()) { // On incoming transaction, make an info balloon // Unless the initial block download is in progress, to prevent balloon-spam QString date = ttm->index(start, TransactionTableModel::Date, parent) .data().toString(); QString type = ttm->index(start, TransactionTableModel::Type, parent) .data().toString(); QString address = ttm->index(start, TransactionTableModel::ToAddress, parent) .data().toString(); trayIcon->showMessage(tr("Incoming transaction"), tr("Date: ") + date + "\n" + tr("Amount: ") + QString::fromStdString(FormatMoney(amount, true)) + "\n" + tr("Type: ") + type + "\n" + tr("Address: ") + address + "\n", QSystemTrayIcon::Information); } }
/* * Qt4 bitcoin GUI. * * W.J. van der Laan 2011 */ #include "bitcoingui.h" #include "transactiontablemodel.h" #include "addressbookdialog.h" #include "sendcoinsdialog.h" #include "optionsdialog.h" #include "aboutdialog.h" #include "clientmodel.h" #include "guiutil.h" #include "editaddressdialog.h" #include "optionsmodel.h" #include "transactiondescdialog.h" #include "addresstablemodel.h" #include "transactionview.h" #include "headers.h" #include <QApplication> #include <QMainWindow> #include <QMenuBar> #include <QMenu> #include <QIcon> #include <QTabWidget> #include <QVBoxLayout> #include <QWidget> #include <QToolBar> #include <QStatusBar> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QLocale> #include <QClipboard> #include <QMessageBox> #include <QProgressBar> #include <QDebug> #include <iostream> BitcoinGUI::BitcoinGUI(QWidget *parent): QMainWindow(parent), trayIcon(0) { resize(850, 550); setWindowTitle(tr("Bitcoin")); setWindowIcon(QIcon(":icons/bitcoin")); createActions(); // Menus QMenu *file = menuBar()->addMenu("&File"); file->addAction(sendcoins); file->addSeparator(); file->addAction(quit); QMenu *settings = menuBar()->addMenu("&Settings"); settings->addAction(receivingAddresses); settings->addAction(options); QMenu *help = menuBar()->addMenu("&Help"); help->addAction(about); // Toolbar QToolBar *toolbar = addToolBar("Main toolbar"); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(sendcoins); toolbar->addAction(addressbook); // Address: <address>: New... : Paste to clipboard QHBoxLayout *hbox_address = new QHBoxLayout(); hbox_address->addWidget(new QLabel(tr("Your Bitcoin address:"))); address = new QLineEdit(); address->setReadOnly(true); address->setFont(GUIUtil::bitcoinAddressFont()); address->setToolTip(tr("Your current default receiving address")); hbox_address->addWidget(address); QPushButton *button_new = new QPushButton(tr("&New address...")); button_new->setToolTip(tr("Create new receiving address")); button_new->setIcon(QIcon(":/icons/add")); QPushButton *button_clipboard = new QPushButton(tr("&Copy to clipboard")); button_clipboard->setToolTip(tr("Copy current receiving address to the system clipboard")); button_clipboard->setIcon(QIcon(":/icons/editcopy")); hbox_address->addWidget(button_new); hbox_address->addWidget(button_clipboard); // Balance: <balance> QHBoxLayout *hbox_balance = new QHBoxLayout(); hbox_balance->addWidget(new QLabel(tr("Balance:"))); hbox_balance->addSpacing(5);/* Add some spacing between the label and the text */ labelBalance = new QLabel(); labelBalance->setFont(QFont("Monospace", -1, QFont::Bold)); labelBalance->setToolTip(tr("Your current balance")); hbox_balance->addWidget(labelBalance); hbox_balance->addStretch(1); QVBoxLayout *vbox = new QVBoxLayout(); vbox->addLayout(hbox_address); vbox->addLayout(hbox_balance); transactionView = new TransactionView(this); connect(transactionView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(transactionDetails(const QModelIndex&))); vbox->addWidget(transactionView); QWidget *centralwidget = new QWidget(this); centralwidget->setLayout(vbox); setCentralWidget(centralwidget); // Create status bar statusBar(); labelConnections = new QLabel(); labelConnections->setFrameStyle(QFrame::Panel | QFrame::Sunken); labelConnections->setMinimumWidth(150); labelConnections->setToolTip(tr("Number of connections to other clients")); labelBlocks = new QLabel(); labelBlocks->setFrameStyle(QFrame::Panel | QFrame::Sunken); labelBlocks->setMinimumWidth(130); labelBlocks->setToolTip(tr("Number of blocks in the block chain")); labelTransactions = new QLabel(); labelTransactions->setFrameStyle(QFrame::Panel | QFrame::Sunken); labelTransactions->setMinimumWidth(130); labelTransactions->setToolTip(tr("Number of transactions in your wallet")); // Progress bar for blocks download progressBarLabel = new QLabel(tr("Synchronizing with network...")); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); progressBar->setToolTip(tr("Block chain synchronization in progress")); progressBar->setVisible(false); statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(labelConnections); statusBar()->addPermanentWidget(labelBlocks); statusBar()->addPermanentWidget(labelTransactions); // Action bindings connect(button_new, SIGNAL(clicked()), this, SLOT(newAddressClicked())); connect(button_clipboard, SIGNAL(clicked()), this, SLOT(copyClipboardClicked())); createTrayIcon(); } void BitcoinGUI::createActions() { quit = new QAction(QIcon(":/icons/quit"), tr("&Exit"), this); quit->setToolTip(tr("Quit application")); sendcoins = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this); sendcoins->setToolTip(tr("Send coins to a bitcoin address")); addressbook = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this); addressbook->setToolTip(tr("Edit the list of stored addresses and labels")); about = new QAction(QIcon(":/icons/bitcoin"), tr("&About"), this); about->setToolTip(tr("Show information about Bitcoin")); receivingAddresses = new QAction(QIcon(":/icons/receiving_addresses"), tr("Your &Receiving Addresses..."), this); receivingAddresses->setToolTip(tr("Show the list of receiving addresses and edit their labels")); options = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); options->setToolTip(tr("Modify configuration options for bitcoin")); openBitcoin = new QAction(QIcon(":/icons/bitcoin"), "Open &Bitcoin", this); openBitcoin->setToolTip(tr("Show the Bitcoin window")); connect(quit, SIGNAL(triggered()), qApp, SLOT(quit())); connect(sendcoins, SIGNAL(triggered()), this, SLOT(sendcoinsClicked())); connect(addressbook, SIGNAL(triggered()), this, SLOT(addressbookClicked())); connect(receivingAddresses, SIGNAL(triggered()), this, SLOT(receivingAddressesClicked())); connect(options, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(about, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(openBitcoin, SIGNAL(triggered()), this, SLOT(show())); } void BitcoinGUI::setModel(ClientModel *model) { this->model = model; // Keep up to date with client setBalance(model->getBalance()); connect(model, SIGNAL(balanceChanged(qint64)), this, SLOT(setBalance(qint64))); setNumConnections(model->getNumConnections()); connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumTransactions(model->getNumTransactions()); connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int))); setNumBlocks(model->getNumBlocks()); connect(model, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int))); setAddress(model->getAddressTableModel()->getDefaultAddress()); connect(model->getAddressTableModel(), SIGNAL(defaultAddressChanged(QString)), this, SLOT(setAddress(QString))); // Report errors from network/worker thread connect(model, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString))); // Put transaction list in tabs transactionView->setModel(model->getTransactionTableModel()); // Balloon popup for new transaction connect(model->getTransactionTableModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(incomingTransaction(const QModelIndex &, int, int))); } void BitcoinGUI::createTrayIcon() { QMenu *trayIconMenu = new QMenu(this); trayIconMenu->addAction(openBitcoin); trayIconMenu->addAction(sendcoins); trayIconMenu->addAction(options); trayIconMenu->addSeparator(); trayIconMenu->addAction(quit); trayIcon = new QSystemTrayIcon(this); trayIcon->setContextMenu(trayIconMenu); trayIcon->setIcon(QIcon(":/icons/toolbar")); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); trayIcon->show(); } void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::DoubleClick) { // Doubleclick on system tray icon triggers "open bitcoin" openBitcoin->trigger(); } } void BitcoinGUI::sendcoinsClicked() { SendCoinsDialog dlg; dlg.setModel(model); dlg.exec(); } void BitcoinGUI::addressbookClicked() { AddressBookDialog dlg(AddressBookDialog::ForEditing); dlg.setModel(model->getAddressTableModel()); dlg.setTab(AddressBookDialog::SendingTab); dlg.exec(); } void BitcoinGUI::receivingAddressesClicked() { AddressBookDialog dlg(AddressBookDialog::ForEditing); dlg.setModel(model->getAddressTableModel()); dlg.setTab(AddressBookDialog::ReceivingTab); dlg.exec(); } void BitcoinGUI::optionsClicked() { OptionsDialog dlg; dlg.setModel(model->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { AboutDialog dlg; dlg.exec(); } void BitcoinGUI::newAddressClicked() { EditAddressDialog dlg(EditAddressDialog::NewReceivingAddress); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { QString newAddress = dlg.saveCurrentRow(); } } void BitcoinGUI::copyClipboardClicked() { // Copy text in address to clipboard QApplication::clipboard()->setText(address->text()); } void BitcoinGUI::setBalance(qint64 balance) { labelBalance->setText(QString::fromStdString(FormatMoney(balance)) + QString(" BTC")); } void BitcoinGUI::setAddress(const QString &addr) { address->setText(addr); } void BitcoinGUI::setNumConnections(int count) { QString icon; switch(count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } labelConnections->setTextFormat(Qt::RichText); labelConnections->setText("<img src=\""+icon+"\"> " + tr("%n connection(s)", "", count)); } void BitcoinGUI::setNumBlocks(int count) { int total = model->getTotalBlocksEstimate(); if(count < total) { progressBarLabel->setVisible(true); progressBar->setVisible(true); progressBar->setMaximum(total); progressBar->setValue(count); } else { progressBarLabel->setVisible(false); progressBar->setVisible(false); } labelBlocks->setText(tr("%n block(s)", "", count)); } void BitcoinGUI::setNumTransactions(int count) { labelTransactions->setText(tr("%n transaction(s)", "", count)); } void BitcoinGUI::error(const QString &title, const QString &message) { // Report errors from network/worker thread if(trayIcon->supportsMessages()) { // Show as "balloon" message if possible trayIcon->showMessage(title, message, QSystemTrayIcon::Critical); } else { // Fall back to old fashioned popup dialog if not QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok); } } void BitcoinGUI::changeEvent(QEvent *e) { if (e->type() == QEvent::WindowStateChange) { if(model->getOptionsModel()->getMinimizeToTray()) { if (isMinimized()) { hide(); e->ignore(); } else { e->accept(); } } } QMainWindow::changeEvent(e); } void BitcoinGUI::closeEvent(QCloseEvent *event) { if(!model->getOptionsModel()->getMinimizeToTray() && !model->getOptionsModel()->getMinimizeOnClose()) { qApp->quit(); } QMainWindow::closeEvent(event); } void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee) { QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, " "which goes to the nodes that process your transaction and helps to support the network. " "Do you want to pay the fee?").arg(QString::fromStdString(FormatMoney(nFeeRequired))); QMessageBox::StandardButton retval = QMessageBox::question( this, tr("Sending..."), strMessage, QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes); *payFee = (retval == QMessageBox::Yes); } void BitcoinGUI::transactionDetails(const QModelIndex& idx) { // A transaction is doubleclicked TransactionDescDialog dlg(idx); dlg.exec(); } void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end) { TransactionTableModel *ttm = model->getTransactionTableModel(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent) .data(Qt::EditRole).toULongLong(); if(amount>0 && !model->inInitialBlockDownload()) { // On incoming transaction, make an info balloon // Unless the initial block download is in progress, to prevent balloon-spam QString date = ttm->index(start, TransactionTableModel::Date, parent) .data().toString(); QString type = ttm->index(start, TransactionTableModel::Type, parent) .data().toString(); QString address = ttm->index(start, TransactionTableModel::ToAddress, parent) .data().toString(); trayIcon->showMessage(tr("Incoming transaction"), tr("Date: ") + date + "\n" + tr("Amount: ") + QString::fromStdString(FormatMoney(amount, true)) + "\n" + tr("Type: ") + type + "\n" + tr("Address: ") + address + "\n", QSystemTrayIcon::Information); } }
Make it more clear what the "New" button does
Make it more clear what the "New" button does
C++
mit
phplaboratory/psiacoin,DSPay/DSPay,kallewoof/elements,senadmd/coinmarketwatch,ZiftrCOIN/ziftrcoin,KillerByte/memorypool,dexX7/bitcoin,freelion93/mtucicoin,palm12341/jnc,applecoin-official/fellatio,truthcoin/blocksize-market,fanquake/bitcoin,sbaks0820/bitcoin,ANCompany/birdcoin-dev,vertcoin/vertcoin,oklink-dev/bitcoin_block,Rav3nPL/doubloons-08,Cancercoin/Cancercoin,yenliangl/bitcoin,Har01d/bitcoin,qreatora/worldcoin-v0.8,Mirobit/bitcoin,phelixbtc/bitcoin,icook/vertcoin,Anfauglith/iop-hd,fussl/elements,starwalkerz/fincoin-fork,alexandrcoin/vertcoin,gapcoin/gapcoin,projectinterzone/ITZ,ionomy/ion,prodigal-son/blackcoin,Crowndev/crowncoin,GlobalBoost/GlobalBoost,oklink-dev/litecoin_block,dannyperez/bolivarcoin,Chancoin-core/CHANCOIN,mb300sd/bitcoin,ccoin-project/ccoin,bittylicious/bitcoin,vcoin-project/vcoin0.8zeta-dev,apoelstra/bitcoin,zotherstupidguy/bitcoin,scamcoinz/scamcoin,kigooz/smalltest,novacoin-project/novacoin,myriadteam/myriadcoin,arnuschky/bitcoin,ixcoinofficialpage/master,andreaskern/bitcoin,GeekBrony/ponycoin-old,starwels/starwels,tuaris/bitcoin,SandyCohen/mincoin,adpg211/bitcoin-master,TheSeven/ppcoin,bitpay/bitcoin,thesoftwarejedi/bitcoin,jlay11/sharecoin,stamhe/ppcoin,CoinBlack/bitcoin,AllanDoensen/BitcoinUnlimited,koltcoin/koltcoin,TierNolan/bitcoin,Darknet-Crypto/Darknet,zemrys/vertcoin,practicalswift/bitcoin,isle2983/bitcoin,patricklodder/dogecoin,lbrtcoin/albertcoin,cybermatatu/bitcoin,chrisfranko/aiden,genavarov/ladacoin,bitcoinsSG/bitcoin,mrtexaznl/mediterraneancoin,kazcw/bitcoin,cddjr/BitcoinUnlimited,bitpay/bitcoin,kallewoof/elements,scamcoinz/scamcoin,tmagik/catcoin,ardsu/bitcoin,senadmd/coinmarketwatch,balajinandhu/bitcoin,NateBrune/bitcoin-fio,Xekyo/bitcoin,credits-currency/credits,kleetus/bitcoinxt,gwillen/elements,FuzzyBearBTC/Peershares,starwels/starwels,Flurbos/Flurbo,FuzzyBearBTC/Peershares2,bdelzell/creditcoin-org-creditcoin,jmcorgan/bitcoin,Tetcoin/tetcoin,phorensic/yacoin,jul2711/jucoin,josephbisch/namecoin-core,FuzzyBearBTC/Peershares2,cddjr/BitcoinUnlimited,jaromil/faircoin2,NicolasDorier/bitcoin,CoinGame/BCEShadow,stevemyers/bitcoinxt,Kcoin-project/kcoin,majestrate/twister-core,GlobalBoost/GlobalBoost,benzmuircroft/REWIRE.io,bitgrowchain/bitgrow,cqtenq/Feathercoin,MidasPaymentLTD/midascoin,appop/bitcoin,plncoin/PLNcoin_Core,Megacoin2/Megacoin,kryptokredyt/ProjektZespolowyCoin,ingresscoin/ingresscoin,zetacoin/zetacoin,botland/bitcoin,bitgrowchain/bitgrow,mrbandrews/bitcoin,TheOncomingStorm/logincoinadvanced,chaincoin/chaincoin,karek314/bitcoin,rustyrussell/bitcoin,haisee/dogecoin,AsteraCoin/AsteraCoin,stamhe/litecoin,ohac/sakuracoin,Jcing95/iop-hd,dcousens/bitcoin,GeopaymeEE/e-goldcoin,deuscoin/deuscoin,Rav3nPL/doubloons-0.10,dan-mi-sun/bitcoin,mycointest/owncoin,tropa/axecoin,afk11/bitcoin,daveperkins-github/bitcoin-dev,jrick/bitcoin,domob1812/crowncoin,wastholm/bitcoin,shelvenzhou/BTCGPU,stevemyers/bitcoinxt,midnightmagic/bitcoin,Thracky/monkeycoin,degenorate/Deftcoin,CoinBlack/blackcoin,Carrsy/PoundCoin,collapsedev/circlecash,hyperwang/bitcoin,RongxinZhang/bitcoinxt,gmaxwell/bitcoin,namecoin/namecoin-core,thunderrabbit/clams,cryptoprojects/ultimateonlinecash,MazaCoin/maza,LanaCoin/lanacoin,argentumproject/argentum,Diapolo/bitcoin,CarpeDiemCoin/CarpeDiemLaunch,braydonf/bitcoin,pataquets/namecoin-core,dooglus/bitcoin,GwangJin/gwangmoney-core,globaltoken/globaltoken,haobtc/bitcoin,inkvisit/sarmacoins,ya4-old-c-coder/yacoin,fujicoin/fujicoin,jtimon/bitcoin,ixcoinofficialpage/master,jlay11/sharecoin,grumpydevelop/singularity,butterflypay/bitcoin,pataquets/namecoin-core,tmagik/catcoin,coinkeeper/2015-06-22_18-56_megacoin,isocolsky/bitcoinxt,GIJensen/bitcoin,parvez3019/bitcoin,jyap808/jumbucks,sugruedes/bitcoin,nailtaras/nailcoin,koharjidan/dogecoin,romanornr/viacoin,imton/bitcoin,coinkeeper/2015-06-22_18-42_litecoin,world-bank/unpay-core,vcoin-project/vcoincore,andres-root/bitcoinxt,isghe/bitcoinxt,misdess/bitcoin,collapsedev/circlecash,worldbit/worldbit,zander/bitcoinclassic,UFOCoins/ufo,rromanchuk/bitcoinxt,wellenreiter01/Feathercoin,Thracky/monkeycoin,vertcoin/vertcoin,Richcoin-Project/RichCoin,safecoin/safecoin,fujicoin/fujicoin,ptschip/bitcoinxt,celebritycoin/CelebrityCoin,PIVX-Project/PIVX,TheSeven/ppcoin,celebritycoin/investorcoin,Michagogo/bitcoin,OfficialTitcoin/titcoin-wallet,coinkeeper/2015-06-22_18-56_megacoin,mm-s/bitcoin,gravio-net/graviocoin,GroestlCoin/bitcoin,sipa/bitcoin,Dajackal/Ronpaulcoin,GIJensen/bitcoin,erqan/twister-core,rawodb/bitcoin,vectorcoindev/Vector,shadowproject/shadow,cculianu/bitcoin-abc,dmrtsvetkov/flowercoin,okinc/bitcoin,knolza/gamblr,sickpig/BitcoinUnlimited,sirk390/bitcoin,iQcoin/iQcoin,digideskio/namecoin,greenaddress/bitcoin,paveljanik/bitcoin,xXDavasXx/Davascoin,AquariusNetwork/ARCO,TrainMAnB/vcoincore,Peershares/Peershares,MeshCollider/bitcoin,superjudge/bitcoin,bickojima/bitzeny,Coinfigli/coinfigli,greencoin-dev/greencoin-dev,cryptoprojects/ultimateonlinecash,drwasho/bitcoinxt,puticcoin/putic,Kore-Core/kore,snakie/ppcoin,peerdb/cors,untrustbank/litecoin,globaltoken/globaltoken,whatrye/twister-core,Dinarcoin/dinarcoin,ericshawlinux/bitcoin,webdesignll/coin,qtumproject/qtum,jarymoth/dogecoin,JeremyRand/namecore,qubitcoin-project/QubitCoinQ2C,shaolinfry/litecoin,Exceltior/dogecoin,theuni/bitcoin,FeatherCoin/Feathercoin,zotherstupidguy/bitcoin,prodigal-son/blackcoin,AquariusNetwork/ARCO,instagibbs/bitcoin,jiffe/cosinecoin,peerdb/cors,marscoin/marscoin,Bitcoin-ABC/bitcoin-abc,xurantju/bitcoin,terracoin/terracoin,bitpagar/bitpagar,Lucky7Studio/bitcoin,ivansib/sibcoin,creath/barcoin,funkshelper/woodcore,destenson/bitcoin--bitcoin,sigmike/peercoin,thodg/ppcoin,rat4/bitcoin,KnCMiner/bitcoin,bitpay/bitcoin,CarpeDiemCoin/CarpeDiemLaunch,Bloom-Project/Bloom,Kefkius/clams,cryptocoins4all/zcoin,lbryio/lbrycrd,okinc/bitcoin,laudaa/bitcoin,MonetaryUnit/MUE-Src,rebroad/bitcoin,kleetus/bitcoinxt,TheBlueMatt/bitcoin,cinnamoncoin/groupcoin-1,EntropyFactory/creativechain-core,UFOCoins/ufo,Jheguy2/Mercury,aniemerg/zcash,Christewart/bitcoin,rsdevgun16e/energi,antcheck/antcoin,XX-net/twister-core,plncoin/PLNcoin_Core,phplaboratory/psiacoin,DMDcoin/Diamond,WorldLeadCurrency/WLC,mmpool/coiledcoin,bitcoinplusorg/xbcwalletsource,mincoin-project/mincoin,rustyrussell/bitcoin,gazbert/bitcoin,PandaPayProject/PandaPay,Friedbaumer/litecoin,knolza/gamblr,projectinterzone/ITZ,stamhe/bitcoin,goldcoin/Goldcoin-GLD,se3000/bitcoin,xranby/blackcoin,coinerd/krugercoin,puticcoin/putic,hsavit1/bitcoin,3lambert/Molecular,Exceltior/dogecoin,denverl/bitcoin,KnCMiner/bitcoin,dakk/soundcoin,vertcoin/vertcoin,leofidus/glowing-octo-ironman,osuyuushi/laughingmancoin,CoinGame/NuShadowNet,szlaozhu/twister-core,Kogser/bitcoin,metacoin/florincoin,Tetpay/bitcoin,BTCfork/hardfork_prototype_1_mvf-core,jl2012/litecoin,manuel-zulian/CoMoNet,PRabahy/bitcoin,phelix/bitcoin,TierNolan/bitcoin,jonghyeopkim/bitcoinxt,cryptcoins/cryptcoin,isle2983/bitcoin,core-bitcoin/bitcoin,TrainMAnB/vcoincore,apoelstra/bitcoin,WorldcoinGlobal/WorldcoinLegacy,sbellem/bitcoin,domob1812/bitcoin,DigiByte-Team/digibyte,karek314/bitcoin,gjhiggins/fuguecoin,razor-coin/razor,Bloom-Project/Bloom,jlcurby/NobleCoin,jiangyonghang/bitcoin,multicoins/marycoin,bitjson/hivemind,joshrabinowitz/bitcoin,credits-currency/credits,phorensic/yacoin,CoinGame/BCEShadowNet,litecoin-project/bitcoinomg,ghostlander/Orbitcoin,coinkeeper/2015-06-22_18-42_litecoin,franko-org/franko,ahmedbodi/test2,constantine001/bitcoin,jaromil/faircoin2,erikYX/yxcoin-FIRST,jtimon/bitcoin,reddcoin-project/reddcoin,BTCGPU/BTCGPU,se3000/bitcoin,Alonzo-Coeus/bitcoin,GreenParhelia/bitcoin,masterbraz/dg,Bluejudy/worldcoin,Crypto-Currency/BitBar,Kogser/bitcoin,bcpki/bitcoin,MarcoFalke/bitcoin,funkshelper/woodcoin-b,keo/bitcoin,rat4/bitcoin,tatafiore/mycoin,kfitzgerald/titcoin,phelixbtc/bitcoin,Darknet-Crypto/Darknet,Diapolo/bitcoin,braydonf/bitcoin,stamhe/ppcoin,Blackcoin/blackcoin,coinkeeper/2015-06-22_18-51_vertcoin,amaivsimau/bitcoin,TierNolan/bitcoin,okinc/bitcoin,sigmike/peercoin,pocopoco/yacoin,theuni/bitcoin,jiffe/cosinecoin,kbccoin/kbc,ryanofsky/bitcoin,BenjaminsCrypto/Benjamins-1,OmniLayer/omnicore,Dinarcoin/dinarcoin,okcashpro/okcash,nathaniel-mahieu/bitcoin,cmgustavo/bitcoin,erqan/twister-core,imharrywu/fastcoin,lbryio/lbrycrd,zcoinofficial/zcoin,svcop3/svcop3,bfroemel/smallchange,djpnewton/bitcoin,AsteraCoin/AsteraCoin,krzysztofwos/BitcoinUnlimited,ahmedbodi/test2,gjhiggins/vcoincore,KaSt/ekwicoin,ftrader-bitcoinabc/bitcoin-abc,borgcoin/Borgcoin.rar,tatafiore/mycoin,peerdb/cors,worldcoinproject/worldcoin-v0.8,Rav3nPL/polcoin,xawksow/GroestlCoin,SproutsEx/SproutsExtreme,unsystemizer/bitcoin,PRabahy/bitcoin,koharjidan/bitcoin,n1bor/bitcoin,syscoin/syscoin,nvmd/bitcoin,PIVX-Project/PIVX,schinzelh/dash,united-scrypt-coin-project/unitedscryptcoin,EntropyFactory/creativechain-core,40thoughts/Coin-QualCoin,inkvisit/sarmacoins,RyanLucchese/energi,byncoin-project/byncoin,brettwittam/geocoin,chrisfranko/aiden,robvanmieghem/clams,apoelstra/elements,ya4-old-c-coder/yacoin,ticclassic/ic,AllanDoensen/BitcoinUnlimited,webdesignll/coin,ingresscoin/ingresscoin,goldmidas/goldmidas,dpayne9000/Rubixz-Coin,gravio-net/graviocoin,mastercoin-MSC/mastercore,coinkeeper/2015-06-22_19-00_ziftrcoin,xuyangcn/opalcoin,Jeff88Ho/bitcoin,czr5014iph/bitcoin4e,zander/bitcoinclassic,mruddy/bitcoin,earonesty/bitcoin,cryptodev35/icash,celebritycoin/investorcoin,tensaix2j/bananacoin,bfroemel/smallchange,lateminer/DopeCoinGold,knolza/gamblr,FinalHashLLC/namecore,aniemerg/zcash,ddombrowsky/radioshares,iadix/iadixcoin,rdqw/sscoin,vericoin/vericoin-core,lordsajan/erupee,pinheadmz/bitcoin,FeatherCoin/Feathercoin,myriadcoin/myriadcoin,Bushstar/UFO-Project,isocolsky/bitcoinxt,HeliumGas/helium,BlockchainTechLLC/3dcoin,Diapolo/bitcoin,hg5fm/nexuscoin,czr5014iph/bitcoin4e,p2peace/oliver-twister-core,cryptodev35/icash,Electronic-Gulden-Foundation/egulden,coinkeeper/2015-06-22_18-51_vertcoin,vbernabe/freicoin,jarymoth/dogecoin,kigooz/smalltest,neureal/noocoin,faircoin/faircoin,anditto/bitcoin,REAP720801/bitcoin,mm-s/bitcoin,imharrywu/fastcoin,coinkeeper/2015-06-22_18-39_feathercoin,Kangmo/bitcoin,stronghands/stronghands,MikeAmy/bitcoin,mincoin-project/mincoin,coinkeeper/anoncoin_20150330_fixes,bespike/litecoin,Bushstar/UFO-Project,3lambert/Molecular,40thoughts/Coin-QualCoin,cddjr/BitcoinUnlimited,bmp02050/ReddcoinUpdates,qreatora/worldcoin-v0.8,habibmasuro/bitcoinxt,Tetpay/bitcoin,JeremyRand/namecoin-core,jamesob/bitcoin,Jeff88Ho/bitcoin,OstlerDev/florincoin,ludbb/bitcoin,Ziftr/bitcoin,uphold/bitcoin,ya4-old-c-coder/yacoin,appop/bitcoin,kirkalx/bitcoin,wbchen99/bitcoin-hnote0,Chancoin-core/CHANCOIN,JeremyRubin/bitcoin,MikeAmy/bitcoin,ionux/freicoin,leofidus/glowing-octo-ironman,neuroidss/bitcoin,majestrate/twister-core,ixcoinofficialpage/master,phelix/namecore,Jeff88Ho/bitcoin,funkshelper/woodcore,matlongsi/micropay,xuyangcn/opalcoin,DrCrypto/darkcoin,s-matthew-english/bitcoin,sdaftuar/bitcoin,rnicoll/bitcoin,ya4-old-c-coder/yacoin,marlengit/hardfork_prototype_1_mvf-bu,raasakh/bardcoin.exe,ashleyholman/bitcoin,kazcw/bitcoin,argentumproject/argentum,5mil/SuperTurboStake,ahmedbodi/terracoin,mikehearn/bitcoinxt,denverl/bitcoin,aspanta/bitcoin,zander/bitcoinclassic,BTCGPU/BTCGPU,markf78/dollarcoin,awemany/BitcoinUnlimited,BTCDDev/bitcoin,cheehieu/bitcoin,fsb4000/novacoin,wcwu/bitcoin,josephbisch/namecoin-core,sarielsaz/sarielsaz,mycointest/owncoin,Erkan-Yilmaz/twister-core,myriadteam/myriadcoin,npccoin/npccoin,2XL/bitcoin,dakk/soundcoin,RibbitFROG/ribbitcoin,11755033isaprimenumber/Feathercoin,thrasher-/litecoin,Infernoman/crowncoin,peercoin/peercoin,gazbert/bitcoin,RongxinZhang/bitcoinxt,andreaskern/bitcoin,wiggi/huntercore,romanornr/viacoin,genavarov/lamacoin,xurantju/bitcoin,bmp02050/ReddcoinUpdates,PandaPayProject/PandaPay,jlopp/statoshi,thrasher-/litecoin,florincoin/florincoin,EthanHeilman/bitcoin,CarpeDiemCoin/CarpeDiemLaunch,stronghands/stronghands,domob1812/huntercore,Ziftr/ppcoin,FuzzyBearBTC/Peershares-1,OfficialTitcoin/titcoin-wallet,mb300sd/bitcoin,theuni/bitcoin,antcheck/antcoin,domob1812/huntercore,Ziftr/bitcoin,manuel-zulian/accumunet,ashleyholman/bitcoin,celebritycoin/CelebrityCoin,sickpig/BitcoinUnlimited,scmorse/bitcoin,imharrywu/fastcoin,laanwj/bitcoin-qt,droark/bitcoin,jimblasko/UnbreakableCoin-master,osuyuushi/laughingmancoin,nbenoit/bitcoin,elliotolds/bitcoin,DynamicCoinOrg/DMC,practicalswift/bitcoin,ronpaulcoin/ronpaulcoin,langerhans/dogecoin,GroestlCoin/GroestlCoin,Climbee/artcoin,senadmd/coinmarketwatch,jonghyeopkim/bitcoinxt,monacoinproject/monacoin,Cocosoft/bitcoin,mitchellcash/bitcoin,elecoin/elecoin,Anfauglith/iop-hd,nochowderforyou/clams,segsignal/bitcoin,cerebrus29301/crowncoin,pinkevich/dash,UASF/bitcoin,vmp32k/litecoin,BTCfork/hardfork_prototype_1_mvf-core,HerkCoin/herkcoin,whatrye/twister-core,BitzenyCoreDevelopers/bitzeny,mockcoin/mockcoin,arruah/ensocoin,IlfirinIlfirin/shavercoin,maraoz/proofcoin,nvmd/bitcoin,iadix/iadixcoin,cainca/liliucoin,TripleSpeeder/bitcoin,pelorusjack/BlockDX,gjhiggins/fuguecoin,DigitalPandacoin/pandacoin,sickpig/BitcoinUnlimited,pinkmagicdev/SwagBucks,gapcoin/gapcoin,coinkeeper/2015-06-22_18-30_anoncoin,litecoin-project/litecore-litecoin,randy-waterhouse/bitcoin,IlfirinCano/shavercoin,dmrtsvetkov/flowercoin,acid1789/bitcoin,Mrs-X/Darknet,MarcoFalke/bitcoin,gades/novacoin,MikeAmy/bitcoin,vcoin-project/vcoincore,gorgoy/novacoin,forrestv/bitcoin,okinc/bitcoin,thelazier/dash,core-bitcoin/bitcoin,syscoin/syscoin,cryptocoins4all/zcoin,andres-root/bitcoinxt,digibyte/digibyte,chaincoin/chaincoin,peercoin/peercoin,ravenbyron/phtevencoin,TheoremCrypto/TheoremCoin,puticcoin/putic,RibbitFROG/ribbitcoin,segsignal/bitcoin,osuyuushi/laughingmancoin,myriadteam/myriadcoin,LIMXTEC/DMDv3,DGCDev/digitalcoin,brishtiteveja/truthcoin-cpp,rebroad/bitcoin,alejandromgk/Lunar,multicoins/marycoin,HashUnlimited/Einsteinium-Unlimited,novacoin-project/novacoin,balajinandhu/bitcoin,ClusterCoin/ClusterCoin,llluiop/bitcoin,balajinandhu/bitcoin,tecnovert/particl-core,Kenwhite23/litecoin,Someguy123/novafoil,s-matthew-english/bitcoin,GeopaymeEE/e-goldcoin,jlcurby/NobleCoin,Ziftr/litecoin,crowning-/dash,ediston/energi,bcpki/nonce2,dagurval/bitcoinxt,TrainMAnB/vcoincore,sugruedes/bitcoinxt,pouta/bitcoin,scippio/bitcoin,martindale/elements,dakk/soundcoin,Electronic-Gulden-Foundation/egulden,PandaPayProject/PandaPay,pstratem/bitcoin,habibmasuro/bitcoinxt,fullcoins/fullcoin,aniemerg/zcash,bitbrazilcoin-project/bitbrazilcoin,gazbert/bitcoin,thormuller/yescoin2,ghostlander/Orbitcoin,mrtexaznl/mediterraneancoin,cinnamoncoin/groupcoin-1,Someguy123/novafoil,jimblasko/2015_UNB_Wallets,nightlydash/darkcoin,HashUnlimited/Einsteinium-Unlimited,FuzzyBearBTC/Peershares2,Mrs-X/PIVX,jyap808/jumbucks,scippio/bitcoin,bfroemel/smallchange,koharjidan/litecoin,vizidrixfork/Peershares,willwray/dash,drwasho/bitcoinxt,earthcoinproject/earthcoin,gandrewstone/bitcoinxt,icook/vertcoin,memorycoin/memorycoin,JeremyRand/namecore,TierNolan/bitcoin,apoelstra/elements,petertodd/bitcoin,jrmithdobbs/bitcoin,KibiCoin/kibicoin,zzkt/solarcoin,vcoin-project/vcoincore,borgcoin/Borgcoin.rar,Checkcoin/checkcoin,zemrys/vertcoin,sebrandon1/bitcoin,achow101/bitcoin,jrick/bitcoin,elcrypto/Pulse,netswift/vertcoin,HashUnlimited/Einsteinium-Unlimited,arruah/ensocoin,miguelfreitas/twister-core,paveljanik/bitcoin,pinkmagicdev/SwagBucks,dev1972/Satellitecoin,elambert2014/cbx2,LIMXTEC/DMDv3,mooncoin-project/mooncoin-landann,Bitcoin-com/BUcash,Carrsy/PoundCoin,gazbert/bitcoin,reddink/reddcoin,n1bor/bitcoin,kseistrup/twister-core,domob1812/i0coin,blackcoinhelp/blackcoin,theuni/bitcoin,cdecker/bitcoin,bitgrowchain/bitgrow,nathan-at-least/zcash,Blackcoin/blackcoin,zemrys/vertcoin,TripleSpeeder/bitcoin,Kogser/bitcoin,forrestv/bitcoin,freelion93/mtucicoin,PRabahy/bitcoin,taenaive/zetacoin,scamcoinz/scamcoin,Peer3/homework,marlengit/BitcoinUnlimited,viacoin/viacoin,Kixunil/keynescoin,Vector2000/bitcoin,ColossusCoinXT/ColossusCoinXT,scippio/bitcoin,amaivsimau/bitcoin,gravio-net/graviocoin,szlaozhu/twister-core,JeremyRubin/bitcoin,Geekcoin-Project/Geekcoin,webdesignll/coin,coinkeeper/terracoin_20150327,compasscoin/compasscoin,goldcoin/goldcoin,RyanLucchese/energi,MasterX1582/bitcoin-becoin,thunderrabbit/clams,ALEXIUMCOIN/alexium,ftrader-bitcoinabc/bitcoin-abc,40thoughts/Coin-QualCoin,tatafiore/mycoin,diggcoin/diggcoin,tedlz123/Bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,bitcoinplusorg/xbcwalletsource,mincoin-project/mincoin,xeddmc/twister-core,syscoin/syscoin,presstab/PIVX,laudaa/bitcoin,bitpay/bitcoin,Electronic-Gulden-Foundation/egulden,jiangyonghang/bitcoin,BTCfork/hardfork_prototype_1_mvf-core,Cocosoft/bitcoin,droark/bitcoin,zsulocal/bitcoin,kleetus/bitcoin,earonesty/bitcoin,hsavit1/bitcoin,effectsToCause/vericoin,majestrate/twister-core,nikkitan/bitcoin,BitcoinPOW/BitcoinPOW,dooglus/clams,Vector2000/bitcoin,peercoin/peercoin,tjth/lotterycoin,safecoin/safecoin,xXDavasXx/Davascoin,BlockchainTechLLC/3dcoin,pocopoco/yacoin,laanwj/bitcoin-qt,argentumproject/argentum,sifcoin/sifcoin,Petr-Economissa/gvidon,gfneto/Peershares,lateminer/DopeCoinGold,kevin-cantwell/crunchcoin,DigiByte-Team/digibyte,bittylicious/bitcoin,axelxod/braincoin,tedlz123/Bitcoin,fsb4000/bitcoin,dgarage/bc3,Bloom-Project/Bloom,segsignal/bitcoin,IOCoin/DIONS,Alex-van-der-Peet/bitcoin,cqtenq/feathercoin_core,metrocoins/metrocoin,antcheck/antcoin,litecoin-project/litecoin,CTRoundTable/Encrypted.Cash,maraoz/proofcoin,tuaris/bitcoin,constantine001/bitcoin,coinkeeper/megacoin_20150410_fixes,svost/bitcoin,shaolinfry/litecoin,AdrianaDinca/bitcoin,llamasoft/ProtoShares_Cycle,zsulocal/bitcoin,valorbit/valorbit,tuaris/bitcoin,millennial83/bitcoin,parvez3019/bitcoin,knolza/gamblr,syscoin/syscoin,sifcoin/sifcoin,gandrewstone/BitcoinUnlimited,CarpeDiemCoin/CarpeDiemLaunch,kigooz/smalltest,biblepay/biblepay,ahmedbodi/temp_vert,tjth/lotterycoin,ajtowns/bitcoin,DSPay/DSPay,sigmike/peercoin,Matoking/bitcoin,RazorLove/cloaked-octo-spice,AquariusNetwork/ARCOv2,cryptocoins4all/zcoin,greencoin-dev/greencoin-dev,franko-org/franko,phorensic/yacoin,randy-waterhouse/bitcoin,sbaks0820/bitcoin,keo/bitcoin,sirk390/bitcoin,neuroidss/bitcoin,genavarov/brcoin,goldcoin/goldcoin,gzuser01/zetacoin-bitcoin,adpg211/bitcoin-master,dobbscoin/dobbscoin-source,ghostlander/Feathercoin,bittylicious/bitcoin,rebroad/bitcoin,wiggi/huntercore,aniemerg/zcash,bitcoinknots/bitcoin,torresalyssa/bitcoin,octocoin-project/octocoin,droark/bitcoin,Friedbaumer/litecoin,TGDiamond/Diamond,jgarzik/bitcoin,faircoin/faircoin,axelxod/braincoin,glv2/peerunity,11755033isaprimenumber/Feathercoin,ericshawlinux/bitcoin,Bitcoinsulting/bitcoinxt,Chancoin-core/CHANCOIN,leofidus/glowing-octo-ironman,Erkan-Yilmaz/twister-core,IOCoin/DIONS,isocolsky/bitcoinxt,brishtiteveja/sherlockholmescoin,itmanagerro/tresting,adpg211/bitcoin-master,tobeyrowe/BitStarCoin,coinerd/krugercoin,llluiop/bitcoin,jimblasko/2015_UNB_Wallets,droark/bitcoin,applecoin-official/fellatio,jimmysong/bitcoin,razor-coin/razor,oklink-dev/litecoin_block,MikeAmy/bitcoin,sstone/bitcoin,btc1/bitcoin,apoelstra/bitcoin,vericoin/vericoin-core,Rav3nPL/doubloons-08,ychaim/smallchange,Infernoman/crowncoin,okcashpro/okcash,shomeser/bitcoin,mortalvikinglive/bitcoinclassic,AquariusNetwork/ARCOv2,llamasoft/ProtoShares_Cycle,mrbandrews/bitcoin,GroestlCoin/GroestlCoin,syscoin/syscoin,jtimon/bitcoin,gades/novacoin,ahmedbodi/vertcoin,BenjaminsCrypto/Benjamins-1,kallewoof/elements,inutoshi/inutoshi,cculianu/bitcoin-abc,goldcoin/Goldcoin-GLD,Anoncoin/anoncoin,Rav3nPL/doubloons-08,zixan/bitcoin,novacoin-project/novacoin,bmp02050/ReddcoinUpdates,mmpool/coiledcoin,pouta/bitcoin,NateBrune/bitcoin-fio,Bitcoin-com/BUcash,mikehearn/bitcoinxt,hsavit1/bitcoin,rromanchuk/bitcoinxt,landcoin-ldc/landcoin,CodeShark/bitcoin,jtimon/elements,VsyncCrypto/Vsync,Charlesugwu/Vintagecoin,cmgustavo/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,funbucks/notbitcoinxt,DigitalPandacoin/pandacoin,slimcoin-project/Slimcoin,brishtiteveja/sherlockcoin,rjshaver/bitcoin,botland/bitcoin,kevcooper/bitcoin,biblepay/biblepay,Justaphf/BitcoinUnlimited,gzuser01/zetacoin-bitcoin,rnicoll/dogecoin,bickojima/bitzeny,cannabiscoindev/cannabiscoin420,cerebrus29301/crowncoin,elcrypto/Pulse,sipa/elements,gmaxwell/bitcoin,yenliangl/bitcoin,kallewoof/bitcoin,destenson/bitcoin--bitcoin,fussl/elements,LIMXTEC/DMDv3,prark/bitcoinxt,andreaskern/bitcoin,zcoinofficial/zcoin,Bitcoinsulting/bitcoinxt,therealaltcoin/altcoin,morcos/bitcoin,wiggi/huntercore,stamhe/bitcoin,jiangyonghang/bitcoin,FuzzyBearBTC/Peerunity,CoinBlack/bitcoin,Tetcoin/tetcoin,Vsync-project/Vsync,jrmithdobbs/bitcoin,PandaPayProject/PandaPay,OfficialTitcoin/titcoin-wallet,langerhans/dogecoin,earonesty/bitcoin,KillerByte/memorypool,Stakemaker/OMFGcoin,ddombrowsky/radioshares,borgcoin/Borgcoin.rar,elecoin/elecoin,knolza/gamblr,Vsync-project/Vsync,ForceMajeure/BitPenny-Client,Paymium/bitcoin,joulecoin/joulecoin,kevcooper/bitcoin,maaku/bitcoin,MoMoneyMonetarism/ppcoin,koharjidan/litecoin,emc2foundation/einsteinium,genavarov/brcoin,Climbee/artcoin,vertcoin/eyeglass,ctwiz/stardust,zander/bitcoinclassic,amaivsimau/bitcoin,funbucks/notbitcoinxt,oleganza/bitcoin-duo,pascalguru/florincoin,Anfauglith/iop-hd,11755033isaprimenumber/Feathercoin,x-kalux/bitcoin_WiG-B,jameshilliard/bitcoin,plankton12345/litecoin,afk11/bitcoin,Matoking/bitcoin,worldcoinproject/worldcoin-v0.8,nsacoin/nsacoin,SmeltFool/Wonker,jtimon/bitcoin,morcos/bitcoin,coinerd/krugercoin,Rimbit/Wallets,okinc/bitcoin,butterflypay/bitcoin,shadowproject/shadow,nikkitan/bitcoin,wangxinxi/litecoin,ccoin-project/ccoin,aburan28/elements,genavarov/brcoin,gorgoy/novacoin,rat4/blackcoin,degenorate/Deftcoin,BTCfork/hardfork_prototype_1_mvf-core,bankonmecoin/bitcoin,simdeveloper/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,tobeyrowe/KitoniaCoin,ptschip/bitcoin,royosherove/bitcoinxt,shurcoin/shurcoin,lbrtcoin/albertcoin,coinwarp/dogecoin,prodigal-son/blackcoin,tripmode/pxlcoin,AdrianaDinca/bitcoin,cainca/liliucoin,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,dgenr8/bitcoinxt,untrustbank/litecoin,genavarov/ladacoin,gmaxwell/bitcoin,jimmysong/bitcoin,likecoin-dev/bitcoin,kallewoof/bitcoin,neuroidss/bitcoin,josephbisch/namecoin-core,DynamicCoinOrg/DMC,jimmykiselak/lbrycrd,brishtiteveja/truthcoin-cpp,mortalvikinglive/bitcoinclassic,iosdevzone/bitcoin,gmaxwell/bitcoin,gjhiggins/vcoin09,NunoEdgarGub1/elements,GroestlCoin/GroestlCoin,peacedevelop/peacecoin,ionomy/ion,digideskio/namecoin,masterbraz/dg,kfitzgerald/titcoin,superjudge/bitcoin,bitpay/bitcoin,MOIN/moin,botland/bitcoin,cddjr/BitcoinUnlimited,richo/dongcoin,Anoncoin/anoncoin,bitcoin/bitcoin,likecoin-dev/bitcoin,dscotese/bitcoin,basicincome/unpcoin-core,karek314/bitcoin,Kenwhite23/litecoin,maaku/bitcoin,BigBlueCeiling/augmentacoin,laudaa/bitcoin,phelix/bitcoin,ekankyesme/bitcoinxt,SartoNess/BitcoinUnlimited,romanornr/viacoin,syscoin/syscoin2,FuzzyBearBTC/Peershares-1,5mil/Tradecoin,prark/bitcoinxt,crowning-/dash,sipsorcery/bitcoin,deuscoin/deuscoin,brightcoin/brightcoin,sugruedes/bitcoin,Blackcoin/blackcoin,nsacoin/nsacoin,nmarley/dash,1185/starwels,unsystemizer/bitcoin,rnicoll/dogecoin,snakie/ppcoin,NunoEdgarGub1/elements,mruddy/bitcoin,Flowdalic/bitcoin,dgarage/bc2,reddcoin-project/reddcoin,tdudz/elements,GwangJin/gwangmoney-core,gwillen/elements,celebritycoin/CelebrityCoin,wellenreiter01/Feathercoin,Magicking/neucoin,nlgcoin/guldencoin-official,coinkeeper/2015-06-22_18-51_vertcoin,ya4-old-c-coder/yacoin,bcpki/nonce2,GroestlCoin/bitcoin,BlockchainTechLLC/3dcoin,donaloconnor/bitcoin,neuroidss/bitcoin,bcpki/testblocks,Bitcoin-com/BUcash,akabmikua/flowcoin,reddcoin-project/reddcoin,Krellan/bitcoin,Litecoindark/LTCD,creath/barcoin,globaltoken/globaltoken,zsulocal/bitcoin,vmp32k/litecoin,myriadteam/myriadcoin,apoelstra/elements,neuroidss/bitcoin,Mrs-X/Darknet,FuzzyBearBTC/Peershares-1,coinkeeper/anoncoin_20150330_fixes,2XL/bitcoin,jeromewu/bitcoin-opennet,FinalHashLLC/namecore,MazaCoin/mazacoin-new,BTCfork/hardfork_prototype_1_mvf-core,CoinGame/BCEShadow,worldbit/worldbit,mrbandrews/bitcoin,m0gliE/fastcoin-cli,privatecoin/privatecoin,SartoNess/BitcoinUnlimited,x-kalux/bitcoin_WiG-B,rebroad/bitcoin,projectinterzone/ITZ,wangliu/bitcoin,dmrtsvetkov/flowercoin,JeremyRand/namecoin-core,Jcing95/iop-hd,nailtaras/nailcoin,xieta/mincoin,SmeltFool/Yippe-Hippe,psionin/smartcoin,shea256/bitcoin,Erkan-Yilmaz/twister-core,cinnamoncoin/Feathercoin,BTCfork/hardfork_prototype_1_mvf-bu,GreenParhelia/bitcoin,Tetcoin/tetcoin,fullcoins/fullcoin,cyrixhero/bitcoin,btcdrak/bitcoin,xieta/mincoin,zotherstupidguy/bitcoin,zzkt/solarcoin,Someguy123/novafoil,Exgibichi/statusquo,ludbb/bitcoin,joroob/reddcoin,domob1812/bitcoin,goldcoin/goldcoin,npccoin/npccoin,jnewbery/bitcoin,psionin/smartcoin,coinkeeper/2015-06-22_18-41_ixcoin,vcoin-project/vcoincore,greenaddress/bitcoin,marlengit/hardfork_prototype_1_mvf-bu,WorldcoinGlobal/WorldcoinLegacy,BlockchainTechLLC/3dcoin,CryptArc/bitcoin,marscoin/marscoin,mitchellcash/bitcoin,aciddude/Feathercoin,Rav3nPL/doubloons-0.10,Matoking/bitcoin,brettwittam/geocoin,botland/bitcoin,BitcoinHardfork/bitcoin,nlgcoin/guldencoin-official,sebrandon1/bitcoin,AquariusNetwork/ARCOv2,majestrate/twister-core,DigiByte-Team/digibyte,guncoin/guncoin,nightlydash/darkcoin,shadowproject/shadow,magacoin/magacoin,tjps/bitcoin,landcoin-ldc/landcoin,grumpydevelop/singularity,fedoracoin-dev/fedoracoin,rustyrussell/bitcoin,byncoin-project/byncoin,funbucks/notbitcoinxt,bitbrazilcoin-project/bitbrazilcoin,simdeveloper/bitcoin,11755033isaprimenumber/Feathercoin,NicolasDorier/bitcoin,GroestlCoin/bitcoin,micryon/GPUcoin,manuel-zulian/CoMoNet,bitcoin-hivemind/hivemind,Kenwhite23/litecoin,wiggi/fairbrix-0.6.3,ctwiz/stardust,marlengit/BitcoinUnlimited,florincoin/florincoin,haraldh/bitcoin,gwangjin2/gwangcoin-core,netswift/vertcoin,cmgustavo/bitcoin,RHavar/bitcoin,monacoinproject/monacoin,benosa/bitcoin,Vector2000/bitcoin,Charlesugwu/Vintagecoin,ahmedbodi/temp_vert,ptschip/bitcoinxt,GeopaymeEE/e-goldcoin,whatrye/twister-core,LanaCoin/lanacoin,domob1812/huntercore,midnightmagic/bitcoin,jn2840/bitcoin,nmarley/dash,Rav3nPL/doubloons-0.10,JeremyRubin/bitcoin,JeremyRand/bitcoin,lbrtcoin/albertcoin,Paymium/bitcoin,Petr-Economissa/gvidon,gazbert/bitcoin,lbrtcoin/albertcoin,dpayne9000/Rubixz-Coin,marscoin/marscoin,welshjf/bitcoin,Dinarcoin/dinarcoin,emc2foundation/einsteinium,RyanLucchese/energi,brandonrobertz/namecoin-core,FrictionlessCoin/iXcoin,fussl/elements,lordsajan/erupee,TheoremCrypto/TheoremCoin,m0gliE/fastcoin-cli,Domer85/dogecoin,Erkan-Yilmaz/twister-core,digideskio/namecoin,wastholm/bitcoin,ivansib/sib16,richo/dongcoin,iosdevzone/bitcoin,btcdrak/bitcoin,balajinandhu/bitcoin,loxal/zcash,XertroV/bitcoin-nulldata,MOIN/moin,achow101/bitcoin,Stakemaker/OMFGcoin,CTRoundTable/Encrypted.Cash,globaltoken/globaltoken,mobicoins/mobicoin-core,freelion93/mtucicoin,jameshilliard/bitcoin,kaostao/bitcoin,Friedbaumer/litecoin,zestcoin/ZESTCOIN,coinkeeper/2015-06-22_19-00_ziftrcoin,netswift/vertcoin,koharjidan/litecoin,CoinGame/BCEShadow,gmaxwell/bitcoin,dgarage/bc3,vmp32k/litecoin,droark/bitcoin,fujicoin/fujicoin,neutrinofoundation/neutrino-digital-currency,tecnovert/particl-core,jlcurby/NobleCoin,lbryio/lbrycrd,kirkalx/bitcoin,Har01d/bitcoin,lbryio/lbrycrd,and2099/twister-core,crowning2/dash,BigBlueCeiling/augmentacoin,byncoin-project/byncoin,diggcoin/diggcoin,NunoEdgarGub1/elements,ALEXIUMCOIN/alexium,itmanagerro/tresting,TripleSpeeder/bitcoin,FarhanHaque/bitcoin,barcoin-project/nothingcoin,cerebrus29301/crowncoin,stamhe/novacoin,javgh/bitcoin,shaulkf/bitcoin,zebrains/Blotter,Earlz/dobbscoin-source,internaut-me/ppcoin,ddombrowsky/radioshares,worldbit/worldbit,ctwiz/stardust,arruah/ensocoin,sipsorcery/bitcoin,prark/bitcoinxt,capitalDIGI/DIGI-v-0-10-4,lbrtcoin/albertcoin,BlueMeanie/PeerShares,palm12341/jnc,bitchip/bitchip,stamhe/novacoin,tjps/bitcoin,BitcoinPOW/BitcoinPOW,ticclassic/ic,MitchellMintCoins/AutoCoin,oleganza/bitcoin-duo,jamesob/bitcoin,ohac/sha1coin,Mrs-X/Darknet,isghe/bitcoinxt,meighti/bitcoin,kbccoin/kbc,zebrains/Blotter,achow101/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,leofidus/glowing-octo-ironman,FeatherCoin/Feathercoin,celebritycoin/investorcoin,pelorusjack/BlockDX,daveperkins-github/bitcoin-dev,StarbuckBG/BTCGPU,Enticed87/Decipher,coinkeeper/terracoin_20150327,SoreGums/bitcoinxt,wederw/bitcoin,Stakemaker/OMFGcoin,Open-Source-Coins/EZ,dscotese/bitcoin,bdelzell/creditcoin-org-creditcoin,world-bank/unpay-core,crowning-/dash,namecoin/namecoin-core,error10/bitcoin,zestcoin/ZESTCOIN,RyanLucchese/energi,omefire/bitcoin,krzysztofwos/BitcoinUnlimited,5mil/Bolt,jimmysong/bitcoin,phorensic/yacoin,kleetus/bitcoin,ronpaulcoin/ronpaulcoin,haisee/dogecoin,mikehearn/bitcoinxt,putinclassic/putic,Bitcoin-ABC/bitcoin-abc,funkshelper/woodcore,cannabiscoindev/cannabiscoin420,koharjidan/bitcoin,qtumproject/qtum,thelazier/dash,gzuser01/zetacoin-bitcoin,safecoin/safecoin,erqan/twister-core,gjhiggins/fuguecoin,Flurbos/Flurbo,sipa/elements,mycointest/owncoin,raasakh/bardcoin,dperel/bitcoin,Whitecoin-org/Whitecoin,rnicoll/dogecoin,metrocoins/metrocoin,coinkeeper/2015-04-19_21-20_litecoindark,applecoin-official/applecoin,Sjors/bitcoin,dagurval/bitcoinxt,NicolasDorier/bitcoin,CoinGame/BCEShadow,djtms/ltc,stevemyers/bitcoinxt,totallylegitbiz/totallylegitcoin,n1bor/bitcoin,segwit/atbcoin-insight,GlobalBoost/GlobalBoost,collapsedev/circlecash,SocialCryptoCoin/SocialCoin,TGDiamond/Diamond,DGCDev/argentum,pascalguru/florincoin,rsdevgun16e/energi,cannabiscoindev/cannabiscoin420,sbaks0820/bitcoin,cmgustavo/bitcoin,sugruedes/bitcoinxt,gandrewstone/bitcoinxt,koltcoin/koltcoin,tatafiore/mycoin,Adaryian/E-Currency,bitcoinsSG/zcash,mruddy/bitcoin,novaexchange/EAC,Credit-Currency/CoinTestComp,Mrs-X/PIVX,GlobalBoost/GlobalBoost,REAP720801/bitcoin,mb300sd/bitcoin,1185/starwels,DrCrypto/darkcoin,CoinBlack/blackcoin,joshrabinowitz/bitcoin,AsteraCoin/AsteraCoin,nlgcoin/guldencoin-official,SmeltFool/Yippe-Hippe,megacoin/megacoin,gavinandresen/bitcoin-git,borgcoin/Borgcoin1,mastercoin-MSC/mastercore,kbccoin/kbc,dexX7/mastercore,renatolage/wallets-BRCoin,basicincome/unpcoin-core,Open-Source-Coins/EZ,ekankyesme/bitcoinxt,BTCfork/hardfork_prototype_1_mvf-core,zander/bitcoinclassic,neutrinofoundation/neutrino-digital-currency,randy-waterhouse/bitcoin,webdesignll/coin,sbaks0820/bitcoin,karek314/bitcoin,pouta/bitcoin,iceinsidefire/peershare-edit,Darknet-Crypto/Darknet,Coinfigli/coinfigli,franko-org/franko,themusicgod1/bitcoin,PIVX-Project/PIVX,crowning2/dash,segsignal/bitcoin,crowning-/dash,chaincoin/chaincoin,dannyperez/bolivarcoin,SartoNess/BitcoinUnlimited,nmarley/dash,lordsajan/erupee,slingcoin/sling-market,willwray/dash,Alonzo-Coeus/bitcoin,tedlz123/Bitcoin,emc2foundation/einsteinium,iadix/iadixcoin,randy-waterhouse/bitcoin,Megacoin2/Megacoin,markf78/dollarcoin,ripper234/bitcoin,anditto/bitcoin,ahmedbodi/Bytecoin-MM,cybermatatu/bitcoin,shouhuas/bitcoin,plncoin/PLNcoin_Core,mapineda/litecoin,ajtowns/bitcoin,bitcoinsSG/bitcoin,TheBlueMatt/bitcoin,monacoinproject/monacoin,se3000/bitcoin,celebritycoin/CelebrityCoin,Christewart/bitcoin,Horrorcoin/horrorcoin,tuaris/bitcoin,DrCrypto/darkcoin,donaloconnor/bitcoin,Jeff88Ho/bitcoin,penek/novacoin,Har01d/bitcoin,Gazer022/bitcoin,MazaCoin/mazacoin-new,haraldh/bitcoin,basicincome/unpcoin-core,Xekyo/bitcoin,KaSt/equikoin,Adaryian/E-Currency,mrbandrews/bitcoin,howardrya/AcademicCoin,pascalguru/florincoin,practicalswift/bitcoin,practicalswift/bitcoin,Peerunity/Peerunity,Xekyo/bitcoin,erqan/twister-core,ingresscoin/ingresscoin,nathaniel-mahieu/bitcoin,CodeShark/bitcoin,NeuCoin/neucoin,florincoin/florincoin,p2peace/oliver-twister-core,benzmuircroft/REWIRE.io,puticcoin/putic,gameunits/gameunits,matlongsi/micropay,celebritycoin/investorcoin,MOIN/moin,riecoin/riecoin,robvanmieghem/clams,jimblasko/UnbreakableCoin-master,BitcoinUnlimited/BitcoinUnlimited,constantine001/bitcoin,bitcoinplusorg/xbcwalletsource,lateminer/bitcoin,ddombrowsky/radioshares,HerkCoin/herkcoin,jonghyeopkim/bitcoinxt,DigitalPandacoin/pandacoin,iadix/iadixcoin,sipsorcery/bitcoin,keisercoin-official/keisercoin,bcpki/bitcoin,ShadowMyst/creativechain-core,pinkevich/dash,pstratem/elements,HashUnlimited/Einsteinium-Unlimited,novaexchange/EAC,pinkevich/dash,meighti/bitcoin,Bitcoin-ABC/bitcoin-abc,nsacoin/nsacoin,pocopoco/yacoin,pelorusjack/BlockDX,pelorusjack/BlockDX,Bluejudy/worldcoin,celebritycoin/CelebrityCoin,lakepay/lake,PIVX-Project/PIVX,JeremyRand/namecoin-core,aspanta/bitcoin,privatecoin/privatecoin,AdrianaDinca/bitcoin,CryptArc/bitcoin,stamhe/litecoin,Rav3nPL/bitcoin,goku1997/bitcoin,tdudz/elements,gades/novacoin,Anoncoin/anoncoin,DigitalPandacoin/pandacoin,roques/bitcoin,rjshaver/bitcoin,shapiroisme/datadollar,TheoremCrypto/TheoremCoin,iQcoin/iQcoin,whatrye/twister-core,metrocoins/metrocoin,jambolo/bitcoin,hasanatkazmi/bitcoin,ghostlander/Testcoin,coinkeeper/2015-06-22_19-19_worldcoin,daeMOn63/Peershares,fsb4000/bitcoin,atgreen/bitcoin,hophacker/bitcoin_malleability,marlengit/BitcoinUnlimited,zcoinofficial/zcoin,llamasoft/ProtoShares_Cycle,pevernon/picoin,marlengit/hardfork_prototype_1_mvf-bu,mincoin-project/mincoin,nathan-at-least/zcash,dooglus/bitcoin,dgarage/bc3,rsdevgun16e/energi,manuel-zulian/CoMoNet,my-first/octocoin,genavarov/lamacoin,penek/novacoin,jnewbery/bitcoin,zemrys/vertcoin,ivansib/sib16,XertroV/bitcoin-nulldata,Flurbos/Flurbo,FarhanHaque/bitcoin,cdecker/bitcoin,SocialCryptoCoin/SocialCoin,FuzzyBearBTC/Peerunity,HerkCoin/herkcoin,ardsu/bitcoin,jeromewu/bitcoin-opennet,plankton12345/litecoin,Kogser/bitcoin,Kore-Core/kore,jonghyeopkim/bitcoinxt,jakeva/bitcoin-pwcheck,degenorate/Deftcoin,aburan28/elements,grumpydevelop/singularity,HerkCoin/herkcoin,svcop3/svcop3,kleetus/bitcoinxt,cainca/liliucoin,MitchellMintCoins/AutoCoin,digibyte/digibyte,lordsajan/erupee,ingresscoin/ingresscoin,patricklodder/dogecoin,koharjidan/dogecoin,DMDcoin/Diamond,KaSt/equikoin,KibiCoin/kibicoin,accraze/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,MasterX1582/bitcoin-becoin,SmeltFool/Wonker,RyanLucchese/energi,LanaCoin/lanacoin,MoMoneyMonetarism/ppcoin,putinclassic/putic,bfroemel/smallchange,WorldLeadCurrency/WLC,1185/starwels,supcoin/supcoin,starwalkerz/fincoin-fork,mikehearn/bitcoinxt,nbenoit/bitcoin,kaostao/bitcoin,schildbach/bitcoin,biblepay/biblepay,KillerByte/memorypool,oleganza/bitcoin-duo,morcos/bitcoin,slingcoin/sling-market,CryptArc/bitcoin,jn2840/bitcoin,gmaxwell/bitcoin,IOCoin/iocoin,nbenoit/bitcoin,vectorcoindev/Vector,penek/novacoin,anditto/bitcoin,simonmulser/bitcoin,Credit-Currency/CoinTestComp,Rav3nPL/bitcoin,BigBlueCeiling/augmentacoin,markf78/dollarcoin,oklink-dev/bitcoin_block,Crowndev/crowncoin,nanocoins/mycoin,h4x3rotab/BTCGPU,reddink/reddcoin,applecoin-official/applecoin,ahmedbodi/vertcoin,WorldcoinGlobal/WorldcoinLegacy,Metronotes/bitcoin,Petr-Economissa/gvidon,111t8e/bitcoin,coinkeeper/2015-06-22_18-30_anoncoin,MidasPaymentLTD/midascoin,vectorcoindev/Vector,Action-Committee/Spaceballz,unsystemizer/bitcoin,bitbrazilcoin-project/bitbrazilcoin,WorldcoinGlobal/WorldcoinLegacy,bitcoinxt/bitcoinxt,appop/bitcoin,CoinProjects/AmsterdamCoin-v4,pinheadmz/bitcoin,particl/particl-core,svost/bitcoin,basicincome/unpcoin-core,Jeff88Ho/bitcoin,Czarcoin/czarcoin,OfficialTitcoin/titcoin-wallet,coinkeeper/2015-06-22_18-42_litecoin,marlengit/BitcoinUnlimited,thunderrabbit/clams,dexX7/bitcoin,metrocoins/metrocoin,tdudz/elements,keo/bitcoin,ceptacle/libcoinqt,pdrobek/Polcoin-1-3,lbrtcoin/albertcoin,jiangyonghang/bitcoin,guncoin/guncoin,uphold/bitcoin,Cocosoft/bitcoin,czr5014iph/bitcoin4e,meighti/bitcoin,oklink-dev/bitcoin,steakknife/bitcoin-qt,nbenoit/bitcoin,cdecker/bitcoin,lateminer/bitcoin,DMDcoin/Diamond,AquariusNetwork/ARCO,monacoinproject/monacoin,royosherove/bitcoinxt,omefire/bitcoin,llluiop/bitcoin,isle2983/bitcoin,wiggi/fairbrix-0.6.3,domob1812/i0coin,tropa/axecoin,jrmithdobbs/bitcoin,DGCDev/argentum,botland/bitcoin,accraze/bitcoin,shapiroisme/datadollar,collapsedev/circlecash,xeddmc/twister-core,riecoin/riecoin,brishtiteveja/sherlockholmescoin,mapineda/litecoin,DGCDev/digitalcoin,WorldLeadCurrency/WLC,pstratem/elements,redfish64/nomiccoin,daliwangi/bitcoin,tjth/lotterycoin,kallewoof/bitcoin,valorbit/valorbit,NateBrune/bitcoin-nate,neureal/noocoin,GreenParhelia/bitcoin,bankonmecoin/bitcoin,ColossusCoinXT/ColossusCoinXT,Litecoindark/LTCD,xieta/mincoin,ShwoognationHQ/bitcoin,akabmikua/flowcoin,litecoin-project/litecore-litecoin,benma/bitcoin,phelix/namecore,r8921039/bitcoin,1185/starwels,dpayne9000/Rubixz-Coin,dev1972/Satellitecoin,CoinBlack/bitcoin,dan-mi-sun/bitcoin,putinclassic/putic,crowning2/dash,Kenwhite23/litecoin,elecoin/elecoin,howardrya/AcademicCoin,pstratem/elements,peercoin/peercoin,MonetaryUnit/MUE-Src,tedlz123/Bitcoin,ahmedbodi/bytecoin,Jeff88Ho/bitcoin,cyrixhero/bitcoin,goku1997/bitcoin,coinkeeper/terracoin_20150327,KaSt/ekwicoin,fanquake/bitcoin,Earlz/renamedcoin,daliwangi/bitcoin,Justaphf/BitcoinUnlimited,rustyrussell/bitcoin,deeponion/deeponion,SandyCohen/mincoin,shaolinfry/litecoin,coinkeeper/2015-06-22_18-31_bitcoin,Rimbit/Wallets,collapsedev/circlecash,dev1972/Satellitecoin,grumpydevelop/singularity,accraze/bitcoin,rromanchuk/bitcoinxt,tecnovert/particl-core,ionomy/ion,jmgilbert2/energi,coinwarp/dogecoin,Bitcoin-com/BUcash,CryptArc/bitcoinxt,pstratem/bitcoin,MitchellMintCoins/AutoCoin,coinkeeper/2015-06-22_19-00_ziftrcoin,UdjinM6/dash,daeMOn63/Peershares,altcoinpro/addacoin,MarcoFalke/bitcoin,Chancoin-core/CHANCOIN,ShadowMyst/creativechain-core,afk11/bitcoin,globaltoken/globaltoken,Chancoin-core/CHANCOIN,KaSt/ekwicoin,kallewoof/elements,21E14/bitcoin,achow101/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,CoinGame/BCEShadow,namecoin/namecore,48thct2jtnf/P,ekankyesme/bitcoinxt,segwit/atbcoin-insight,BitcoinPOW/BitcoinPOW,odemolliens/bitcoinxt,novaexchange/EAC,GwangJin/gwangmoney-core,coinkeeper/megacoin_20150410_fixes,wangxinxi/litecoin,rnicoll/bitcoin,jimblasko/UnbreakableCoin-master,bitshares/bitshares-pts,ychaim/smallchange,scmorse/bitcoin,nlgcoin/guldencoin-official,trippysalmon/bitcoin,AllanDoensen/BitcoinUnlimited,saydulk/Feathercoin,ajweiss/bitcoin,atgreen/bitcoin,prusnak/bitcoin,goku1997/bitcoin,Kefkius/clams,npccoin/npccoin,ahmedbodi/vertcoin,sifcoin/sifcoin,digideskio/namecoin,wiggi/huntercore,mikehearn/bitcoin,FuzzyBearBTC/Peerunity,tmagik/catcoin,aburan28/elements,byncoin-project/byncoin,unsystemizer/bitcoin,torresalyssa/bitcoin,haobtc/bitcoin,collapsedev/cashwatt,hg5fm/nexuscoin,FuzzyBearBTC/Fuzzyshares,collapsedev/cashwatt,penek/novacoin,madman5844/poundkoin,error10/bitcoin,vertcoin/vertcoin,masterbraz/dg,coinkeeper/2015-06-22_19-07_digitalcoin,omefire/bitcoin,coinkeeper/2015-06-22_18-41_ixcoin,reddink/reddcoin,ddombrowsky/radioshares,Earlz/dobbscoin-source,FrictionlessCoin/iXcoin,arruah/ensocoin,MonetaryUnit/MUE-Src,5mil/Bolt,imharrywu/fastcoin,borgcoin/Borgcoin1,fujicoin/fujicoin,wiggi/huntercore,adpg211/bitcoin-master,slingcoin/sling-market,Dajackal/Ronpaulcoin,bitcoinplusorg/xbcwalletsource,starwels/starwels,reorder/viacoin,kryptokredyt/ProjektZespolowyCoin,Flurbos/Flurbo,Peer3/homework,KillerByte/memorypool,Richcoin-Project/RichCoin,domob1812/crowncoin,r8921039/bitcoin,MasterX1582/bitcoin-becoin,safecoin/safecoin,millennial83/bitcoin,ShadowMyst/creativechain-core,raasakh/bardcoin,rdqw/sscoin,laanwj/bitcoin-qt,MeshCollider/bitcoin,Diapolo/bitcoin,nanocoins/mycoin,domob1812/bitcoin,irvingruan/bitcoin,Earlz/renamedcoin,alexwaters/Bitcoin-Testing,shaolinfry/litecoin,bespike/litecoin,micryon/GPUcoin,ahmedbodi/bytecoin,gjhiggins/vcoin09,multicoins/marycoin,cryptohelper/premine,iadix/iadixcoin,coinkeeper/2015-06-22_18-31_bitcoin,millennial83/bitcoin,jn2840/bitcoin,axelxod/braincoin,diggcoin/diggcoin,Alex-van-der-Peet/bitcoin,Friedbaumer/litecoin,ahmedbodi/terracoin,gameunits/gameunits,mikehearn/bitcoin,ingresscoin/ingresscoin,ryanofsky/bitcoin,mitchellcash/bitcoin,enlighter/Feathercoin,janko33bd/bitcoin,deuscoin/deuscoin,nikkitan/bitcoin,fussl/elements,hg5fm/nexuscoin,martindale/elements,habibmasuro/bitcoinxt,schildbach/bitcoin,antcheck/antcoin,sipa/elements,zestcoin/ZESTCOIN,s-matthew-english/bitcoin,wastholm/bitcoin,sbaks0820/bitcoin,ionux/freicoin,simdeveloper/bitcoin,elcrypto/Pulse,BTCTaras/bitcoin,greenaddress/bitcoin,zzkt/solarcoin,alecalve/bitcoin,dev1972/Satellitecoin,adpg211/bitcoin-master,ripper234/bitcoin,supcoin/supcoin,multicoins/marycoin,svost/bitcoin,worldbit/worldbit,achow101/bitcoin,acid1789/bitcoin,marlengit/BitcoinUnlimited,tobeyrowe/smallchange,ajtowns/bitcoin,rustyrussell/bitcoin,jrick/bitcoin,dperel/bitcoin,ashleyholman/bitcoin,koharjidan/bitcoin,sdaftuar/bitcoin,prark/bitcoinxt,torresalyssa/bitcoin,barcoin-project/nothingcoin,phplaboratory/psiacoin,tobeyrowe/BitStarCoin,stamhe/litecoin,Megacoin2/Megacoin,internaut-me/ppcoin,jimmysong/bitcoin,marcusdiaz/BitcoinUnlimited,ghostlander/Orbitcoin,sebrandon1/bitcoin,atgreen/bitcoin,coinwarp/dogecoin,andres-root/bitcoinxt,DSPay/DSPay,vtafaucet/virtacoin,domob1812/huntercore,wcwu/bitcoin,bcpki/nonce2testblocks,Exgibichi/statusquo,truthcoin/blocksize-market,erikYX/yxcoin-FIRST,IOCoin/iocoin,mm-s/bitcoin,cryptcoins/cryptcoin,zetacoin/zetacoin,Bushstar/UFO-Project,ajweiss/bitcoin,Flurbos/Flurbo,litecoin-project/bitcoinomg,BTCTaras/bitcoin,mrbandrews/bitcoin,ShwoognationHQ/bitcoin,ajtowns/bitcoin,achow101/bitcoin,irvingruan/bitcoin,pinheadmz/bitcoin,memorycoin/memorycoin,xeddmc/twister-core,gzuser01/zetacoin-bitcoin,redfish64/nomiccoin,ediston/energi,BTCfork/hardfork_prototype_1_mvf-bu,internaut-me/ppcoin,roques/bitcoin,s-matthew-english/bitcoin,gjhiggins/fuguecoin,keesdewit82/LasVegasCoin,Peer3/homework,vertcoin/eyeglass,Theshadow4all/ShadowCoin,Darknet-Crypto/Darknet,cyrixhero/bitcoin,micryon/GPUcoin,joshrabinowitz/bitcoin,FinalHashLLC/namecore,mincoin-project/mincoin,denverl/bitcoin,SandyCohen/mincoin,sarielsaz/sarielsaz,bitcoinsSG/zcash,jn2840/bitcoin,ghostlander/Testcoin,dagurval/bitcoinxt,Tetcoin/tetcoin,shouhuas/bitcoin,XX-net/twister-core,48thct2jtnf/P,brishtiteveja/sherlockholmescoin,zestcoin/ZESTCOIN,TeamBitBean/bitcoin-core,deeponion/deeponion,gandrewstone/BitcoinUnlimited,nathaniel-mahieu/bitcoin,donaloconnor/bitcoin,dannyperez/bolivarcoin,GroestlCoin/GroestlCoin,coinkeeper/anoncoin_20150330_fixes,donaloconnor/bitcoin,royosherove/bitcoinxt,SmeltFool/Yippe-Hippe,Climbee/artcoin,bitshares/bitshares-pts,and2099/twister-core,unsystemizer/bitcoin,manuel-zulian/accumunet,segsignal/bitcoin,awemany/BitcoinUnlimited,BitzenyCoreDevelopers/bitzeny,sdaftuar/bitcoin,FarhanHaque/bitcoin,lateminer/DopeCoinGold,IOCoin/DIONS,nomnombtc/bitcoin,Twyford/Indigo,erqan/twister-core,jakeva/bitcoin-pwcheck,jeromewu/bitcoin-opennet,novaexchange/EAC,lbryio/lbrycrd,sbellem/bitcoin,tripmode/pxlcoin,REAP720801/bitcoin,bespike/litecoin,inutoshi/inutoshi,itmanagerro/tresting,monacoinproject/monacoin,tatafiore/mycoin,IlfirinIlfirin/shavercoin,kleetus/bitcoin,nathaniel-mahieu/bitcoin,tjps/bitcoin,spiritlinxl/BTCGPU,appop/bitcoin,ardsu/bitcoin,ShwoognationHQ/bitcoin,tuaris/bitcoin,svost/bitcoin,loxal/zcash,KnCMiner/bitcoin,EntropyFactory/creativechain-core,dgenr8/bitcoin,BitcoinPOW/BitcoinPOW,particl/particl-core,elecoin/elecoin,joulecoin/joulecoin,Ziftr/bitcoin,totallylegitbiz/totallylegitcoin,destenson/bitcoin--bitcoin,coinkeeper/2015-06-22_18-52_viacoin,Cloudsy/bitcoin,iadix/iadixcoin,Exceltior/dogecoin,ccoin-project/ccoin,OstlerDev/florincoin,yacoin/yacoin,ravenbyron/phtevencoin,Exgibichi/statusquo,killerstorm/bitcoin,GIJensen/bitcoin,OmniLayer/omnicore,FeatherCoin/Feathercoin,iosdevzone/bitcoin,magacoin/magacoin,tmagik/catcoin,JeremyRand/bitcoin,etercoin/etercoin,Horrorcoin/horrorcoin,midnightmagic/bitcoin,deadalnix/bitcoin,Open-Source-Coins/EZ,Theshadow4all/ShadowCoin,wederw/bitcoin,cculianu/bitcoin-abc,iceinsidefire/peershare-edit,fanquake/bitcoin,Bloom-Project/Bloom,dogecoin/dogecoin,MoMoneyMonetarism/ppcoin,mikehearn/bitcoinxt,dexX7/mastercore,Earlz/dobbscoin-source,Cocosoft/bitcoin,DigitalPandacoin/pandacoin,howardrya/AcademicCoin,ElementsProject/elements,vmp32k/litecoin,elliotolds/bitcoin,arnuschky/bitcoin,syscoin/syscoin2,hyperwang/bitcoin,bitcoin-hivemind/hivemind,killerstorm/bitcoin,wangxinxi/litecoin,coinkeeper/2015-06-22_18-52_viacoin,XX-net/twister-core,keesdewit82/LasVegasCoin,matlongsi/micropay,sickpig/BitcoinUnlimited,schinzelh/dash,xieta/mincoin,sbellem/bitcoin,Dinarcoin/dinarcoin,Climbee/artcoin,majestrate/twister-core,zixan/bitcoin,cryptcoins/cryptcoin,vlajos/bitcoin,richo/dongcoin,mruddy/bitcoin,bootycoin-project/bootycoin,111t8e/bitcoin,jtimon/elements,instagibbs/bitcoin,netswift/vertcoin,bcpki/nonce2testblocks,dan-mi-sun/bitcoin,MitchellMintCoins/MortgageCoin,VsyncCrypto/Vsync,dooglus/clams,Adaryian/E-Currency,scippio/bitcoin,BTCGPU/BTCGPU,jarymoth/dogecoin,nvmd/bitcoin,AquariusNetwork/ARCO,erikYX/yxcoin-FIRST,etercoin/etercoin,blackcoinhelp/blackcoin,CrimeaCoin/crimeacoin,elliotolds/bitcoin,jmgilbert2/energi,ahmedbodi/temp_vert,MazaCoin/mazacoin-new,Action-Committee/Spaceballz,BitzenyCoreDevelopers/bitzeny,yacoin/yacoin,bitcoin/bitcoin,jonasnick/bitcoin,Kore-Core/kore,elambert2014/novacoin,llluiop/bitcoin,itmanagerro/tresting,ColossusCoinXT/ColossusCoinXT,my-first/octocoin,Ziftr/ppcoin,vcoin-project/vcoin0.8zeta-dev,VsyncCrypto/Vsync,Vector2000/bitcoin,jameshilliard/bitcoin,vlajos/bitcoin,JeremyRubin/bitcoin,HashUnlimited/Einsteinium-Unlimited,instagibbs/bitcoin,vcoin-project/vcoin0.8zeta-dev,credits-currency/credits,dscotese/bitcoin,gwillen/elements,gavinandresen/bitcoin-git,djpnewton/bitcoin,Exgibichi/statusquo,Magicking/neucoin,markf78/dollarcoin,brightcoin/brightcoin,amaivsimau/bitcoin,qtumproject/qtum,habibmasuro/bitcoin,svost/bitcoin,p2peace/oliver-twister-core,neureal/noocoin,joshrabinowitz/bitcoin,lateminer/bitcoin,truthcoin/truthcoin-cpp,dpayne9000/Rubixz-Coin,TeamBitBean/bitcoin-core,jl2012/litecoin,jimmysong/bitcoin,bcpki/testblocks,48thct2jtnf/P,mastercoin-MSC/mastercore,ALEXIUMCOIN/alexium,biblepay/biblepay,BitcoinHardfork/bitcoin,SproutsEx/SproutsExtreme,romanornr/viacoin,willwray/dash,Vector2000/bitcoin,plncoin/PLNcoin_Core,iQcoin/iQcoin,mikehearn/bitcoinxt,XertroV/bitcoin-nulldata,p2peace/oliver-twister-core,bitcoin/bitcoin,qreatora/worldcoin-v0.8,core-bitcoin/bitcoin,ptschip/bitcoin,NunoEdgarGub1/elements,megacoin/megacoin,ftrader-bitcoinabc/bitcoin-abc,shaulkf/bitcoin,bcpki/bitcoin,Twyford/Indigo,Kangmo/bitcoin,blocktrail/bitcoin,40thoughts/Coin-QualCoin,coinkeeper/2015-04-19_21-20_litecoindark,cotner/bitcoin,Checkcoin/checkcoin,zotherstupidguy/bitcoin,Litecoindark/LTCD,ludbb/bitcoin,midnight-miner/LasVegasCoin,FarhanHaque/bitcoin,afk11/bitcoin,llamasoft/ProtoShares_Cycle,FrictionlessCoin/iXcoin,ahmedbodi/temp_vert,ceptacle/libcoinqt,MoMoneyMonetarism/ppcoin,fujicoin/fujicoin,Har01d/bitcoin,OstlerDev/florincoin,Rav3nPL/bitcoin,Electronic-Gulden-Foundation/egulden,okinc/litecoin,funkshelper/woodcoin-b,coinkeeper/megacoin_20150410_fixes,martindale/elements,capitalDIGI/litecoin,marcusdiaz/BitcoinUnlimited,bitcoinxt/bitcoinxt,petertodd/bitcoin,Michagogo/bitcoin,Horrorcoin/horrorcoin,presstab/PIVX,karek314/bitcoin,bootycoin-project/bootycoin,btc1/bitcoin,GroestlCoin/GroestlCoin,DSPay/DSPay,bitbrazilcoin-project/bitbrazilcoin,dobbscoin/dobbscoin-source,bitgoldcoin-project/bitgoldcoin,bootycoin-project/bootycoin,coinkeeper/2015-06-22_18-46_razor,DGCDev/argentum,xXDavasXx/Davascoin,aspanta/bitcoin,Theshadow4all/ShadowCoin,pevernon/picoin,jul2711/jucoin,Infernoman/crowncoin,Bluejudy/worldcoin,5mil/SuperTurboStake,ohac/sha1coin,marscoin/marscoin,bcpki/bitcoin,gcc64/bitcoin,chrisfranko/aiden,kigooz/smalltestnew,NateBrune/bitcoin-fio,greencoin-dev/greencoin-dev,GeekBrony/ponycoin-old,ctwiz/stardust,domob1812/namecore,shomeser/bitcoin,CoinProjects/AmsterdamCoin-v4,altcoinpro/addacoin,TheoremCrypto/TheoremCoin,habibmasuro/bitcoin,GroundRod/anoncoin,tensaix2j/bananacoin,midnight-miner/LasVegasCoin,ionomy/ion,and2099/twister-core,nigeriacoin/nigeriacoin,joroob/reddcoin,cainca/liliucoin,octocoin-project/octocoin,lateminer/DopeCoinGold,bitcoinsSG/zcash,nlgcoin/guldencoin-official,anditto/bitcoin,Christewart/bitcoin,Ziftr/bitcoin,vcoin-project/vcoincore,zsulocal/bitcoin,forrestv/bitcoin,deuscoin/deuscoin,peerdb/cors,SmeltFool/Wonker,royosherove/bitcoinxt,Mrs-X/PIVX,schinzelh/dash,IlfirinIlfirin/shavercoin,blood2/bloodcoin-0.9,Rav3nPL/doubloons-0.10,FarhanHaque/bitcoin,and2099/twister-core,erikYX/yxcoin-FIRST,lentza/SuperTurboStake,neuroidss/bitcoin,coinkeeper/2015-06-22_18-56_megacoin,x-kalux/bitcoin_WiG-B,meighti/bitcoin,GroundRod/anoncoin,daliwangi/bitcoin,Earlz/dobbscoin-source,jonasnick/bitcoin,Xekyo/bitcoin,zcoinofficial/zcoin,21E14/bitcoin,zander/bitcoinclassic,SocialCryptoCoin/SocialCoin,Thracky/monkeycoin,borgcoin/Borgcoin1,tobeyrowe/KitoniaCoin,nightlydash/darkcoin,Cancercoin/Cancercoin,Darknet-Crypto/Darknet,ppcoin/ppcoin,ixcoinofficialpage/master,kaostao/bitcoin,Cocosoft/bitcoin,fsb4000/bitcoin,Peer3/homework,torresalyssa/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,destenson/bitcoin--bitcoin,bittylicious/bitcoin,krzysztofwos/BitcoinUnlimited,byncoin-project/byncoin,rat4/blackcoin,elambert2014/novacoin,LanaCoin/lanacoin,shadowoneau/ozcoin,OmniLayer/omnicore,odemolliens/bitcoinxt,Rav3nPL/PLNcoin,PIVX-Project/PIVX,XX-net/twister-core,isghe/bitcoinxt,funbucks/notbitcoinxt,oklink-dev/litecoin_block,DGCDev/argentum,djtms/ltc,brandonrobertz/namecoin-core,shea256/bitcoin,gjhiggins/vcoin0.8zeta-dev,lbrtcoin/albertcoin,ryanxcharles/bitcoin,IlfirinCano/shavercoin,midnight-miner/LasVegasCoin,Kogser/bitcoin,jamesob/bitcoin,koltcoin/koltcoin,NeuCoin/neucoin,dagurval/bitcoinxt,ForceMajeure/BitPenny-Client,lateminer/bitcoin,EntropyFactory/creativechain-core,vertcoin/eyeglass,isghe/bitcoinxt,bankonmecoin/bitcoin,elambert2014/novacoin,GlobalBoost/GlobalBoost,FrictionlessCoin/iXcoin,terracoin/terracoin,Dinarcoin/dinarcoin,vericoin/vericoin-core,bankonmecoin/bitcoin,arruah/ensocoin,Stakemaker/OMFGcoin,droark/elements,dperel/bitcoin,senadmd/coinmarketwatch,laudaa/bitcoin,earonesty/bitcoin,maraoz/proofcoin,mapineda/litecoin,Michagogo/bitcoin,mortalvikinglive/bitcoinclassic,zebrains/Blotter,zixan/bitcoin,h4x3rotab/BTCGPU,pelorusjack/BlockDX,wangliu/bitcoin,gjhiggins/vcoin0.8zeta-dev,manuel-zulian/accumunet,robvanbentem/bitcoin,cheehieu/bitcoin,reddcoin-project/reddcoin,deeponion/deeponion,robvanbentem/bitcoin,cannabiscoindev/cannabiscoin420,mitchellcash/bitcoin,Jcing95/iop-hd,kbccoin/kbc,koharjidan/dogecoin,zetacoin/zetacoin,coinwarp/dogecoin,vbernabe/freicoin,phelix/bitcoin,spiritlinxl/BTCGPU,memorycoin/memorycoin,sbellem/bitcoin,iadix/iadixcoin,ALEXIUMCOIN/alexium,zixan/bitcoin,VsyncCrypto/Vsync,mincoin-project/mincoin,Bloom-Project/Bloom,MeshCollider/bitcoin,dev1972/Satellitecoin,zottejos/merelcoin,cqtenq/feathercoin_core,bcpki/nonce2,hasanatkazmi/bitcoin,simdeveloper/bitcoin,peacedevelop/peacecoin,ppcoin/ppcoin,joulecoin/joulecoin,nmarley/dash,Justaphf/BitcoinUnlimited,bitcoin/bitcoin,KibiCoin/kibicoin,SocialCryptoCoin/SocialCoin,OstlerDev/florincoin,miguelfreitas/twister-core,gavinandresen/bitcoin-git,Thracky/monkeycoin,world-bank/unpay-core,thelazier/dash,diggcoin/diggcoin,phelix/bitcoin,cybermatatu/bitcoin,shaulkf/bitcoin,Peerapps/ppcoin,joshrabinowitz/bitcoin,ingresscoin/ingresscoin,Kenwhite23/litecoin,jlopp/statoshi,scamcoinz/scamcoin,Justaphf/BitcoinUnlimited,Friedbaumer/litecoin,Kogser/bitcoin,BigBlueCeiling/augmentacoin,RibbitFROG/ribbitcoin,goldcoin/goldcoin,cinnamoncoin/groupcoin-1,KibiCoin/kibicoin,manuel-zulian/accumunet,bitcoin/bitcoin,pstratem/bitcoin,freelion93/mtucicoin,dgarage/bc3,vertcoin/eyeglass,Someguy123/novafoil,Exceltior/dogecoin,javgh/bitcoin,scmorse/bitcoin,ohac/sakuracoin,FuzzyBearBTC/Fuzzyshares,aspirecoin/aspire,Thracky/monkeycoin,capitalDIGI/DIGI-v-0-10-4,guncoin/guncoin,brandonrobertz/namecoin-core,Exgibichi/statusquo,GroestlCoin/bitcoin,jimblasko/UnbreakableCoin-master,Krellan/bitcoin,Kenwhite23/litecoin,Krellan/bitcoin,CryptArc/bitcoin,coinkeeper/2015-06-22_18-56_megacoin,denverl/bitcoin,ahmedbodi/temp_vert,NicolasDorier/bitcoin,aspirecoin/aspire,gandrewstone/bitcoinxt,NeuCoin/neucoin,KaSt/equikoin,nomnombtc/bitcoin,wekuiz/wekoin,worldcoinproject/worldcoin-v0.8,fullcoins/fullcoin,KaSt/ekwicoin,litecoin-project/litecoin,viacoin/viacoin,stronghands/stronghands,blood2/bloodcoin-0.9,paveljanik/bitcoin,lbrtcoin/albertcoin,Kogser/bitcoin,IOCoin/DIONS,BTCDDev/bitcoin,cerebrus29301/crowncoin,Kogser/bitcoin,okinc/litecoin,Kcoin-project/kcoin,reddink/reddcoin,jaromil/faircoin2,sickpig/BitcoinUnlimited,segwit/atbcoin-insight,united-scrypt-coin-project/unitedscryptcoin,aburan28/elements,bitjson/hivemind,jlcurby/NobleCoin,Peerapps/ppcoin,ZiftrCOIN/ziftrcoin,jmcorgan/bitcoin,KaSt/ekwicoin,haisee/dogecoin,Mrs-X/PIVX,acid1789/bitcoin,reddink/reddcoin,Kore-Core/kore,SartoNess/BitcoinUnlimited,48thct2jtnf/P,degenorate/Deftcoin,Adaryian/E-Currency,metacoin/florincoin,pastday/bitcoinproject,axelxod/braincoin,MazaCoin/mazacoin-new,goku1997/bitcoin,nanocoins/mycoin,daliwangi/bitcoin,coinkeeper/2015-06-22_19-19_worldcoin,BTCTaras/bitcoin,renatolage/wallets-BRCoin,richo/dongcoin,xieta/mincoin,TrainMAnB/vcoincore,dscotese/bitcoin,MazaCoin/maza,mastercoin-MSC/mastercore,apoelstra/elements,earonesty/bitcoin,earthcoinproject/earthcoin,GreenParhelia/bitcoin,kleetus/bitcoin,prusnak/bitcoin,BlueMeanie/PeerShares,BTCfork/hardfork_prototype_1_mvf-bu,taenaive/zetacoin,myriadcoin/myriadcoin,sugruedes/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,Peerunity/Peerunity,Cancercoin/Cancercoin,sproutcoin/sprouts,SartoNess/BitcoinUnlimited,ftrader-bitcoinabc/bitcoin-abc,bcpki/nonce2,brettwittam/geocoin,HeliumGas/helium,Ziftr/litecoin,josephbisch/namecoin-core,jarymoth/dogecoin,tjps/bitcoin,howardrya/AcademicCoin,constantine001/bitcoin,inutoshi/inutoshi,gazbert/bitcoin,jrick/bitcoin,Krellan/bitcoin,Alonzo-Coeus/bitcoin,gorgoy/novacoin,tobeyrowe/smallchange,morcos/bitcoin,bitcoinxt/bitcoinxt,sbellem/bitcoin,MitchellMintCoins/MortgageCoin,nightlydash/darkcoin,mrtexaznl/mediterraneancoin,vbernabe/freicoin,MitchellMintCoins/MortgageCoin,VsyncCrypto/Vsync,sirk390/bitcoin,pastday/bitcoinproject,laudaa/bitcoin,upgradeadvice/MUE-Src,lentza/SuperTurboStake,uphold/bitcoin,kleetus/bitcoin,RongxinZhang/bitcoinxt,mm-s/bitcoin,haraldh/bitcoin,CTRoundTable/Encrypted.Cash,ForceMajeure/BitPenny-Client-0.4.0.1,AllanDoensen/BitcoinUnlimited,mooncoin-project/mooncoin-landann,stamhe/novacoin,marlengit/hardfork_prototype_1_mvf-bu,haraldh/bitcoin,goldcoin/goldcoin,hyperwang/bitcoin,world-bank/unpay-core,Vsync-project/Vsync,domob1812/i0coin,Xekyo/bitcoin,ivansib/sib16,rnicoll/bitcoin,brettwittam/geocoin,mmpool/coiledcoin,Metronotes/bitcoin,h4x3rotab/BTCGPU,themusicgod1/bitcoin,etercoin/etercoin,ionomy/ion,namecoin/namecore,totallylegitbiz/totallylegitcoin,CrimeaCoin/crimeacoin,Litecoindark/LTCD,bitcoinec/bitcoinec,imton/bitcoin,themusicgod1/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,marklai9999/Taiwancoin,Lucky7Studio/bitcoin,javgh/bitcoin,kevin-cantwell/crunchcoin,bitjson/hivemind,dooglus/clams,loxal/zcash,r8921039/bitcoin,d5000/ppcoin,phelixbtc/bitcoin,cryptoprojects/ultimateonlinecash,zenywallet/bitzeny,constantine001/bitcoin,manuel-zulian/CoMoNet,JeremyRand/bitcoin,ahmedbodi/test2,Kore-Core/kore,ychaim/smallchange,upgradeadvice/MUE-Src,zixan/bitcoin,ANCompany/birdcoin-dev,174high/bitcoin,MoMoneyMonetarism/ppcoin,FuzzyBearBTC/peercoin,pastday/bitcoinproject,petertodd/bitcoin,alecalve/bitcoin,gwillen/elements,argentumproject/argentum,fujicoin/fujicoin,credits-currency/credits,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,xuyangcn/opalcoin,akabmikua/flowcoin,ghostlander/Feathercoin,rawodb/bitcoin,experiencecoin/experiencecoin,vlajos/bitcoin,thrasher-/litecoin,dcousens/bitcoin,irvingruan/bitcoin,CTRoundTable/Encrypted.Cash,REAP720801/bitcoin,renatolage/wallets-BRCoin,ForceMajeure/BitPenny-Client,Petr-Economissa/gvidon,gfneto/Peershares,bitcoin-hivemind/hivemind,Rav3nPL/doubloons-0.10,mammix2/ccoin-dev,hsavit1/bitcoin,akabmikua/flowcoin,senadj/yacoin,rdqw/sscoin,cqtenq/Feathercoin,Rav3nPL/PLNcoin,manuel-zulian/CoMoNet,nailtaras/nailcoin,saydulk/Feathercoin,drwasho/bitcoinxt,KnCMiner/bitcoin,cyrixhero/bitcoin,riecoin/riecoin,coinkeeper/2015-06-22_18-51_vertcoin,awemany/BitcoinUnlimited,jmgilbert2/energi,BlueMeanie/PeerShares,Ziftr/litecoin,Christewart/bitcoin,bcpki/nonce2,biblepay/biblepay,reorder/viacoin,HeliumGas/helium,dooglus/clams,se3000/bitcoin,neutrinofoundation/neutrino-digital-currency,HerkCoin/herkcoin,KibiCoin/kibicoin,skaht/bitcoin,starwels/starwels,iosdevzone/bitcoin,steakknife/bitcoin-qt,barcoin-project/nothingcoin,bitcoinclassic/bitcoinclassic,AkioNak/bitcoin,bespike/litecoin,wederw/bitcoin,PIVX-Project/PIVX,roques/bitcoin,coinkeeper/2015-06-22_18-46_razor,jamesob/bitcoin,keisercoin-official/keisercoin,nanocoins/mycoin,som4paul/BolieC,slingcoin/sling-market,gandrewstone/BitcoinUnlimited,tripmode/pxlcoin,PRabahy/bitcoin,czr5014iph/bitcoin4e,Peerapps/ppcoin,dexX7/bitcoin,genavarov/brcoin,Sjors/bitcoin,AllanDoensen/BitcoinUnlimited,bitcoinxt/bitcoinxt,bitcoinsSG/bitcoin,keo/bitcoin,daeMOn63/Peershares,jambolo/bitcoin,Rav3nPL/PLNcoin,compasscoin/compasscoin,manuel-zulian/accumunet,elacoin/elacoin,tropa/axecoin,Mrs-X/Darknet,elambert2014/cbx2,litecoin-project/litecoin,p2peace/oliver-twister-core,Rav3nPL/PLNcoin,shadowoneau/ozcoin,gades/novacoin,EthanHeilman/bitcoin,zenywallet/bitzeny,nochowderforyou/clams,destenson/bitcoin--bitcoin,truthcoin/blocksize-market,hsavit1/bitcoin,CTRoundTable/Encrypted.Cash,kseistrup/twister-core,coinkeeper/2015-06-22_19-19_worldcoin,wastholm/bitcoin,applecoin-official/applecoin,SocialCryptoCoin/SocialCoin,kaostao/bitcoin,BigBlueCeiling/augmentacoin,thunderrabbit/clams,rebroad/bitcoin,Flurbos/Flurbo,blocktrail/bitcoin,anditto/bitcoin,antonio-fr/bitcoin,trippysalmon/bitcoin,psionin/smartcoin,bitreserve/bitcoin,Vsync-project/Vsync,Petr-Economissa/gvidon,AkioNak/bitcoin,richo/dongcoin,rat4/bitcoin,ericshawlinux/bitcoin,greencoin-dev/digitalcoin,xawksow/GroestlCoin,sproutcoin/sprouts,RongxinZhang/bitcoinxt,rawodb/bitcoin,thesoftwarejedi/bitcoin,crowning-/dash,nvmd/bitcoin,elambert2014/cbx2,razor-coin/razor,XertroV/bitcoin-nulldata,111t8e/bitcoin,schinzelh/dash,gameunits/gameunits,svcop3/svcop3,yacoin/yacoin,bankonmecoin/bitcoin,lordsajan/erupee,pinkevich/dash,cinnamoncoin/groupcoin-1,ohac/sakuracoin,llluiop/bitcoin,hg5fm/nexuscoin,Bitcoin-com/BUcash,effectsToCause/vericoin,qtumproject/qtum,gwangjin2/gwangcoin-core,projectinterzone/ITZ,ANCompany/birdcoin-dev,jonasnick/bitcoin,elacoin/elacoin,ZiftrCOIN/ziftrcoin,Peerunity/Peerunity,viacoin/viacoin,namecoin/namecore,cerebrus29301/crowncoin,gades/novacoin,ElementsProject/elements,shadowoneau/ozcoin,tobeyrowe/smallchange,coinerd/krugercoin,genavarov/brcoin,shomeser/bitcoin,Infernoman/crowncoin,Dajackal/Ronpaulcoin,aciddude/Feathercoin,ivansib/sib16,deuscoin/deuscoin,ardsu/bitcoin,Bitcoinsulting/bitcoinxt,irvingruan/bitcoin,gjhiggins/fuguecoin,qreatora/worldcoin-v0.8,aciddude/Feathercoin,elacoin/elacoin,martindale/elements,jmgilbert2/energi,pevernon/picoin,som4paul/BolieC,BTCTaras/bitcoin,r8921039/bitcoin,ryanofsky/bitcoin,razor-coin/razor,bitgoldcoin-project/bitgoldcoin,compasscoin/compasscoin,jlay11/sharecoin,UdjinM6/dash,trippysalmon/bitcoin,haraldh/bitcoin,xawksow/GroestlCoin,cryptocoins4all/zcoin,Anfauglith/iop-hd,goku1997/bitcoin,domob1812/crowncoin,XX-net/twister-core,coinkeeper/2015-06-22_19-07_digitalcoin,Theshadow4all/ShadowCoin,Rav3nPL/bitcoin,ashleyholman/bitcoin,pdrobek/Polcoin-1-3,ptschip/bitcoin,MasterX1582/bitcoin-becoin,raasakh/bardcoin.exe,theuni/bitcoin,Electronic-Gulden-Foundation/egulden,Kabei/Ippan,untrustbank/litecoin,cainca/liliucoin,NunoEdgarGub1/elements,jakeva/bitcoin-pwcheck,Bloom-Project/Bloom,zebrains/Blotter,d5000/ppcoin,ElementsProject/elements,Richcoin-Project/RichCoin,odemolliens/bitcoinxt,greencoin-dev/GreenCoinV2,sarielsaz/sarielsaz,byncoin-project/byncoin,Michagogo/bitcoin,laanwj/bitcoin-qt,domob1812/huntercore,nvmd/bitcoin,CoinProjects/AmsterdamCoin-v4,alecalve/bitcoin,cdecker/bitcoin,manuel-zulian/accumunet,elcrypto/Pulse,redfish64/nomiccoin,BitcoinUnlimited/BitcoinUnlimited,haraldh/bitcoin,AkioNak/bitcoin,coblee/litecoin-old,oleganza/bitcoin-duo,cqtenq/Feathercoin,Coinfigli/coinfigli,nailtaras/nailcoin,magacoin/magacoin,barcoin-project/nothingcoin,BTCDDev/bitcoin,daeMOn63/Peershares,cyrixhero/bitcoin,capitalDIGI/DIGI-v-0-10-4,elacoin/elacoin,enlighter/Feathercoin,Justaphf/BitcoinUnlimited,bitgrowchain/bitgrow,ericshawlinux/bitcoin,applecoin-official/fellatio,jashandeep-sohi/ppcoin,shaulkf/bitcoin,faircoin/faircoin,DogTagRecon/Still-Leraning,effectsToCause/vericoin,particl/particl-core,jakeva/bitcoin-pwcheck,Diapolo/bitcoin,tensaix2j/bananacoin,syscoin/syscoin2,vizidrixfork/Peershares,raasakh/bardcoin,midnight-miner/LasVegasCoin,xranby/blackcoin,pinheadmz/bitcoin,isle2983/bitcoin,PandaPayProject/PandaPay,Alex-van-der-Peet/bitcoin,litecoin-project/litecore-litecoin,bitcoinplusorg/xbcwalletsource,viacoin/viacoin,mortalvikinglive/bitcoinlight,fullcoins/fullcoin,rdqw/sscoin,millennial83/bitcoin,benzmuircroft/REWIRE.io,sdaftuar/bitcoin,Richcoin-Project/RichCoin,CryptArc/bitcoin,joulecoin/joulecoin,Charlesugwu/Vintagecoin,schildbach/bitcoin,ravenbyron/phtevencoin,NateBrune/bitcoin-nate,antcheck/antcoin,metrocoins/metrocoin,namecoin/namecore,omefire/bitcoin,likecoin-dev/bitcoin,CoinProjects/AmsterdamCoin-v4,Geekcoin-Project/Geekcoin,rjshaver/bitcoin,torresalyssa/bitcoin,cybermatatu/bitcoin,Adaryian/E-Currency,simdeveloper/bitcoin,coinkeeper/2015-06-22_18-45_peercoin,iadix/iadixcoin,dpayne9000/Rubixz-Coin,coinkeeper/2015-06-22_18-52_viacoin,biblepay/biblepay,Checkcoin/checkcoin,rsdevgun16e/energi,truthcoin/truthcoin-cpp,error10/bitcoin,Kixunil/keynescoin,puticcoin/putic,nigeriacoin/nigeriacoin,SproutsEx/SproutsExtreme,okcashpro/okcash,peacedevelop/peacecoin,ionux/freicoin,scmorse/bitcoin,jlay11/sharecoin,n1bor/bitcoin,ardsu/bitcoin,faircoin/faircoin2,fussl/elements,Rav3nPL/polcoin,lbrtcoin/albertcoin,ZiftrCOIN/ziftrcoin,janko33bd/bitcoin,jimmykiselak/lbrycrd,sebrandon1/bitcoin,jmcorgan/bitcoin,se3000/bitcoin,funkshelper/woodcoin-b,ryanofsky/bitcoin,Bitcoinsulting/bitcoinxt,benma/bitcoin,joulecoin/joulecoin,blackcoinhelp/blackcoin,GroestlCoin/bitcoin,som4paul/BolieC,cdecker/bitcoin,presstab/PIVX,ElementsProject/elements,40thoughts/Coin-QualCoin,schinzelh/dash,dperel/bitcoin,imharrywu/fastcoin,jonasnick/bitcoin,raasakh/bardcoin.exe,AdrianaDinca/bitcoin,Theshadow4all/ShadowCoin,zsulocal/bitcoin,bitchip/bitchip,robvanbentem/bitcoin,elliotolds/bitcoin,Kangmo/bitcoin,marklai9999/Taiwancoin,omefire/bitcoin,Sjors/bitcoin,wcwu/bitcoin,Rav3nPL/polcoin,dmrtsvetkov/flowercoin,Kcoin-project/kcoin,pocopoco/yacoin,wangxinxi/litecoin,gandrewstone/BitcoinUnlimited,xieta/mincoin,robvanmieghem/clams,Horrorcoin/horrorcoin,jlcurby/NobleCoin,lordsajan/erupee,brishtiteveja/sherlockcoin,ppcoin/ppcoin,shadowproject/shadow,ShadowMyst/creativechain-core,fsb4000/bitcoin,bankonmecoin/bitcoin,2XL/bitcoin,bitcoinsSG/zcash,cryptohelper/premine,btc1/bitcoin,lordsajan/erupee,goldmidas/goldmidas,droark/elements,genavarov/lamacoin,SartoNess/BitcoinUnlimited,mammix2/ccoin-dev,wastholm/bitcoin,denverl/bitcoin,wbchen99/bitcoin-hnote0,wtogami/bitcoin,compasscoin/compasscoin,KnCMiner/bitcoin,EntropyFactory/creativechain-core,nikkitan/bitcoin,bitcoin/bitcoin,experiencecoin/experiencecoin,wangliu/bitcoin,h4x3rotab/BTCGPU,Ziftr/bitcoin,alejandromgk/Lunar,IlfirinCano/shavercoin,mruddy/bitcoin,bickojima/bitzeny,coblee/litecoin-old,21E14/bitcoin,fsb4000/novacoin,ripper234/bitcoin,Peershares/Peershares,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,ixcoinofficialpage/master,sipa/bitcoin,Czarcoin/czarcoin,IOCoin/iocoin,bitreserve/bitcoin,trippysalmon/bitcoin,shelvenzhou/BTCGPU,dooglus/bitcoin,Checkcoin/checkcoin,martindale/elements,ArgonToken/ArgonToken,djtms/ltc,ctwiz/stardust,BlueMeanie/PeerShares,Whitecoin-org/Whitecoin,terracoin/terracoin,vizidrixfork/Peershares,BitcoinUnlimited/BitcoinUnlimited,JeremyRand/namecore,fanquake/bitcoin,bitcoinec/bitcoinec,borgcoin/Borgcoin1,cculianu/bitcoin-abc,Paymium/bitcoin,daveperkins-github/bitcoin-dev,jakeva/bitcoin-pwcheck,redfish64/nomiccoin,balajinandhu/bitcoin,Chancoin-core/CHANCOIN,CoinGame/BCEShadowNet,fussl/elements,Xekyo/bitcoin,nsacoin/nsacoin,bitcoin-hivemind/hivemind,ohac/sha1coin,reddcoin-project/reddcoin,haisee/dogecoin,Kabei/Ippan,BTCTaras/bitcoin,NicolasDorier/bitcoin,brishtiteveja/sherlockcoin,BeirdoMud/MudCoin,jimmykiselak/lbrycrd,stamhe/bitcoin,ryanxcharles/bitcoin,keo/bitcoin,pinkevich/dash,Paymium/bitcoin,BitzenyCoreDevelopers/bitzeny,mortalvikinglive/bitcoinlight,ForceMajeure/BitPenny-Client-0.4.0.1,zottejos/merelcoin,kallewoof/elements,appop/bitcoin,mockcoin/mockcoin,gjhiggins/vcoin09,dmrtsvetkov/flowercoin,memorycoin/memorycoin,maaku/bitcoin,brishtiteveja/truthcoin-cpp,jrick/bitcoin,valorbit/valorbit-oss,ediston/energi,elambert2014/cbx2,pastday/bitcoinproject,FuzzyBearBTC/Peershares-1,kfitzgerald/titcoin,bitpagar/bitpagar,mrtexaznl/mediterraneancoin,dcousens/bitcoin,greenaddress/bitcoin,grumpydevelop/singularity,JeremyRand/namecoin-core,REAP720801/bitcoin,goldcoin/Goldcoin-GLD,ptschip/bitcoinxt,NateBrune/bitcoin-fio,valorbit/valorbit-oss,creath/barcoin,phelixbtc/bitcoin,gravio-net/graviocoin,Ziftr/ppcoin,wbchen99/bitcoin-hnote0,PIVX-Project/PIVX,Bitcoin-ABC/bitcoin-abc,SoreGums/bitcoinxt,DigitalPandacoin/pandacoin,rat4/bitcoin,apoelstra/bitcoin,kazcw/bitcoin,scippio/bitcoin,sipa/elements,robvanmieghem/clams,senadj/yacoin,okcashpro/okcash,donaloconnor/bitcoin,mooncoin-project/mooncoin-landann,ticclassic/ic,Megacoin2/Megacoin,creath/barcoin,GwangJin/gwangmoney-core,experiencecoin/experiencecoin,Erkan-Yilmaz/twister-core,stamhe/novacoin,gjhiggins/vcoin0.8zeta-dev,zcoinofficial/zcoin,ShwoognationHQ/bitcoin,Enticed87/Decipher,ticclassic/ic,ahmedbodi/Bytecoin-MM,dgarage/bc2,privatecoin/privatecoin,domob1812/crowncoin,syscoin/syscoin2,bitcoinsSG/zcash,stamhe/bitcoin,gwillen/elements,fullcoins/fullcoin,ahmedbodi/terracoin,osuyuushi/laughingmancoin,coinkeeper/megacoin_20150410_fixes,gfneto/Peershares,jambolo/bitcoin,sirk390/bitcoin,sbaks0820/bitcoin,goldmidas/goldmidas,coinkeeper/2015-06-22_18-39_feathercoin,argentumproject/argentum,Peerapps/ppcoin,greencoin-dev/digitalcoin,goldcoin/Goldcoin-GLD,Jcing95/iop-hd,funbucks/notbitcoinxt,florincoin/florincoin,mammix2/ccoin-dev,5mil/Bolt,bcpki/testblocks,cqtenq/feathercoin_core,oklink-dev/bitcoin_block,d5000/ppcoin,landcoin-ldc/landcoin,Kogser/bitcoin,fedoracoin-dev/fedoracoin,miguelfreitas/twister-core,rromanchuk/bitcoinxt,thrasher-/litecoin,raasakh/bardcoin.exe,altcoinpro/addacoin,saydulk/Feathercoin,ivansib/sib16,AsteraCoin/AsteraCoin,ghostlander/Orbitcoin,Vsync-project/Vsync,kigooz/smalltestnew,ardsu/bitcoin,xeddmc/twister-core,inkvisit/sarmacoins,qubitcoin-project/QubitCoinQ2C,Cocosoft/bitcoin,segwit/atbcoin-insight,ryanxcharles/bitcoin,Bluejudy/worldcoin,maraoz/proofcoin,scmorse/bitcoin,jonasschnelli/bitcoin,dgarage/bc2,segwit/atbcoin-insight,greencoin-dev/digitalcoin,BitcoinHardfork/bitcoin,thormuller/yescoin2,rromanchuk/bitcoinxt,jrmithdobbs/bitcoin,Mirobit/bitcoin,hophacker/bitcoin_malleability,guncoin/guncoin,gandrewstone/bitcoinxt,ivansib/sibcoin,supcoin/supcoin,Mrs-X/Darknet,fullcoins/fullcoin,zetacoin/zetacoin,hasanatkazmi/bitcoin,applecoin-official/applecoin,MazaCoin/mazacoin-new,dannyperez/bolivarcoin,coinkeeper/2015-06-22_18-36_darkcoin,rawodb/bitcoin,Geekcoin-Project/Geekcoin,argentumproject/argentum,ahmedbodi/vertcoin,argentumproject/argentum,Ziftr/ppcoin,jonasschnelli/bitcoin,ForceMajeure/BitPenny-Client,pocopoco/yacoin,markf78/dollarcoin,XertroV/bitcoin-nulldata,prark/bitcoinxt,shelvenzhou/BTCGPU,IOCoin/iocoin,slimcoin-project/Slimcoin,multicoins/marycoin,gravio-net/graviocoin,AdrianaDinca/bitcoin,coinkeeper/2015-06-22_18-30_anoncoin,Cancercoin/Cancercoin,CryptArc/bitcoinxt,PandaPayProject/PandaPay,cryptohelper/premine,AllanDoensen/BitcoinUnlimited,bitpagar/bitpagar,jimblasko/2015_UNB_Wallets,GIJensen/bitcoin,Whitecoin-org/Whitecoin,Rav3nPL/bitcoin,IOCoin/DIONS,jeromewu/bitcoin-opennet,palm12341/jnc,Jcing95/iop-hd,bitcoinclassic/bitcoinclassic,TripleSpeeder/bitcoin,kryptokredyt/ProjektZespolowyCoin,sigmike/peercoin,rat4/bitcoin,11755033isaprimenumber/Feathercoin,cddjr/BitcoinUnlimited,ALEXIUMCOIN/alexium,donaloconnor/bitcoin,TBoehm/greedynode,wiggi/huntercore,particl/particl-core,digibyte/digibyte,domob1812/crowncoin,2XL/bitcoin,SoreGums/bitcoinxt,cryptohelper/premine,Bitcoin-ABC/bitcoin-abc,wangxinxi/litecoin,RazorLove/cloaked-octo-spice,gorgoy/novacoin,Flowdalic/bitcoin,som4paul/BolieC,iosdevzone/bitcoin,rjshaver/bitcoin,dashpay/dash,PRabahy/bitcoin,wangxinxi/litecoin,TurboStake/TurboStake,aspanta/bitcoin,deeponion/deeponion,brishtiteveja/truthcoin-cpp,welshjf/bitcoin,and2099/twister-core,tjth/lotterycoin,jlopp/statoshi,phorensic/yacoin,thormuller/yescoin2,cybermatatu/bitcoin,bdelzell/creditcoin-org-creditcoin,bitcoinclassic/bitcoinclassic,itmanagerro/tresting,yenliangl/bitcoin,LIMXTEC/DMDv3,bdelzell/creditcoin-org-creditcoin,senadmd/coinmarketwatch,ivansib/sibcoin,MOIN/moin,jl2012/litecoin,landcoin-ldc/landcoin,ghostlander/Testcoin,Kogser/bitcoin,andreaskern/bitcoin,Mirobit/bitcoin,okcashpro/okcash,ryanofsky/bitcoin,nbenoit/bitcoin,Gazer022/bitcoin,Cloudsy/bitcoin,Coinfigli/coinfigli,vbernabe/freicoin,glv2/peerunity,ftrader-bitcoinabc/bitcoin-abc,qtumproject/qtum,nigeriacoin/nigeriacoin,Jheguy2/Mercury,apoelstra/bitcoin,simonmulser/bitcoin,cryptodev35/icash,mammix2/ccoin-dev,Bitcoinsulting/bitcoinxt,rnicoll/bitcoin,zzkt/solarcoin,loxal/zcash,pinkmagicdev/SwagBucks,TurboStake/TurboStake,bitcoin-hivemind/hivemind,JeremyRand/bitcoin,ahmedbodi/terracoin,jnewbery/bitcoin,cinnamoncoin/Feathercoin,ShwoognationHQ/bitcoin,kirkalx/bitcoin,gjhiggins/vcoincore,plankton12345/litecoin,worldcoinproject/worldcoin-v0.8,pstratem/elements,bitreserve/bitcoin,ekankyesme/bitcoinxt,zottejos/merelcoin,cotner/bitcoin,Lucky7Studio/bitcoin,roques/bitcoin,BTCTaras/bitcoin,vcoin-project/vcoin0.8zeta-dev,putinclassic/putic,jtimon/bitcoin,ryanxcharles/bitcoin,isocolsky/bitcoinxt,patricklodder/dogecoin,jmcorgan/bitcoin,viacoin/viacoin,pstratem/bitcoin,bitshares/bitshares-pts,pataquets/namecoin-core,BitzenyCoreDevelopers/bitzeny,uphold/bitcoin,worldbit/worldbit,Sjors/bitcoin,stamhe/ppcoin,s-matthew-english/bitcoin,rat4/blackcoin,ekankyesme/bitcoinxt,goldmidas/goldmidas,bitcoinsSG/bitcoin,KillerByte/memorypool,kevcooper/bitcoin,valorbit/valorbit-oss,bitcoinclassic/bitcoinclassic,blackcoinhelp/blackcoin,wcwu/bitcoin,coinkeeper/2015-06-22_19-19_worldcoin,ahmedbodi/Bytecoin-MM,xurantju/bitcoin,syscoin/syscoin2,misdess/bitcoin,ericshawlinux/bitcoin,atgreen/bitcoin,MidasPaymentLTD/midascoin,dooglus/bitcoin,Kefkius/clams,tedlz123/Bitcoin,BitcoinHardfork/bitcoin,btcdrak/bitcoin,deadalnix/bitcoin,rjshaver/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,wbchen99/bitcoin-hnote0,osuyuushi/laughingmancoin,p2peace/oliver-twister-core,sugruedes/bitcoinxt,aciddude/Feathercoin,isocolsky/bitcoinxt,droark/elements,joroob/reddcoin,capitalDIGI/DIGI-v-0-10-4,DynamicCoinOrg/DMC,CrimeaCoin/crimeacoin,jimblasko/UnbreakableCoin-master,daveperkins-github/bitcoin-dev,vbernabe/freicoin,kseistrup/twister-core,TheoremCrypto/TheoremCoin,KaSt/equikoin,Litecoindark/LTCD,andres-root/bitcoinxt,hyperwang/bitcoin,pascalguru/florincoin,sproutcoin/sprouts,Bushstar/UFO-Project,untrustbank/litecoin,brishtiteveja/sherlockholmescoin,jlopp/statoshi,mb300sd/bitcoin,ripper234/bitcoin,GroundRod/anoncoin,dgenr8/bitcoin,nochowderforyou/clams,litecoin-project/litecore-litecoin,ahmedbodi/bytecoin,BitcoinUnlimited/BitcoinUnlimited,FuzzyBearBTC/Peershares,vertcoin/eyeglass,putinclassic/putic,alexwaters/Bitcoin-Testing,ShadowMyst/creativechain-core,UASF/bitcoin,bitchip/bitchip,gjhiggins/vcoin09,BeirdoMud/MudCoin,whatrye/twister-core,misdess/bitcoin,litecoin-project/litecoin,kirkalx/bitcoin,paveljanik/bitcoin,sstone/bitcoin,tobeyrowe/KitoniaCoin,vcoin-project/vcoin0.8zeta-dev,FuzzyBearBTC/Peershares-1,schildbach/bitcoin,tdudz/elements,constantine001/bitcoin,gwangjin2/gwangcoin-core,GIJensen/bitcoin,jaromil/faircoin2,tensaix2j/bananacoin,qubitcoin-project/QubitCoinQ2C,111t8e/bitcoin,bitgoldcoin-project/bitgoldcoin,dgarage/bc2,borgcoin/Borgcoin1,JeremyRand/bitcoin,instagibbs/bitcoin,ClusterCoin/ClusterCoin,braydonf/bitcoin,cmgustavo/bitcoin,dagurval/bitcoinxt,biblepay/biblepay,zcoinofficial/zcoin,wtogami/bitcoin,pastday/bitcoinproject,dcousens/bitcoin,CoinGame/BCEShadowNet,Exceltior/dogecoin,NicolasDorier/bitcoin,karek314/bitcoin,novacoin-project/novacoin,nathan-at-least/zcash,iceinsidefire/peershare-edit,imton/bitcoin,RyanLucchese/energi,inutoshi/inutoshi,vtafaucet/virtacoin,3lambert/Molecular,raasakh/bardcoin.exe,iceinsidefire/peershare-edit,lbrtcoin/albertcoin,zotherstupidguy/bitcoin,ccoin-project/ccoin,Rav3nPL/PLNcoin,aspanta/bitcoin,shapiroisme/datadollar,coinkeeper/2015-06-22_19-00_ziftrcoin,jonasnick/bitcoin,NateBrune/bitcoin-nate,mmpool/coiledcoin,CoinBlack/blackcoin,langerhans/dogecoin,dgenr8/bitcoinxt,fsb4000/bitcoin,Horrorcoin/horrorcoin,pevernon/picoin,czr5014iph/bitcoin4e,mruddy/bitcoin,kevcooper/bitcoin,bitreserve/bitcoin,cheehieu/bitcoin,brishtiteveja/sherlockcoin,zcoinofficial/zcoin,isle2983/bitcoin,gjhiggins/vcoin0.8zeta-dev,ForceMajeure/BitPenny-Client-0.4.0.1,royosherove/bitcoinxt,jrmithdobbs/bitcoin,djtms/ltc,genavarov/ladacoin,kbccoin/kbc,BTCDDev/bitcoin,wellenreiter01/Feathercoin,WorldLeadCurrency/WLC,rromanchuk/bitcoinxt,nathan-at-least/zcash,senadj/yacoin,jonghyeopkim/bitcoinxt,m0gliE/fastcoin-cli,appop/bitcoin,emc2foundation/einsteinium,aspirecoin/aspire,fanquake/bitcoin,bcpki/nonce2testblocks,mm-s/bitcoin,apoelstra/bitcoin,ionomy/ion,Peershares/Peershares,earthcoinproject/earthcoin,5mil/Tradecoin,coinkeeper/terracoin_20150327,Mirobit/bitcoin,majestrate/twister-core,Bitcoinsulting/bitcoinxt,MonetaryUnit/MUE-Src,digibyte/digibyte,jtimon/elements,wellenreiter01/Feathercoin,Kixunil/keynescoin,DogTagRecon/Still-Leraning,habibmasuro/bitcoin,phelixbtc/bitcoin,Kcoin-project/kcoin,tropa/axecoin,bitshares/bitshares-pts,MazaCoin/mazacoin-new,faircoin/faircoin2,RazorLove/cloaked-octo-spice,zenywallet/bitzeny,romanornr/viacoin,dakk/soundcoin,GreenParhelia/bitcoin,altcoinpro/addacoin,phplaboratory/psiacoin,sipsorcery/bitcoin,gcc64/bitcoin,namecoin/namecoin-core,fedoracoin-dev/fedoracoin,enlighter/Feathercoin,jambolo/bitcoin,stamhe/bitcoin,goldcoin/goldcoin,jakeva/bitcoin-pwcheck,benosa/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,glv2/peerunity,JeremyRand/namecore,MazaCoin/maza,droark/elements,jul2711/jucoin,united-scrypt-coin-project/unitedscryptcoin,guncoin/guncoin,instagibbs/bitcoin,FuzzyBearBTC/Peershares,ftrader-bitcoinabc/bitcoin-abc,torresalyssa/bitcoin,dogecoin/dogecoin,Bushstar/UFO-Project,untrustbank/litecoin,safecoin/safecoin,Mrs-X/Darknet,emc2foundation/einsteinium,marklai9999/Taiwancoin,deadalnix/bitcoin,CoinBlack/bitcoin,syscoin/syscoin,shaolinfry/litecoin,174high/bitcoin,nigeriacoin/nigeriacoin,oklink-dev/bitcoin_block,shadowoneau/ozcoin,gjhiggins/vcoin09,cinnamoncoin/Feathercoin,FrictionlessCoin/iXcoin,ahmedbodi/vertcoin,antonio-fr/bitcoin,aniemerg/zcash,alexandrcoin/vertcoin,cinnamoncoin/Feathercoin,JeremyRand/namecoin-core,mooncoin-project/mooncoin-landann,capitalDIGI/litecoin,MOIN/moin,chaincoin/chaincoin,iadix/iadixcoin,iadix/iadixcoin,stevemyers/bitcoinxt,kaostao/bitcoin,mycointest/owncoin,digibyte/digibyte,Twyford/Indigo,zzkt/solarcoin,novaexchange/EAC,sipsorcery/bitcoin,awemany/BitcoinUnlimited,2XL/bitcoin,pataquets/namecoin-core,coinkeeper/2015-06-22_19-13_florincoin,lentza/SuperTurboStake,shea256/bitcoin,shurcoin/shurcoin,langerhans/dogecoin,gjhiggins/vcoincore,svcop3/svcop3,wiggi/fairbrix-0.6.3,Charlesugwu/Vintagecoin,haobtc/bitcoin,psionin/smartcoin,namecoin/namecoin-core,botland/bitcoin,chaincoin/chaincoin,PRabahy/bitcoin,btc1/bitcoin,dev1972/Satellitecoin,simonmulser/bitcoin,174high/bitcoin,Gazer022/bitcoin,domob1812/crowncoin,MazaCoin/maza,applecoin-official/fellatio,ajtowns/bitcoin,h4x3rotab/BTCGPU,BeirdoMud/MudCoin,UASF/bitcoin,RazorLove/cloaked-octo-spice,faircoin/faircoin,zixan/bitcoin,leofidus/glowing-octo-ironman,FuzzyBearBTC/Fuzzyshares,szlaozhu/twister-core,alecalve/bitcoin,StarbuckBG/BTCGPU,Lucky7Studio/bitcoin,peerdb/cors,1185/starwels,welshjf/bitcoin,AdrianaDinca/bitcoin,marscoin/marscoin,ceptacle/libcoinqt,UASF/bitcoin,awemany/BitcoinUnlimited,laudaa/bitcoin,ohac/sakuracoin,funkshelper/woodcore,icook/vertcoin,CoinGame/NuShadowNet,chaincoin/chaincoin,namecoin/namecoin-core,Czarcoin/czarcoin,gwillen/elements,cinnamoncoin/groupcoin-1,domob1812/bitcoin,Twyford/Indigo,gwangjin2/gwangcoin-core,senadj/yacoin,ColossusCoinXT/ColossusCoinXT,bitcoinec/bitcoinec,imharrywu/fastcoin,domob1812/bitcoin,shapiroisme/datadollar,DMDcoin/Diamond,ludbb/bitcoin,RibbitFROG/ribbitcoin,pinkmagicdev/SwagBucks,janko33bd/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,brightcoin/brightcoin,shea256/bitcoin,lakepay/lake,WorldLeadCurrency/WLC,unsystemizer/bitcoin,Krellan/bitcoin,micryon/GPUcoin,morcos/bitcoin,superjudge/bitcoin,Bushstar/UFO-Project,bitcoinec/bitcoinec,SoreGums/bitcoinxt,cryptocoins4all/zcoin,Petr-Economissa/gvidon,cryptohelper/premine,romanornr/viacoin,mooncoin-project/mooncoin-landann,therealaltcoin/altcoin,borgcoin/Borgcoin.rar,Gazer022/bitcoin,bitcoinxt/bitcoinxt,namecoin/namecore,iQcoin/iQcoin,raasakh/bardcoin,FeatherCoin/Feathercoin,gavinandresen/bitcoin-git,BitcoinHardfork/bitcoin,FuzzyBearBTC/Peershares2,capitalDIGI/litecoin,robvanbentem/bitcoin,lclc/bitcoin,world-bank/unpay-core,peerdb/cors,ptschip/bitcoinxt,StarbuckBG/BTCGPU,sipa/bitcoin,Earlz/dobbscoin-source,phelix/namecore,kleetus/bitcoinxt,morcos/bitcoin,psionin/smartcoin,alexwaters/Bitcoin-Testing,braydonf/bitcoin,ptschip/bitcoinxt,BitcoinPOW/BitcoinPOW,coinwarp/dogecoin,presstab/PIVX,steakknife/bitcoin-qt,MazaCoin/maza,nigeriacoin/nigeriacoin,inkvisit/sarmacoins,my-first/octocoin,lakepay/lake,OstlerDev/florincoin,pstratem/elements,cmgustavo/bitcoin,upgradeadvice/MUE-Src,sacarlson/MultiCoin-qt,reddcoin-project/reddcoin,vtafaucet/virtacoin,erqan/twister-core,Kixunil/keynescoin,sdaftuar/bitcoin,dogecoin/dogecoin,GeopaymeEE/e-goldcoin,shadowproject/shadow,sacarlson/MultiCoin-qt,antonio-fr/bitcoin,kallewoof/bitcoin,Gazer022/bitcoin,hyperwang/bitcoin,mortalvikinglive/bitcoinclassic,genavarov/lamacoin,tobeyrowe/KitoniaCoin,coblee/litecoin-old,dashpay/dash,valorbit/valorbit,blocktrail/bitcoin,worldbit/worldbit,bitcoinec/bitcoinec,btcdrak/bitcoin,bitcoinknots/bitcoin,madman5844/poundkoin,thesoftwarejedi/bitcoin,haobtc/bitcoin,experiencecoin/experiencecoin,majestrate/twister-core,ghostlander/Feathercoin,Sjors/bitcoin,UFOCoins/ufo,Earlz/renamedcoin,vericoin/vericoin-core,Rav3nPL/doubloons-08,shurcoin/shurcoin,matlongsi/micropay,Bitcoin-ABC/bitcoin-abc,rnicoll/dogecoin,benosa/bitcoin,petertodd/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,loxal/zcash,kevcooper/bitcoin,parvez3019/bitcoin,jaromil/faircoin2,AquariusNetwork/ARCOv2,shadowoneau/ozcoin,mobicoins/mobicoin-core,GeekBrony/ponycoin-old,kseistrup/twister-core,aciddude/Feathercoin,reorder/viacoin,elambert2014/novacoin,coinkeeper/2015-06-22_19-13_florincoin,compasscoin/compasscoin,FuzzyBearBTC/Peershares,saydulk/Feathercoin,bitcoinknots/bitcoin,HeliumGas/helium,BeirdoMud/MudCoin,prusnak/bitcoin,valorbit/valorbit,nmarley/dash,ArgonToken/ArgonToken,lbrtcoin/albertcoin,totallylegitbiz/totallylegitcoin,marlengit/BitcoinUnlimited,gjhiggins/vcoin0.8zeta-dev,drwasho/bitcoinxt,bitbrazilcoin-project/bitbrazilcoin,shaolinfry/litecoin,thesoftwarejedi/bitcoin,xawksow/GroestlCoin,mb300sd/bitcoin,gameunits/gameunits,Kcoin-project/kcoin,ticclassic/ic,jameshilliard/bitcoin,Christewart/bitcoin,ANCompany/birdcoin-dev,butterflypay/bitcoin,Flowdalic/bitcoin,ahmedbodi/terracoin,theuni/bitcoin,coinkeeper/2015-06-22_18-41_ixcoin,dscotese/bitcoin,RongxinZhang/bitcoinxt,tecnovert/particl-core,brishtiteveja/sherlockholmescoin,thesoftwarejedi/bitcoin,BlockchainTechLLC/3dcoin,oklink-dev/litecoin_block,koharjidan/litecoin,megacoin/megacoin,ionux/freicoin,marscoin/marscoin,prusnak/bitcoin,jl2012/litecoin,bitgoldcoin-project/bitgoldcoin,jgarzik/bitcoin,barcoin-project/nothingcoin,AkioNak/bitcoin,iQcoin/iQcoin,48thct2jtnf/P,pinkevich/dash,Justaphf/BitcoinUnlimited,UdjinM6/dash,zottejos/merelcoin,mycointest/owncoin,drwasho/bitcoinxt,faircoin/faircoin2,wiggi/fairbrix-0.6.3,midnight-miner/LasVegasCoin,Diapolo/bitcoin,error10/bitcoin,zenywallet/bitzeny,likecoin-dev/bitcoin,Open-Source-Coins/EZ,cybermatatu/bitcoin,mapineda/litecoin,jiffe/cosinecoin,r8921039/bitcoin,phelix/bitcoin,tdudz/elements,peercoin/peercoin,coinkeeper/2015-06-22_18-36_darkcoin,PIVX-Project/PIVX,npccoin/npccoin,Anfauglith/iop-hd,gavinandresen/bitcoin-git,Alex-van-der-Peet/bitcoin,bcpki/testblocks,coinkeeper/2015-04-19_21-20_litecoindark,untrustbank/litecoin,jiangyonghang/bitcoin,shapiroisme/datadollar,coinkeeper/2015-06-22_19-07_digitalcoin,pstratem/bitcoin,aburan28/elements,nlgcoin/guldencoin-official,dopecoin-dev/DopeCoinGold,starwels/starwels,killerstorm/bitcoin,funbucks/notbitcoinxt,nathaniel-mahieu/bitcoin,lbrtcoin/albertcoin,Kogser/bitcoin,TurboStake/TurboStake,cddjr/BitcoinUnlimited,bfroemel/smallchange,freelion93/mtucicoin,ShwoognationHQ/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,fsb4000/novacoin,marlengit/hardfork_prototype_1_mvf-bu,dexX7/mastercore,core-bitcoin/bitcoin,marlengit/hardfork_prototype_1_mvf-bu,goldcoin/Goldcoin-GLD,koharjidan/bitcoin,Anoncoin/anoncoin,united-scrypt-coin-project/unitedscryptcoin,gandrewstone/bitcoinxt,keesdewit82/LasVegasCoin,elecoin/elecoin,jyap808/jumbucks,Crypto-Currency/BitBar,SartoNess/BitcoinUnlimited,alejandromgk/Lunar,kryptokredyt/ProjektZespolowyCoin,practicalswift/bitcoin,m0gliE/fastcoin-cli,yacoin/yacoin,GeopaymeEE/e-goldcoin,magacoin/magacoin,cryptodev35/icash,m0gliE/fastcoin-cli,kigooz/smalltestnew,marcusdiaz/BitcoinUnlimited,StarbuckBG/BTCGPU,bdelzell/creditcoin-org-creditcoin,haobtc/bitcoin,dperel/bitcoin,1185/starwels,FeatherCoin/Feathercoin,vmp32k/litecoin,sstone/bitcoin,Rimbit/Wallets,BTCDDev/bitcoin,florincoin/florincoin,pdrobek/Polcoin-1-3,benzhi888/renminbi,EntropyFactory/creativechain-core,martindale/elements,Ziftr/Peerunity,bitcoinxt/bitcoinxt,Rav3nPL/PLNcoin,earthcoinproject/earthcoin,Earlz/renamedcoin,andres-root/bitcoinxt,thodg/ppcoin,cculianu/bitcoin-abc,ashleyholman/bitcoin,rdqw/sscoin,isghe/bitcoinxt,effectsToCause/vericoin,UdjinM6/dash,afk11/bitcoin,sugruedes/bitcoin,CoinGame/BCEShadowNet,ShadowMyst/creativechain-core,koltcoin/koltcoin,lclc/bitcoin,Flowdalic/bitcoin,themusicgod1/bitcoin,TBoehm/greedynode,starwalkerz/fincoin-fork,jimmykiselak/lbrycrd,ftrader-bitcoinabc/bitcoin-abc,jaromil/faircoin2,madman5844/poundkoin,braydonf/bitcoin,Vector2000/bitcoin,upgradeadvice/MUE-Src,Rimbit/Wallets,alecalve/bitcoin,AquariusNetwork/ARCO,ghostlander/Testcoin,coinkeeper/2015-06-22_19-19_worldcoin,stamhe/ppcoin,tripmode/pxlcoin,greencoin-dev/GreenCoinV2,slimcoin-project/Slimcoin,MitchellMintCoins/AutoCoin,wastholm/bitcoin,UASF/bitcoin,thodg/ppcoin,lbryio/lbrycrd,coinkeeper/2015-06-22_18-45_peercoin,btc1/bitcoin,krzysztofwos/BitcoinUnlimited,pouta/bitcoin,myriadcoin/myriadcoin,cculianu/bitcoin-abc,ahmedbodi/test2,Cloudsy/bitcoin,CrimeaCoin/crimeacoin,nomnombtc/bitcoin,NateBrune/bitcoin-fio,genavarov/lamacoin,wederw/bitcoin,mortalvikinglive/bitcoinlight,robvanmieghem/clams,TheOncomingStorm/logincoinadvanced,pastday/bitcoinproject,megacoin/megacoin,habibmasuro/bitcoin,langerhans/dogecoin,renatolage/wallets-BRCoin,domob1812/bitcoin,bickojima/bitzeny,jtimon/elements,CodeShark/bitcoin,randy-waterhouse/bitcoin,koharjidan/dogecoin,ahmedbodi/bytecoin,shouhuas/bitcoin,starwalkerz/fincoin-fork,Theshadow4all/ShadowCoin,coinkeeper/2015-06-22_18-51_vertcoin,deeponion/deeponion,Exgibichi/statusquo,FinalHashLLC/namecore,schildbach/bitcoin,franko-org/franko,DrCrypto/darkcoin,zebrains/Blotter,ftrader-bitcoinabc/bitcoin-abc,upgradeadvice/MUE-Src,kirkalx/bitcoin,plncoin/PLNcoin_Core,ahmedbodi/Bytecoin-MM,gapcoin/gapcoin,bespike/litecoin,lclc/bitcoin,bitcoinplusorg/xbcwalletsource,tecnovert/particl-core,MasterX1582/bitcoin-becoin,cotner/bitcoin,xawksow/GroestlCoin,ForceMajeure/BitPenny-Client-0.4.0.1,shomeser/bitcoin,RHavar/bitcoin,djtms/ltc,litecoin-project/bitcoinomg,valorbit/valorbit-oss,particl/particl-core,nikkitan/bitcoin,mockcoin/mockcoin,xurantju/bitcoin,Czarcoin/czarcoin,MazaCoin/maza,diggcoin/diggcoin,keesdewit82/LasVegasCoin,pdrobek/Polcoin-1-3,5mil/SuperTurboStake,Erkan-Yilmaz/twister-core,bootycoin-project/bootycoin,KibiCoin/kibicoin,coinkeeper/2015-06-22_18-36_darkcoin,UASF/bitcoin,antonio-fr/bitcoin,Cancercoin/Cancercoin,mapineda/litecoin,pstratem/elements,cannabiscoindev/cannabiscoin420,ForceMajeure/BitPenny-Client-0.4.0.1,odemolliens/bitcoinxt,jimmykiselak/lbrycrd,TierNolan/bitcoin,wangliu/bitcoin,domob1812/namecore,SandyCohen/mincoin,szlaozhu/twister-core,elliotolds/bitcoin,mobicoins/mobicoin-core,FuzzyBearBTC/Peerunity,stamhe/novacoin,dobbscoin/dobbscoin-source,Bluejudy/worldcoin,ElementsProject/elements,nomnombtc/bitcoin,Ziftr/litecoin,randy-waterhouse/bitcoin,BenjaminsCrypto/Benjamins-1,djpnewton/bitcoin,miguelfreitas/twister-core,sbellem/bitcoin,forrestv/bitcoin,brightcoin/brightcoin,jmgilbert2/energi,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,megacoin/megacoin,blocktrail/bitcoin,marcusdiaz/BitcoinUnlimited,hasanatkazmi/bitcoin,xuyangcn/opalcoin,ravenbyron/phtevencoin,vectorcoindev/Vector,djpnewton/bitcoin,pataquets/namecoin-core,dopecoin-dev/DopeCoinGold,bitjson/hivemind,ohac/sha1coin,cotner/bitcoin,Credit-Currency/CoinTestComp,x-kalux/bitcoin_WiG-B,dopecoin-dev/DopeCoinGold,rustyrussell/bitcoin,keo/bitcoin,5mil/Tradecoin,amaivsimau/bitcoin,lclc/bitcoin,shaulkf/bitcoin,Bitcoin-ABC/bitcoin-abc,vericoin/vericoin-core,DGCDev/argentum,oleganza/bitcoin-duo,peacedevelop/peacecoin,jn2840/bitcoin,benzhi888/renminbi,jmgilbert2/energi,cryptcoins/cryptcoin,MeshCollider/bitcoin,scamcoinz/scamcoin,basicincome/unpcoin-core,jl2012/litecoin,zemrys/vertcoin,btcdrak/bitcoin,h4x3rotab/BTCGPU,Rav3nPL/polcoin,bitgoldcoin-project/bitgoldcoin,greencoin-dev/GreenCoinV2,CoinProjects/AmsterdamCoin-v4,alejandromgk/Lunar,ronpaulcoin/ronpaulcoin,goldcoin/Goldcoin-GLD,rat4/blackcoin,dagurval/bitcoinxt,error10/bitcoin,slingcoin/sling-market,sugruedes/bitcoinxt,willwray/dash,Magicking/neucoin,bespike/litecoin,CoinBlack/blackcoin,hasanatkazmi/bitcoin,dexX7/mastercore,RibbitFROG/ribbitcoin,butterflypay/bitcoin,thesoftwarejedi/bitcoin,plankton12345/litecoin,prodigal-son/blackcoin,sproutcoin/sprouts,funkshelper/woodcoin-b,atgreen/bitcoin,ivansib/sibcoin,crowning2/dash,razor-coin/razor,cinnamoncoin/Feathercoin,IlfirinIlfirin/shavercoin,faircoin/faircoin2,Kangmo/bitcoin,wiggi/fairbrix-0.6.3,brishtiteveja/truthcoin-cpp,riecoin/riecoin,ericshawlinux/bitcoin,sipa/elements,fsb4000/novacoin,Thracky/monkeycoin,midnight-miner/LasVegasCoin,nailtaras/nailcoin,zcoinofficial/zcoin,MidasPaymentLTD/midascoin,pelorusjack/BlockDX,se3000/bitcoin,brandonrobertz/namecoin-core,SmeltFool/Wonker,isle2983/bitcoin,greencoin-dev/GreenCoinV2,ryanxcharles/bitcoin,CTRoundTable/Encrypted.Cash,SmeltFool/Yippe-Hippe,Alonzo-Coeus/bitcoin,wtogami/bitcoin,5mil/Bolt,Har01d/bitcoin,GlobalBoost/GlobalBoost,Peer3/homework,ptschip/bitcoinxt,phelix/namecore,Alex-van-der-Peet/bitcoin,accraze/bitcoin,wekuiz/wekoin,habibmasuro/bitcoin,manuel-zulian/CoMoNet,CarpeDiemCoin/CarpeDiemLaunch,shomeser/bitcoin,DogTagRecon/Still-Leraning,5mil/Tradecoin,Earlz/renamedcoin,coinkeeper/2015-06-22_18-37_dogecoin,SoreGums/bitcoinxt,thodg/ppcoin,Alonzo-Coeus/bitcoin,landcoin-ldc/landcoin,ryanofsky/bitcoin,Christewart/bitcoin,brettwittam/geocoin,thelazier/dash,hophacker/bitcoin_malleability,cqtenq/feathercoin_core,keesdewit82/LasVegasCoin,pdrobek/Polcoin-1-3,gandrewstone/BitcoinUnlimited,dgarage/bc3,puticcoin/putic,habibmasuro/bitcoinxt,vertcoin/vertcoin,DynamicCoinOrg/DMC,ceptacle/libcoinqt,UFOCoins/ufo,genavarov/brcoin,litecoin-project/litecore-litecoin,mastercoin-MSC/mastercore,cotner/bitcoin,xawksow/GroestlCoin,sebrandon1/bitcoin,AquariusNetwork/ARCOv2,tuaris/bitcoin,credits-currency/credits,emc2foundation/einsteinium,ColossusCoinXT/ColossusCoinXT,micryon/GPUcoin,RHavar/bitcoin,robvanbentem/bitcoin,yacoin/yacoin,tobeyrowe/BitStarCoin,Action-Committee/Spaceballz,dannyperez/bolivarcoin,AkioNak/bitcoin,syscoin/syscoin,pstratem/bitcoin,djpnewton/bitcoin,21E14/bitcoin,DSPay/DSPay,CoinBlack/bitcoin,dperel/bitcoin,coinkeeper/2015-06-22_19-13_florincoin,DigiByte-Team/digibyte,coinkeeper/2015-06-22_18-31_bitcoin,neureal/noocoin,zetacoin/zetacoin,ravenbyron/phtevencoin,vizidrixfork/Peershares,killerstorm/bitcoin,koltcoin/koltcoin,experiencecoin/experiencecoin,howardrya/AcademicCoin,zottejos/merelcoin,superjudge/bitcoin,jul2711/jucoin,jamesob/bitcoin,supcoin/supcoin,dooglus/bitcoin,Kixunil/keynescoin,truthcoin/truthcoin-cpp,ClusterCoin/ClusterCoin,franko-org/franko,mikehearn/bitcoin,itmanagerro/tresting,icook/vertcoin,MitchellMintCoins/MortgageCoin,kallewoof/bitcoin,jimmykiselak/lbrycrd,CoinGame/BCEShadowNet,stamhe/litecoin,apoelstra/elements,dooglus/clams,and2099/twister-core,paveljanik/bitcoin,faircoin/faircoin2,valorbit/valorbit,prodigal-son/blackcoin,UFOCoins/ufo,faircoin/faircoin,neutrinofoundation/neutrino-digital-currency,hophacker/bitcoin_malleability,Ziftr/Peerunity,zestcoin/ZESTCOIN,BlueMeanie/PeerShares,nathan-at-least/zcash,simonmulser/bitcoin,Har01d/bitcoin,whatrye/twister-core,aspanta/bitcoin,thrasher-/litecoin,Rav3nPL/bitcoin,TheOncomingStorm/logincoinadvanced,dgenr8/bitcoin,174high/bitcoin,TierNolan/bitcoin,Action-Committee/Spaceballz,marcusdiaz/BitcoinUnlimited,deadalnix/bitcoin,coinkeeper/2015-04-19_21-20_litecoindark,arnuschky/bitcoin,dopecoin-dev/DopeCoinGold,Bitcoin-ABC/bitcoin-abc,benzmuircroft/REWIRE.io,brandonrobertz/namecoin-core,joshrabinowitz/bitcoin,xeddmc/twister-core,kazcw/bitcoin,wellenreiter01/Feathercoin,collapsedev/cashwatt,accraze/bitcoin,mrtexaznl/mediterraneancoin,cryptoprojects/ultimateonlinecash,wcwu/bitcoin,josephbisch/namecoin-core,aspirecoin/aspire,Enticed87/Decipher,qtumproject/qtum,Kabei/Ippan,DogTagRecon/Still-Leraning,crowning-/dash,ivansib/sibcoin,sebrandon1/bitcoin,terracoin/terracoin,coinkeeper/terracoin_20150327,maaku/bitcoin,mrbandrews/bitcoin,nochowderforyou/clams,Lucky7Studio/bitcoin,Mrs-X/PIVX,EthanHeilman/bitcoin,tdudz/elements,dakk/soundcoin,CoinBlack/bitcoin,Anfauglith/iop-hd,brightcoin/brightcoin,Ziftr/Peerunity,deeponion/deeponion,bitcoinsSG/bitcoin,elambert2014/cbx2,collapsedev/cashwatt,myriadteam/myriadcoin,alejandromgk/Lunar,ahmedbodi/temp_vert,namecoin/namecore,hophacker/bitcoin_malleability,drwasho/bitcoinxt,ediston/energi,greencoin-dev/digitalcoin,CodeShark/bitcoin,oklink-dev/bitcoin_block,collapsedev/cashwatt,vlajos/bitcoin,gandrewstone/bitcoinxt,ClusterCoin/ClusterCoin,borgcoin/Borgcoin.rar,coinkeeper/2015-06-22_18-30_anoncoin,myriadcoin/myriadcoin,FuzzyBearBTC/Fuzzyshares,kfitzgerald/titcoin,spiritlinxl/BTCGPU,blackcoinhelp/blackcoin,ctwiz/stardust,DGCDev/digitalcoin,SoreGums/bitcoinxt,hsavit1/bitcoin,TrainMAnB/vcoincore,privatecoin/privatecoin,tropa/axecoin,axelxod/braincoin,imton/bitcoin,ronpaulcoin/ronpaulcoin,jonghyeopkim/bitcoinxt,Metronotes/bitcoin,atgreen/bitcoin,reorder/viacoin,SmeltFool/Yippe-Hippe,TGDiamond/Diamond,deadalnix/bitcoin,tripmode/pxlcoin,droark/bitcoin,NateBrune/bitcoin-nate,kallewoof/elements,kryptokredyt/ProjektZespolowyCoin,stevemyers/bitcoinxt,raasakh/bardcoin,lclc/bitcoin,Blackcoin/blackcoin,bitcoinclassic/bitcoinclassic,OmniLayer/omnicore,BlockchainTechLLC/3dcoin,m0gliE/fastcoin-cli,cheehieu/bitcoin,IlfirinCano/shavercoin,denverl/bitcoin,Kefkius/clams,enlighter/Feathercoin,effectsToCause/vericoin,svcop3/svcop3,oklink-dev/litecoin_block,Infernoman/crowncoin,janko33bd/bitcoin,qubitcoin-project/QubitCoinQ2C,gandrewstone/BitcoinUnlimited,kirkalx/bitcoin,RHavar/bitcoin,peercoin/peercoin,n1bor/bitcoin,particl/particl-core,IOCoin/DIONS,redfish64/nomiccoin,pascalguru/florincoin,applecoin-official/applecoin,21E14/bitcoin,Kangmo/bitcoin,valorbit/valorbit-oss,shea256/bitcoin,lateminer/bitcoin,chrisfranko/aiden,destenson/bitcoin--bitcoin,jeromewu/bitcoin-opennet,acid1789/bitcoin,dexX7/bitcoin,BitzenyCoreDevelopers/bitzeny,robvanbentem/bitcoin,GroundRod/anoncoin,jamesob/bitcoin,starwels/starwels,coinkeeper/2015-06-22_18-42_litecoin,benma/bitcoin,jl2012/litecoin,pevernon/picoin,ronpaulcoin/ronpaulcoin,cdecker/bitcoin,Blackcoin/blackcoin,TheBlueMatt/bitcoin,celebritycoin/investorcoin,antcheck/antcoin,bitreserve/bitcoin,etercoin/etercoin,bitjson/hivemind,Jheguy2/Mercury,pascalguru/florincoin,goldmidas/goldmidas,coinkeeper/megacoin_20150410_fixes,gfneto/Peershares,simdeveloper/bitcoin,Jcing95/iop-hd,lentza/SuperTurboStake,presstab/PIVX,Bitcoin-ABC/bitcoin-abc,gzuser01/zetacoin-bitcoin,coinkeeper/2015-06-22_18-36_darkcoin,sstone/bitcoin,czr5014iph/bitcoin4e,iadix/iadixcoin,ArgonToken/ArgonToken,patricklodder/dogecoin,CryptArc/bitcoinxt,digibyte/digibyte,IOCoin/DIONS,nailtaras/nailcoin,koharjidan/bitcoin,MeshCollider/bitcoin,ptschip/bitcoin,dan-mi-sun/bitcoin,dmrtsvetkov/flowercoin,REAP720801/bitcoin,elliotolds/bitcoin,senadmd/coinmarketwatch,dcousens/bitcoin,okcashpro/okcash,x-kalux/bitcoin_WiG-B,Dajackal/Ronpaulcoin,bmp02050/ReddcoinUpdates,TGDiamond/Diamond,joulecoin/joulecoin,nathan-at-least/zcash,gavinandresen/bitcoin-git,cheehieu/bitcoin,domob1812/namecore,viacoin/viacoin,IOCoin/DIONS,javgh/bitcoin,bitreserve/bitcoin,daeMOn63/Peershares,misdess/bitcoin,jonasschnelli/bitcoin,franko-org/franko,LIMXTEC/DMDv3,prusnak/bitcoin,schinzelh/dash,fedoracoin-dev/fedoracoin,ptschip/bitcoin,domob1812/namecore,capitalDIGI/litecoin,experiencecoin/experiencecoin,tropa/axecoin,capitalDIGI/DIGI-v-0-10-4,janko33bd/bitcoin,lakepay/lake,coinkeeper/2015-06-22_18-46_razor,shouhuas/bitcoin,cyrixhero/bitcoin,okinc/litecoin,CryptArc/bitcoin,my-first/octocoin,TheOncomingStorm/logincoinadvanced,ychaim/smallchange,antonio-fr/bitcoin,Metronotes/bitcoin,szlaozhu/twister-core,psionin/smartcoin,myriadteam/myriadcoin,coinkeeper/2015-06-22_18-45_peercoin,sarielsaz/sarielsaz,initaldk/bitcoin,superjudge/bitcoin,koharjidan/litecoin,genavarov/lamacoin,sugruedes/bitcoin,genavarov/ladacoin,jgarzik/bitcoin,penek/novacoin,mortalvikinglive/bitcoinlight,FuzzyBearBTC/Peershares2,benzmuircroft/REWIRE.io,parvez3019/bitcoin,superjudge/bitcoin,daliwangi/bitcoin,bitshares/bitshares-pts,coinkeeper/2015-06-22_18-52_viacoin,dobbscoin/dobbscoin-source,sickpig/BitcoinUnlimited,nightlydash/darkcoin,vbernabe/freicoin,rnicoll/dogecoin,Cloudsy/bitcoin,jtimon/elements,Open-Source-Coins/EZ,bcpki/bitcoin,habibmasuro/bitcoin,domob1812/i0coin,coblee/litecoin-old,isocolsky/bitcoinxt,steakknife/bitcoin-qt,stamhe/bitcoin,EthanHeilman/bitcoin,GroestlCoin/bitcoin,ahmedbodi/bytecoin,ajweiss/bitcoin,qubitcoin-project/QubitCoinQ2C,lentza/SuperTurboStake,elecoin/elecoin,benzmuircroft/REWIRE.io,fsb4000/novacoin,funkshelper/woodcoin-b,skaht/bitcoin,arruah/ensocoin,vectorcoindev/Vector,misdess/bitcoin,rjshaver/bitcoin,tmagik/catcoin,ripper234/bitcoin,jnewbery/bitcoin,my-first/octocoin,degenorate/Deftcoin,mitchellcash/bitcoin,therealaltcoin/altcoin,Krellan/bitcoin,ghostlander/Feathercoin,DogTagRecon/Still-Leraning,djpnewton/bitcoin,jonasschnelli/bitcoin,wbchen99/bitcoin-hnote0,NateBrune/bitcoin-nate,DigiByte-Team/digibyte,dgenr8/bitcoin,Rav3nPL/doubloons-08,XertroV/bitcoin-nulldata,sirk390/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,mockcoin/mockcoin,riecoin/riecoin,mobicoins/mobicoin-core,sdaftuar/bitcoin,Checkcoin/checkcoin,MitchellMintCoins/MortgageCoin,GroundRod/anoncoin,memorycoin/memorycoin,metacoin/florincoin,coinkeeper/2015-06-22_18-45_peercoin,mikehearn/bitcoin,dogecoin/dogecoin,faircoin/faircoin2,okinc/litecoin,lclc/bitcoin,Crypto-Currency/BitBar,AkioNak/bitcoin,ticclassic/ic,truthcoin/truthcoin-cpp,Darknet-Crypto/Darknet,StarbuckBG/BTCGPU,oklink-dev/bitcoin,iosdevzone/bitcoin,Mrs-X/PIVX,supcoin/supcoin,fedoracoin-dev/fedoracoin,RHavar/bitcoin,HeliumGas/helium,gjhiggins/vcoincore,Rav3nPL/polcoin,loxal/zcash,novacoin-project/novacoin,trippysalmon/bitcoin,dobbscoin/dobbscoin-source,oklink-dev/bitcoin_block,isghe/bitcoinxt,ionux/freicoin,penek/novacoin,brandonrobertz/namecoin-core,zottejos/merelcoin,netswift/vertcoin,slimcoin-project/Slimcoin,coinkeeper/2015-06-22_18-36_darkcoin,vlajos/bitcoin,MonetaryUnit/MUE-Src,vtafaucet/virtacoin,ludbb/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,OmniLayer/omnicore,uphold/bitcoin,elambert2014/novacoin,gades/novacoin,coinkeeper/2015-06-22_18-56_megacoin,mockcoin/mockcoin,xurantju/bitcoin,droark/elements,mammix2/ccoin-dev,kevcooper/bitcoin,shurcoin/shurcoin,oklink-dev/bitcoin,sifcoin/sifcoin,benma/bitcoin,mycointest/owncoin,Climbee/artcoin,SproutsEx/SproutsExtreme,dgarage/bc2,bitpagar/bitpagar,arnuschky/bitcoin,yenliangl/bitcoin,jashandeep-sohi/ppcoin,DGCDev/digitalcoin,jameshilliard/bitcoin,applecoin-official/fellatio,Enticed87/Decipher,stevemyers/bitcoinxt,coinkeeper/2015-06-22_18-52_viacoin,ixcoinofficialpage/master,sacarlson/MultiCoin-qt,Kcoin-project/kcoin,jgarzik/bitcoin,fanquake/bitcoin,coblee/litecoin-old,truthcoin/blocksize-market,SmeltFool/Wonker,pataquets/namecoin-core,jtimon/elements,Matoking/bitcoin,tensaix2j/bananacoin,goku1997/bitcoin,shadowproject/shadow,koharjidan/dogecoin,EthanHeilman/bitcoin,ahmedbodi/Bytecoin-MM,Carrsy/PoundCoin,forrestv/bitcoin,MidasPaymentLTD/midascoin,tobeyrowe/smallchange,ionux/freicoin,bitcoinclassic/bitcoinclassic,marklai9999/Taiwancoin,111t8e/bitcoin,initaldk/bitcoin,imton/bitcoin,Alonzo-Coeus/bitcoin,JeremyRubin/bitcoin,alexwaters/Bitcoin-Testing,dexX7/bitcoin,nikkitan/bitcoin,NateBrune/bitcoin-nate,capitalDIGI/DIGI-v-0-10-4,ahmedbodi/vertcoin,gameunits/gameunits,CoinProjects/AmsterdamCoin-v4,jimblasko/2015_UNB_Wallets,ediston/energi,funkshelper/woodcore,jmcorgan/bitcoin,lateminer/bitcoin,ArgonToken/ArgonToken,xurantju/bitcoin,domob1812/huntercore,joroob/reddcoin,etercoin/etercoin,josephbisch/namecoin-core,balajinandhu/bitcoin,dcousens/bitcoin,rawodb/bitcoin,tecnovert/particl-core,Tetpay/bitcoin,ivansib/sibcoin,manuel-zulian/accumunet,nbenoit/bitcoin,practicalswift/bitcoin,cryptodev35/icash,alexandrcoin/vertcoin,BigBlueCeiling/augmentacoin,qreatora/worldcoin-v0.8,akabmikua/flowcoin,wangliu/bitcoin,enlighter/Feathercoin,ftrader-bitcoinabc/bitcoin-abc,totallylegitbiz/totallylegitcoin,coinkeeper/2015-06-22_19-13_florincoin,qtumproject/qtum,spiritlinxl/BTCGPU,48thct2jtnf/P,Domer85/dogecoin,scmorse/bitcoin,wekuiz/wekoin,bitcoinsSG/zcash,elacoin/elacoin,mockcoin/mockcoin,andres-root/bitcoinxt,coinkeeper/2015-06-22_18-37_dogecoin,llluiop/bitcoin,Czarcoin/czarcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,butterflypay/bitcoin,ohac/sha1coin,litecoin-project/litecoin,sipa/bitcoin,wtogami/bitcoin,FarhanHaque/bitcoin,jrmithdobbs/bitcoin,prark/bitcoinxt,DynamicCoinOrg/DMC,bitcoinec/bitcoinec,greencoin-dev/GreenCoinV2,awemany/BitcoinUnlimited,therealaltcoin/altcoin,core-bitcoin/bitcoin,nmarley/dash,coinkeeper/2015-06-22_18-41_ixcoin,jimblasko/2015_UNB_Wallets,ANCompany/birdcoin-dev,blocktrail/bitcoin,spiritlinxl/BTCGPU,TheBlueMatt/bitcoin,Gazer022/bitcoin,TheSeven/ppcoin,jiffe/cosinecoin,okinc/bitcoin,metacoin/florincoin,domob1812/i0coin,aspirecoin/aspire,shelvenzhou/BTCGPU,nsacoin/nsacoin,svost/bitcoin,MarcoFalke/bitcoin,dopecoin-dev/DopeCoinGold,jlay11/sharecoin,koharjidan/litecoin,spiritlinxl/BTCGPU,alecalve/bitcoin,plncoin/PLNcoin_Core,UdjinM6/dash,FuzzyBearBTC/peercoin,dexX7/bitcoin,sarielsaz/sarielsaz,Bitcoin-com/BUcash,BitcoinUnlimited/BitcoinUnlimited,zsulocal/bitcoin,kallewoof/bitcoin,x-kalux/bitcoin_WiG-B,PIVX-Project/PIVX,ahmedbodi/terracoin,gzuser01/zetacoin-bitcoin,jlopp/statoshi,ZiftrCOIN/ziftrcoin,brishtiteveja/sherlockcoin,aniemerg/zcash,nochowderforyou/clams,KnCMiner/bitcoin,sifcoin/sifcoin,mm-s/bitcoin,raasakh/bardcoin.exe,bickojima/bitzeny,Jheguy2/Mercury,ElementsProject/elements,myriadcoin/myriadcoin,welshjf/bitcoin,RongxinZhang/bitcoinxt,BitcoinUnlimited/BitcoinUnlimited,meighti/bitcoin,HashUnlimited/Einsteinium-Unlimited,vmp32k/litecoin,truthcoin/blocksize-market,raasakh/bardcoin,phplaboratory/psiacoin,DigiByte-Team/digibyte,keisercoin-official/keisercoin,ahmedbodi/test2,privatecoin/privatecoin,LanaCoin/lanacoin,rat4/bitcoin,upgradeadvice/MUE-Src,knolza/gamblr,lordsajan/erupee,metacoin/florincoin,greenaddress/bitcoin,millennial83/bitcoin,royosherove/bitcoinxt,RibbitFROG/ribbitcoin,CryptArc/bitcoinxt,Mirobit/bitcoin,madman5844/poundkoin,kevin-cantwell/crunchcoin,shouhuas/bitcoin,afk11/bitcoin,npccoin/npccoin,Erkan-Yilmaz/twister-core,dogecoin/dogecoin,MarcoFalke/bitcoin,antonio-fr/bitcoin,bitjson/hivemind,dogecoin/dogecoin,brishtiteveja/truthcoin-cpp,truthcoin/truthcoin-cpp,monacoinproject/monacoin,Crowndev/crowncoin,mobicoins/mobicoin-core,rebroad/bitcoin,vcoin-project/vcoincore,btcdrak/bitcoin,biblepay/biblepay,lakepay/lake,skaht/bitcoin,ClusterCoin/ClusterCoin,fedoracoin-dev/fedoracoin,cinnamoncoin/groupcoin-1,Ziftr/litecoin,IOCoin/iocoin,CoinGame/NuShadowNet,maraoz/proofcoin,maaku/bitcoin,xuyangcn/opalcoin,Rav3nPL/doubloons-0.10,Kabei/Ippan,bootycoin-project/bootycoin,d5000/ppcoin,pouta/bitcoin,bcpki/testblocks,inkvisit/sarmacoins,Whitecoin-org/Whitecoin,TeamBitBean/bitcoin-core,vtafaucet/virtacoin,odemolliens/bitcoinxt,elambert2014/novacoin,nmarley/dash,meighti/bitcoin,parvez3019/bitcoin,coinkeeper/2015-06-22_18-46_razor,initaldk/bitcoin,btc1/bitcoin,JeremyRand/bitcoin,JeremyRubin/bitcoin,mapineda/litecoin,sugruedes/bitcoinxt,fsb4000/novacoin,jimmysong/bitcoin,shaulkf/bitcoin,BenjaminsCrypto/Benjamins-1,cryptcoins/cryptcoin,rnicoll/bitcoin,kleetus/bitcoinxt,earonesty/bitcoin,gorgoy/novacoin,Credit-Currency/CoinTestComp,NateBrune/bitcoin-fio,terracoin/terracoin,thelazier/dash,GreenParhelia/bitcoin,BTCDDev/bitcoin,reorder/viacoin,NunoEdgarGub1/elements,rsdevgun16e/energi,metacoin/florincoin,janko33bd/bitcoin,cqtenq/Feathercoin,zemrys/vertcoin,MeshCollider/bitcoin,Jheguy2/Mercury,Kangmo/bitcoin,omefire/bitcoin,zenywallet/bitzeny,TrainMAnB/vcoincore,Magicking/neucoin,odemolliens/bitcoinxt,Cloudsy/bitcoin,dscotese/bitcoin,memorycoin/memorycoin,ppcoin/ppcoin,bittylicious/bitcoin,taenaive/zetacoin,jashandeep-sohi/ppcoin,ajweiss/bitcoin,capitalDIGI/litecoin,OmniLayer/omnicore,bitcoinknots/bitcoin,oleganza/bitcoin-duo,initaldk/bitcoin,benosa/bitcoin,midnightmagic/bitcoin,hg5fm/nexuscoin,Lucky7Studio/bitcoin,BitcoinHardfork/bitcoin,jnewbery/bitcoin,Tetpay/bitcoin,FuzzyBearBTC/peercoin,gjhiggins/vcoincore,BTCGPU/BTCGPU,sipa/elements,CoinGame/NuShadowNet,rnicoll/bitcoin,3lambert/Molecular,WorldcoinGlobal/WorldcoinLegacy,netswift/vertcoin,TheBlueMatt/bitcoin,skaht/bitcoin,pinheadmz/bitcoin,keisercoin-official/keisercoin,gjhiggins/vcoincore,bitchip/bitchip,Geekcoin-Project/Geekcoin,core-bitcoin/bitcoin,Domer85/dogecoin,anditto/bitcoin,ptschip/bitcoin,themusicgod1/bitcoin,Rav3nPL/polcoin,GIJensen/bitcoin,krzysztofwos/BitcoinUnlimited,chrisfranko/aiden,ArgonToken/ArgonToken,gravio-net/graviocoin,yenliangl/bitcoin,tjps/bitcoin,namecoin/namecoin-core,snakie/ppcoin,MonetaryUnit/MUE-Src,mortalvikinglive/bitcoinlight,mortalvikinglive/bitcoinclassic,joroob/reddcoin,apoelstra/elements,rsdevgun16e/energi,Richcoin-Project/RichCoin,sstone/bitcoin,BTCGPU/BTCGPU,Tetpay/bitcoin,aspirecoin/aspire,shouhuas/bitcoin,ajweiss/bitcoin,som4paul/BolieC,tjth/lotterycoin,domob1812/i0coin,domob1812/namecore,langerhans/dogecoin,TBoehm/greedynode,szlaozhu/twister-core,jiangyonghang/bitcoin,bitcoinsSG/bitcoin,internaut-me/ppcoin,nathaniel-mahieu/bitcoin,alexwaters/Bitcoin-Testing,EthanHeilman/bitcoin,bitcoinknots/bitcoin,reorder/viacoin,oklink-dev/bitcoin,alejandromgk/Lunar,fsb4000/bitcoin,CoinBlack/blackcoin,jlay11/sharecoin,taenaive/zetacoin,acid1789/bitcoin,coinkeeper/2015-06-22_19-13_florincoin,jtimon/bitcoin,pouta/bitcoin,CrimeaCoin/crimeacoin,andreaskern/bitcoin,jashandeep-sohi/ppcoin,cculianu/bitcoin-abc,UFOCoins/ufo,GeekBrony/ponycoin-old,nomnombtc/bitcoin,Credit-Currency/CoinTestComp,111t8e/bitcoin,OstlerDev/florincoin,okinc/litecoin,braydonf/bitcoin,zetacoin/zetacoin,instagibbs/bitcoin,diggcoin/diggcoin,plankton12345/litecoin,arnuschky/bitcoin,Earlz/dobbscoin-source,MikeAmy/bitcoin,kseistrup/twister-core,zcoinofficial/zcoin,therealaltcoin/altcoin,mikehearn/bitcoin,habibmasuro/bitcoinxt,FuzzyBearBTC/Peershares,ekankyesme/bitcoinxt,MasterX1582/bitcoin-becoin,shurcoin/shurcoin,mmpool/coiledcoin,matlongsi/micropay,kazcw/bitcoin,DMDcoin/Diamond,jambolo/bitcoin,senadj/yacoin,coinkeeper/anoncoin_20150330_fixes,mb300sd/bitcoin,midnightmagic/bitcoin,GroestlCoin/GroestlCoin,ColossusCoinXT/ColossusCoinXT,jonasschnelli/bitcoin,pinheadmz/bitcoin,tjps/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,lbryio/lbrycrd,bitpay/bitcoin,dgenr8/bitcoinxt,phelix/namecore,TurboStake/TurboStake,slimcoin-project/Slimcoin,magacoin/magacoin,CodeShark/bitcoin,crowning2/dash,globaltoken/globaltoken,misdess/bitcoin,haobtc/bitcoin,dpayne9000/Rubixz-Coin,midnightmagic/bitcoin,tjth/lotterycoin,nomnombtc/bitcoin,Michagogo/bitcoin,TheSeven/ppcoin,guncoin/guncoin,wcwu/bitcoin,sugruedes/bitcoin,jarymoth/dogecoin,40thoughts/Coin-QualCoin,bcpki/nonce2testblocks,JeremyRand/namecore,Carrsy/PoundCoin,dannyperez/bolivarcoin,Peershares/Peershares,glv2/peerunity,CryptArc/bitcoinxt,sarielsaz/sarielsaz,Kefkius/clams,coinkeeper/2015-06-22_18-30_anoncoin,bitjson/hivemind,litecoin-project/bitcoinomg,kigooz/smalltestnew,Infernoman/crowncoin,Rimbit/Wallets,hyperwang/bitcoin,greencoin-dev/digitalcoin,putinclassic/putic,greencoin-dev/greencoin-dev,FuzzyBearBTC/peercoin,dexX7/bitcoin,lateminer/DopeCoinGold,wbchen99/bitcoin-hnote0,CoinGame/NuShadowNet,error10/bitcoin,Crowndev/crowncoin,dashpay/dash,trippysalmon/bitcoin,shelvenzhou/BTCGPU,SandyCohen/mincoin,steakknife/bitcoin-qt,BitcoinPOW/BitcoinPOW,Metronotes/bitcoin,projectinterzone/ITZ,welshjf/bitcoin,wederw/bitcoin,coinkeeper/2015-04-19_21-20_litecoindark,phelix/bitcoin,genavarov/ladacoin,domob1812/namecore,irvingruan/bitcoin,Kabei/Ippan,2XL/bitcoin,axelxod/braincoin,n1bor/bitcoin,ghostlander/Orbitcoin,presstab/PIVX,vlajos/bitcoin,dashpay/dash,tobeyrowe/BitStarCoin,ajtowns/bitcoin,rawodb/bitcoin,zcoinofficial/zcoin,gapcoin/gapcoin,TBoehm/greedynode,kevin-cantwell/crunchcoin,xuyangcn/opalcoin,IlfirinIlfirin/shavercoin,Enticed87/Decipher,truthcoin/blocksize-market,peacedevelop/peacecoin,ghostlander/Feathercoin,gcc64/bitcoin,uphold/bitcoin,ftrader-bitcoinabc/bitcoin-abc,blood2/bloodcoin-0.9,rat4/blackcoin,r8921039/bitcoin,hasanatkazmi/bitcoin,wekuiz/wekoin,droark/elements,blocktrail/bitcoin,Crowndev/crowncoin,Kore-Core/kore,kigooz/smalltest,alexandrcoin/vertcoin,blood2/bloodcoin-0.9,gwangjin2/gwangcoin-core,bitbrazilcoin-project/bitbrazilcoin,vtafaucet/virtacoin,multicoins/marycoin,parvez3019/bitcoin,bittylicious/bitcoin,renatolage/wallets-BRCoin,TheSeven/ppcoin,genavarov/ladacoin,Ziftr/Peerunity,kleetus/bitcoin,bdelzell/creditcoin-org-creditcoin,npccoin/npccoin,keesdewit82/LasVegasCoin,aburan28/elements,vertcoin/vertcoin,Megacoin2/Megacoin,ludbb/bitcoin,kevin-cantwell/crunchcoin,jyap808/jumbucks,Crypto-Currency/BitBar,MarcoFalke/bitcoin,icook/vertcoin,bmp02050/ReddcoinUpdates,jgarzik/bitcoin,deadalnix/bitcoin,Peerunity/Peerunity,Vsync-project/Vsync,ArgonToken/ArgonToken,StarbuckBG/BTCGPU,Bitcoin-ABC/bitcoin-abc,benzhi888/renminbi,kfitzgerald/titcoin,MikeAmy/bitcoin,earthcoinproject/earthcoin,wekuiz/wekoin,faircoin/faircoin,segsignal/bitcoin,daveperkins-github/bitcoin-dev,RazorLove/cloaked-octo-spice,willwray/dash,vericoin/vericoin-core,thrasher-/litecoin,thodg/ppcoin,BTCGPU/BTCGPU,roques/bitcoin,Bitcoin-ABC/bitcoin-abc,redfish64/nomiccoin,Crowndev/crowncoin,sugruedes/bitcoinxt,Ziftr/ppcoin,supcoin/supcoin,benzhi888/renminbi,prusnak/bitcoin,174high/bitcoin,adpg211/bitcoin-master,syscoin/syscoin2,cculianu/bitcoin-abc,manuel-zulian/CoMoNet,oklink-dev/bitcoin,paveljanik/bitcoin,gcc64/bitcoin,dashpay/dash,initaldk/bitcoin,amaivsimau/bitcoin,Electronic-Gulden-Foundation/egulden,palm12341/jnc,oklink-dev/bitcoin,truthcoin/truthcoin-cpp,Flowdalic/bitcoin,jn2840/bitcoin,skaht/bitcoin,jmcorgan/bitcoin,jlopp/statoshi,florincoin/florincoin,TeamBitBean/bitcoin-core,wederw/bitcoin,jambolo/bitcoin,matlongsi/micropay,simonmulser/bitcoin,segwit/atbcoin-insight,thormuller/yescoin2,cryptoprojects/ultimateonlinecash,Coinfigli/coinfigli,TeamBitBean/bitcoin-core,5mil/Tradecoin,my-first/octocoin,grumpydevelop/singularity,coinkeeper/2015-06-22_18-46_razor,HeliumGas/helium,pinkmagicdev/SwagBucks,Alex-van-der-Peet/bitcoin,rdqw/sscoin,palm12341/jnc,likecoin-dev/bitcoin,digideskio/namecoin,blood2/bloodcoin-0.9,octocoin-project/octocoin,bitcoin-hivemind/hivemind,dgarage/bc2,DMDcoin/Diamond,andreaskern/bitcoin,KaSt/equikoin,bitcoin-hivemind/hivemind,dobbscoin/dobbscoin-source,dgenr8/bitcoin,benzhi888/renminbi,acid1789/bitcoin,haisee/dogecoin,CodeShark/bitcoin,TripleSpeeder/bitcoin,millennial83/bitcoin,ajweiss/bitcoin,miguelfreitas/twister-core,xXDavasXx/Davascoin,jyap808/jumbucks,kleetus/bitcoinxt,snakie/ppcoin,slingcoin/sling-market,inkvisit/sarmacoins,worldcoinproject/worldcoin-v0.8,habibmasuro/bitcoinxt,xeddmc/twister-core,octocoin-project/octocoin,XX-net/twister-core,initaldk/bitcoin,phplaboratory/psiacoin,Michagogo/bitcoin,CryptArc/bitcoinxt,daveperkins-github/bitcoin-dev,ravenbyron/phtevencoin,benma/bitcoin,TheBlueMatt/bitcoin,koharjidan/dogecoin,capitalDIGI/litecoin,scippio/bitcoin,webdesignll/coin,ryanxcharles/bitcoin,Flowdalic/bitcoin,novacoin-project/novacoin,marcusdiaz/BitcoinUnlimited,MitchellMintCoins/AutoCoin,willwray/dash,magacoin/magacoin,accraze/bitcoin,nvmd/bitcoin,ahmedbodi/test2,masterbraz/dg,gcc64/bitcoin,lakepay/lake,butterflypay/bitcoin,Mirobit/bitcoin,myriadcoin/myriadcoin,bcpki/nonce2testblocks,Tetcoin/tetcoin,GlobalBoost/GlobalBoost,phelix/namecore,ashleyholman/bitcoin,koharjidan/bitcoin,taenaive/zetacoin,Anoncoin/anoncoin,zotherstupidguy/bitcoin,thormuller/yescoin2,s-matthew-english/bitcoin,greencoin-dev/greencoin-dev,saydulk/Feathercoin,MOIN/moin,cheehieu/bitcoin,patricklodder/dogecoin,kazcw/bitcoin,sstone/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,gameunits/gameunits,5mil/SuperTurboStake,daliwangi/bitcoin,DynamicCoinOrg/DMC,wtogami/bitcoin,nanocoins/mycoin,dan-mi-sun/bitcoin,wellenreiter01/Feathercoin,sipa/bitcoin,dgenr8/bitcoinxt,thunderrabbit/clams,dan-mi-sun/bitcoin,krzysztofwos/BitcoinUnlimited,TGDiamond/Diamond,shelvenzhou/BTCGPU,Cloudsy/bitcoin,litecoin-project/litecore-litecoin,irvingruan/bitcoin,Domer85/dogecoin,ohac/sakuracoin,cerebrus29301/crowncoin,Dajackal/Ronpaulcoin,kseistrup/twister-core,NeuCoin/neucoin,dgarage/bc3,mitchellcash/bitcoin,jameshilliard/bitcoin,Whitecoin-org/Whitecoin,syscoin/syscoin,ediston/energi,Carrsy/PoundCoin,TeamBitBean/bitcoin-core,IlfirinCano/shavercoin,arnuschky/bitcoin,litecoin-project/litecoin,WorldLeadCurrency/WLC,Friedbaumer/litecoin,ivansib/sib16,united-scrypt-coin-project/unitedscryptcoin,OfficialTitcoin/titcoin-wallet,simonmulser/bitcoin,roques/bitcoin,LIMXTEC/DMDv3,masterbraz/dg,octocoin-project/octocoin,coinkeeper/anoncoin_20150330_fixes,slimcoin-project/Slimcoin,stronghands/stronghands,RHavar/bitcoin,keisercoin-official/keisercoin,javgh/bitcoin,DGCDev/digitalcoin,FinalHashLLC/namecore,xranby/blackcoin,174high/bitcoin,cqtenq/Feathercoin,sigmike/peercoin,coinkeeper/2015-06-22_18-41_ixcoin,Kogser/bitcoin,octocoin-project/octocoin,jrick/bitcoin,maaku/bitcoin,sipsorcery/bitcoin,xranby/blackcoin,cqtenq/feathercoin_core,freelion93/mtucicoin,cryptoprojects/ultimateonlinecash,benosa/bitcoin,welshjf/bitcoin,yenliangl/bitcoin,21E14/bitcoin,petertodd/bitcoin,cannabiscoindev/cannabiscoin420,terracoin/terracoin
c9015cdf3c2bb0f42f0897cadcd1083354401a64
src/DMXSerial.cpp
src/DMXSerial.cpp
// - - - - - // DMXSerial - A Arduino library for sending and receiving DMX using the builtin serial hardware port. // DMXSerial.cpp: Library implementation file // // Copyright (c) 2011-2020 by Matthias Hertel, http://www.mathertel.de // This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx // // Documentation and samples are available at http://www.mathertel.de/Arduino // Changelog: See DMXSerial.h // - - - - - #include "Arduino.h" #include "DMXSerial.h" // ----- forwards ----- void _DMXStartSending(); void _DMXStartReceiving(); // register interrupt for receiving data and frameerrors that calls _DMXReceived() void _DMXReceived(uint8_t data, uint8_t frameerror); void _DMXTransmitted(); // These functions all exist in the processor specific implementations: void _DMX_init(); void _DMX_setMode(); void _DMX_writeByte(uint8_t data); void _DMX_flush(); // ----- Serial UART Modes ----- // There are 4 different modes required while receiving and sending DMX using the Serial // State of receiving DMX Bytes typedef enum { OFF = 0, // Turn off RONLY = 1, // Receive DMX data only RDATA = 2, // Receive DMX data + Interrupt TBREAK = 3, // Transmit DMX Break + Interrupt on Transmission completed TDATA = 4, // Transmit DMX Data + Interrupt on Register empty TDONE = 5 // Transmit DMX Data + Interrupt on Transmission completed } __attribute__((packed)) DMXUARTMode; // Baud rate for DMX protocol #define DMXSPEED 250000L // the break timing is 10 bits (start + 8 data + 1 (even) parity) of this speed // the mark-after-break is 1 bit of this speed plus approx 6 usec // 100000 bit/sec is good: gives 100 usec break and 16 usec MAB // 1990 spec says transmitter must send >= 92 usec break and >= 12 usec MAB // receiver must accept 88 us break and 8 us MAB #define BREAKSPEED 100000L #define BREAKFORMAT SERIAL_8E2 #define DMXFORMAT SERIAL_8N2 #define DMXREADFORMAT SERIAL_8N1 // ----- include processor specific definitions and functions. #if defined(ARDUINO_ARCH_AVR) #include "DMXSerial_avr.h" #elif defined(ARDUINO_ARCH_MEGAAVR) #include "DMXSerial_megaavr.h" #endif // ----- Enumerations ----- // State of receiving DMX Bytes typedef enum { STARTUP = 1, // wait for any interrupt BEFORE starting analyzing the DMX protocoll. IDLE = 2, // wait for a BREAK condition. BREAK = 3, // BREAK was detected. DATA = 4, // DMX data. DONE = 5 // All channels received. } __attribute__((packed)) DMXReceivingState; // ----- DMXSerial Private variables ----- // These variables are not class members because they have to be reached by the interrupt implementations. // don't use these variable from outside, use the appropriate methods. DMXMode _dmxMode; // Mode of Operation int _dmxModePin; // pin used for I/O direction. uint8_t _dmxRecvState; // Current State of receiving DMX Bytes int _dmxChannel; // the next channel byte to be sent. volatile unsigned int _dmxMaxChannel = 32; // the last channel used for sending (1..32). volatile unsigned long _dmxLastPacket = 0; // the last time (using the millis function) a packet was received. bool _dmxUpdated = true; // is set to true when new data arrived. // Array of DMX values (raw). // Entry 0 will never be used for DMX data but will store the startbyte (0 for DMX mode). uint8_t _dmxData[DMXSERIAL_MAX + 1]; // This pointer will point to the next byte in _dmxData; uint8_t *_dmxDataPtr; // This pointer will point to the last byte in _dmxData; uint8_t *_dmxDataLastPtr; // Create a single class instance. Multiple class instances (multiple simultaneous DMX ports) are not supported. DMXSerialClass DMXSerial; // ----- Class implementation ----- // Initialize the specified mode. void DMXSerialClass::init(int mode) { init(mode, DMXMODEPIN); } // (Re)Initialize the specified mode. // The mode parameter should be a value from enum DMXMode. void DMXSerialClass::init(int mode, int dmxModePin) { // initialize global variables _dmxMode = DMXNone; _dmxModePin = dmxModePin; _dmxRecvState = STARTUP; // initial state _dmxChannel = 0; _dmxDataPtr = _dmxData; _dmxLastPacket = millis(); // remember current (relative) time in msecs. _dmxMaxChannel = DMXSERIAL_MAX; // The default in Receiver mode is reading all possible 512 channels. _dmxDataLastPtr = _dmxData + _dmxMaxChannel; // initialize the DMX buffer // memset(_dmxData, 0, sizeof(_dmxData)); for (int n = 0; n < DMXSERIAL_MAX + 1; n++) _dmxData[n] = 0; // now start _dmxMode = (DMXMode)mode; if ((_dmxMode == DMXController) || (_dmxMode == DMXReceiver) || (_dmxMode == DMXProbe)) { // a valid mode was given // Setup external mode signal _DMX_init(); pinMode(_dmxModePin, OUTPUT); // enables the pin for output to control data direction digitalWrite(_dmxModePin, DmxModeIn); // data in direction, to avoid problems on the DMX line for now. if (_dmxMode == DMXController) { digitalWrite(_dmxModePin, DmxModeOut); // data Out direction _dmxMaxChannel = 32; // The default in Controller mode is sending 32 channels. _DMXStartSending(); } else if (_dmxMode == DMXReceiver) { // Setup Hardware _DMXStartReceiving(); // } else if (_dmxMode == DMXProbe) { // // don't setup the Hardware now } // if } // if } // init() // Set the maximum used channel. // This method can be called any time before or after the init() method. void DMXSerialClass::maxChannel(int channel) { if (channel < 1) channel = 1; if (channel > DMXSERIAL_MAX) channel = DMXSERIAL_MAX; _dmxMaxChannel = channel; _dmxDataLastPtr = _dmxData + channel; } // maxChannel // Read the current value of a channel. uint8_t DMXSerialClass::read(int channel) { // adjust parameter if (channel < 1) channel = 1; if (channel > DMXSERIAL_MAX) channel = DMXSERIAL_MAX; // read value from buffer return (_dmxData[channel]); } // read() // Write the value into the channel. // The value is just stored in the sending buffer and will be picked up // by the DMX sending interrupt routine. void DMXSerialClass::write(int channel, uint8_t value) { // adjust parameters if (channel < 1) channel = 1; if (channel > DMXSERIAL_MAX) channel = DMXSERIAL_MAX; if (value < 0) value = 0; if (value > 255) value = 255; // store value for later sending _dmxData[channel] = value; // Make sure we transmit enough channels for the ones used if (channel > _dmxMaxChannel) { _dmxMaxChannel = channel; _dmxDataLastPtr = _dmxData + _dmxMaxChannel; } // if } // write() // Return the DMX buffer for un-save direct but faster access uint8_t *DMXSerialClass::getBuffer() { return (_dmxData); } // getBuffer() // Calculate how long no data packet was received unsigned long DMXSerialClass::noDataSince() { unsigned long now = millis(); return (now - _dmxLastPacket); } // noDataSince() // return true when some DMX data was updated. bool DMXSerialClass::dataUpdated() { return (_dmxUpdated); } // reset DMX data update flag. void DMXSerialClass::resetUpdated() { _dmxUpdated = false; } // When mode is DMXProbe this function reads one DMX buffer and then returns. // wait a meaningful time on a packet. // return true when a packet has been received. bool DMXSerialClass::receive() { return (receive(DMXPROBE_RECV_MAX)); } // receive() // When mode is DMXProbe this function reads one DMX buffer and then returns. // wait approximately gives the number of msecs for waiting on a packet. // return true when a packet has been received. bool DMXSerialClass::receive(uint8_t wait) { bool ret = false; if (_dmxMode == DMXProbe) { _DMXStartReceiving(); // UCSRnA while ((wait > 0) && (_dmxRecvState != DONE)) { delay(1); wait--; } // while if (_dmxRecvState == DONE) { ret = true; } else { _DMX_setMode(DMXUARTMode::RONLY); } // if } // if return (ret); } // receive(wait) // Terminate operation void DMXSerialClass::term(void) { // Disable all USART Features, including Interrupts _DMX_setMode(DMXUARTMode::OFF); } // term() // ----- internal functions and interrupt implementations ----- // Setup Hardware for Sending void _DMXStartSending() { // Start sending a BREAK and send more bytes in UDRE ISR // Enable transmitter and interrupt _DMX_setMode(DMXUARTMode::TBREAK); _DMX_writeByte((uint8_t)0); } // _DMXStartSending() // Setup Hardware for Receiving void _DMXStartReceiving() { uint8_t voiddata; // Enable receiver and Receive interrupt _dmxDataPtr = _dmxData; _dmxRecvState = STARTUP; _DMX_setMode(DMXUARTMode::RDATA); _DMX_flush(); } // _DMXStartReceiving() // This function is called by the Interrupt Service Routine when a byte or frame error was received. // In DMXController mode this interrupt is disabled and will not occur. // In DMXReceiver mode when a byte was received it is stored to the dmxData buffer. void _DMXReceived(uint8_t data, uint8_t frameerror) { uint8_t DmxState = _dmxRecvState; //just load once from SRAM to increase speed if (DmxState == STARTUP) { // just ignore any first frame comming in _dmxRecvState = IDLE; return; } if (frameerror) { //check for break // break condition detected. _dmxRecvState = BREAK; _dmxDataPtr = _dmxData; } else if (DmxState == BREAK) { // first byte after a break was read. if (data == 0) { // normal DMX start code (0) detected _dmxRecvState = DATA; _dmxLastPacket = millis(); // remember current (relative) time in msecs. _dmxDataPtr++; // start saving data with channel # 1 } else { // This might be a RDM or customer DMX command -> not implemented so wait for next BREAK ! _dmxRecvState = DONE; } // if } else if (DmxState == DATA) { // check for new data if (*_dmxDataPtr != data) { _dmxUpdated = true; // store received data into dmx data buffer. *_dmxDataPtr = data; } // if _dmxDataPtr++; if (_dmxDataPtr > _dmxDataLastPtr) { // all channels received. _dmxRecvState = DONE; } // if } // if if (_dmxRecvState == DONE) { if (_dmxMode == DMXProbe) { // stop creating interrupts on the serial port for now. _DMX_setMode(DMXUARTMode::RONLY); } else { // continue on DMXReceiver mode. _dmxRecvState = IDLE; // wait for next break } } // if } // _DMXReceived() // This function is called by the Transmission complete or Data Register empty interrupt routine. // When changing speed (after sending BREAK) we use TX finished interrupt that occurs shortly after the last stop bit is sent // When staying at the same speed (sending data bytes) we use data register empty interrupt that occurs shortly after the start bit of the *previous* byte // When sending a DMX sequence it just takes the next channel byte and sends it out. // In DMXController mode when the buffer was sent completely the DMX sequence will resent, starting with a BREAK pattern. // In DMXReceiver mode this interrupt is disabled and will not occur. void _DMXTransmitted() { if ((_dmxMode == DMXController) && (_dmxChannel == -1)) { // this occurs after the stop bits of the last data byte // start sending a BREAK and loop forever in ISR _DMX_setMode(DMXUARTMode::TBREAK); _DMX_writeByte((uint8_t)0); _dmxChannel = 0; // next time send start byte } else if (_dmxChannel == 0) { // this occurs after the stop bits of the break byte // now back to DMX speed: 250000baud // take next interrupt when data register empty (early) _DMX_setMode(DMXUARTMode::TDATA); // write start code _DMX_writeByte((uint8_t)0); _dmxChannel = 1; } else { _DMX_writeByte(_dmxData[_dmxChannel++]); if (_dmxChannel > _dmxMaxChannel) { _dmxChannel = -1; // this series is done. Next time: restart with break. _DMX_setMode(DMXUARTMode::TDONE); } // if } // if } // _DMXTransmitted // The End
// - - - - - // DMXSerial - A Arduino library for sending and receiving DMX using the builtin serial hardware port. // DMXSerial.cpp: Library implementation file // // Copyright (c) 2011-2020 by Matthias Hertel, http://www.mathertel.de // This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx // // Documentation and samples are available at http://www.mathertel.de/Arduino // Changelog: See DMXSerial.h // - - - - - #include "Arduino.h" #include "DMXSerial.h" // ----- forwards ----- void _DMXStartSending(); void _DMXStartReceiving(); // register interrupt for receiving data and frameerrors that calls _DMXReceived() void _DMXReceived(uint8_t data, uint8_t frameerror); void _DMXTransmitted(); // These functions all exist in the processor specific implementations: void _DMX_init(); void _DMX_setMode(); void _DMX_writeByte(uint8_t data); void _DMX_flush(); // ----- Serial UART Modes ----- // There are 4 different modes required while receiving and sending DMX using the Serial // State of receiving DMX Bytes typedef enum { OFF = 0, // Turn off RONLY = 1, // Receive DMX data only RDATA = 2, // Receive DMX data + Interrupt TBREAK = 3, // Transmit DMX Break + Interrupt on Transmission completed TDATA = 4, // Transmit DMX Data + Interrupt on Register empty TDONE = 5 // Transmit DMX Data + Interrupt on Transmission completed } __attribute__((packed)) DMXUARTMode; // Baud rate for DMX protocol #define DMXSPEED 250000L // the break timing is 10 bits (start + 8 data + 1 (even) parity) of this speed // the mark-after-break is 1 bit of this speed plus approx 6 usec // 100000 bit/sec is good: gives 100 usec break and 16 usec MAB // 1990 spec says transmitter must send >= 92 usec break and >= 12 usec MAB // receiver must accept 88 us break and 8 us MAB #define BREAKSPEED 100000L #define BREAKFORMAT SERIAL_8E2 #define DMXFORMAT SERIAL_8N2 #define DMXREADFORMAT SERIAL_8N1 // ----- include processor specific definitions and functions. #if defined(ARDUINO_ARCH_AVR) #include "DMXSerial_avr.h" #elif defined(ARDUINO_ARCH_MEGAAVR) #include "DMXSerial_megaavr.h" #endif // ----- Enumerations ----- // State of receiving DMX Bytes typedef enum { STARTUP = 1, // wait for any interrupt BEFORE starting analyzing the DMX protocoll. IDLE = 2, // wait for a BREAK condition. BREAK = 3, // BREAK was detected. DATA = 4, // DMX data. DONE = 5 // All channels received. } __attribute__((packed)) DMXReceivingState; // ----- DMXSerial Private variables ----- // These variables are not class members because they have to be reached by the interrupt implementations. // don't use these variable from outside, use the appropriate methods. DMXMode _dmxMode; // Mode of Operation int _dmxModePin; // pin used for I/O direction. uint8_t _dmxRecvState; // Current State of receiving DMX Bytes int _dmxChannel; // the next channel byte to be sent. volatile unsigned int _dmxMaxChannel = 32; // the last channel used for sending (1..32). volatile unsigned long _dmxLastPacket = 0; // the last time (using the millis function) a packet was received. bool _dmxUpdated = true; // is set to true when new data arrived. // Array of DMX values (raw). // Entry 0 will never be used for DMX data but will store the startbyte (0 for DMX mode). uint8_t _dmxData[DMXSERIAL_MAX + 1]; // This pointer will point to the next byte in _dmxData; uint8_t *_dmxDataPtr; // This pointer will point to the last byte in _dmxData; uint8_t *_dmxDataLastPtr; // Create a single class instance. Multiple class instances (multiple simultaneous DMX ports) are not supported. DMXSerialClass DMXSerial; // ----- Class implementation ----- // Initialize the specified mode. void DMXSerialClass::init(int mode) { init(mode, DMXMODEPIN); } // (Re)Initialize the specified mode. // The mode parameter should be a value from enum DMXMode. void DMXSerialClass::init(int mode, int dmxModePin) { // initialize global variables _dmxMode = DMXNone; _dmxModePin = dmxModePin; _dmxRecvState = STARTUP; // initial state _dmxChannel = 0; _dmxDataPtr = _dmxData; _dmxLastPacket = millis(); // remember current (relative) time in msecs. _dmxMaxChannel = DMXSERIAL_MAX; // The default in Receiver mode is reading all possible 512 channels. _dmxDataLastPtr = _dmxData + _dmxMaxChannel; // initialize the DMX buffer // memset(_dmxData, 0, sizeof(_dmxData)); for (int n = 0; n < DMXSERIAL_MAX + 1; n++) _dmxData[n] = 0; // now start _dmxMode = (DMXMode)mode; if ((_dmxMode == DMXController) || (_dmxMode == DMXReceiver) || (_dmxMode == DMXProbe)) { // a valid mode was given // Setup external mode signal _DMX_init(); pinMode(_dmxModePin, OUTPUT); // enables the pin for output to control data direction digitalWrite(_dmxModePin, DmxModeIn); // data in direction, to avoid problems on the DMX line for now. if (_dmxMode == DMXController) { digitalWrite(_dmxModePin, DmxModeOut); // data Out direction _dmxMaxChannel = 32; // The default in Controller mode is sending 32 channels. _DMXStartSending(); } else if (_dmxMode == DMXReceiver) { // Setup Hardware _DMXStartReceiving(); // } else if (_dmxMode == DMXProbe) { // // don't setup the Hardware now } // if } // if } // init() // Set the maximum used channel. // This method can be called any time before or after the init() method. void DMXSerialClass::maxChannel(int channel) { if (channel < 1) channel = 1; if (channel > DMXSERIAL_MAX) channel = DMXSERIAL_MAX; _dmxMaxChannel = channel; _dmxDataLastPtr = _dmxData + channel; } // maxChannel // Read the current value of a channel. uint8_t DMXSerialClass::read(int channel) { // adjust parameter if (channel < 1) channel = 1; if (channel > DMXSERIAL_MAX) channel = DMXSERIAL_MAX; // read value from buffer return (_dmxData[channel]); } // read() // Write the value into the channel. // The value is just stored in the sending buffer and will be picked up // by the DMX sending interrupt routine. void DMXSerialClass::write(int channel, uint8_t value) { // adjust parameters if (channel < 1) channel = 1; if (channel > DMXSERIAL_MAX) channel = DMXSERIAL_MAX; if (value < 0) value = 0; if (value > 255) value = 255; // store value for later sending _dmxData[channel] = value; // Make sure we transmit enough channels for the ones used if (channel > _dmxMaxChannel) { _dmxMaxChannel = channel; _dmxDataLastPtr = _dmxData + _dmxMaxChannel; } // if } // write() // Return the DMX buffer for un-save direct but faster access uint8_t *DMXSerialClass::getBuffer() { return (_dmxData); } // getBuffer() // Calculate how long no data packet was received unsigned long DMXSerialClass::noDataSince() { unsigned long now = millis(); return (now - _dmxLastPacket); } // noDataSince() // return true when some DMX data was updated. bool DMXSerialClass::dataUpdated() { return (_dmxUpdated); } // reset DMX data update flag. void DMXSerialClass::resetUpdated() { _dmxUpdated = false; } // When mode is DMXProbe this function reads one DMX buffer and then returns. // wait a meaningful time on a packet. // return true when a packet has been received. bool DMXSerialClass::receive() { return (receive(DMXPROBE_RECV_MAX)); } // receive() // When mode is DMXProbe this function reads one DMX buffer and then returns. // wait approximately gives the number of msecs for waiting on a packet. // return true when a packet has been received. bool DMXSerialClass::receive(uint8_t wait) { bool ret = false; if (_dmxMode == DMXProbe) { _DMXStartReceiving(); // UCSRnA while ((wait > 0) && (_dmxRecvState != DONE)) { delay(1); wait--; } // while if (_dmxRecvState == DONE) { ret = true; } else { _DMX_setMode(DMXUARTMode::RONLY); } // if } // if return (ret); } // receive(wait) // Terminate operation void DMXSerialClass::term(void) { // Disable all USART Features, including Interrupts _DMX_setMode(DMXUARTMode::OFF); } // term() // ----- internal functions and interrupt implementations ----- // Setup Hardware for Sending void _DMXStartSending() { // Start sending a BREAK and send more bytes in UDRE ISR // Enable transmitter and interrupt _DMX_setMode(DMXUARTMode::TBREAK); _DMX_writeByte((uint8_t)0); } // _DMXStartSending() // Setup Hardware for Receiving void _DMXStartReceiving() { uint8_t voiddata; // Enable receiver and Receive interrupt _dmxDataPtr = _dmxData; _dmxRecvState = STARTUP; _DMX_setMode(DMXUARTMode::RDATA); _DMX_flush(); } // _DMXStartReceiving() // This function is called by the Interrupt Service Routine when a byte or frame error was received. // In DMXController mode this interrupt is disabled and will not occur. // In DMXReceiver mode when a byte was received it is stored to the dmxData buffer. void _DMXReceived(uint8_t data, uint8_t frameerror) { uint8_t DmxState = _dmxRecvState; //just load once from SRAM to increase speed if (DmxState == STARTUP) { // just ignore any first frame comming in _dmxRecvState = IDLE; return; } if (frameerror) { //check for break // break condition detected. _dmxRecvState = BREAK; _dmxDataPtr = _dmxData; } else if (DmxState == BREAK) { // first byte after a break was read. if (data == 0) { // normal DMX start code (0) detected _dmxRecvState = DATA; _dmxLastPacket = millis(); // remember current (relative) time in msecs. _dmxDataPtr++; // start saving data with channel # 1 } else { // This might be a RDM or customer DMX command -> not implemented so wait for next BREAK ! _dmxRecvState = DONE; } // if } else if (DmxState == DATA) { // check for new data if (*_dmxDataPtr != data) { _dmxUpdated = true; // store received data into dmx data buffer. *_dmxDataPtr = data; } // if _dmxDataPtr++; if (_dmxDataPtr > _dmxDataLastPtr) { // all channels received. _dmxRecvState = DONE; } // if } // if if (_dmxRecvState == DONE) { if (_dmxMode == DMXProbe) { // stop creating interrupts on the serial port for now. _DMX_setMode(DMXUARTMode::RONLY); } else { // continue on DMXReceiver mode. _dmxRecvState = IDLE; // wait for next break } } // if } // _DMXReceived() // This function is called by the Transmission complete or Data Register empty interrupt routine. // When changing speed (after sending BREAK) we use TX finished interrupt that occurs shortly after the last stop bit is sent // When staying at the same speed (sending data bytes) we use data register empty interrupt that occurs shortly after the start bit of the *previous* byte // When sending a DMX sequence it just takes the next channel byte and sends it out. // In DMXController mode when the buffer was sent completely the DMX sequence will resent, starting with a BREAK pattern. // In DMXReceiver mode this interrupt is disabled and will not occur. void _DMXTransmitted() { if ((_dmxMode == DMXController) && (_dmxChannel == -1)) { // this occurs after the stop bits of the last data byte // start sending a BREAK and loop forever in ISR _DMX_setMode(DMXUARTMode::TBREAK); _DMX_writeByte((uint8_t)0); _dmxChannel = 0; // next time send start byte } else if (_dmxChannel == 0) { // this occurs after the stop bits of the break byte // now back to DMX speed: 250000baud // take next interrupt when data register empty (early) _DMX_setMode(DMXUARTMode::TDATA); // write start code _DMX_writeByte((uint8_t)0); _dmxChannel = 1; } else { if (_dmxChannel < _dmxMaxChannel) { // just send the next data _DMX_writeByte(_dmxData[_dmxChannel++]); } else { // last data _DMX_setMode(DMXUARTMode::TDONE); _DMX_writeByte(_dmxData[_dmxChannel]); _dmxChannel = -1; // this series is done. Next time: restart with break. _DMX_setMode(DMXUARTMode::TDONE); } // if } // if } // _DMXTransmitted // The End
set mode before write
set mode before write
C++
bsd-3-clause
mathertel/DMXSerial,mathertel/DMXSerial
2b213e4a24d9e985c93600889e5f68d65e248e34
fnord-dproc/LocalScheduler.cc
fnord-dproc/LocalScheduler.cc
/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <fnord-base/io/file.h> #include <fnord-base/io/fileutil.h> #include <fnord-base/io/mmappedfile.h> #include <fnord-base/logging.h> #include <fnord-base/io/fileutil.h> #include <fnord-dproc/LocalScheduler.h> namespace fnord { namespace dproc { LocalScheduler::LocalScheduler( const String& tempdir /* = "/tmp" */, size_t max_threads /* = 8 */, size_t max_requests /* = 32 */) : tempdir_(tempdir), tpool_(max_threads), req_tpool_(max_requests) {} void LocalScheduler::start() { req_tpool_.start(); tpool_.start(); } void LocalScheduler::stop() { req_tpool_.stop(); tpool_.stop(); } RefPtr<TaskResult> LocalScheduler::run( RefPtr<Application> app, const TaskSpec& task) { RefPtr<TaskResult> result(new TaskResult()); try { auto instance = mkRef( new LocalTaskRef( app, task.task_name(), Buffer(task.params().data(), task.params().size()))); req_tpool_.run([this, app, result, instance] () { try { LocalTaskPipeline pipeline; pipeline.tasks.push_back(instance); run(app.get(), &pipeline); result->returnResult( new io::MmappedFile( File::openFile(instance->output_filename, File::O_READ))); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } }); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } return result; } void LocalScheduler::run( Application* app, LocalTaskPipeline* pipeline) { fnord::logInfo( "fnord.dproc", "Starting local pipeline id=$0 tasks=$1", (void*) pipeline, pipeline->tasks.size()); std::unique_lock<std::mutex> lk(pipeline->mutex); while (pipeline->tasks.size() > 0) { bool waiting = true; size_t num_waiting = 0; size_t num_running = 0; size_t num_completed = 0; for (auto& taskref : pipeline->tasks) { if (taskref->finished) { ++num_completed; continue; } if (taskref->running) { ++num_running; continue; } if (!taskref->expanded) { taskref->expanded = true; auto parent_task = taskref; for (const auto& dep : taskref->task->dependencies()) { RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params)); parent_task->dependencies.emplace_back(depref); pipeline->tasks.emplace_back(depref); } waiting = false; break; } bool deps_finished = true; for (const auto& dep : taskref->dependencies) { if (!dep->finished) { deps_finished = false; } } if (!deps_finished) { ++num_waiting; continue; } taskref->running = true; tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref)); waiting = false; } fnord::logInfo( "fnord.dproc", "Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4", (void*) pipeline, pipeline->tasks.size(), num_running, num_waiting, num_completed); if (waiting) { pipeline->wakeup.wait(lk); } while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) { pipeline->tasks.pop_back(); } } fnord::logInfo( "fnord.dproc", "Completed local pipeline id=$0", (void*) pipeline); } void LocalScheduler::runTask( LocalTaskPipeline* pipeline, RefPtr<LocalTaskRef> task) { auto cache_key = task->task->cacheKey(); String output_file; if (cache_key.isEmpty()) { auto tmpid = Random::singleton()->hex128(); output_file = FileUtil::joinPaths( tempdir_, StringUtil::format("tmp_$0", tmpid)); } else { output_file = FileUtil::joinPaths( tempdir_, StringUtil::format("cache_$0", cache_key.get())); } auto cached = !cache_key.isEmpty() && FileUtil::exists(output_file); fnord::logDebug( "fnord.dproc", "Running task: $0 (cached=$1)", task->debug_name, cached); if (!cached) { try { auto res = task->task->run(task.get()); auto file = File::openFile( output_file + "~", File::O_CREATEOROPEN | File::O_WRITE); file.write(res->data(), res->size()); FileUtil::mv(output_file + "~", output_file); } catch (const std::exception& e) { fnord::logError("fnord.dproc", e, "error"); } } std::unique_lock<std::mutex> lk(pipeline->mutex); task->output_filename = output_file; task->finished = true; lk.unlock(); pipeline->wakeup.notify_all(); } LocalScheduler::LocalTaskRef::LocalTaskRef( RefPtr<Application> app, const String& task_name, const Buffer& params) : task(app->getTaskInstance(task_name, params)), debug_name(StringUtil::format("$0#$1", app->name(), task_name)), running(false), expanded(false), finished(false) {} RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) { if (index >= dependencies.size()) { RAISEF(kIndexError, "invalid dependecy index: $0", index); } const auto& dep = dependencies[index]; if (!FileUtil::exists(dep->output_filename)) { RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename); } return RefPtr<VFSFile>( new io::MmappedFile( File::openFile(dep->output_filename, File::O_READ))); } size_t LocalScheduler::LocalTaskRef::numDependencies() const { return dependencies.size(); } } // namespace dproc } // namespace fnord
/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <fnord-base/io/file.h> #include <fnord-base/io/fileutil.h> #include <fnord-base/io/mmappedfile.h> #include <fnord-base/logging.h> #include <fnord-base/io/fileutil.h> #include <fnord-dproc/LocalScheduler.h> namespace fnord { namespace dproc { LocalScheduler::LocalScheduler( const String& tempdir /* = "/tmp" */, size_t max_threads /* = 8 */, size_t max_requests /* = 32 */) : tempdir_(tempdir), tpool_(max_threads), req_tpool_(max_requests) {} void LocalScheduler::start() { req_tpool_.start(); tpool_.start(); } void LocalScheduler::stop() { req_tpool_.stop(); tpool_.stop(); } RefPtr<TaskResult> LocalScheduler::run( RefPtr<Application> app, const TaskSpec& task) { RefPtr<TaskResult> result(new TaskResult()); try { auto instance = mkRef( new LocalTaskRef( app, task.task_name(), Buffer(task.params().data(), task.params().size()))); req_tpool_.run([this, app, result, instance] () { try { LocalTaskPipeline pipeline; pipeline.tasks.push_back(instance); run(app.get(), &pipeline); result->returnResult( new io::MmappedFile( File::openFile(instance->output_filename, File::O_READ))); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } }); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } return result; } void LocalScheduler::run( Application* app, LocalTaskPipeline* pipeline) { fnord::logInfo( "fnord.dproc", "Starting local pipeline id=$0 tasks=$1", (void*) pipeline, pipeline->tasks.size()); std::unique_lock<std::mutex> lk(pipeline->mutex); while (pipeline->tasks.size() > 0) { bool waiting = true; size_t num_waiting = 0; size_t num_running = 0; size_t num_completed = 0; for (auto& taskref : pipeline->tasks) { if (taskref->finished) { ++num_completed; continue; } if (taskref->running) { ++num_running; continue; } if (!taskref->expanded) { taskref->expanded = true; auto cache_key = taskref->task->cacheKey(); if (cache_key.isEmpty()) { auto tmpid = Random::singleton()->hex128(); taskref->output_filename = FileUtil::joinPaths( tempdir_, StringUtil::format("tmp_$0", tmpid)); } else { taskref->output_filename = FileUtil::joinPaths( tempdir_, StringUtil::format("cache_$0", cache_key.get())); } auto cached = !cache_key.isEmpty() && FileUtil::exists(taskref->output_filename); if (cached) { fnord::logDebug( "fnord.dproc", "Running task [cached]: $0", taskref->debug_name); taskref->finished = true; continue; } auto parent_task = taskref; for (const auto& dep : taskref->task->dependencies()) { RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params)); parent_task->dependencies.emplace_back(depref); pipeline->tasks.emplace_back(depref); } waiting = false; break; } bool deps_finished = true; for (const auto& dep : taskref->dependencies) { if (!dep->finished) { deps_finished = false; } } if (!deps_finished) { ++num_waiting; continue; } fnord::logDebug("fnord.dproc", "Running task: $0", taskref->debug_name); taskref->running = true; tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref)); waiting = false; } fnord::logInfo( "fnord.dproc", "Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4", (void*) pipeline, pipeline->tasks.size(), num_running, num_waiting, num_completed); if (waiting) { pipeline->wakeup.wait(lk); } while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) { pipeline->tasks.pop_back(); } } fnord::logInfo( "fnord.dproc", "Completed local pipeline id=$0", (void*) pipeline); } void LocalScheduler::runTask( LocalTaskPipeline* pipeline, RefPtr<LocalTaskRef> task) { auto output_file = task->output_filename; try { auto res = task->task->run(task.get()); auto file = File::openFile( output_file + "~", File::O_CREATEOROPEN | File::O_WRITE); file.write(res->data(), res->size()); FileUtil::mv(output_file + "~", output_file); } catch (const std::exception& e) { fnord::logError("fnord.dproc", e, "error"); } std::unique_lock<std::mutex> lk(pipeline->mutex); task->finished = true; lk.unlock(); pipeline->wakeup.notify_all(); } LocalScheduler::LocalTaskRef::LocalTaskRef( RefPtr<Application> app, const String& task_name, const Buffer& params) : task(app->getTaskInstance(task_name, params)), debug_name(StringUtil::format("$0#$1", app->name(), task_name)), running(false), expanded(false), finished(false) {} RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) { if (index >= dependencies.size()) { RAISEF(kIndexError, "invalid dependecy index: $0", index); } const auto& dep = dependencies[index]; if (!FileUtil::exists(dep->output_filename)) { RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename); } return RefPtr<VFSFile>( new io::MmappedFile( File::openFile(dep->output_filename, File::O_READ))); } size_t LocalScheduler::LocalTaskRef::numDependencies() const { return dependencies.size(); } } // namespace dproc } // namespace fnord
check cache before expanding deps
check cache before expanding deps
C++
agpl-3.0
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
0694bfc93d9535818603cd529bb22d75d7524153
auditd/src/testauditd.cc
auditd/src/testauditd.cc
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2014 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <iostream> #include <fstream> #include <sstream> #include <limits.h> #include <cJSON.h> #include <platform/dirutils.h> #include "memcached/extension.h" #include "memcached/extension_loggers.h" #include "memcached/audit_interface.h" #include "auditd.h" int main (int argc, char *argv[]) { #ifdef WIN32 #define sleep(a) Sleep(a * 1000) #endif /* create the test directory */ if (!CouchbaseDirectoryUtilities::isDirectory(std::string("test"))) { #ifdef WIN32 if (!CreateDirectory("test", NULL)) { #else if (mkdir("test", S_IREAD | S_IWRITE | S_IEXEC) != 0) { #endif std::cerr << "error, unable to create directory" << std::endl; return -1; } } /* create the test_audit.json file */ cJSON *config_json = cJSON_CreateObject(); if (config_json == NULL) { std::cerr << "error, unable to create object" << std::endl; return -1; } std::stringstream descriptors_path; descriptors_path << DESTINATION_ROOT << DIRECTORY_SEPARATOR_CHARACTER << "etc" << DIRECTORY_SEPARATOR_CHARACTER << "security"; cJSON_AddNumberToObject(config_json, "version", 1); cJSON_AddFalseToObject(config_json,"auditd_enabled"); cJSON_AddNumberToObject(config_json, "rotate_interval", 1); cJSON_AddStringToObject(config_json, "log_path", "test"); cJSON_AddStringToObject(config_json, "archive_path", "test"); cJSON_AddStringToObject(config_json, "descriptors_path", descriptors_path.str().c_str()); cJSON *disabled_arr = cJSON_CreateArray(); if (disabled_arr == NULL) { std::cerr << "error, unable to create int array" << std::endl; return -1; } cJSON_AddItemToObject(config_json, "disabled", disabled_arr); cJSON *sync_arr = cJSON_CreateArray(); if (sync_arr == NULL) { std::cerr << "error, unable to create array" << std::endl; return -1; } cJSON_AddItemToObject(config_json, "sync", sync_arr); std::stringstream audit_fname; audit_fname << "test_audit.json"; std::ofstream configfile; configfile.open(audit_fname.str().c_str(), std::ios::out | std::ios::binary); if (!configfile.is_open()) { std::cerr << "error, unable to create test_audit.json" << std::endl; return -1; } char *data = cJSON_Print(config_json); assert(data != NULL); configfile << data; configfile.close(); /*create the test1_audit.json file */ //cJSON_ReplaceItemInObject(config_json, "rotate_interval", cJSON_CreateNumber(3.0)); cJSON_DeleteItemFromObject(config_json, "auditd_enabled"); cJSON_AddTrueToObject(config_json,"auditd_enabled"); std::stringstream audit_fname1; audit_fname1 << "test1_audit.json"; configfile.open(audit_fname1.str().c_str(), std::ios::out | std::ios::binary); if (!configfile.is_open()) { std::cerr << "error, unable to create test1_audit.json" << std::endl; return -1; } data = cJSON_Print(config_json); assert(data != NULL); configfile << data; configfile.close(); AUDIT_EXTENSION_DATA audit_extension_data; audit_extension_data.version = 1; audit_extension_data.min_file_rotation_time = 1; audit_extension_data.max_file_rotation_time = 604800; // 1 week = 60*60*24*7 audit_extension_data.log_extension = get_stderr_logger(); /* start the tests */ if (start_auditdaemon(&audit_extension_data) != AUDIT_SUCCESS) { std::cerr << "start audit daemon: FAILED" << std::endl; return -1; } else { std::cerr << "start audit daemon: SUCCESS\n" << std::endl; } if (configure_auditdaemon(audit_fname.str().c_str()) != AUDIT_SUCCESS) { std::cerr << "initialize audit daemon: FAILED" << std::endl; return -1; } else { std::cerr << "initialize audit daemon: SUCCESS\n" << std::endl; } /* sleep is used to ensure get to cb_cond_wait(&events_arrived, &producer_consumer_lock); */ /* will also give time to rotate */ sleep(2); if (configure_auditdaemon(audit_fname1.str().c_str()) != AUDIT_SUCCESS) { std::cerr << "reload: FAILED" << std::endl; return -1; } else { std::cerr << "reload: SUCCESS\n" << std::endl; } sleep(4); if (shutdown_auditdaemon(audit_fname1.str().c_str()) != AUDIT_SUCCESS) { std::cerr << "shutdown audit daemon: FAILED" << std::endl; return -1; } else { std::cerr << "shutdown audit daemon: SUCCESS" << std::endl; } return 0; }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2014 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <iostream> #include <fstream> #include <sstream> #include <limits.h> #include <cJSON.h> #include <platform/dirutils.h> #include "memcached/extension.h" #include "memcached/extension_loggers.h" #include "memcached/audit_interface.h" #include "auditd.h" int main (int argc, char *argv[]) { #ifdef WIN32 #define sleep(a) Sleep(a * 1000) #endif /* create the test directory */ if (!CouchbaseDirectoryUtilities::isDirectory(std::string("test"))) { #ifdef WIN32 if (!CreateDirectory("test", NULL)) { #else if (mkdir("test", S_IREAD | S_IWRITE | S_IEXEC) != 0) { #endif std::cerr << "error, unable to create directory" << std::endl; return -1; } } /* create the test_audit.json file */ cJSON *config_json = cJSON_CreateObject(); if (config_json == NULL) { std::cerr << "error, unable to create object" << std::endl; return -1; } cJSON_AddNumberToObject(config_json, "version", 1); cJSON_AddFalseToObject(config_json,"auditd_enabled"); cJSON_AddNumberToObject(config_json, "rotate_interval", 1); cJSON_AddStringToObject(config_json, "log_path", "test"); cJSON_AddStringToObject(config_json, "archive_path", "test"); cJSON_AddStringToObject(config_json, "descriptors_path", "."); cJSON *disabled_arr = cJSON_CreateArray(); if (disabled_arr == NULL) { std::cerr << "error, unable to create int array" << std::endl; return -1; } cJSON_AddItemToObject(config_json, "disabled", disabled_arr); cJSON *sync_arr = cJSON_CreateArray(); if (sync_arr == NULL) { std::cerr << "error, unable to create array" << std::endl; return -1; } cJSON_AddItemToObject(config_json, "sync", sync_arr); std::stringstream audit_fname; audit_fname << "test_audit.json"; std::ofstream configfile; configfile.open(audit_fname.str().c_str(), std::ios::out | std::ios::binary); if (!configfile.is_open()) { std::cerr << "error, unable to create test_audit.json" << std::endl; return -1; } char *data = cJSON_Print(config_json); assert(data != NULL); configfile << data; configfile.close(); /*create the test1_audit.json file */ //cJSON_ReplaceItemInObject(config_json, "rotate_interval", cJSON_CreateNumber(3.0)); cJSON_DeleteItemFromObject(config_json, "auditd_enabled"); cJSON_AddTrueToObject(config_json,"auditd_enabled"); std::stringstream audit_fname1; audit_fname1 << "test1_audit.json"; configfile.open(audit_fname1.str().c_str(), std::ios::out | std::ios::binary); if (!configfile.is_open()) { std::cerr << "error, unable to create test1_audit.json" << std::endl; return -1; } data = cJSON_Print(config_json); assert(data != NULL); configfile << data; configfile.close(); AUDIT_EXTENSION_DATA audit_extension_data; audit_extension_data.version = 1; audit_extension_data.min_file_rotation_time = 1; audit_extension_data.max_file_rotation_time = 604800; // 1 week = 60*60*24*7 audit_extension_data.log_extension = get_stderr_logger(); /* start the tests */ if (start_auditdaemon(&audit_extension_data) != AUDIT_SUCCESS) { std::cerr << "start audit daemon: FAILED" << std::endl; return -1; } else { std::cerr << "start audit daemon: SUCCESS\n" << std::endl; } if (configure_auditdaemon(audit_fname.str().c_str()) != AUDIT_SUCCESS) { std::cerr << "initialize audit daemon: FAILED" << std::endl; return -1; } else { std::cerr << "initialize audit daemon: SUCCESS\n" << std::endl; } /* sleep is used to ensure get to cb_cond_wait(&events_arrived, &producer_consumer_lock); */ /* will also give time to rotate */ sleep(2); if (configure_auditdaemon(audit_fname1.str().c_str()) != AUDIT_SUCCESS) { std::cerr << "reload: FAILED" << std::endl; return -1; } else { std::cerr << "reload: SUCCESS\n" << std::endl; } sleep(4); if (shutdown_auditdaemon(audit_fname1.str().c_str()) != AUDIT_SUCCESS) { std::cerr << "shutdown audit daemon: FAILED" << std::endl; return -1; } else { std::cerr << "shutdown audit daemon: SUCCESS" << std::endl; } return 0; }
Fix unit test failure
MB-13419: Fix unit test failure Change-Id: If2912985a60c79ad62a7d358c9ce32af1f0529eb Reviewed-on: http://review.couchbase.org/46738 Reviewed-by: Trond Norbye <[email protected]> Tested-by: Trond Norbye <[email protected]>
C++
bsd-3-clause
couchbase/memcached,daverigby/kv_engine,couchbase/memcached,owendCB/memcached,owendCB/memcached,owendCB/memcached,daverigby/memcached,owendCB/memcached,cloudrain21/memcached-1,cloudrain21/memcached-1,couchbase/memcached,daverigby/memcached,mrkwse/memcached,mrkwse/memcached,cloudrain21/memcached-1,daverigby/kv_engine,daverigby/kv_engine,daverigby/memcached,mrkwse/memcached,cloudrain21/memcached-1,couchbase/memcached,mrkwse/memcached,daverigby/memcached,daverigby/kv_engine
e5c8f5f684e68d7a6688148ac3850d5484eb24ff
test/Driver/XRay/xray-shared-noxray.cpp
test/Driver/XRay/xray-shared-noxray.cpp
// RUN: %clangxx -shared -fPIC -o /dev/null -v -fxray-instrument %s 2>&1 | \ // RUN: FileCheck %s --check-prefix=SHARED // RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s 2>&1 -DMAIN | \ // RUN: FileCheck %s --check-prefix=STATIC // // SHARED-NOT: {{clang_rt\.xray-}} // STATIC: {{clang_rt\.xray-}} // // REQUIRES: linux int foo() { return 42; } #ifdef MAIN int main() { return foo(); } #endif
// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s 2>&1 | \ // RUN: FileCheck %s --check-prefix=SHARED // RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s 2>&1 -DMAIN | \ // RUN: FileCheck %s --check-prefix=STATIC // // SHARED-NOT: {{clang_rt\.xray-}} // STATIC: {{clang_rt\.xray-}} // // REQUIRES: linux int foo() { return 42; } #ifdef MAIN int main() { return foo(); } #endif
Remove -fPIC from shared build test.
[XRay] Remove -fPIC from shared build test. Follow-up to D38226. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@314190 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang
17cf5a9c162cf1af4e2a9f45eec51a91b690d7cf
lib/ReaderWriter/PECOFF/PECOFFLinkingContext.cpp
lib/ReaderWriter/PECOFF/PECOFFLinkingContext.cpp
//===- lib/ReaderWriter/PECOFF/PECOFFLinkingContext.cpp -------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Atoms.h" #include "EdataPass.h" #include "GroupedSectionsPass.h" #include "IdataPass.h" #include "LinkerGeneratedSymbolFile.h" #include "SetSubsystemPass.h" #include "lld/Core/PassManager.h" #include "lld/Passes/LayoutPass.h" #include "lld/Passes/RoundTripNativePass.h" #include "lld/Passes/RoundTripYAMLPass.h" #include "lld/ReaderWriter/PECOFFLinkingContext.h" #include "lld/ReaderWriter/Reader.h" #include "lld/ReaderWriter/Simple.h" #include "lld/ReaderWriter/Writer.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Path.h" #include <bitset> #include <climits> #include <set> namespace lld { bool PECOFFLinkingContext::validateImpl(raw_ostream &diagnostics) { if (_stackReserve < _stackCommit) { diagnostics << "Invalid stack size: reserve size must be equal to or " << "greater than commit size, but got " << _stackCommit << " and " << _stackReserve << ".\n"; return false; } if (_heapReserve < _heapCommit) { diagnostics << "Invalid heap size: reserve size must be equal to or " << "greater than commit size, but got " << _heapCommit << " and " << _heapReserve << ".\n"; return false; } // It's an error if the base address is not multiple of 64K. if (_baseAddress & 0xffff) { diagnostics << "Base address have to be multiple of 64K, but got " << _baseAddress << "\n"; return false; } // Check for duplicate export ordinals. std::set<int> exports; for (const PECOFFLinkingContext::ExportDesc &desc : getDllExports()) { if (desc.ordinal == -1) continue; if (exports.count(desc.ordinal) == 1) { diagnostics << "Duplicate export ordinals: " << desc.ordinal << "\n"; return false; } exports.insert(desc.ordinal); } std::bitset<64> alignment(_sectionDefaultAlignment); if (alignment.count() != 1) { diagnostics << "Section alignment must be a power of 2, but got " << _sectionDefaultAlignment << "\n"; return false; } // Architectures other than i386 is not supported yet. if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) { diagnostics << "Machine type other than x86 is not supported.\n"; return false; } _writer = createWriterPECOFF(*this); return true; } std::unique_ptr<File> PECOFFLinkingContext::createEntrySymbolFile() const { return LinkingContext::createEntrySymbolFile("command line option /entry"); } std::unique_ptr<File> PECOFFLinkingContext::createUndefinedSymbolFile() const { return LinkingContext::createUndefinedSymbolFile("command line option /include"); } bool PECOFFLinkingContext::createImplicitFiles( std::vector<std::unique_ptr<File> > &) const { std::unique_ptr<SimpleFileNode> fileNode( new SimpleFileNode("Implicit Files")); std::unique_ptr<File> linkerGeneratedSymFile( new pecoff::LinkerGeneratedSymbolFile(*this)); fileNode->appendInputFile(std::move(linkerGeneratedSymFile)); inputGraph().insertOneElementAt(std::move(fileNode), InputGraph::Position::END); return true; } /// Returns the section name in the resulting executable. /// /// Sections in object files are usually output to the executable with the same /// name, but you can rename by command line option. /merge:from=to makes the /// linker to combine "from" section contents to "to" section in the /// executable. We have a mapping for the renaming. This method looks up the /// table and returns a new section name if renamed. StringRef PECOFFLinkingContext::getOutputSectionName(StringRef sectionName) const { auto it = _renamedSections.find(sectionName); if (it == _renamedSections.end()) return sectionName; return getOutputSectionName(it->second); } /// Adds a mapping to the section renaming table. This method will be used for /// /merge command line option. bool PECOFFLinkingContext::addSectionRenaming(raw_ostream &diagnostics, StringRef from, StringRef to) { auto it = _renamedSections.find(from); if (it != _renamedSections.end()) { if (it->second == to) // There's already the same mapping. return true; diagnostics << "Section \"" << from << "\" is already mapped to \"" << it->second << ", so it cannot be mapped to \"" << to << "\"."; return true; } // Add a mapping, and check if there's no cycle in the renaming mapping. The // cycle detection algorithm we use here is naive, but that's OK because the // number of mapping is usually less than 10. _renamedSections[from] = to; for (auto elem : _renamedSections) { StringRef sectionName = elem.first; std::set<StringRef> visited; visited.insert(sectionName); for (;;) { auto pos = _renamedSections.find(sectionName); if (pos == _renamedSections.end()) break; if (visited.count(pos->second)) { diagnostics << "/merge:" << from << "=" << to << " makes a cycle"; return false; } sectionName = pos->second; visited.insert(sectionName); } } return true; } StringRef PECOFFLinkingContext::getAlternateName(StringRef def) const { auto it = _alternateNames.find(def); if (it == _alternateNames.end()) return ""; return it->second; } void PECOFFLinkingContext::setAlternateName(StringRef weak, StringRef def) { _alternateNames[def] = weak; } /// Try to find the input library file from the search paths and append it to /// the input file list. Returns true if the library file is found. StringRef PECOFFLinkingContext::searchLibraryFile(StringRef filename) const { // Current directory always takes precedence over the search paths. if (llvm::sys::path::is_absolute(filename) || llvm::sys::fs::exists(filename)) return filename; // Iterate over the search paths. for (StringRef dir : _inputSearchPaths) { SmallString<128> path = dir; llvm::sys::path::append(path, filename); if (llvm::sys::fs::exists(path.str())) return allocate(path.str()); } return filename; } /// Returns the decorated name of the given symbol name. On 32-bit x86, it /// adds "_" at the beginning of the string. On other architectures, the /// return value is the same as the argument. StringRef PECOFFLinkingContext::decorateSymbol(StringRef name) const { if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) return name; std::string str = "_"; str.append(name); return allocate(str); } StringRef PECOFFLinkingContext::undecorateSymbol(StringRef name) const { if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) return name; assert(name.startswith("_")); return name.substr(1); } Writer &PECOFFLinkingContext::writer() const { return *_writer; } void PECOFFLinkingContext::setSectionSetMask(StringRef sectionName, uint32_t newFlags) { _sectionSetMask[sectionName] |= newFlags; _sectionClearMask[sectionName] &= ~newFlags; const uint32_t rwx = (llvm::COFF::IMAGE_SCN_MEM_READ | llvm::COFF::IMAGE_SCN_MEM_WRITE | llvm::COFF::IMAGE_SCN_MEM_EXECUTE); if (newFlags & rwx) _sectionClearMask[sectionName] |= ~_sectionSetMask[sectionName] & rwx; assert((_sectionSetMask[sectionName] & _sectionClearMask[sectionName]) == 0); } void PECOFFLinkingContext::setSectionClearMask(StringRef sectionName, uint32_t newFlags) { _sectionClearMask[sectionName] |= newFlags; _sectionSetMask[sectionName] &= ~newFlags; assert((_sectionSetMask[sectionName] & _sectionClearMask[sectionName]) == 0); } uint32_t PECOFFLinkingContext::getSectionAttributes(StringRef sectionName, uint32_t flags) const { auto si = _sectionSetMask.find(sectionName); uint32_t setMask = (si == _sectionSetMask.end()) ? 0 : si->second; auto ci = _sectionClearMask.find(sectionName); uint32_t clearMask = (ci == _sectionClearMask.end()) ? 0 : ci->second; return (flags | setMask) & ~clearMask; } // Returns true if two export descriptors have conflicting contents, // e.g. different export ordinals. static bool exportConflicts(const PECOFFLinkingContext::ExportDesc &a, const PECOFFLinkingContext::ExportDesc &b) { if (a.ordinal > 0 && b.ordinal > 0 && a.ordinal != b.ordinal) return true; if (a.noname != b.noname) return true; if (a.isData != b.isData) return true; return false; } void PECOFFLinkingContext::addDllExport(ExportDesc &desc) { auto existing = _dllExports.insert(desc); if (existing.second) return; if (!exportConflicts(*existing.first, desc)) { _dllExports.erase(existing.first); _dllExports.insert(desc); return; } llvm::errs() << "Export symbol '" << desc.name << "' specified more than once.\n"; } void PECOFFLinkingContext::addPasses(PassManager &pm) { pm.add(std::unique_ptr<Pass>(new pecoff::SetSubsystemPass(*this))); pm.add(std::unique_ptr<Pass>(new pecoff::EdataPass(*this))); pm.add(std::unique_ptr<Pass>(new pecoff::IdataPass(*this))); pm.add(std::unique_ptr<Pass>(new LayoutPass())); pm.add(std::unique_ptr<Pass>(new pecoff::GroupedSectionsPass())); } } // end namespace lld
//===- lib/ReaderWriter/PECOFF/PECOFFLinkingContext.cpp -------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Atoms.h" #include "EdataPass.h" #include "GroupedSectionsPass.h" #include "IdataPass.h" #include "LinkerGeneratedSymbolFile.h" #include "SetSubsystemPass.h" #include "lld/Core/PassManager.h" #include "lld/Passes/LayoutPass.h" #include "lld/Passes/RoundTripNativePass.h" #include "lld/Passes/RoundTripYAMLPass.h" #include "lld/ReaderWriter/PECOFFLinkingContext.h" #include "lld/ReaderWriter/Reader.h" #include "lld/ReaderWriter/Simple.h" #include "lld/ReaderWriter/Writer.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Path.h" #include <bitset> #include <climits> #include <set> namespace lld { bool PECOFFLinkingContext::validateImpl(raw_ostream &diagnostics) { if (_stackReserve < _stackCommit) { diagnostics << "Invalid stack size: reserve size must be equal to or " << "greater than commit size, but got " << _stackCommit << " and " << _stackReserve << ".\n"; return false; } if (_heapReserve < _heapCommit) { diagnostics << "Invalid heap size: reserve size must be equal to or " << "greater than commit size, but got " << _heapCommit << " and " << _heapReserve << ".\n"; return false; } // It's an error if the base address is not multiple of 64K. if (_baseAddress & 0xffff) { diagnostics << "Base address have to be multiple of 64K, but got " << _baseAddress << "\n"; return false; } // Check for duplicate export ordinals. std::set<int> exports; for (const PECOFFLinkingContext::ExportDesc &desc : getDllExports()) { if (desc.ordinal == -1) continue; if (exports.count(desc.ordinal) == 1) { diagnostics << "Duplicate export ordinals: " << desc.ordinal << "\n"; return false; } exports.insert(desc.ordinal); } std::bitset<64> alignment(_sectionDefaultAlignment); if (alignment.count() != 1) { diagnostics << "Section alignment must be a power of 2, but got " << _sectionDefaultAlignment << "\n"; return false; } // Architectures other than i386 is not supported yet. if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) { diagnostics << "Machine type other than x86 is not supported.\n"; return false; } _writer = createWriterPECOFF(*this); return true; } std::unique_ptr<File> PECOFFLinkingContext::createEntrySymbolFile() const { return LinkingContext::createEntrySymbolFile("command line option /entry"); } std::unique_ptr<File> PECOFFLinkingContext::createUndefinedSymbolFile() const { return LinkingContext::createUndefinedSymbolFile("command line option /include"); } bool PECOFFLinkingContext::createImplicitFiles( std::vector<std::unique_ptr<File> > &) const { std::unique_ptr<SimpleFileNode> fileNode( new SimpleFileNode("Implicit Files")); std::unique_ptr<File> linkerGeneratedSymFile( new pecoff::LinkerGeneratedSymbolFile(*this)); fileNode->appendInputFile(std::move(linkerGeneratedSymFile)); inputGraph().insertOneElementAt(std::move(fileNode), InputGraph::Position::END); return true; } /// Returns the section name in the resulting executable. /// /// Sections in object files are usually output to the executable with the same /// name, but you can rename by command line option. /merge:from=to makes the /// linker to combine "from" section contents to "to" section in the /// executable. We have a mapping for the renaming. This method looks up the /// table and returns a new section name if renamed. StringRef PECOFFLinkingContext::getOutputSectionName(StringRef sectionName) const { auto it = _renamedSections.find(sectionName); if (it == _renamedSections.end()) return sectionName; return getOutputSectionName(it->second); } /// Adds a mapping to the section renaming table. This method will be used for /// /merge command line option. bool PECOFFLinkingContext::addSectionRenaming(raw_ostream &diagnostics, StringRef from, StringRef to) { auto it = _renamedSections.find(from); if (it != _renamedSections.end()) { if (it->second == to) // There's already the same mapping. return true; diagnostics << "Section \"" << from << "\" is already mapped to \"" << it->second << ", so it cannot be mapped to \"" << to << "\"."; return true; } // Add a mapping, and check if there's no cycle in the renaming mapping. The // cycle detection algorithm we use here is naive, but that's OK because the // number of mapping is usually less than 10. _renamedSections[from] = to; for (auto elem : _renamedSections) { StringRef sectionName = elem.first; std::set<StringRef> visited; visited.insert(sectionName); for (;;) { auto pos = _renamedSections.find(sectionName); if (pos == _renamedSections.end()) break; if (visited.count(pos->second)) { diagnostics << "/merge:" << from << "=" << to << " makes a cycle"; return false; } sectionName = pos->second; visited.insert(sectionName); } } return true; } StringRef PECOFFLinkingContext::getAlternateName(StringRef def) const { auto it = _alternateNames.find(def); if (it == _alternateNames.end()) return ""; return it->second; } void PECOFFLinkingContext::setAlternateName(StringRef weak, StringRef def) { _alternateNames[def] = weak; } /// Try to find the input library file from the search paths and append it to /// the input file list. Returns true if the library file is found. StringRef PECOFFLinkingContext::searchLibraryFile(StringRef filename) const { // Current directory always takes precedence over the search paths. if (llvm::sys::path::is_absolute(filename) || llvm::sys::fs::exists(filename)) return filename; // Iterate over the search paths. for (StringRef dir : _inputSearchPaths) { SmallString<128> path = dir; llvm::sys::path::append(path, filename); if (llvm::sys::fs::exists(path.str())) return allocate(path.str()); } return filename; } /// Returns the decorated name of the given symbol name. On 32-bit x86, it /// adds "_" at the beginning of the string. On other architectures, the /// return value is the same as the argument. StringRef PECOFFLinkingContext::decorateSymbol(StringRef name) const { if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) return name; std::string str = "_"; str.append(name); return allocate(str); } StringRef PECOFFLinkingContext::undecorateSymbol(StringRef name) const { if (_machineType != llvm::COFF::IMAGE_FILE_MACHINE_I386) return name; assert(name.startswith("_")); return name.substr(1); } Writer &PECOFFLinkingContext::writer() const { return *_writer; } void PECOFFLinkingContext::setSectionSetMask(StringRef sectionName, uint32_t newFlags) { _sectionSetMask[sectionName] |= newFlags; _sectionClearMask[sectionName] &= ~newFlags; const uint32_t rwx = (llvm::COFF::IMAGE_SCN_MEM_READ | llvm::COFF::IMAGE_SCN_MEM_WRITE | llvm::COFF::IMAGE_SCN_MEM_EXECUTE); if (newFlags & rwx) _sectionClearMask[sectionName] |= ~_sectionSetMask[sectionName] & rwx; assert((_sectionSetMask[sectionName] & _sectionClearMask[sectionName]) == 0); } void PECOFFLinkingContext::setSectionClearMask(StringRef sectionName, uint32_t newFlags) { _sectionClearMask[sectionName] |= newFlags; _sectionSetMask[sectionName] &= ~newFlags; assert((_sectionSetMask[sectionName] & _sectionClearMask[sectionName]) == 0); } uint32_t PECOFFLinkingContext::getSectionAttributes(StringRef sectionName, uint32_t flags) const { auto si = _sectionSetMask.find(sectionName); uint32_t setMask = (si == _sectionSetMask.end()) ? 0 : si->second; auto ci = _sectionClearMask.find(sectionName); uint32_t clearMask = (ci == _sectionClearMask.end()) ? 0 : ci->second; return (flags | setMask) & ~clearMask; } // Returns true if two export descriptors have conflicting contents, // e.g. different export ordinals. static bool exportConflicts(const PECOFFLinkingContext::ExportDesc &a, const PECOFFLinkingContext::ExportDesc &b) { return (a.ordinal > 0 && b.ordinal > 0 && a.ordinal != b.ordinal) || a.noname != b.noname || a.isData != b.isData; } void PECOFFLinkingContext::addDllExport(ExportDesc &desc) { auto existing = _dllExports.insert(desc); if (existing.second) return; if (!exportConflicts(*existing.first, desc)) { _dllExports.erase(existing.first); _dllExports.insert(desc); return; } llvm::errs() << "Export symbol '" << desc.name << "' specified more than once.\n"; } void PECOFFLinkingContext::addPasses(PassManager &pm) { pm.add(std::unique_ptr<Pass>(new pecoff::SetSubsystemPass(*this))); pm.add(std::unique_ptr<Pass>(new pecoff::EdataPass(*this))); pm.add(std::unique_ptr<Pass>(new pecoff::IdataPass(*this))); pm.add(std::unique_ptr<Pass>(new LayoutPass())); pm.add(std::unique_ptr<Pass>(new pecoff::GroupedSectionsPass())); } } // end namespace lld
Simplify if ... return repetition.
Simplify if ... return repetition. git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@198108 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lld,llvm-mirror/lld
9896baeb5a142beefbdde96ed99ee95383fcbea2
fpcmp/fpcmp.cpp
fpcmp/fpcmp.cpp
//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r and -a options. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include <iostream> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); std::string ErrorMsg; int DF = DiffFilesWithTolerance(sys::PathWithStatus(File1), sys::PathWithStatus(File2), AbsTolerance, RelTolerance, &ErrorMsg); if (!ErrorMsg.empty()) std::cerr << argv[0] << ": " << ErrorMsg << "\n"; return DF; }
//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r and -a options. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); std::string ErrorMsg; int DF = DiffFilesWithTolerance(sys::PathWithStatus(File1), sys::PathWithStatus(File2), AbsTolerance, RelTolerance, &ErrorMsg); if (!ErrorMsg.empty()) errs() << argv[0] << ": " << ErrorMsg << "\n"; return DF; }
Remove unnecessary uses of <iostream>.
Remove unnecessary uses of <iostream>. git-svn-id: a4a6f32337ebd29ad4763b423022f00f68d1c7b7@101338 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-3-clause
lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx
2165a1f052dcd5b14b437895dc8f4ae7e1ef0cde
src/S2LoadBalancer.cpp
src/S2LoadBalancer.cpp
/// /// @file S2LoadBalancer.cpp /// @brief Dynamically increase or decrease the segment_size or the /// segments_per_thread in order to improve the load balancing /// in the computation of the special leaves. The algorithm /// calculates the relative standard deviation of the timings /// of the individual threads and then decides whether to /// assign more work (low relative standard deviation) or less /// work (large relative standard deviation) to the threads. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <ptypes.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_average(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } double relative_standard_deviation(aligned_vector<double>& timings) { size_t n = timings.size(); double average = get_average(timings); double sum = 0; if (average == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - average; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / average; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z) : x_((double) x) { double divisor = log(x_) * log(log(x_)); int64_t size = (int64_t) (isqrt(z) / max(1.0, divisor)); size = max((int64_t) (1 << 9), size); min_size_ = next_power_of_2(size); max_size_ = next_power_of_2(isqrt(z)); } double S2LoadBalancer::get_rsd() const { return rsd_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } bool S2LoadBalancer::decrease_size(double seconds, double decrease) const { return seconds > 0.01 && rsd_ > decrease; } bool S2LoadBalancer::increase_size(double seconds, double max_seconds, double decrease) const { return seconds < max_seconds && !decrease_size(seconds, decrease); } /// Synchronize threads after at most max_seconds double S2LoadBalancer::get_max_seconds(int64_t threads) const { double t = (double) threads; return max(5.0, log(x_) * log(t)); } /// Used to decide whether to use a smaller or larger /// segment_size and/or segments_per_thread. /// double S2LoadBalancer::get_decrease_threshold(double seconds, int64_t threads) const { double t = (double) threads; double dividend = max(0.7, log(t) / 3); double quotient = max(1.0, dividend / (seconds * log(seconds))); double dont_decrease = min(quotient, dividend * 10); return rsd_ + dont_decrease; } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { double seconds = get_average(timings); double max_seconds = get_max_seconds(threads); double decrease_threshold = get_decrease_threshold(seconds, threads); rsd_ = max(0.1, relative_standard_deviation(timings)); // 1 segment per thread if (*segment_size < max_size_) { if (increase_size(seconds, max_seconds, decrease_threshold)) *segment_size <<= 1; else if (decrease_size(seconds, decrease_threshold)) if (*segment_size > min_size_) *segment_size >>= 1; // near sqrt(z) there is a short peak of special // leaves so we use the minium segment size int64_t high = low + *segment_size * *segments_per_thread * threads; if (low <= max_size_ && high > max_size_) *segment_size = min_size_; } else // many segments per thread { double factor = decrease_threshold / rsd_; factor = in_between(0.25, factor, 4.0); double n = *segments_per_thread * factor; n = max(1.0, n); if ((n < *segments_per_thread && seconds > 0.01) || (n > *segments_per_thread && seconds < max_seconds)) *segments_per_thread = (int) n; } } } //namespace
/// /// @file S2LoadBalancer.cpp /// @brief Dynamically increase or decrease the segment_size or the /// segments_per_thread in order to improve the load balancing /// in the computation of the special leaves. The algorithm /// calculates the relative standard deviation of the timings /// of the individual threads and then decides whether to /// assign more work (low relative standard deviation) or less /// work (large relative standard deviation) to the threads. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <ptypes.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_average(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } double relative_standard_deviation(aligned_vector<double>& timings) { size_t n = timings.size(); double average = get_average(timings); double sum = 0; if (average == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - average; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / average; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z) : x_((double) x), rsd_(40) { double divisor = log(x_) * log(log(x_)); int64_t size = (int64_t) (isqrt(z) / max(1.0, divisor)); size = max((int64_t) (1 << 9), size); min_size_ = next_power_of_2(size); max_size_ = next_power_of_2(isqrt(z)); } double S2LoadBalancer::get_rsd() const { return rsd_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } bool S2LoadBalancer::decrease_size(double seconds, double decrease) const { return seconds > 0.01 && rsd_ > decrease; } bool S2LoadBalancer::increase_size(double seconds, double max_seconds, double decrease) const { return seconds < max_seconds && !decrease_size(seconds, decrease); } /// Synchronize threads after at most max_seconds double S2LoadBalancer::get_max_seconds(int64_t threads) const { double t = (double) threads; return max(5.0, log(x_) * log(t)); } /// Used to decide whether to use a smaller or larger /// segment_size and/or segments_per_thread. /// double S2LoadBalancer::get_decrease_threshold(double seconds, int64_t threads) const { double t = (double) threads; double dividend = max(0.7, log(t) / 3); double quotient = max(1.0, dividend / (seconds * log(seconds))); double dont_decrease = min(quotient, dividend * 10); return rsd_ + dont_decrease; } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { double seconds = get_average(timings); double max_seconds = get_max_seconds(threads); double decrease_threshold = get_decrease_threshold(seconds, threads); rsd_ = max(0.1, relative_standard_deviation(timings)); // 1 segment per thread if (*segment_size < max_size_) { if (increase_size(seconds, max_seconds, decrease_threshold)) *segment_size <<= 1; else if (decrease_size(seconds, decrease_threshold)) if (*segment_size > min_size_) *segment_size >>= 1; // near sqrt(z) there is a short peak of special // leaves so we use the minium segment size int64_t high = low + *segment_size * *segments_per_thread * threads; if (low <= max_size_ && high > max_size_) *segment_size = min_size_; } else // many segments per thread { double factor = decrease_threshold / rsd_; factor = in_between(0.25, factor, 4.0); double n = *segments_per_thread * factor; n = max(1.0, n); if ((n < *segments_per_thread && seconds > 0.01) || (n > *segments_per_thread && seconds < max_seconds)) *segments_per_thread = (int) n; } } } //namespace
Fix uninitialized variable
Fix uninitialized variable
C++
bsd-2-clause
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
6ee1e53709404d7fc43d5361cdc2ff5c118ca488
src/c4/type_name.hpp
src/c4/type_name.hpp
#ifndef _C4_TYPENAME_HPP_ #define _C4_TYPENAME_HPP_ #include "c4/span.hpp" #include <stdio.h> /// @cond dev struct _c4t { template< size_t N > _c4t(const char (&s)[N]) : str(s), sz(N-1) {} // take off the \0 const char *str; size_t sz; }; // this is a more abbreviated way of getting the type name // (if we used span in the return type the name would involve // templates and would create longer type name strings, // as well as more differences between compilers) template< class T > C4_CONSTEXPR14 C4_ALWAYS_INLINE _c4t _c4tn() { auto p = _c4t(C4_PRETTY_FUNC); return p; } /// @endcond C4_BEGIN_NAMESPACE(c4) /** adapted from this answer: http://stackoverflow.com/a/20170989/5875572 */ template< class T > C4_CONSTEXPR14 cspan<char> type_name() { const _c4t p = _c4tn< T >(); #if 0 && defined(_C4_THIS_IS_A_DEBUG_SCAFFOLD) for(int index = 0; index < p.sz; ++index) { printf(" %2c", p.str[index]); } printf("\n"); for(int index = 0; index < p.sz; ++index) { printf(" %2d", index); } printf("\n"); #endif #if defined(_MSC_VER) # if defined(__clang__) // Visual Studio has the clang toolset // example: // ..........................xxx. // _c4t __cdecl _c4tn() [T = int] enum { tstart = 26, tend = 1}; # elif defined(C4_MSVC_2015) || defined(C4_MSVC_2017) // Note: subtract 7 at the end because the function terminates with ">(void)" in VS2015+ cspan<char>::size_type tstart = 26, tend = 7; const char *s = p.str + tstart; // look at the start // we're not using strcmp to spare the #include // does it start with 'class '? if(p.sz > 6 && s[0] == 'c' && s[1] == 'l' && s[2] == 'a' && s[3] == 's' && s[4] == 's' && s[5] == ' ') { tstart += 6; } // does it start with 'struct '? else if(p.sz > 7 && s[0] == 's' && s[1] == 't' && s[2] == 'r' && s[3] == 'u' && s[4] == 'c' && s[5] == 't' && s[6] == ' ') { tstart += 7; } # else C4_NOT_IMPLEMENTED(); # endif #elif defined(__ICC) // example: // ........................xxx. // "_c4t _c4tn() [with T = int]" enum { tstart = 23, tend = 1}; #elif defined(__clang__) // example: // ...................xxx. // "_c4t _c4tn() [T = int]" enum { tstart = 18, tend = 1}; #elif defined(__GNUC__) // example: // ........................xxx. // "_c4t _c4tn() [with T = int]" enum { tstart = 23, tend = 1 }; #else C4_NOT IMPLEMENTED(); #endif cspan<char> o(p.str + tstart, p.sz - tstart - tend); return o; } C4_END_NAMESPACE(c4) #endif //_C4_TYPENAME_HPP_
#ifndef _C4_TYPENAME_HPP_ #define _C4_TYPENAME_HPP_ #include "c4/span.hpp" /// @cond dev struct _c4t { const char *str; size_t sz; template< size_t N > _c4t(const char (&s)[N]) : str(s), sz(N-1) {} // take off the \0 }; // this is a more abbreviated way of getting the type name // (if we used span in the return type, the name would involve // templates and would create longer type name strings, // as well as larger differences between compilers) template< class T > C4_CONSTEXPR14 C4_ALWAYS_INLINE _c4t _c4tn() { auto p = _c4t(C4_PRETTY_FUNC); return p; } /// @endcond C4_BEGIN_NAMESPACE(c4) template< class T > C4_CONSTEXPR14 cspan<char> type_name(); template< class T > C4_CONSTEXPR14 C4_ALWAYS_INLINE cspan<char> type_name(T const& var) { return type_name< T >(); } /** adapted from this answer: http://stackoverflow.com/a/20170989/5875572 */ template< class T > C4_CONSTEXPR14 cspan<char> type_name() { const _c4t p = _c4tn< T >(); #if 0 && defined(_C4_THIS_IS_A_DEBUG_SCAFFOLD) for(int index = 0; index < p.sz; ++index) { printf(" %2c", p.str[index]); } printf("\n"); for(int index = 0; index < p.sz; ++index) { printf(" %2d", index); } printf("\n"); #endif #if defined(_MSC_VER) # if defined(__clang__) // Visual Studio has the clang toolset // example: // ..........................xxx. // _c4t __cdecl _c4tn() [T = int] enum { tstart = 26, tend = 1}; # elif defined(C4_MSVC_2015) || defined(C4_MSVC_2017) // Note: subtract 7 at the end because the function terminates with ">(void)" in VS2015+ cspan<char>::size_type tstart = 26, tend = 7; const char *s = p.str + tstart; // look at the start // we're not using strcmp to spare the #include // does it start with 'class '? if(p.sz > 6 && s[0] == 'c' && s[1] == 'l' && s[2] == 'a' && s[3] == 's' && s[4] == 's' && s[5] == ' ') { tstart += 6; } // does it start with 'struct '? else if(p.sz > 7 && s[0] == 's' && s[1] == 't' && s[2] == 'r' && s[3] == 'u' && s[4] == 'c' && s[5] == 't' && s[6] == ' ') { tstart += 7; } # else C4_NOT_IMPLEMENTED(); # endif #elif defined(__ICC) // example: // ........................xxx. // "_c4t _c4tn() [with T = int]" enum { tstart = 23, tend = 1}; #elif defined(__clang__) // example: // ...................xxx. // "_c4t _c4tn() [T = int]" enum { tstart = 18, tend = 1}; #elif defined(__GNUC__) // example: // ........................xxx. // "_c4t _c4tn() [with T = int]" enum { tstart = 23, tend = 1 }; #else C4_NOT_IMPLEMENTED(); #endif cspan<char> o(p.str + tstart, p.sz - tstart - tend); return o; } C4_END_NAMESPACE(c4) #endif //_C4_TYPENAME_HPP_
add overload, fix call to C4_NOT_IMPLEMENTED()
type_name: add overload, fix call to C4_NOT_IMPLEMENTED()
C++
mit
biojppm/c4stl,biojppm/c4stl,biojppm/c4stl,biojppm/c4stl,biojppm/c4stl,biojppm/c4stl
ad5d6c5e777056bad8c832eecefa5ca049f128f9
src/QtConvertVisitor.cpp
src/QtConvertVisitor.cpp
#include "QtConvertVisitor.h" #include <CustomPrinter.h> #include <TypeMatchers.h> #include <clang/AST/DeclCXX.h> #include <clang/AST/ASTContext.h> QtConvertVisitor::QtConvertVisitor(clang::ASTContext *Context) : Context(Context), _rewriter(Context->getSourceManager(), Context->getLangOpts()), m_resolver(Context->getLangOpts()) { m_connectMatcher.matchClassName("QObject") .matchMethodName("connect") .matchReturnType(TypeMatchers::isQMetaObjectConnectionType) .matchAccessSpecifier(clang::AccessSpecifier::AS_public) .matchParameter(TypeMatchers::isQObjectPtrType) .matchParameter(TypeMatchers::isConstCharPtrType) .matchParameter(TypeMatchers::isQObjectPtrType) .matchParameter(TypeMatchers::isConstCharPtrType) .matchParameter(TypeMatchers::isQtConnectionTypeEnum); } bool QtConvertVisitor::VisitNamespaceDecl(clang::NamespaceDecl* context) { m_resolver.visitDeclContext(context); return true; } bool QtConvertVisitor::VisitCXXMethodDecl(clang::CXXMethodDecl* declaration) { if (m_connectMatcher.isMatch(declaration)) { CustomPrinter::printMethod(declaration); myset.insert(declaration); } return true; } bool QtConvertVisitor::VisitCallExpr(clang::CallExpr *callExpression) { std::string methodCall, lastTypeString; if (callExpression->getDirectCallee()) { if (myset.find(callExpression->getDirectCallee()->getFirstDecl()) != myset.end()) { for (auto i = 0ul ; i < callExpression->getNumArgs() ; i++) { if (const clang::CallExpr *qflaglocationCall = clang::dyn_cast<clang::CallExpr>(callExpression->getArg(i))) { if (const clang::ImplicitCastExpr *castExpr = clang::dyn_cast<clang::ImplicitCastExpr>(qflaglocationCall->getArg(0))) { if (const clang::StringLiteral* literal = clang::dyn_cast<clang::StringLiteral>(*castExpr->child_begin())) { methodCall = extractMethodCall(literal->getBytes()); } } } if (callExpression->getArg(i)->getLocEnd().isValid()) { auto& sm = Context->getSourceManager(); if (callExpression->getArg(i)->getLocStart().isMacroID()) { auto fullStartLocation = Context->getSourceManager().getImmediateExpansionRange(callExpression->getArg(i)->getLocStart()); std::string replacementText = "&"; replacementText += lastTypeString; replacementText += "::"; replacementText += methodCall; _rewriter.ReplaceText(clang::SourceRange(fullStartLocation.first, fullStartLocation.second), replacementText); methodCall.clear(); } } clang::QualType argumentType; if (const clang::ImplicitCastExpr* castExpr = clang::dyn_cast<clang::ImplicitCastExpr>(callExpression->getArg(i))) { if (const clang::Expr* expr = clang::dyn_cast<clang::Expr>(*castExpr->child_begin())) { argumentType = expr->getType(); } } else { argumentType = callExpression->getArg(i)->getType(); } lastTypeString = m_resolver.ResolveType(argumentType); } } } return true; } void QtConvertVisitor::dumpToOutputStream() { _rewriter.getEditBuffer(Context->getSourceManager().getMainFileID()).write(llvm::outs()); } std::string QtConvertVisitor::extractMethodCall(const std::string& literal) { std::string result = literal; if (!result.empty()) { result.erase(result.begin(), result.begin() + 1); auto parenPos = result.find('('); result = result.substr(0, parenPos); } return result; }
#include "QtConvertVisitor.h" #include <CustomPrinter.h> #include <TypeMatchers.h> #include <clang/AST/DeclCXX.h> #include <clang/AST/ASTContext.h> QtConvertVisitor::QtConvertVisitor(clang::ASTContext *Context) : Context(Context), _rewriter(Context->getSourceManager(), Context->getLangOpts()), m_resolver(Context->getLangOpts()) { m_connectMatcher.matchClassName("QObject") .matchMethodName("connect") .matchReturnType(TypeMatchers::isQMetaObjectConnectionType) .matchAccessSpecifier(clang::AccessSpecifier::AS_public) .matchParameter(TypeMatchers::isQObjectPtrType) .matchParameter(TypeMatchers::isConstCharPtrType) .matchParameter(TypeMatchers::isQObjectPtrType) .matchParameter(TypeMatchers::isConstCharPtrType) .matchParameter(TypeMatchers::isQtConnectionTypeEnum); } bool QtConvertVisitor::VisitNamespaceDecl(clang::NamespaceDecl* context) { m_resolver.visitDeclContext(context); return true; } bool QtConvertVisitor::VisitCXXMethodDecl(clang::CXXMethodDecl* declaration) { if (m_connectMatcher.isMatch(declaration)) { CustomPrinter::printMethod(declaration); myset.insert(declaration); } return true; } bool QtConvertVisitor::VisitCallExpr(clang::CallExpr *callExpression) { std::string methodCall, lastTypeString; if (callExpression->getDirectCallee()) { if (myset.find(callExpression->getDirectCallee()->getFirstDecl()) != myset.end()) { for (auto i = 0ul ; i < callExpression->getNumArgs() ; i++) { if (const clang::CallExpr *qflaglocationCall = clang::dyn_cast<clang::CallExpr>(callExpression->getArg(i))) { if (const clang::ImplicitCastExpr *castExpr = clang::dyn_cast<clang::ImplicitCastExpr>(qflaglocationCall->getArg(0))) { if (const clang::StringLiteral* literal = clang::dyn_cast<clang::StringLiteral>(*castExpr->child_begin())) { methodCall = extractMethodCall(literal->getBytes()); } } } if (callExpression->getArg(i)->getLocEnd().isValid()) { if (callExpression->getArg(i)->getLocStart().isMacroID()) { auto fullStartLocation = Context->getSourceManager().getImmediateExpansionRange(callExpression->getArg(i)->getLocStart()); std::string replacementText = "&"; replacementText += lastTypeString; replacementText += "::"; replacementText += methodCall; _rewriter.ReplaceText(clang::SourceRange(fullStartLocation.first, fullStartLocation.second), replacementText); methodCall.clear(); } } clang::QualType argumentType; if (const clang::ImplicitCastExpr* castExpr = clang::dyn_cast<clang::ImplicitCastExpr>(callExpression->getArg(i))) { if (const clang::Expr* expr = clang::dyn_cast<clang::Expr>(*castExpr->child_begin())) { argumentType = expr->getType(); } } else { argumentType = callExpression->getArg(i)->getType(); } lastTypeString = m_resolver.ResolveType(argumentType); } } } return true; } void QtConvertVisitor::dumpToOutputStream() { _rewriter.getEditBuffer(Context->getSourceManager().getMainFileID()).write(llvm::outs()); } std::string QtConvertVisitor::extractMethodCall(const std::string& literal) { std::string result = literal; if (!result.empty()) { result.erase(result.begin(), result.begin() + 1); auto parenPos = result.find('('); result = result.substr(0, parenPos); } return result; }
Remove unused variable
Remove unused variable
C++
mit
hebaishi/qt4-qt5-convert,hebaishi/qt4-qt5-convert
4321071f9c47e5db379603904684c55a7197ad02
src/Forwarder.hpp
src/Forwarder.hpp
#ifndef _CBR_FORWARDER_HPP_ #define _CBR_FORWARDER_HPP_ #include "Utility.hpp" #include "SpaceContext.hpp" #include "Message.hpp" #include "Network.hpp" #include "ServerNetwork.hpp" #include "ForwarderUtilityClasses.hpp" #include "Queue.hpp" #include "FairQueue.hpp" #include "TimeProfiler.hpp" namespace CBR { class Object; class ServerIDMap; class ObjectSegmentation; class CoordinateSegmentation; class ServerMessageQueue; class Network; class Trace; class ObjectConnection; class ForwarderQueue{ public: class CanSendPredicate{ ServerMessageQueue* mServerMessageQueue; public: CanSendPredicate(ServerMessageQueue* s){ mServerMessageQueue=s; } bool operator() (MessageRouter::SERVICES svc, const Message* msg); }; typedef FairQueue<Message, MessageRouter::SERVICES, AbstractQueue<Message*>, AlwaysUsePredicate, true> OutgoingFairQueue; std::vector<OutgoingFairQueue*> mQueues; uint32 mQueueSize; ServerMessageQueue *mServerMessageQueue; ForwarderQueue(ServerMessageQueue*smq, uint32 size){ mServerMessageQueue=smq; } size_t numServerQueues()const { return mQueues.size(); } OutgoingFairQueue& getFairQueue(ServerID sid) { while (mQueues.size()<=sid) { mQueues.push_back(NULL); } if(!mQueues[sid]) { mQueues[sid]=new OutgoingFairQueue(AlwaysUsePredicate()); for(unsigned int i=0;i<MessageRouter::NUM_SERVICES;++i) { mQueues[sid]->addQueue(new Queue<Message*>(mQueueSize),(MessageRouter::SERVICES)i,1.0); } } return *mQueues[sid]; } ~ForwarderQueue (){ for(unsigned int i=0;i<mQueues.size();++i) { if(mQueues[i]) { delete mQueues[i]; } } } }; class Forwarder : public MessageDispatcher, public MessageRouter, public MessageRecipient { private: //Unique to forwarder std::deque<SelfMessage> mSelfMessages; //will be used in route. ForwarderQueue *mOutgoingMessages; SpaceContext* mContext; //Shared with server CoordinateSegmentation* mCSeg; ObjectSegmentation* mOSeg; ServerMessageQueue* mServerMessageQueue; uint64 mUniqueConnIDs; struct MessageAndForward { bool mIsForward; CBR::Protocol::Object::ObjectMessage* mMessage; }; typedef std::vector<MessageAndForward> ObjectMessageList; // typedef std::vector<CBR::Protocol::Object::ObjectMessage*> ObjectMessageList; std::map<UUID,ObjectMessageList> mObjectsInTransit; //this is a map of messages's for objects that are being looked up in oseg or are in transit. OSegLookupQueue queueMap; //this maps the object ids to a list of messages that are being looked up in oseg. Time mLastSampleTime; Duration mSampleRate; struct UniqueObjConn { uint64 id; ObjectConnection* conn; }; // typedef std::map<UUID, ObjectConnection*> ObjectConnectionMap; // ObjectConnectionMap mObjectConnections; typedef std::map<UUID, UniqueObjConn> ObjectConnectionMap; ObjectConnectionMap mObjectConnections; TimeProfiler mProfiler; //Private Functions void processChunk(Message* msg, bool forwarded_self_msg); typedef std::vector<ServerID> ListServersUpdate; typedef std::map<UUID,ListServersUpdate> ObjectServerUpdateMap; ObjectServerUpdateMap mServersToUpdate; protected: virtual void dispatchMessage(Message* msg) const; virtual void dispatchMessage(const CBR::Protocol::Object::ObjectMessage& msg) const; public: Forwarder(SpaceContext* ctx); ~Forwarder(); //D-E-S-T-R-U-C-T-O-R void initialize(CoordinateSegmentation* cseg, ObjectSegmentation* oseg, ServerMessageQueue* smq); void service(); void tickOSeg(const Time&t); // Routing interface for servers. This is used to route messages that originate from // a server provided service, and thus don't have a source object. Messages may be destined // for either servers or objects. The second form will simply automatically do the destination // server lookup. // if forwarding is true the message will be stuck onto a queue no matter what, otherwise it may be delivered directly //__attribute__ ((warn_unused_result)) bool route(MessageRouter::SERVICES svc, Message* msg, bool is_forward = false); //note: whenever we're forwarding a message from another object, we'll want to include the forwardFrom ServerID so that we can send an oseg update message to the server with //the stale cache value. __attribute__ ((warn_unused_result)) bool route(CBR::Protocol::Object::ObjectMessage* msg, bool is_forward = false, ServerID forwardFrom = NullServerID); // void route(CBR::Protocol::Object::ObjectMessage* msg, bool is_forward, ServerID forwardFrom ); // private: // This version is provided if you already know which server the message should be sent to __attribute__ ((warn_unused_result)) bool routeObjectMessageToServer(CBR::Protocol::Object::ObjectMessage* msg, ServerID dest_serv, bool is_forward=false, MessageRouter::SERVICES from_another_object=MessageRouter::OBJECT_MESSAGESS); public: bool routeObjectHostMessage(CBR::Protocol::Object::ObjectMessage* obj_msg); void receiveMessage(Message* msg); void addObjectConnection(const UUID& dest_obj, ObjectConnection* conn); ObjectConnection* removeObjectConnection(const UUID& dest_obj); ObjectConnection* getObjectConnection(const UUID& dest_obj); ObjectConnection* getObjectConnection(const UUID& dest_obj, uint64& uniqueconnid ); };//end class Forwarder } //end namespace CBR #endif //_CBR_FORWARDER_HPP_
#ifndef _CBR_FORWARDER_HPP_ #define _CBR_FORWARDER_HPP_ #include "Utility.hpp" #include "SpaceContext.hpp" #include "Message.hpp" #include "Network.hpp" #include "ServerNetwork.hpp" #include "ForwarderUtilityClasses.hpp" #include "Queue.hpp" #include "FairQueue.hpp" #include "TimeProfiler.hpp" namespace CBR { class Object; class ServerIDMap; class ObjectSegmentation; class CoordinateSegmentation; class ServerMessageQueue; class Network; class Trace; class ObjectConnection; class ForwarderQueue{ public: class CanSendPredicate{ ServerMessageQueue* mServerMessageQueue; public: CanSendPredicate(ServerMessageQueue* s){ mServerMessageQueue=s; } bool operator() (MessageRouter::SERVICES svc, const Message* msg); }; typedef FairQueue<Message, MessageRouter::SERVICES, AbstractQueue<Message*>, AlwaysUsePredicate, true> OutgoingFairQueue; std::vector<OutgoingFairQueue*> mQueues; uint32 mQueueSize; ServerMessageQueue *mServerMessageQueue; ForwarderQueue(ServerMessageQueue*smq, uint32 size){ mServerMessageQueue=smq; mQueueSize=size; } size_t numServerQueues()const { return mQueues.size(); } OutgoingFairQueue& getFairQueue(ServerID sid) { while (mQueues.size()<=sid) { mQueues.push_back(NULL); } if(!mQueues[sid]) { mQueues[sid]=new OutgoingFairQueue(AlwaysUsePredicate()); for(unsigned int i=0;i<MessageRouter::NUM_SERVICES;++i) { mQueues[sid]->addQueue(new Queue<Message*>(mQueueSize),(MessageRouter::SERVICES)i,1.0); } } return *mQueues[sid]; } ~ForwarderQueue (){ for(unsigned int i=0;i<mQueues.size();++i) { if(mQueues[i]) { delete mQueues[i]; } } } }; class Forwarder : public MessageDispatcher, public MessageRouter, public MessageRecipient { private: //Unique to forwarder std::deque<SelfMessage> mSelfMessages; //will be used in route. ForwarderQueue *mOutgoingMessages; SpaceContext* mContext; //Shared with server CoordinateSegmentation* mCSeg; ObjectSegmentation* mOSeg; ServerMessageQueue* mServerMessageQueue; uint64 mUniqueConnIDs; struct MessageAndForward { bool mIsForward; CBR::Protocol::Object::ObjectMessage* mMessage; }; typedef std::vector<MessageAndForward> ObjectMessageList; // typedef std::vector<CBR::Protocol::Object::ObjectMessage*> ObjectMessageList; std::map<UUID,ObjectMessageList> mObjectsInTransit; //this is a map of messages's for objects that are being looked up in oseg or are in transit. OSegLookupQueue queueMap; //this maps the object ids to a list of messages that are being looked up in oseg. Time mLastSampleTime; Duration mSampleRate; struct UniqueObjConn { uint64 id; ObjectConnection* conn; }; // typedef std::map<UUID, ObjectConnection*> ObjectConnectionMap; // ObjectConnectionMap mObjectConnections; typedef std::map<UUID, UniqueObjConn> ObjectConnectionMap; ObjectConnectionMap mObjectConnections; TimeProfiler mProfiler; //Private Functions void processChunk(Message* msg, bool forwarded_self_msg); typedef std::vector<ServerID> ListServersUpdate; typedef std::map<UUID,ListServersUpdate> ObjectServerUpdateMap; ObjectServerUpdateMap mServersToUpdate; protected: virtual void dispatchMessage(Message* msg) const; virtual void dispatchMessage(const CBR::Protocol::Object::ObjectMessage& msg) const; public: Forwarder(SpaceContext* ctx); ~Forwarder(); //D-E-S-T-R-U-C-T-O-R void initialize(CoordinateSegmentation* cseg, ObjectSegmentation* oseg, ServerMessageQueue* smq); void service(); void tickOSeg(const Time&t); // Routing interface for servers. This is used to route messages that originate from // a server provided service, and thus don't have a source object. Messages may be destined // for either servers or objects. The second form will simply automatically do the destination // server lookup. // if forwarding is true the message will be stuck onto a queue no matter what, otherwise it may be delivered directly //__attribute__ ((warn_unused_result)) bool route(MessageRouter::SERVICES svc, Message* msg, bool is_forward = false); //note: whenever we're forwarding a message from another object, we'll want to include the forwardFrom ServerID so that we can send an oseg update message to the server with //the stale cache value. __attribute__ ((warn_unused_result)) bool route(CBR::Protocol::Object::ObjectMessage* msg, bool is_forward = false, ServerID forwardFrom = NullServerID); // void route(CBR::Protocol::Object::ObjectMessage* msg, bool is_forward, ServerID forwardFrom ); // private: // This version is provided if you already know which server the message should be sent to __attribute__ ((warn_unused_result)) bool routeObjectMessageToServer(CBR::Protocol::Object::ObjectMessage* msg, ServerID dest_serv, bool is_forward=false, MessageRouter::SERVICES from_another_object=MessageRouter::OBJECT_MESSAGESS); public: bool routeObjectHostMessage(CBR::Protocol::Object::ObjectMessage* obj_msg); void receiveMessage(Message* msg); void addObjectConnection(const UUID& dest_obj, ObjectConnection* conn); ObjectConnection* removeObjectConnection(const UUID& dest_obj); ObjectConnection* getObjectConnection(const UUID& dest_obj); ObjectConnection* getObjectConnection(const UUID& dest_obj, uint64& uniqueconnid ); };//end class Forwarder } //end namespace CBR #endif //_CBR_FORWARDER_HPP_
initialize the queue sizes in the ForwarderQueue
initialize the queue sizes in the ForwarderQueue
C++
bsd-3-clause
sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata
4f54da00cbafad1ea3184b5ce0abef290469b7ab
src/examples/GDLExample/mainwindow.cpp
src/examples/GDLExample/mainwindow.cpp
/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <QMenuBar> #include <KFileDialog> #include <gluon/gdlhandler.h> #include <gluon/gluonobject.h> #include <QTextEdit> #include <QVBoxLayout> MainWindow::MainWindow() : GluonMainWindow() { setupGluon(); QAction* openFile = menu()->addAction("Open File"); connect(openFile, SIGNAL(triggered(bool)), SLOT(openFile(bool))); m_text = new QTextEdit; QWidget* main = new QWidget; QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(view()); layout->addWidget(m_text); main->setLayout(layout); setCentralWidget(main); } MainWindow::~MainWindow() { } void MainWindow::openFile(bool ) { QString filename = KFileDialog::getOpenFileName(); if(filename != "") { QFile file(filename); file.open(QIODevice::ReadOnly); QString data = file.readAll(); qDebug() << "Parsing data: " << data; QList<Gluon::GluonObject*> objects = Gluon::GDLHandler::instance()->parseGDL(data, this); m_text->append(QString("Number of objects: %1").arg(objects.length())); foreach(Gluon::GluonObject* object, objects) { m_text->append(object->name()); } } }
/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <QMenuBar> #include <KFileDialog> #include <gluon/gdlhandler.h> #include <gluon/gluonobject.h> #include <QTextEdit> #include <QVBoxLayout> MainWindow::MainWindow() : GluonMainWindow() { KStandardAction::open(this, SLOT(openFile(bool)), actionCollection()); setupGluon(); m_text = new QTextEdit; delete view(); QWidget* main = new QWidget; QVBoxLayout* layout = new QVBoxLayout; //layout->addWidget(view()); layout->addWidget(m_text); main->setLayout(layout); setCentralWidget(main); } MainWindow::~MainWindow() { } void MainWindow::openFile(bool ) { QString filename = KFileDialog::getOpenFileName(); if(filename != "") { QFile file(filename); file.open(QIODevice::ReadOnly); QString data = file.readAll(); qDebug() << "Parsing data: " << data; QList<Gluon::GluonObject*> objects = Gluon::GDLHandler::instance()->parseGDL(data, this); m_text->append(QString("Number of objects: %1").arg(objects.length())); foreach(Gluon::GluonObject* object, objects) { m_text->append(object->name()); } } }
Fix compile
Fix compile
C++
lgpl-2.1
cgaebel/gluon,cgaebel/gluon,pranavrc/example-gluon,cgaebel/gluon,KDE/gluon,KDE/gluon,cgaebel/gluon,KDE/gluon,pranavrc/example-gluon,pranavrc/example-gluon,KDE/gluon,pranavrc/example-gluon
1671a96294593d0b7161f284b0c2c24f85b29a42
src/SenseKit/Logging.cpp
src/SenseKit/Logging.cpp
#include "Logging.h" #include <SenseKit/sensekit_types.h> INITIALIZE_LOGGING namespace sensekit { void initialize_logging(const char* logFilePath) { const char TRUE_STRING[] = "true"; el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically); el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging); el::Loggers::setLoggingLevel(el::Level::Info); el::Configurations defaultConf; defaultConf.setToDefault(); defaultConf.setGlobally(el::ConfigurationType::Enabled, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToFile, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::Filename, logFilePath); el::Loggers::setDefaultConfigurations(defaultConf, true); defaultConf.clear(); } }
#include "Logging.h" #include <SenseKit/sensekit_types.h> INITIALIZE_LOGGING namespace sensekit { void initialize_logging(const char* logFilePath) { const char TRUE_STRING[] = "true"; el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically); el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging); el::Configurations defaultConf; defaultConf.setToDefault(); defaultConf.setGlobally(el::ConfigurationType::Enabled, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToFile, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::Filename, logFilePath); el::Loggers::setDefaultConfigurations(defaultConf, true); el::Loggers::setLoggingLevel(el::Level::Debug); defaultConf.clear(); } }
Change logging level to show >=INFO severity
Change logging level to show >=INFO severity
C++
apache-2.0
orbbec/astra,orbbec/astra,orbbec/astra,orbbec/astra,orbbec/astra
b1edee052799db1e6e89c0b8f793f54836133c63
src/VideoWriterWrap.cc
src/VideoWriterWrap.cc
#include "VideoWriterWrap.h" #include "Matrix.h" #include "OpenCV.h" #include <iostream> #ifdef HAVE_OPENCV_VIDEOIO Nan::Persistent<FunctionTemplate> VideoWriterWrap::constructor; struct videowriter_baton { Nan::Persistent<Function> cb; VideoWriterWrap *vc; Matrix *im; uv_work_t request; }; void VideoWriterWrap::Init(Local<Object> target) { Nan::HandleScope scope; //Class Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(VideoWriterWrap::New); constructor.Reset(ctor); ctor->InstanceTemplate()->SetInternalFieldCount(1); ctor->SetClassName(Nan::New("VideoWriter").ToLocalChecked()); Nan::SetPrototypeMethod(ctor, "write", Write); Nan::SetPrototypeMethod(ctor, "writeSync", WriteSync); Nan::SetPrototypeMethod(ctor, "release", Release); target->Set(Nan::New("VideoWriter").ToLocalChecked(), ctor->GetFunction()); } NAN_METHOD(VideoWriterWrap::New) { Nan::HandleScope scope; if (info.This()->InternalFieldCount() == 0) return Nan::ThrowTypeError("Cannot Instantiate without new"); VideoWriterWrap *v; // Arg 0 is the output filename std::string filename = std::string(*Nan::Utf8String(info[0]->ToString())); // Arg 1 is the fourcc code const char *fourccStr = std::string(*Nan::Utf8String(info[1]->ToString())).c_str(); int fourcc = CV_FOURCC(fourccStr[0],fourccStr[1],fourccStr[2],fourccStr[3]); // Arg 2 is the output fps double fps = Nan::To<double>(info[2]).FromJust(); // Arg 3 is the image size cv::Size imageSize; if (info[3]->IsArray()) { Local<Object> v8sz = info[3]->ToObject(); imageSize = cv::Size(v8sz->Get(1)->IntegerValue(), v8sz->Get(0)->IntegerValue()); } else { JSTHROW_TYPE("Must pass image size"); } // Arg 4 is the color flag bool isColor = info[4]->BooleanValue(); v = new VideoWriterWrap(filename, fourcc, fps, imageSize, isColor); v->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } VideoWriterWrap::VideoWriterWrap(const std::string& filename, int fourcc, double fps, cv::Size frameSize, bool isColor) { Nan::HandleScope scope; writer.open(filename, fourcc, fps, frameSize, isColor); if(!writer.isOpened()) { Nan::ThrowError("Writer could not be opened"); } } NAN_METHOD(VideoWriterWrap::Release) { Nan::HandleScope scope; VideoWriterWrap *v = Nan::ObjectWrap::Unwrap<VideoWriterWrap>(info.This()); v->writer.release(); return; } class AsyncVWWorker: public Nan::AsyncWorker { public: AsyncVWWorker(Nan::Callback *callback, VideoWriterWrap *vw, Matrix *im) : Nan::AsyncWorker(callback), vw(vw), im(im) { } ~AsyncVWWorker() { } // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute() { this->vw->writer.write(im->mat); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback() { Nan::HandleScope scope; Local<Value> argv[] = { Nan::Null() }; Nan::TryCatch try_catch; callback->Call(1, argv); if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } } private: VideoWriterWrap *vw; Matrix* im; }; NAN_METHOD(VideoWriterWrap::Write) { Nan::HandleScope scope; VideoWriterWrap *v = Nan::ObjectWrap::Unwrap<VideoWriterWrap>(info.This()); Matrix *im = Nan::ObjectWrap::Unwrap < Matrix > (info[0]->ToObject()); REQ_FUN_ARG(1, cb); Nan::Callback *callback = new Nan::Callback(cb.As<Function>()); Nan::AsyncQueueWorker(new AsyncVWWorker(callback, v, im)); return; } NAN_METHOD(VideoWriterWrap::WriteSync) { Nan::HandleScope scope; VideoWriterWrap *v = Nan::ObjectWrap::Unwrap<VideoWriterWrap>(info.This()); Matrix *im = Nan::ObjectWrap::Unwrap < Matrix > (info[0]->ToObject()); v->writer.write(im->mat); info.GetReturnValue().Set(Nan::Null()); } #endif
#include "VideoWriterWrap.h" #include "Matrix.h" #include "OpenCV.h" #include <iostream> #ifdef HAVE_OPENCV_VIDEOIO Nan::Persistent<FunctionTemplate> VideoWriterWrap::constructor; struct videowriter_baton { Nan::Persistent<Function> cb; VideoWriterWrap *vc; Matrix *im; uv_work_t request; }; void VideoWriterWrap::Init(Local<Object> target) { Nan::HandleScope scope; //Class Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(VideoWriterWrap::New); constructor.Reset(ctor); ctor->InstanceTemplate()->SetInternalFieldCount(1); ctor->SetClassName(Nan::New("VideoWriter").ToLocalChecked()); Nan::SetPrototypeMethod(ctor, "write", Write); Nan::SetPrototypeMethod(ctor, "writeSync", WriteSync); Nan::SetPrototypeMethod(ctor, "release", Release); target->Set(Nan::New("VideoWriter").ToLocalChecked(), ctor->GetFunction()); } NAN_METHOD(VideoWriterWrap::New) { Nan::HandleScope scope; if (info.This()->InternalFieldCount() == 0) return Nan::ThrowTypeError("Cannot Instantiate without new"); VideoWriterWrap *v; // Arg 0 is the output filename std::string filename = std::string(*Nan::Utf8String(info[0]->ToString())); // Arg 1 is the fourcc code const char *fourccStr = std::string(*Nan::Utf8String(info[1]->ToString())).c_str(); int fourcc = CV_FOURCC(fourccStr[0],fourccStr[1],fourccStr[2],fourccStr[3]); // Arg 2 is the output fps double fps = Nan::To<double>(info[2]).FromJust(); // Arg 3 is the image size cv::Size imageSize; if (info[3]->IsArray()) { Local<Object> v8sz = info[3]->ToObject(); imageSize = cv::Size(v8sz->Get(1)->IntegerValue(), v8sz->Get(0)->IntegerValue()); } else { JSTHROW_TYPE("Must pass image size"); } // Arg 4 is the color flag bool isColor = info[4]->BooleanValue(); v = new VideoWriterWrap(filename, fourcc, fps, imageSize, isColor); v->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } VideoWriterWrap::VideoWriterWrap(const std::string& filename, int fourcc, double fps, cv::Size frameSize, bool isColor) { Nan::HandleScope scope; writer.open(filename, fourcc, fps, frameSize, isColor); if(!writer.isOpened()) { Nan::ThrowError("Writer could not be opened"); } } NAN_METHOD(VideoWriterWrap::Release) { Nan::HandleScope scope; VideoWriterWrap *v = Nan::ObjectWrap::Unwrap<VideoWriterWrap>(info.This()); v->writer.release(); return; } class AsyncVWWorker: public Nan::AsyncWorker { public: AsyncVWWorker(Nan::Callback *callback, VideoWriterWrap *vw, cv::Mat mat) : Nan::AsyncWorker(callback), vw(vw), mat(mat) { } ~AsyncVWWorker() { } // Executed inside the worker-thread. // It is not safe to access V8, or V8 data structures // here, so everything we need for input and output // should go on `this`. void Execute() { this->vw->writer.write(mat); } // Executed when the async work is complete // this function will be run inside the main event loop // so it is safe to use V8 again void HandleOKCallback() { Nan::HandleScope scope; Local<Value> argv[] = { Nan::Null() }; Nan::TryCatch try_catch; callback->Call(1, argv); if (try_catch.HasCaught()) { Nan::FatalException(try_catch); } } private: VideoWriterWrap *vw; cv::Mat mat; }; NAN_METHOD(VideoWriterWrap::Write) { Nan::HandleScope scope; VideoWriterWrap *v = Nan::ObjectWrap::Unwrap<VideoWriterWrap>(info.This()); Matrix *im = Nan::ObjectWrap::Unwrap < Matrix > (info[0]->ToObject()); REQ_FUN_ARG(1, cb); Nan::Callback *callback = new Nan::Callback(cb.As<Function>()); Nan::AsyncQueueWorker(new AsyncVWWorker(callback, v, im->mat)); return; } NAN_METHOD(VideoWriterWrap::WriteSync) { Nan::HandleScope scope; VideoWriterWrap *v = Nan::ObjectWrap::Unwrap<VideoWriterWrap>(info.This()); Matrix *im = Nan::ObjectWrap::Unwrap < Matrix > (info[0]->ToObject()); v->writer.write(im->mat); info.GetReturnValue().Set(Nan::Null()); } #endif
make safe to mat.release() before async is complete
VideoWriter: make safe to mat.release() before async is complete
C++
mit
peterbraden/node-opencv,peterbraden/node-opencv,peterbraden/node-opencv,peterbraden/node-opencv
c5dacbfc8483d5980c6ec95f24f5a7a4f03117c3
src/file_manager/server/FileServer.cpp
src/file_manager/server/FileServer.cpp
#include "FileServer.h" #include "socket.h" #ifndef C_WIN_SOCK #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #endif #include <stdio.h> #include <stdlib.h> #include <cstring> #include <iostream> #include <chrono> #include <thread> #define MAX_LENGTH_OF_QUEUE_PANDING 5 using namespace std; FileServer::FileServer(int port, string dbFilePath): dbFilePath(move(dbFilePath)), buffer(unique_ptr<char[]>(new char[SIZE_BUFFER])) { fd = fopen(this->dbFilePath.c_str(), "ab+"); if(fd == NULL) { cerr << "can't open the file" << endl; exit(1); } isBind = false; this->port = port; fseek(fd, 0, SEEK_END); fileSize = ftell(fd); memset(buffer.get(), 0, SIZE_BUFFER); recoverServer(); ///////// socket.makeNonblocking(); //cout << "line 40\n"; socket.bindTo(port); //cout << "line 42\n"; ::listen(socket, MAX_LENGTH_OF_QUEUE_PANDING); } FileServer::~FileServer() { fclose(fd); } int FileServer::acceptClient() // TODO change the name { return accept(socket, nullptr, nullptr); } bool FileServer::receive() { connection = acceptClient(); if (connection < 0) { return true; // no client - all is ok } bool result = false; auto etype = eventType(connection); switch (etype) { case 0: if (initialAppend(connection)) { result = appendToFile(connection); } break; case 1: result = sendFileToClient(connection); break; } #ifdef C_WIN_SOCK closesocket(connection); #else close(connection); #endif return result; } bool FileServer::recieveSizeOfFile(int connection) { int receivedBytes = -1; int retries = 100; while(retries && receivedBytes <= 0) { //cout << "line: 95 - recieveSizeOfFile\n"; receivedBytes = ::recv( connection, reinterpret_cast<char *>(&info.sizeOfFile), sizeof(uint64_t), 0); if (receivedBytes == 0) { cout << "Connection to remote client closed" << endl; return false; } else if (receivedBytes == -1) { this_thread::sleep_for(chrono::milliseconds(1)); // give client time to receive size --retries; } } if (!retries) { cout << "Failed to receive size of file" << endl; return false; } if(receivedBytes) { info.id = nextFreeId++; all_ids.push_back(nextFreeId); } return receivedBytes; } bool FileServer::initialAppend(int connection) { int writtenBytes = 0; if (recieveSizeOfFile(connection)) { fclose(fd); fd = fopen(dbFilePath.c_str(), "ab+"); if (!fd) { return 0; } writtenBytes = fwrite(&info, sizeof(InfoData), 1, fd); } return writtenBytes == 1; } bool FileServer::appendToFile(int connection) { int readBytes = -1; uint64_t sizeOfFile = info.sizeOfFile; int retries = 100; while(sizeOfFile && retries) { readBytes = ::recv(connection, buffer.get(), SIZE_BUFFER, 0); if (readBytes == -1) { --retries; this_thread::sleep_for(chrono::milliseconds(1)); // give it time to receive data //cout << "line 136\n"; continue; } else if (readBytes == 0) { cout << "Connection to client closed while receiveing file" << endl; return false; } fwrite(buffer.get(), sizeof(char), readBytes, fd); if (sizeOfFile < readBytes) { cout << "Failed to append to file - wrong file size - would inf loop" << endl; return false; } sizeOfFile -= readBytes; } fileSize += info.sizeOfFile; retries = 100; while(--retries) { if(sizeof(uint64_t) == ::send(connection, reinterpret_cast<const char *>(&info.id), sizeof(uint64_t), 0)) { break; } //cout << "Send line: 152\n"; this_thread::sleep_for(chrono::milliseconds(1)); // give client time to receive id } if (!retries) { std::cerr << "Failed to send file ID to client" << endl; return false; } if (readBytes < 0) { std::cerr << "ERROR writing to socket"; return false; } return true; } bool FileServer::sendInfoFileToClient(int newfd) { int retries = 100; while(--retries) { if( sizeof(uint64_t) == ::send( newfd, reinterpret_cast<const char *>(&info.sizeOfFile), sizeof(uint64_t), 0) ) { return true; } this_thread::sleep_for(chrono::milliseconds(1)); // give client time to receive size //cout << "Send line: 174\n"; } return false; } uint64_t FileServer::getIdByClient(int connection) { uint64_t id = 0; int retries = 100; while(--retries && sizeof(uint64_t) != ::recv(connection, reinterpret_cast<char*>(&id), sizeof(uint64_t), 0)) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } return id; } bool FileServer::sendFileToClient(int newfd) { uint64_t id = getIdByClient(newfd); uint64_t bytesToTransfer = seek2File(id); if(bytesToTransfer == 0) { cout << "ERROR: you are trying to get file with wrong id!!!\n"; return false; } int retries = 100; while (--retries && sizeof(uint64_t) != ::send(newfd, reinterpret_cast<const char*>(&bytesToTransfer), sizeof(uint64_t), 0)) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); //cout << "Send line: 205\n"; } if (!retries) { return false; } while(bytesToTransfer > 0) { int readBytes = fread(buffer.get(), sizeof(char), SIZE_BUFFER, this->fd); if ( ferror(fd) || readBytes < 0 ) { cout << "Failed to read from db file" << endl; return false; } else if ( feof(fd) ) { break; } else if (-1 == readBytes) { continue; } if (bytesToTransfer < readBytes) { cout << "Wrong sent size - would go into inf loop" << endl; return false; } bytesToTransfer -= readBytes; while(readBytes > 0) { int sentBytes = ::send(newfd, buffer.get(), readBytes, 0); if (sentBytes == -1) { continue; } if (readBytes < sentBytes) { cout << "Failed to send bytes from db to client" << endl; return false; } readBytes -= sentBytes; } if(bytesToTransfer > 0 && bytesToTransfer < SIZE_BUFFER) // TODO { fread(buffer.get(), sizeof(char), bytesToTransfer, fd); ::send(newfd, buffer.get(), bytesToTransfer, 0); break; } } } uint64_t FileServer::seek2File(uint64_t id) { InfoData data; uint64_t currentSize = fileSize; fclose(fd); fd = fopen(dbFilePath.c_str(), "ab+"); fseek(fd, 0, SEEK_SET); while(currentSize > 0) { auto read = fread(reinterpret_cast<char*>(&data), sizeof(InfoData), 1, fd); if (read != 1) { perror("Failed to read InfoData"); return 0; } currentSize -= sizeof(InfoData); if(id == data.id) { return data.sizeOfFile; } auto seek = fseek(fd, data.sizeOfFile, SEEK_CUR); if (currentSize < data.sizeOfFile) { cout << "Failed to read data structure from db" << endl; return 0; } currentSize -= data.sizeOfFile; } return 0; } uint64_t FileServer::eventType(int connection) { uint64_t type = -1; int retries = 100; while(--retries && sizeof(uint64_t) != ::recv( connection, reinterpret_cast<char *>(&type), sizeof(uint64_t), 0)) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); // give the client time to send type //cout << "Send line: 275\n"; } if (!retries) { cout << "Failed to receive event type from client"; return -1; } return type; } bool FileServer::doesFileExist() { return fileSize; } std::vector<uint64_t> FileServer::getAllIds() { return all_ids; } void FileServer::run() { isRun = true; if(doesFileExist()) { recoverServer(); } while(isRun) { if (!receive()) { cout << "Failed to server user action" << endl; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } int FileServer::getPort() { return port; } void FileServer::setPort(int newPort) { port = newPort; } void FileServer::recoverServer() { uint64_t file_sz = fileSize; uint64_t readBytes; InfoData data; fseek(fd, 0, SEEK_SET); while(file_sz) { readBytes = fread(reinterpret_cast<char*>(&data), sizeof(InfoData), 1, fd); if(readBytes != 1) { cout << "Can't read InfoData structure - failed read" << endl; exit(1); } file_sz -= sizeof(InfoData); fseek(fd, data.sizeOfFile, SEEK_CUR); if (file_sz < data.sizeOfFile) { cout << "Can't read InfoData structure - broken file" << endl; exit(1); } file_sz -= data.sizeOfFile; all_ids.push_back(data.id); } setNextFreeId(); } void FileServer::setNextFreeId() { if(!all_ids.size()) { nextFreeId = 1; return; } uint64_t max_id = all_ids[0]; for(auto& iter : all_ids) { if(max_id < iter) { max_id = iter; } } nextFreeId = ++max_id; } void FileServer::stop() { isRun = false; }
#include "FileServer.h" #include "socket.h" #ifndef C_WIN_SOCK #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #endif #include <stdio.h> #include <stdlib.h> #include <cstring> #include <iostream> #include <chrono> #include <thread> #define MAX_LENGTH_OF_QUEUE_PANDING 5 using namespace std; FileServer::FileServer(int port, string dbFilePath): dbFilePath(move(dbFilePath)), buffer(unique_ptr<char[]>(new char[SIZE_BUFFER])) { fd = fopen(this->dbFilePath.c_str(), "ab+"); if(fd == NULL) { cerr << "can't open the file" << endl; exit(1); } isBind = false; this->port = port; fseek(fd, 0, SEEK_END); fileSize = ftell(fd); memset(buffer.get(), 0, SIZE_BUFFER); recoverServer(); ///////// socket.makeNonblocking(); //cout << "line 40\n"; socket.bindTo(port); //cout << "line 42\n"; ::listen(socket, MAX_LENGTH_OF_QUEUE_PANDING); } FileServer::~FileServer() { fclose(fd); } int FileServer::acceptClient() // TODO change the name { return accept(socket, nullptr, nullptr); } bool FileServer::receive() { connection = acceptClient(); if (connection < 0) { return true; // no client - all is ok } bool result = false; auto etype = eventType(connection); switch (etype) { case 0: if (initialAppend(connection)) { result = appendToFile(connection); } break; case 1: result = sendFileToClient(connection); break; } #ifdef C_WIN_SOCK closesocket(connection); #else close(connection); #endif return result; } bool FileServer::recieveSizeOfFile(int connection) { int receivedBytes = -1; int retries = 100; while(retries && receivedBytes <= 0) { //cout << "line: 95 - recieveSizeOfFile\n"; receivedBytes = ::recv( connection, reinterpret_cast<char *>(&info.sizeOfFile), sizeof(uint64_t), 0); if (receivedBytes == 0) { cout << "Connection to remote client closed" << endl; return false; } else if (receivedBytes == -1) { this_thread::sleep_for(chrono::milliseconds(1)); // give client time to receive size --retries; } } if (!retries) { cout << "Failed to receive size of file" << endl; return false; } if(receivedBytes) { info.id = nextFreeId++; all_ids.push_back(nextFreeId); } return receivedBytes; } bool FileServer::initialAppend(int connection) { int writtenBytes = 0; if (recieveSizeOfFile(connection)) { fclose(fd); fd = fopen(dbFilePath.c_str(), "ab+"); if (!fd) { return 0; } writtenBytes = fwrite(&info, sizeof(InfoData), 1, fd); } return writtenBytes == 1; } bool FileServer::appendToFile(int connection) { int readBytes = -1; uint64_t sizeOfFile = info.sizeOfFile; int retries = 100; while(sizeOfFile && retries) { readBytes = ::recv(connection, buffer.get(), SIZE_BUFFER, 0); if (readBytes == -1) { --retries; this_thread::sleep_for(chrono::milliseconds(1)); // give it time to receive data //cout << "line 136\n"; continue; } else if (readBytes == 0) { cout << "Connection to client closed while receiveing file" << endl; return false; } fwrite(buffer.get(), sizeof(char), readBytes, fd); if (sizeOfFile < readBytes) { cout << "Failed to append to file - wrong file size - would inf loop" << endl; return false; } sizeOfFile -= readBytes; } fileSize += info.sizeOfFile; retries = 100; while(--retries) { if(sizeof(uint64_t) == ::send(connection, reinterpret_cast<const char *>(&info.id), sizeof(uint64_t), 0)) { break; } //cout << "Send line: 152\n"; this_thread::sleep_for(chrono::milliseconds(1)); // give client time to receive id } if (!retries) { std::cerr << "Failed to send file ID to client" << endl; return false; } if (readBytes < 0) { std::cerr << "ERROR writing to socket"; return false; } return true; } bool FileServer::sendInfoFileToClient(int newfd) { int retries = 100; while(--retries) { if( sizeof(uint64_t) == ::send( newfd, reinterpret_cast<const char *>(&info.sizeOfFile), sizeof(uint64_t), 0) ) { return true; } this_thread::sleep_for(chrono::milliseconds(1)); // give client time to receive size //cout << "Send line: 174\n"; } return false; } uint64_t FileServer::getIdByClient(int connection) { uint64_t id = 0; int retries = 100; while(--retries && sizeof(uint64_t) != ::recv(connection, reinterpret_cast<char*>(&id), sizeof(uint64_t), 0)) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } return id; } bool FileServer::sendFileToClient(int newfd) { uint64_t id = getIdByClient(newfd); uint64_t bytesToTransfer = seek2File(id); if(bytesToTransfer == 0) { cout << "ERROR: you are trying to get file with wrong id!!!\n"; return false; } int retries = 100; while (--retries && sizeof(uint64_t) != ::send(newfd, reinterpret_cast<const char*>(&bytesToTransfer), sizeof(uint64_t), 0)) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); //cout << "Send line: 205\n"; } if (!retries) { return false; } while(bytesToTransfer > 0) { int readBytes = fread(buffer.get(), sizeof(char), SIZE_BUFFER, this->fd); if ( ferror(fd) || readBytes < 0 ) { cout << "Failed to read from db file" << endl; return false; } else if ( feof(fd) ) { break; } else if (-1 == readBytes) { continue; } if (bytesToTransfer < readBytes) { cout << "Wrong sent size - would go into inf loop" << endl; return false; } bytesToTransfer -= readBytes; while(readBytes > 0) { int sentBytes = ::send(newfd, buffer.get(), readBytes, 0); if (sentBytes == -1) { continue; } if (readBytes < sentBytes) { cout << "Failed to send bytes from db to client" << endl; return false; } readBytes -= sentBytes; } if(bytesToTransfer > 0 && bytesToTransfer < SIZE_BUFFER) // TODO { fread(buffer.get(), sizeof(char), bytesToTransfer, fd); ::send(newfd, buffer.get(), bytesToTransfer, 0); break; } } return true; } uint64_t FileServer::seek2File(uint64_t id) { InfoData data; uint64_t currentSize = fileSize; fclose(fd); fd = fopen(dbFilePath.c_str(), "ab+"); fseek(fd, 0, SEEK_SET); while(currentSize > 0) { auto read = fread(reinterpret_cast<char*>(&data), sizeof(InfoData), 1, fd); if (read != 1) { perror("Failed to read InfoData"); return 0; } currentSize -= sizeof(InfoData); if(id == data.id) { return data.sizeOfFile; } auto seek = fseek(fd, data.sizeOfFile, SEEK_CUR); if (currentSize < data.sizeOfFile) { cout << "Failed to read data structure from db" << endl; return 0; } currentSize -= data.sizeOfFile; } return 0; } uint64_t FileServer::eventType(int connection) { uint64_t type = -1; int retries = 100; while(--retries && sizeof(uint64_t) != ::recv( connection, reinterpret_cast<char *>(&type), sizeof(uint64_t), 0)) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); // give the client time to send type //cout << "Send line: 275\n"; } if (!retries) { cout << "Failed to receive event type from client"; return -1; } return type; } bool FileServer::doesFileExist() { return fileSize; } std::vector<uint64_t> FileServer::getAllIds() { return all_ids; } void FileServer::run() { isRun = true; if(doesFileExist()) { recoverServer(); } while(isRun) { if (!receive()) { cout << "Failed to server user action" << endl; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } int FileServer::getPort() { return port; } void FileServer::setPort(int newPort) { port = newPort; } void FileServer::recoverServer() { uint64_t file_sz = fileSize; uint64_t readBytes; InfoData data; fseek(fd, 0, SEEK_SET); while(file_sz) { readBytes = fread(reinterpret_cast<char*>(&data), sizeof(InfoData), 1, fd); if(readBytes != 1) { cout << "Can't read InfoData structure - failed read" << endl; exit(1); } file_sz -= sizeof(InfoData); fseek(fd, data.sizeOfFile, SEEK_CUR); if (file_sz < data.sizeOfFile) { cout << "Can't read InfoData structure - broken file" << endl; exit(1); } file_sz -= data.sizeOfFile; all_ids.push_back(data.id); } setNextFreeId(); } void FileServer::setNextFreeId() { if(!all_ids.size()) { nextFreeId = 1; return; } uint64_t max_id = all_ids[0]; for(auto& iter : all_ids) { if(max_id < iter) { max_id = iter; } } nextFreeId = ++max_id; } void FileServer::stop() { isRun = false; }
Fix return val for sendFileToClient
Fix return val for sendFileToClient
C++
mit
Plamenod/P2P
ffc566733fb530af9aa046d8cd3ee198e201a8f1
blackEuro/blackEuro.cpp
blackEuro/blackEuro.cpp
/* ====================================================== Copyright 2016 Liang Ma 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. ====================================================== * * Author: Liang Ma ([email protected]) * * Top function is defined here with interface specified as axi4. * It creates an object of blackScholes and launches the simulation. * *---------------------------------------------------------------------------- */ #include "../common/blackScholes.h" #include "../common/defTypes.h" #include "../common/stockData.h" void blackEuro(data_t *pCall, data_t *pPut, // call price and put price data_t timeT, // time period of options data_t freeRate, // interest rate of the riskless asset data_t volatility, // volatility of the risky asset data_t initPrice, // stock price at time 0 data_t strikePrice) // strike price { #pragma HLS INTERFACE m_axi port=pCall bundle=gmem #pragma HLS INTERFACE s_axilite port=pCall bundle=control #pragma HLS INTERFACE m_axi port=pPut bundle=gmem #pragma HLS INTERFACE s_axilite port=pPut bundle=control #pragma HLS INTERFACE s_axilite port=timeT bundle=gmem #pragma HLS INTERFACE s_axilite port=timeT bundle=control #pragma HLS INTERFACE s_axilite port=freeRate bundle=gmem #pragma HLS INTERFACE s_axilite port=freeRate bundle=control #pragma HLS INTERFACE s_axilite port=volatility bundle=gmem #pragma HLS INTERFACE s_axilite port=volatility bundle=control #pragma HLS INTERFACE s_axilite port=initPrice bundle=gmem #pragma HLS INTERFACE s_axilite port=initPrice bundle=control #pragma HLS INTERFACE s_axilite port=strikePrice bundle=gmem #pragma HLS INTERFACE s_axilite port=strikePrice bundle=control #pragma HLS INTERFACE s_axilite port=return bundle=control stockData sd(timeT,freeRate,volatility,initPrice,strikePrice); blackScholes bs(sd); data_t call,put; bs.simulation(&call,&put); *pCall=call; *pPut=put; return; }
/* ====================================================== Copyright 2016 Liang Ma 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. ====================================================== * * Author: Liang Ma ([email protected]) * * Top function is defined here with interface specified as axi4. * It creates an object of blackScholes and launches the simulation. * *---------------------------------------------------------------------------- */ #include "../common/blackScholes.h" #include "../common/defTypes.h" #include "../common/stockData.h" extern "C" void blackEuro(data_t *pCall, data_t *pPut, // call price and put price data_t timeT, // time period of options data_t freeRate, // interest rate of the riskless asset data_t volatility, // volatility of the risky asset data_t initPrice, // stock price at time 0 data_t strikePrice) // strike price { #pragma HLS INTERFACE m_axi port=pCall bundle=gmem #pragma HLS INTERFACE s_axilite port=pCall bundle=control #pragma HLS INTERFACE m_axi port=pPut bundle=gmem #pragma HLS INTERFACE s_axilite port=pPut bundle=control #pragma HLS INTERFACE s_axilite port=timeT bundle=gmem #pragma HLS INTERFACE s_axilite port=timeT bundle=control #pragma HLS INTERFACE s_axilite port=freeRate bundle=gmem #pragma HLS INTERFACE s_axilite port=freeRate bundle=control #pragma HLS INTERFACE s_axilite port=volatility bundle=gmem #pragma HLS INTERFACE s_axilite port=volatility bundle=control #pragma HLS INTERFACE s_axilite port=initPrice bundle=gmem #pragma HLS INTERFACE s_axilite port=initPrice bundle=control #pragma HLS INTERFACE s_axilite port=strikePrice bundle=gmem #pragma HLS INTERFACE s_axilite port=strikePrice bundle=control #pragma HLS INTERFACE s_axilite port=return bundle=control stockData sd(timeT,freeRate,volatility,initPrice,strikePrice); blackScholes bs(sd); data_t call,put; bs.simulation(&call,&put); *pCall=call; *pPut=put; return; }
add support for SDAccel2016.2
add support for SDAccel2016.2
C++
apache-2.0
KitAway/BlackScholes_MonteCarlo
9e8167ce569e2863f77ff2af707f77657fd4b8dd
cf/8D.cpp
cf/8D.cpp
/* * D. Two Friends * time limit per test1 second * memory limit per test64 megabytes * inputstandard input * outputstandard output * Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. * * Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. * * Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends. * * The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than t1, and the distance covered by Bob should not differ from the shortest one by more than t2. * * Find the maximum distance that Alan and Bob will cover together, discussing the film. * * Input * The first line contains two integers: t1, t2 (0 ≤ t1, t2 ≤ 100). The second line contains the cinema's coordinates, the third one — the house's, and the last line — the shop's. * * All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building. * * Output * In the only line output one number — the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places. * * Examples * input * 0 2 * 0 0 * 4 0 * -3 0 * output * 1.0000000000 * input * 0 0 * 0 0 * 2 0 * 1 0 * output * 2.0000000000 * */ int main() { return 0; }
/* * D. Two Friends * time limit per test1 second * memory limit per test64 megabytes * inputstandard input * outputstandard output * Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. * * Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. * * Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends. * * The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than t1, and the distance covered by Bob should not differ from the shortest one by more than t2. * * Find the maximum distance that Alan and Bob will cover together, discussing the film. * * Input * The first line contains two integers: t1, t2 (0 ≤ t1, t2 ≤ 100). The second line contains the cinema's coordinates, the third one — the house's, and the last line — the shop's. * * All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building. * * Output * In the only line output one number — the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places. * * Examples * input * 0 2 * 0 0 * 4 0 * -3 0 * output * 1.0000000000 * input * 0 0 * 0 0 * 2 0 * 1 0 * output * 2.0000000000 * */ #include <math.h> #include <stdio.h> #include <iostream> using namespace std; double dist(int x1, int y1, int x2, int y2) { int dx = x1-y1; int dy = x2-y2; return sqrt(dx*dx+dy*dy); } int main() { int t1, t2, cx, cy, hx, hy, sx, sy; cin >> t1 >> t2 >>cx >> cy >> hx >> hy >> sx >> sy; double dcs = dist(cx, cy, sx, sy); double dsh = dist(sx, sy, hx, hy); double dch = dist(cx, cy, hx, hy); double T1 = dcs + dsh + t1; double T2 = dch + t2; if (T1 < T2 || fabs(T1-T2) < 1e-6) { cout << T1; return 0; } return 0; }
add cf 8d
add cf 8d
C++
mit
LihuaWu/algorithms
60a4c7d9f6a0fc997e11898f9042977922026052
src/IconButton.cc
src/IconButton.cc
// IconButton.cc // Copyright (c) 2003 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org) // and Simon Bowden (rathnor at users.sourceforge.net) // // 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 "IconButton.hh" #include "IconbarTool.hh" #include "IconbarTheme.hh" #include "Screen.hh" #include "FbTk/App.hh" #include "FbTk/Command.hh" #include "FbTk/EventManager.hh" #include "FbTk/ImageControl.hh" #include "FbTk/TextUtils.hh" #include "FbTk/MacroCommand.hh" #include "FbTk/Menu.hh" #include "FbTk/RefCount.hh" #include "FbTk/SimpleCommand.hh" #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include <X11/Xutil.h> #ifdef SHAPE #include <X11/extensions/shape.h> #endif // SHAPE IconButton::IconButton(const FbTk::FbWindow &parent, FbTk::ThemeProxy<IconbarTheme> &focused_theme, FbTk::ThemeProxy<IconbarTheme> &unfocused_theme, Focusable &win): FbTk::TextButton(parent, focused_theme->text().font(), win.title()), m_win(win), m_icon_window(*this, 1, 1, 1, 1, ExposureMask |EnterWindowMask | LeaveWindowMask | ButtonPressMask | ButtonReleaseMask), m_use_pixmap(true), m_has_tooltip(false), m_theme(win, focused_theme, unfocused_theme), m_pm(win.screen().imageControl()) { m_win.titleSig().attach(this); m_win.focusSig().attach(this); m_win.attentionSig().attach(this); FbTk::EventManager::instance()->add(*this, m_icon_window); reconfigTheme(); update(0); } IconButton::~IconButton() { // ~FbWindow cleans event manager } void IconButton::exposeEvent(XExposeEvent &event) { if (m_icon_window == event.window) m_icon_window.clear(); else FbTk::TextButton::exposeEvent(event); } void IconButton::enterNotifyEvent(XCrossingEvent &ev) { m_has_tooltip = true; showTooltip(); } void IconButton::leaveNotifyEvent(XCrossingEvent &ev) { m_has_tooltip = false; m_win.screen().hideTooltip(); } void IconButton::moveResize(int x, int y, unsigned int width, unsigned int height) { FbTk::TextButton::moveResize(x, y, width, height); if (m_icon_window.width() != FbTk::Button::width() || m_icon_window.height() != FbTk::Button::height()) { update(0); // update icon window } } void IconButton::resize(unsigned int width, unsigned int height) { FbTk::TextButton::resize(width, height); if (m_icon_window.width() != FbTk::Button::width() || m_icon_window.height() != FbTk::Button::height()) { update(0); // update icon window } } void IconButton::showTooltip() { int xoffset = 1; if (m_icon_pixmap.drawable() != 0) xoffset = m_icon_window.x() + m_icon_window.width() + 1; if (FbTk::TextButton::textExceeds(xoffset)) m_win.screen().showTooltip(m_win.title()); } void IconButton::clear() { setupWindow(); } void IconButton::clearArea(int x, int y, unsigned int width, unsigned int height, bool exposure) { FbTk::TextButton::clearArea(x, y, width, height, exposure); } void IconButton::setPixmap(bool use) { if (m_use_pixmap != use) { m_use_pixmap = use; update(0); } } void IconButton::reconfigTheme() { if (m_theme->texture().usePixmap()) m_pm.reset(m_win.screen().imageControl().renderImage( width(), height(), m_theme->texture(), orientation())); else m_pm.reset(0); setAlpha(parent()->alpha()); if (m_pm != 0) setBackgroundPixmap(m_pm); else setBackgroundColor(m_theme->texture().color()); setGC(m_theme->text().textGC()); setFont(m_theme->text().font()); setJustify(m_theme->text().justify()); setBorderWidth(m_theme->border().width()); setBorderColor(m_theme->border().color()); updateBackground(false); } void IconButton::update(FbTk::Subject *subj) { // if the window's focus state changed, we need to update the background if (subj == &m_win.focusSig() || subj == &m_win.attentionSig()) { reconfigTheme(); clear(); return; } // we got signal that either title or // icon pixmap was updated, // so we refresh everything Display *display = FbTk::App::instance()->display(); int screen = m_win.screen().screenNumber(); if (m_use_pixmap && m_win.icon().pixmap().drawable() != None) { // setup icon window m_icon_window.show(); unsigned int w = width(); unsigned int h = height(); FbTk::translateSize(orientation(), w, h); int iconx = 1, icony = 1; unsigned int neww = w, newh = h; if (newh > 2*static_cast<unsigned>(icony)) newh -= 2*icony; else newh = 1; neww = newh; FbTk::translateCoords(orientation(), iconx, icony, w, h); FbTk::translatePosition(orientation(), iconx, icony, neww, newh, 0); m_icon_window.moveResize(iconx, icony, neww, newh); m_icon_pixmap.copy(m_win.icon().pixmap().drawable(), DefaultDepth(display, screen), screen); m_icon_pixmap.scale(m_icon_window.width(), m_icon_window.height()); // rotate the icon or not?? lets go not for now, and see what they say... // need to rotate mask too if we do do this m_icon_pixmap.rotate(orientation()); m_icon_window.setBackgroundPixmap(m_icon_pixmap.drawable()); } else { // no icon pixmap m_icon_window.move(0, 0); m_icon_window.hide(); m_icon_pixmap = 0; } if(m_icon_pixmap.drawable() && m_win.icon().mask().drawable() != None) { m_icon_mask.copy(m_win.icon().mask().drawable(), 0, 0); m_icon_mask.scale(m_icon_pixmap.width(), m_icon_pixmap.height()); m_icon_mask.rotate(orientation()); } else m_icon_mask = 0; #ifdef SHAPE XShapeCombineMask(display, m_icon_window.drawable(), ShapeBounding, 0, 0, m_icon_mask.drawable(), ShapeSet); #endif // SHAPE if (subj != 0) { setupWindow(); } else { m_icon_window.clear(); } // if the title was changed AND the tooltip window is visible AND // we have had an enter notify event ( without the leave notify ) // update the text inside it if (subj == &m_win.titleSig() && m_has_tooltip && m_win.screen().tooltipWindow().isVisible()) { m_win.screen().tooltipWindow().updateText(m_win.title()); } } void IconButton::setupWindow() { m_icon_window.clear(); setText(m_win.title()); FbTk::TextButton::clear(); } void IconButton::drawText(int x, int y, FbTk::FbDrawable *drawable) { // offset text if (m_icon_pixmap.drawable() != 0) FbTk::TextButton::drawText(m_icon_window.x() + m_icon_window.width() + 1, y, drawable); else FbTk::TextButton::drawText(1, y, drawable); } bool IconButton::setOrientation(FbTk::Orientation orient) { if (orientation() == orient) return true; if (FbTk::TextButton::setOrientation(orient)) { int iconx = 1, icony = 1; unsigned int tmpw = width(), tmph = height(); FbTk::translateSize(orient, tmpw, tmph); FbTk::translateCoords(orient, iconx, icony, tmpw, tmph); FbTk::translatePosition(orient, iconx, icony, m_icon_window.width(), m_icon_window.height(), 0); m_icon_window.move(iconx, icony); return true; } else { return false; } }
// IconButton.cc // Copyright (c) 2003 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org) // and Simon Bowden (rathnor at users.sourceforge.net) // // 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 "IconButton.hh" #include "IconbarTool.hh" #include "IconbarTheme.hh" #include "Screen.hh" #include "FbTk/App.hh" #include "FbTk/Command.hh" #include "FbTk/EventManager.hh" #include "FbTk/ImageControl.hh" #include "FbTk/TextUtils.hh" #include "FbTk/MacroCommand.hh" #include "FbTk/Menu.hh" #include "FbTk/RefCount.hh" #include "FbTk/SimpleCommand.hh" #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include <X11/Xutil.h> #ifdef SHAPE #include <X11/extensions/shape.h> #endif // SHAPE IconButton::IconButton(const FbTk::FbWindow &parent, FbTk::ThemeProxy<IconbarTheme> &focused_theme, FbTk::ThemeProxy<IconbarTheme> &unfocused_theme, Focusable &win): FbTk::TextButton(parent, focused_theme->text().font(), win.title()), m_win(win), m_icon_window(*this, 1, 1, 1, 1, ExposureMask |EnterWindowMask | LeaveWindowMask | ButtonPressMask | ButtonReleaseMask), m_use_pixmap(true), m_has_tooltip(false), m_theme(win, focused_theme, unfocused_theme), m_pm(win.screen().imageControl()) { m_win.titleSig().attach(this); m_win.focusSig().attach(this); m_win.attentionSig().attach(this); FbTk::EventManager::instance()->add(*this, m_icon_window); reconfigTheme(); update(0); } IconButton::~IconButton() { // ~FbWindow cleans event manager if (m_has_tooltip) m_win.screen().hideTooltip(); } void IconButton::exposeEvent(XExposeEvent &event) { if (m_icon_window == event.window) m_icon_window.clear(); else FbTk::TextButton::exposeEvent(event); } void IconButton::enterNotifyEvent(XCrossingEvent &ev) { m_has_tooltip = true; showTooltip(); } void IconButton::leaveNotifyEvent(XCrossingEvent &ev) { m_has_tooltip = false; m_win.screen().hideTooltip(); } void IconButton::moveResize(int x, int y, unsigned int width, unsigned int height) { FbTk::TextButton::moveResize(x, y, width, height); if (m_icon_window.width() != FbTk::Button::width() || m_icon_window.height() != FbTk::Button::height()) { update(0); // update icon window } } void IconButton::resize(unsigned int width, unsigned int height) { FbTk::TextButton::resize(width, height); if (m_icon_window.width() != FbTk::Button::width() || m_icon_window.height() != FbTk::Button::height()) { update(0); // update icon window } } void IconButton::showTooltip() { int xoffset = 1; if (m_icon_pixmap.drawable() != 0) xoffset = m_icon_window.x() + m_icon_window.width() + 1; if (FbTk::TextButton::textExceeds(xoffset)) m_win.screen().showTooltip(m_win.title()); } void IconButton::clear() { setupWindow(); } void IconButton::clearArea(int x, int y, unsigned int width, unsigned int height, bool exposure) { FbTk::TextButton::clearArea(x, y, width, height, exposure); } void IconButton::setPixmap(bool use) { if (m_use_pixmap != use) { m_use_pixmap = use; update(0); } } void IconButton::reconfigTheme() { if (m_theme->texture().usePixmap()) m_pm.reset(m_win.screen().imageControl().renderImage( width(), height(), m_theme->texture(), orientation())); else m_pm.reset(0); setAlpha(parent()->alpha()); if (m_pm != 0) setBackgroundPixmap(m_pm); else setBackgroundColor(m_theme->texture().color()); setGC(m_theme->text().textGC()); setFont(m_theme->text().font()); setJustify(m_theme->text().justify()); setBorderWidth(m_theme->border().width()); setBorderColor(m_theme->border().color()); updateBackground(false); } void IconButton::update(FbTk::Subject *subj) { // if the window's focus state changed, we need to update the background if (subj == &m_win.focusSig() || subj == &m_win.attentionSig()) { reconfigTheme(); clear(); return; } // we got signal that either title or // icon pixmap was updated, // so we refresh everything Display *display = FbTk::App::instance()->display(); int screen = m_win.screen().screenNumber(); if (m_use_pixmap && m_win.icon().pixmap().drawable() != None) { // setup icon window m_icon_window.show(); unsigned int w = width(); unsigned int h = height(); FbTk::translateSize(orientation(), w, h); int iconx = 1, icony = 1; unsigned int neww = w, newh = h; if (newh > 2*static_cast<unsigned>(icony)) newh -= 2*icony; else newh = 1; neww = newh; FbTk::translateCoords(orientation(), iconx, icony, w, h); FbTk::translatePosition(orientation(), iconx, icony, neww, newh, 0); m_icon_window.moveResize(iconx, icony, neww, newh); m_icon_pixmap.copy(m_win.icon().pixmap().drawable(), DefaultDepth(display, screen), screen); m_icon_pixmap.scale(m_icon_window.width(), m_icon_window.height()); // rotate the icon or not?? lets go not for now, and see what they say... // need to rotate mask too if we do do this m_icon_pixmap.rotate(orientation()); m_icon_window.setBackgroundPixmap(m_icon_pixmap.drawable()); } else { // no icon pixmap m_icon_window.move(0, 0); m_icon_window.hide(); m_icon_pixmap = 0; } if(m_icon_pixmap.drawable() && m_win.icon().mask().drawable() != None) { m_icon_mask.copy(m_win.icon().mask().drawable(), 0, 0); m_icon_mask.scale(m_icon_pixmap.width(), m_icon_pixmap.height()); m_icon_mask.rotate(orientation()); } else m_icon_mask = 0; #ifdef SHAPE XShapeCombineMask(display, m_icon_window.drawable(), ShapeBounding, 0, 0, m_icon_mask.drawable(), ShapeSet); #endif // SHAPE if (subj != 0) { setupWindow(); } else { m_icon_window.clear(); } // if the title was changed AND the tooltip window is visible AND // we have had an enter notify event ( without the leave notify ) // update the text inside it if (subj == &m_win.titleSig() && m_has_tooltip && m_win.screen().tooltipWindow().isVisible()) { m_win.screen().tooltipWindow().updateText(m_win.title()); } } void IconButton::setupWindow() { m_icon_window.clear(); setText(m_win.title()); FbTk::TextButton::clear(); } void IconButton::drawText(int x, int y, FbTk::FbDrawable *drawable) { // offset text if (m_icon_pixmap.drawable() != 0) FbTk::TextButton::drawText(m_icon_window.x() + m_icon_window.width() + 1, y, drawable); else FbTk::TextButton::drawText(1, y, drawable); } bool IconButton::setOrientation(FbTk::Orientation orient) { if (orientation() == orient) return true; if (FbTk::TextButton::setOrientation(orient)) { int iconx = 1, icony = 1; unsigned int tmpw = width(), tmph = height(); FbTk::translateSize(orient, tmpw, tmph); FbTk::translateCoords(orient, iconx, icony, tmpw, tmph); FbTk::translatePosition(orient, iconx, icony, m_icon_window.width(), m_icon_window.height(), 0); m_icon_window.move(iconx, icony); return true; } else { return false; } }
remove tooltip when IconButton is destroyed
remove tooltip when IconButton is destroyed
C++
mit
luebking/fluxbox,olivergondza/fluxbox,luebking/fluxbox,olivergondza/fluxbox,naimdjon/fluxbox,lukoko/fluxbox,luebking/fluxbox,lukoko/fluxbox,luebking/fluxbox,lukoko/fluxbox,olivergondza/fluxbox,naimdjon/fluxbox,naimdjon/fluxbox,olivergondza/fluxbox,lukoko/fluxbox,luebking/fluxbox,olivergondza/fluxbox,naimdjon/fluxbox,Arkq/fluxbox,Arkq/fluxbox,naimdjon/fluxbox,lukoko/fluxbox,Arkq/fluxbox,Arkq/fluxbox,Arkq/fluxbox
666f253462e2fb1c0e053a1a5d7298263c03f110
src/Main/Main.cpp
src/Main/Main.cpp
#include <iostream> #include "Core/IDifferentiableExecutor.h" #include "Operations/Arithmetic.h" #include "Operations/Value.h" #include "Evaluation/LegacyEvaluator.h" #include "Evaluation/LazyEvaluator.h" #include "Utils/Dictionary.h" #include "Data/Datatypes.h" #include "Data/Initializers/Ones.h" #include "Data/Initializers/Constant.h" #include "Optimizers/GradientDescentOptimizer.h" class TestExecutor: public IExecutor { public: DataObject operator() (const std::vector<DataObject>& inputs) const { return Scalar(100); } }; class TestNode: public Node { public: TestNode(void): Node({}, true) { std::shared_ptr<TestExecutor> executor1(new TestExecutor()); std::shared_ptr<TestExecutor> executor2(new TestExecutor()); RegisterExecutor(executor1); RegisterExecutor(executor2); } DataObject Forward(const std::vector<DataObject>& inputs) const { } }; int main(int argc, char** argv) { LazyEvaluator ev; auto input = Var(); Variables vars; std::cout << ev.EvaluateGraph(input, vars)[input->Channels(0)].ToScalar() << std::endl; input->RegisterNewDefaultValue(Scalar(3.0)); vars[input] = Scalar(5.0); std::cout << ev.EvaluateGraph(input, vars)[input->Channels(0)].ToScalar() << std::endl << std::endl; auto x = std::shared_ptr<Variable>(new Variable(3.0)); ChannelDictionary res = ev.EvaluateGraph(x); std::cout << res[x->Channels(0)] << std::endl; auto c3 = Value(3.0); auto c4 = Value(4.0); res = ev.EvaluateGraph({c3, c4}); std::cout << res[c3->Channels(0)] << std::endl; std::cout << res[c4->Channels(0)] << std::endl; auto seven = c3 + c4; res = ev.EvaluateGraph(seven); std::cout << res[seven->Channels(0)] << std::endl; auto x_squared = x * x; LegacyEvaluator eval; std::cout << ev.EvaluateGraph(x_squared)[x_squared->Channels(0)] << std::endl; GradientDescentOptimizer optimizer(0.25); int i; auto grads = eval.BackwardEvaluate(x_squared, vars); for (i = 0; i < 10; i++) { grads = eval.BackwardEvaluate(x_squared, vars); std::cout << "grad: " << grads[x->Channels(0)] << std::endl; x->Update(optimizer, grads[x->Channels(0)]); std::cout << eval.EvaluateGraph(x_squared)[x_squared->Channels(0)] << std::endl; } std::cout << std::endl; auto y = Var(); auto z = Var(); auto inter1 = y * c3; auto out1 = inter1 + z; auto out2 = inter1 - z; vars[y] = Scalar(2.0); vars[z] = Scalar(1.0); auto results = ev.EvaluateGraph({out1, out2}, vars); std::cout << "out1: " << results[out1->Channels(0)] << std::endl; std::cout << "out2: " << results[out2->Channels(0)] << std::endl; return 0; }
#include <iostream> #include "Core/IDifferentiableExecutor.h" #include "Operations/Arithmetic.h" #include "Operations/Value.h" #include "Evaluation/LegacyEvaluator.h" #include "Evaluation/LazyEvaluator.h" #include "Utils/Dictionary.h" #include "Data/Datatypes.h" #include "Data/Initializers/Ones.h" #include "Data/Initializers/Constant.h" #include "Optimizers/GradientDescentOptimizer.h" class TestExecutor: public IExecutor { public: DataObject operator() (const std::vector<DataObject>& inputs) const { return Scalar(100); } }; class TestNode: public Node { public: TestNode(void): Node({}, true) { std::shared_ptr<TestExecutor> executor1(new TestExecutor()); std::shared_ptr<TestExecutor> executor2(new TestExecutor()); RegisterExecutor(executor1); RegisterExecutor(executor2); } DataObject Forward(const std::vector<DataObject>& inputs) const { } }; int main(int argc, char** argv) { //LazyEvaluator ev; auto input = Input(); auto c1 = Constant(1.0); /*Variables vars; std::cout << ev.EvaluateGraph(input, vars)[input->Channels(0)].ToScalar() << std::endl; input->RegisterNewDefaultValue(Scalar(3.0)); vars[input] = Scalar(5.0); std::cout << ev.EvaluateGraph(input, vars)[input->Channels(0)].ToScalar() << std::endl << std::endl; auto x = std::shared_ptr<Variable>(new Variable(3.0)); ChannelDictionary res = ev.EvaluateGraph(x); std::cout << res[x->Channels(0)] << std::endl; auto c3 = Value(3.0); auto c4 = Value(4.0); res = ev.EvaluateGraph({c3, c4}); std::cout << res[c3->Channels(0)] << std::endl; std::cout << res[c4->Channels(0)] << std::endl; auto seven = c3 + c4; res = ev.EvaluateGraph(seven); std::cout << res[seven->Channels(0)] << std::endl; auto x_squared = x * x; LegacyEvaluator eval; std::cout << ev.EvaluateGraph(x_squared)[x_squared->Channels(0)] << std::endl; GradientDescentOptimizer optimizer(0.25); int i; auto grads = eval.BackwardEvaluate(x_squared, vars); for (i = 0; i < 10; i++) { grads = eval.BackwardEvaluate(x_squared, vars); std::cout << "grad: " << grads[x->Channels(0)] << std::endl; x->Update(optimizer, grads[x->Channels(0)]); std::cout << eval.EvaluateGraph(x_squared)[x_squared->Channels(0)] << std::endl; } std::cout << std::endl; auto y = Var(); auto z = Var(); auto inter1 = y * c3; auto out1 = inter1 + z; auto out2 = inter1 - z; vars[y] = Scalar(2.0); vars[z] = Scalar(1.0); auto results = ev.EvaluateGraph({out1, out2}, vars); std::cout << "out1: " << results[out1->Channels(0)] << std::endl; std::cout << "out2: " << results[out2->Channels(0)] << std::endl; return 0;*/ }
Test class constructors as direct node building method
Test class constructors as direct node building method
C++
mit
alexweav/BackpropFramework,alexweav/BackpropFramework
56a4e6f27479a979c3a2fc224bc4a97d6beb189c
korganizer/koeditoralarms.cpp
korganizer/koeditoralarms.cpp
/* This file is part of KOrganizer. Copyright (c) 2003 Cornelius Schumacher <[email protected]> Copyright (C) 2004 Reinhold Kainhofer <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "koeditoralarms_base.h" #include "koeditoralarms.h" #include <qlayout.h> #include <qlistview.h> #include <qpushbutton.h> #include <qspinbox.h> #include <qcombobox.h> #include <qcheckbox.h> #include <qbuttongroup.h> #include <qtextedit.h> #include <qwidgetstack.h> #include <kurlrequester.h> #include <klocale.h> #include <kdebug.h> #include <libkcal/alarm.h> #include <libkcal/incidence.h> #include <libemailfunctions/email.h> class AlarmListViewItem : public QListViewItem { public: AlarmListViewItem( QListView *parent, KCal::Alarm *alarm ); virtual ~AlarmListViewItem(); KCal::Alarm *alarm() const { return mAlarm; } void construct(); enum AlarmViewColumns { ColAlarmType=0, ColAlarmOffset, ColAlarmRepeat }; protected: KCal::Alarm *mAlarm; }; AlarmListViewItem::AlarmListViewItem( QListView *parent, KCal::Alarm *alarm ) : QListViewItem( parent ) { if ( alarm ) { mAlarm = new KCal::Alarm( *alarm ); } else { mAlarm = new KCal::Alarm( 0 ); } construct(); } AlarmListViewItem::~AlarmListViewItem() { delete mAlarm; } void AlarmListViewItem::construct() { if ( mAlarm ) { // Alarm type: QString type( i18n("Unknown") ); switch ( mAlarm->type() ) { case KCal::Alarm::Display: type = i18n("Reminder Dialog"); break; case KCal::Alarm::Procedure: type = i18n("Application/Script"); break; case KCal::Alarm::Email: type = i18n("Email"); break; case KCal::Alarm::Audio: type = i18n("Audio"); break; default: break; } setText( ColAlarmType, type ); // Alarm offset: QString offsetstr; int offset = 0; if ( mAlarm->hasStartOffset() ) { offset = mAlarm->startOffset().asSeconds(); if ( offset < 0 ) { offsetstr = i18n("N days/hours/minutes before/after the start/end", "%1 before the start"); offset = -offset; } else { offsetstr = i18n("N days/hours/minutes before/after the start/end", "%1 after the start"); } } else if ( mAlarm->hasEndOffset() ) { offset = mAlarm->endOffset().asSeconds(); if ( offset < 0 ) { offsetstr = i18n("N days/hours/minutes before/after the start/end", "%1 before the end"); offset = -offset; } else { offsetstr = i18n("N days/hours/minutes before/after the start/end", "%1 after the end"); } } offset = offset / 60; // make minutes int useoffset = offset; if ( offset % (24*60) == 0 && offset>0 ) { // divides evenly into days? useoffset = offset / (24*60); offsetstr = offsetstr.arg( i18n("1 day", "%n days", useoffset ) ); } else if (offset % 60 == 0 && offset>0 ) { // divides evenly into hours? useoffset = offset / 60; offsetstr = offsetstr.arg( i18n("1 hour", "%n hours", useoffset ) ); } else { useoffset = offset; offsetstr = offsetstr.arg( i18n("1 minute", "%n minutes", useoffset ) ); } setText( ColAlarmOffset, offsetstr ); // Alarm repeat if ( mAlarm->repeatCount()>0 ) { setText( ColAlarmRepeat, i18n("Yes") ); } } } KOEditorAlarms::KOEditorAlarms( KCal::Alarm::List *alarms, QWidget *parent, const char *name ) : KDialogBase( parent, name, true, i18n("Edit Reminders"), Ok | Apply | Cancel ), mAlarms( alarms ) { setMainWidget( mWidget = new KOEditorAlarms_base( this ) ); mWidget->mAlarmList->setColumnWidthMode( 0, QListView::Maximum ); mWidget->mAlarmList->setColumnWidthMode( 1, QListView::Maximum ); connect( mWidget->mAlarmList, SIGNAL( selectionChanged( QListViewItem * ) ), SLOT( selectionChanged( QListViewItem * ) ) ); connect( mWidget->mAddButton, SIGNAL( clicked() ), SLOT( slotAdd() ) ); connect( mWidget->mRemoveButton, SIGNAL( clicked() ), SLOT( slotRemove() ) ); connect( mWidget->mDuplicateButton, SIGNAL( clicked() ), SLOT( slotDuplicate() ) ); connect( mWidget->mAlarmOffset, SIGNAL( valueChanged( int ) ), SLOT( changed() ) ); connect( mWidget->mOffsetUnit, SIGNAL( activated( int ) ), SLOT( changed() ) ); connect( mWidget->mBeforeAfter, SIGNAL( activated( int ) ), SLOT( changed() ) ); connect( mWidget->mRepeats, SIGNAL( toggled( bool ) ), SLOT( changed() ) ); connect( mWidget->mRepeatCount, SIGNAL( valueChanged( int ) ), SLOT( changed() ) ); connect( mWidget->mRepeatInterval, SIGNAL( valueChanged( int ) ), SLOT( changed() ) ); connect( mWidget->mAlarmType, SIGNAL(clicked(int)), SLOT( changed() ) ); connect( mWidget->mDisplayText, SIGNAL( textChanged() ), SLOT( changed() ) ); connect( mWidget->mSoundFile, SIGNAL( textChanged( const QString & ) ), SLOT( changed() ) ); connect( mWidget->mApplication, SIGNAL( textChanged( const QString & ) ), SLOT( changed() ) ); connect( mWidget->mAppArguments, SIGNAL( textChanged( const QString & ) ), SLOT( changed() ) ); connect( mWidget->mEmailAddress, SIGNAL( textChanged( const QString & ) ), SLOT( changed() ) ); connect( mWidget->mEmailText, SIGNAL( textChanged() ), SLOT( changed() ) ); init(); } KOEditorAlarms::~KOEditorAlarms() { } void KOEditorAlarms::changed() { if ( !mInitializing && mCurrentItem ) { writeAlarm( mCurrentItem->alarm() ); mCurrentItem->construct(); } } void KOEditorAlarms::readAlarm( KCal::Alarm *alarm ) { if ( !alarm ) return; mInitializing = true; // Offsets int offset; int beforeafterpos = 0; if ( alarm->hasEndOffset() ) { beforeafterpos = 2; offset = alarm->endOffset().asSeconds(); } else { // TODO: Also allow alarms at fixed times, not relative to start/end offset = alarm->startOffset().asSeconds(); } // Negative offset means before the start/end... if ( offset < 0 ) { offset = -offset; } else { ++beforeafterpos; } mWidget->mBeforeAfter->setCurrentItem( beforeafterpos ); offset = offset / 60; // make minutes int useoffset = offset; if ( offset % (24*60) == 0 && offset>0 ) { // divides evenly into days? useoffset = offset / (24*60); mWidget->mOffsetUnit->setCurrentItem( 2 ); } else if (offset % 60 == 0 && offset>0 ) { // divides evenly into hours? useoffset = offset / 60; mWidget->mOffsetUnit->setCurrentItem( 1 ); } else { useoffset = offset; mWidget->mOffsetUnit->setCurrentItem( 0 ); } mWidget->mAlarmOffset->setValue( useoffset ); // Repeating mWidget->mRepeats->setChecked( alarm->repeatCount()>0 ); if ( alarm->repeatCount()>0 ) { mWidget->mRepeatCount->setValue( alarm->repeatCount() ); mWidget->mRepeatInterval->setValue( alarm->snoozeTime() ); } switch ( alarm->type() ) { case KCal::Alarm::Audio: mWidget->mAlarmType->setButton( 1 ); mWidget->mSoundFile->setURL( alarm->audioFile() ); break; case KCal::Alarm::Procedure: mWidget->mAlarmType->setButton( 2 ); mWidget->mApplication->setURL( alarm->programFile() ); mWidget->mAppArguments->setText( alarm->programArguments() ); break; case KCal::Alarm::Email: { mWidget->mAlarmType->setButton( 3 ); QValueList<KCal::Person> addresses = alarm->mailAddresses(); QStringList add; for ( QValueList<KCal::Person>::ConstIterator it = addresses.begin(); it != addresses.end(); ++it ) { add << (*it).fullName(); } mWidget->mEmailAddress->setText( add.join(", ") ); mWidget->mEmailText->setText( alarm->mailText() ); break;} case KCal::Alarm::Display: case KCal::Alarm::Invalid: default: mWidget->mAlarmType->setButton( 0 ); mWidget->mDisplayText->setText( alarm->text() ); break; } mWidget->mTypeStack->raiseWidget( mWidget->mAlarmType->selectedId() ); mInitializing = false; } void KOEditorAlarms::writeAlarm( KCal::Alarm *alarm ) { // Offsets int offset = mWidget->mAlarmOffset->value()*60; // minutes int offsetunit = mWidget->mOffsetUnit->currentItem(); if ( offsetunit >= 1 ) offset *= 60; // hours if ( offsetunit >= 2 ) offset *= 24; // days if ( offsetunit >= 3 ) offset *= 7; // weeks int beforeafterpos = mWidget->mBeforeAfter->currentItem(); if ( beforeafterpos % 2 == 0 ) { // before -> negative offset = -offset; } // TODO: Add possibility to specify a given time for the reminder if ( beforeafterpos / 2 == 0 ) { // start offset alarm->setStartOffset( KCal::Duration( offset ) ); } else { alarm->setEndOffset( KCal::Duration( offset ) ); } // Repeating if ( mWidget->mRepeats->isChecked() ) { alarm->setRepeatCount( mWidget->mRepeatCount->value() ); alarm->setSnoozeTime( mWidget->mRepeatInterval->value() ); } else { alarm->setRepeatCount( 0 ); } switch ( mWidget->mAlarmType->selectedId() ) { case 1: // Audio alarm->setAudioAlarm( mWidget->mSoundFile->url() ); break; case 2: // Procedure alarm->setProcedureAlarm( mWidget->mApplication->url(), mWidget->mAppArguments->text() ); break; case 3: { // Email QStringList addresses = KPIM::splitEmailAddrList( mWidget->mEmailAddress->text() ); QValueList<KCal::Person> add; for ( QStringList::Iterator it = addresses.begin(); it != addresses.end(); ++it ) { add << KCal::Person( *it ); } // TODO: Add a subject line and possibilities for attachments alarm->setEmailAlarm( QString::null, mWidget->mEmailText->text(), add ); break; } case 0: // Display default: alarm->setDisplayAlarm( mWidget->mDisplayText->text() ); break; } } void KOEditorAlarms::selectionChanged( QListViewItem *listviewitem ) { AlarmListViewItem *item = dynamic_cast<AlarmListViewItem*>(listviewitem); mCurrentItem = item; mWidget->mTimeGroup->setEnabled( item ); mWidget->mTypeGroup->setEnabled( item ); if ( item ) { readAlarm( item->alarm() ); } } void KOEditorAlarms::slotApply() { // copy the mAlarms list if ( mAlarms ) { mAlarms->clear(); QListViewItemIterator it( mWidget->mAlarmList ); while ( it.current() ) { AlarmListViewItem *item = dynamic_cast<AlarmListViewItem*>(*it); if ( item ) { mAlarms->append( new KCal::Alarm( *(item->alarm()) ) ); } ++it; } } } void KOEditorAlarms::slotOk() { slotApply(); accept(); } void KOEditorAlarms::slotAdd() { mCurrentItem = new AlarmListViewItem( mWidget->mAlarmList, 0 ); mWidget->mAlarmList->setCurrentItem( mCurrentItem ); // selectionChanged( mCurrentItem ); } void KOEditorAlarms::slotDuplicate() { if ( mCurrentItem ) { mCurrentItem = new AlarmListViewItem( mWidget->mAlarmList, mCurrentItem->alarm() ); mWidget->mAlarmList->setCurrentItem( mCurrentItem ); // selectionChanged( mCurrentItem ); } } void KOEditorAlarms::slotRemove() { if ( mCurrentItem ) { delete mCurrentItem; mCurrentItem = dynamic_cast<AlarmListViewItem*>( mWidget->mAlarmList->currentItem() ); mWidget->mAlarmList->setSelected( mCurrentItem, true ); } } void KOEditorAlarms::init() { mInitializing = true; KCal::Alarm::List::ConstIterator it; for ( it = mAlarms->begin(); it != mAlarms->end(); ++it ) { new AlarmListViewItem( mWidget->mAlarmList, *it ); } mWidget->mAlarmList->setSelected( mWidget->mAlarmList->firstChild(), true ); mInitializing = false; } #include "koeditoralarms.moc"
/* This file is part of KOrganizer. Copyright (c) 2003 Cornelius Schumacher <[email protected]> Copyright (C) 2004 Reinhold Kainhofer <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "koeditoralarms_base.h" #include "koeditoralarms.h" #include <qlayout.h> #include <qlistview.h> #include <qpushbutton.h> #include <qspinbox.h> #include <qcombobox.h> #include <qcheckbox.h> #include <qbuttongroup.h> #include <qtextedit.h> #include <qwidgetstack.h> #include <kurlrequester.h> #include <klocale.h> #include <kdebug.h> #include <libkcal/alarm.h> #include <libkcal/incidence.h> #include <libemailfunctions/email.h> class AlarmListViewItem : public QListViewItem { public: AlarmListViewItem( QListView *parent, KCal::Alarm *alarm ); virtual ~AlarmListViewItem(); KCal::Alarm *alarm() const { return mAlarm; } void construct(); enum AlarmViewColumns { ColAlarmType=0, ColAlarmOffset, ColAlarmRepeat }; protected: KCal::Alarm *mAlarm; }; AlarmListViewItem::AlarmListViewItem( QListView *parent, KCal::Alarm *alarm ) : QListViewItem( parent ) { if ( alarm ) { mAlarm = new KCal::Alarm( *alarm ); } else { mAlarm = new KCal::Alarm( 0 ); } construct(); } AlarmListViewItem::~AlarmListViewItem() { delete mAlarm; } void AlarmListViewItem::construct() { if ( mAlarm ) { // Alarm type: QString type( i18n("Unknown") ); switch ( mAlarm->type() ) { case KCal::Alarm::Display: type = i18n("Reminder Dialog"); break; case KCal::Alarm::Procedure: type = i18n("Application/Script"); break; case KCal::Alarm::Email: type = i18n("Email"); break; case KCal::Alarm::Audio: type = i18n("Audio"); break; default: break; } setText( ColAlarmType, type ); // Alarm offset: QString offsetstr; int offset = 0; if ( mAlarm->hasStartOffset() ) { offset = mAlarm->startOffset().asSeconds(); if ( offset < 0 ) { offsetstr = i18n("N days/hours/minutes before/after the start/end", "%1 before the start"); offset = -offset; } else { offsetstr = i18n("N days/hours/minutes before/after the start/end", "%1 after the start"); } } else if ( mAlarm->hasEndOffset() ) { offset = mAlarm->endOffset().asSeconds(); if ( offset < 0 ) { offsetstr = i18n("N days/hours/minutes before/after the start/end", "%1 before the end"); offset = -offset; } else { offsetstr = i18n("N days/hours/minutes before/after the start/end", "%1 after the end"); } } offset = offset / 60; // make minutes int useoffset = offset; if ( offset % (24*60) == 0 && offset>0 ) { // divides evenly into days? useoffset = offset / (24*60); offsetstr = offsetstr.arg( i18n("1 day", "%n days", useoffset ) ); } else if (offset % 60 == 0 && offset>0 ) { // divides evenly into hours? useoffset = offset / 60; offsetstr = offsetstr.arg( i18n("1 hour", "%n hours", useoffset ) ); } else { useoffset = offset; offsetstr = offsetstr.arg( i18n("1 minute", "%n minutes", useoffset ) ); } setText( ColAlarmOffset, offsetstr ); // Alarm repeat if ( mAlarm->repeatCount()>0 ) { setText( ColAlarmRepeat, i18n("Yes") ); } } } KOEditorAlarms::KOEditorAlarms( KCal::Alarm::List *alarms, QWidget *parent, const char *name ) : KDialogBase( parent, name, true, i18n("Edit Reminders"), Ok | Apply | Cancel ), mAlarms( alarms ),mCurrentItem(0L) { setMainWidget( mWidget = new KOEditorAlarms_base( this ) ); mWidget->mAlarmList->setColumnWidthMode( 0, QListView::Maximum ); mWidget->mAlarmList->setColumnWidthMode( 1, QListView::Maximum ); connect( mWidget->mAlarmList, SIGNAL( selectionChanged( QListViewItem * ) ), SLOT( selectionChanged( QListViewItem * ) ) ); connect( mWidget->mAddButton, SIGNAL( clicked() ), SLOT( slotAdd() ) ); connect( mWidget->mRemoveButton, SIGNAL( clicked() ), SLOT( slotRemove() ) ); connect( mWidget->mDuplicateButton, SIGNAL( clicked() ), SLOT( slotDuplicate() ) ); connect( mWidget->mAlarmOffset, SIGNAL( valueChanged( int ) ), SLOT( changed() ) ); connect( mWidget->mOffsetUnit, SIGNAL( activated( int ) ), SLOT( changed() ) ); connect( mWidget->mBeforeAfter, SIGNAL( activated( int ) ), SLOT( changed() ) ); connect( mWidget->mRepeats, SIGNAL( toggled( bool ) ), SLOT( changed() ) ); connect( mWidget->mRepeatCount, SIGNAL( valueChanged( int ) ), SLOT( changed() ) ); connect( mWidget->mRepeatInterval, SIGNAL( valueChanged( int ) ), SLOT( changed() ) ); connect( mWidget->mAlarmType, SIGNAL(clicked(int)), SLOT( changed() ) ); connect( mWidget->mDisplayText, SIGNAL( textChanged() ), SLOT( changed() ) ); connect( mWidget->mSoundFile, SIGNAL( textChanged( const QString & ) ), SLOT( changed() ) ); connect( mWidget->mApplication, SIGNAL( textChanged( const QString & ) ), SLOT( changed() ) ); connect( mWidget->mAppArguments, SIGNAL( textChanged( const QString & ) ), SLOT( changed() ) ); connect( mWidget->mEmailAddress, SIGNAL( textChanged( const QString & ) ), SLOT( changed() ) ); connect( mWidget->mEmailText, SIGNAL( textChanged() ), SLOT( changed() ) ); init(); } KOEditorAlarms::~KOEditorAlarms() { } void KOEditorAlarms::changed() { if ( !mInitializing && mCurrentItem ) { writeAlarm( mCurrentItem->alarm() ); mCurrentItem->construct(); } } void KOEditorAlarms::readAlarm( KCal::Alarm *alarm ) { if ( !alarm ) return; mInitializing = true; // Offsets int offset; int beforeafterpos = 0; if ( alarm->hasEndOffset() ) { beforeafterpos = 2; offset = alarm->endOffset().asSeconds(); } else { // TODO: Also allow alarms at fixed times, not relative to start/end offset = alarm->startOffset().asSeconds(); } // Negative offset means before the start/end... if ( offset < 0 ) { offset = -offset; } else { ++beforeafterpos; } mWidget->mBeforeAfter->setCurrentItem( beforeafterpos ); offset = offset / 60; // make minutes int useoffset = offset; if ( offset % (24*60) == 0 && offset>0 ) { // divides evenly into days? useoffset = offset / (24*60); mWidget->mOffsetUnit->setCurrentItem( 2 ); } else if (offset % 60 == 0 && offset>0 ) { // divides evenly into hours? useoffset = offset / 60; mWidget->mOffsetUnit->setCurrentItem( 1 ); } else { useoffset = offset; mWidget->mOffsetUnit->setCurrentItem( 0 ); } mWidget->mAlarmOffset->setValue( useoffset ); // Repeating mWidget->mRepeats->setChecked( alarm->repeatCount()>0 ); if ( alarm->repeatCount()>0 ) { mWidget->mRepeatCount->setValue( alarm->repeatCount() ); mWidget->mRepeatInterval->setValue( alarm->snoozeTime() ); } switch ( alarm->type() ) { case KCal::Alarm::Audio: mWidget->mAlarmType->setButton( 1 ); mWidget->mSoundFile->setURL( alarm->audioFile() ); break; case KCal::Alarm::Procedure: mWidget->mAlarmType->setButton( 2 ); mWidget->mApplication->setURL( alarm->programFile() ); mWidget->mAppArguments->setText( alarm->programArguments() ); break; case KCal::Alarm::Email: { mWidget->mAlarmType->setButton( 3 ); QValueList<KCal::Person> addresses = alarm->mailAddresses(); QStringList add; for ( QValueList<KCal::Person>::ConstIterator it = addresses.begin(); it != addresses.end(); ++it ) { add << (*it).fullName(); } mWidget->mEmailAddress->setText( add.join(", ") ); mWidget->mEmailText->setText( alarm->mailText() ); break;} case KCal::Alarm::Display: case KCal::Alarm::Invalid: default: mWidget->mAlarmType->setButton( 0 ); mWidget->mDisplayText->setText( alarm->text() ); break; } mWidget->mTypeStack->raiseWidget( mWidget->mAlarmType->selectedId() ); mInitializing = false; } void KOEditorAlarms::writeAlarm( KCal::Alarm *alarm ) { // Offsets int offset = mWidget->mAlarmOffset->value()*60; // minutes int offsetunit = mWidget->mOffsetUnit->currentItem(); if ( offsetunit >= 1 ) offset *= 60; // hours if ( offsetunit >= 2 ) offset *= 24; // days if ( offsetunit >= 3 ) offset *= 7; // weeks int beforeafterpos = mWidget->mBeforeAfter->currentItem(); if ( beforeafterpos % 2 == 0 ) { // before -> negative offset = -offset; } // TODO: Add possibility to specify a given time for the reminder if ( beforeafterpos / 2 == 0 ) { // start offset alarm->setStartOffset( KCal::Duration( offset ) ); } else { alarm->setEndOffset( KCal::Duration( offset ) ); } // Repeating if ( mWidget->mRepeats->isChecked() ) { alarm->setRepeatCount( mWidget->mRepeatCount->value() ); alarm->setSnoozeTime( mWidget->mRepeatInterval->value() ); } else { alarm->setRepeatCount( 0 ); } switch ( mWidget->mAlarmType->selectedId() ) { case 1: // Audio alarm->setAudioAlarm( mWidget->mSoundFile->url() ); break; case 2: // Procedure alarm->setProcedureAlarm( mWidget->mApplication->url(), mWidget->mAppArguments->text() ); break; case 3: { // Email QStringList addresses = KPIM::splitEmailAddrList( mWidget->mEmailAddress->text() ); QValueList<KCal::Person> add; for ( QStringList::Iterator it = addresses.begin(); it != addresses.end(); ++it ) { add << KCal::Person( *it ); } // TODO: Add a subject line and possibilities for attachments alarm->setEmailAlarm( QString::null, mWidget->mEmailText->text(), add ); break; } case 0: // Display default: alarm->setDisplayAlarm( mWidget->mDisplayText->text() ); break; } } void KOEditorAlarms::selectionChanged( QListViewItem *listviewitem ) { AlarmListViewItem *item = dynamic_cast<AlarmListViewItem*>(listviewitem); mCurrentItem = item; mWidget->mTimeGroup->setEnabled( item ); mWidget->mTypeGroup->setEnabled( item ); if ( item ) { readAlarm( item->alarm() ); } } void KOEditorAlarms::slotApply() { // copy the mAlarms list if ( mAlarms ) { mAlarms->clear(); QListViewItemIterator it( mWidget->mAlarmList ); while ( it.current() ) { AlarmListViewItem *item = dynamic_cast<AlarmListViewItem*>(*it); if ( item ) { mAlarms->append( new KCal::Alarm( *(item->alarm()) ) ); } ++it; } } } void KOEditorAlarms::slotOk() { slotApply(); accept(); } void KOEditorAlarms::slotAdd() { mCurrentItem = new AlarmListViewItem( mWidget->mAlarmList, 0 ); mWidget->mAlarmList->setCurrentItem( mCurrentItem ); // selectionChanged( mCurrentItem ); } void KOEditorAlarms::slotDuplicate() { if ( mCurrentItem ) { mCurrentItem = new AlarmListViewItem( mWidget->mAlarmList, mCurrentItem->alarm() ); mWidget->mAlarmList->setCurrentItem( mCurrentItem ); // selectionChanged( mCurrentItem ); } } void KOEditorAlarms::slotRemove() { if ( mCurrentItem ) { delete mCurrentItem; mCurrentItem = dynamic_cast<AlarmListViewItem*>( mWidget->mAlarmList->currentItem() ); mWidget->mAlarmList->setSelected( mCurrentItem, true ); } } void KOEditorAlarms::init() { mInitializing = true; KCal::Alarm::List::ConstIterator it; for ( it = mAlarms->begin(); it != mAlarms->end(); ++it ) { new AlarmListViewItem( mWidget->mAlarmList, *it ); } mWidget->mAlarmList->setSelected( mWidget->mAlarmList->firstChild(), true ); mInitializing = false; } #include "koeditoralarms.moc"
Initialize variable to avoid crash
Initialize variable to avoid crash svn path=/branches/KDE/3.5/kdepim/; revision=555779
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
644e2da2fd2eb6c80adf80f2c60c46a9abdb81ae
src/deleglise-rivat/pi_deleglise_rivat1.cpp
src/deleglise-rivat/pi_deleglise_rivat1.cpp
/// /// @file pi_deleglise_rivat_parallel1.cpp /// @brief Implementation of the Deleglise-Rivat prime counting /// algorithm. In the Deleglise-Rivat algorithm there are 3 /// additional types of special leaves compared to the /// Lagarias-Miller-Odlyzko algorithm: trivial special leaves, /// clustered easy leaves and sparse easy leaves. /// /// This implementation is based on the paper: /// Tomás Oliveira e Silva, Computing pi(x): the combinatorial /// method, Revista do DETUA, vol. 4, no. 6, March 2006, /// pp. 759-768. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <BitSieve.hpp> #include <generate.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <tos_counters.hpp> #include <S1.hpp> #include "S2.hpp" #include <stdint.h> #include <algorithm> #include <vector> using namespace std; using namespace primecount; namespace { /// Cross-off the multiples of prime in the sieve array. /// For each element that is unmarked the first time update /// the special counters tree data structure. /// template <typename T> void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, BitSieve& sieve, T& counters) { int64_t segment_size = sieve.size(); int64_t k = next_multiple; for (; k < high; k += prime * 2) { if (sieve[k - low]) { sieve.unset(k - low); cnt_update(counters, k - low, segment_size); } } next_multiple = k; } /// Calculate the contribution of the trivial leaves. /// int64_t S2_trivial(int64_t x, int64_t y, int64_t z, int64_t c, vector<int32_t>& pi, vector<int32_t>& primes) { int64_t pi_y = pi[y]; int64_t pi_sqrtz = pi[min(isqrt(z), y)]; int64_t S2_result = 0; // Find all trivial leaves: n = primes[b] * primes[l] // which satisfy phi(x / n), b - 1) = 1 for (int64_t b = max(c, pi_sqrtz + 1); b < pi_y; b++) { int64_t prime = primes[b]; S2_result += pi_y - pi[max(x / (prime * prime), prime)]; } return S2_result; } /// Calculate the contribution of the special leaves which require /// a sieve (in order to reduce the memory usage). /// int64_t S2_sieve(int64_t x, int64_t y, int64_t z, int64_t c, vector<int32_t>& pi, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu) { int64_t limit = z + 1; int64_t segment_size = next_power_of_2(isqrt(limit)); int64_t pi_sqrty = pi[isqrt(y)]; int64_t pi_sqrtz = pi[min(isqrt(z), y)]; int64_t S2_result = 0; BitSieve sieve(segment_size); vector<int32_t> counters(segment_size); vector<int64_t> next(primes.begin(), primes.end()); vector<int64_t> phi(primes.size(), 0); // Segmented sieve of Eratosthenes for (int64_t low = 1; low < limit; low += segment_size) { // Current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = 2; sieve.fill(low, high); // phi(y, b) nodes with b <= c do not contribute to S2, so we // simply sieve out the multiples of the first c primes for (; b <= c; b++) { int64_t k = next[b]; for (int64_t prime = primes[b]; k < high; k += prime * 2) sieve.unset(k - low); next[b] = k; } // Initialize special tree data structure from sieve cnt_finit(sieve, counters, segment_size); // For c + 1 <= b <= pi_sqrty // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrty; b++) { int64_t prime = primes[b]; int64_t min_m = max(x / (prime * high), y / prime); int64_t max_m = min(x / (prime * low), y); if (prime >= max_m) goto next_segment; for (int64_t m = max_m; m > min_m; m--) { if (mu[m] != 0 && prime < lpf[m]) { int64_t n = prime * m; int64_t count = cnt_query(counters, (x / n) - low); int64_t phi_xn = phi[b] + count; S2_result -= mu[m] * phi_xn; } } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } // For pi_sqrty <= b <= pi_sqrtz // Find all hard special leaves: n = primes[b] * primes[l] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrtz; b++) { int64_t prime = primes[b]; int64_t l = pi[min3(x / (prime * low), z / prime, y)]; int64_t min_hard_leaf = max3(x / (prime * high), y / prime, prime); if (prime >= primes[l]) goto next_segment; for (; primes[l] > min_hard_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; int64_t count = cnt_query(counters, xn - low); int64_t phi_xn = phi[b] + count; S2_result += phi_xn; } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } next_segment:; } return S2_result; } /// Calculate the contribution of the special leaves. /// @pre y > 0 && c > 1 /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t c, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu) { vector<int32_t> pi = generate_pi(y); int64_t S2_total = 0; S2_total += S2_trivial(x, y, z, c, pi, primes); S2_total += S2_easy(x, y, z, c, pi, primes, 1); S2_total += S2_sieve(x, y, z, c, pi, primes, lpf, mu); return S2_total; } /// alpha is a tuning factor which should grow like (log(x))^3 /// for the Deleglise-Rivat prime counting algorithm. /// double compute_alpha(int64_t x) { double d = (double) x; double alpha = log(d) * log(d) * log(d) / 1500; return in_between(1, alpha, iroot<6>(x)); } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat1(int64_t x) { if (x < 2) return 0; double alpha = compute_alpha(x); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = x / y; int64_t p2 = P2(x, y, 1); vector<int32_t> mu = generate_moebius(y); vector<int32_t> lpf = generate_least_prime_factors(y); vector<int32_t> primes = generate_primes(y); int64_t pi_y = primes.size() - 1; int64_t c = min(pi_y, PhiTiny::max_a()); int64_t s1 = S1(x, y, c, primes[c], lpf , mu, 1); int64_t s2 = S2(x, y, z, c, primes, lpf , mu); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount
/// /// @file pi_deleglise_rivat_parallel1.cpp /// @brief Implementation of the Deleglise-Rivat prime counting /// algorithm. In the Deleglise-Rivat algorithm there are 3 /// additional types of special leaves compared to the /// Lagarias-Miller-Odlyzko algorithm: trivial special leaves, /// clustered easy leaves and sparse easy leaves. /// /// This implementation is based on the paper: /// Tomás Oliveira e Silva, Computing pi(x): the combinatorial /// method, Revista do DETUA, vol. 4, no. 6, March 2006, /// pp. 759-768. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "S2.hpp" #include <primecount-internal.hpp> #include <BitSieve.hpp> #include <generate.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <tos_counters.hpp> #include <S1.hpp> #include <stdint.h> #include <algorithm> #include <vector> using namespace std; using namespace primecount; namespace { /// Cross-off the multiples of prime in the sieve array. /// For each element that is unmarked the first time update /// the special counters tree data structure. /// template <typename T> void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, BitSieve& sieve, T& counters) { int64_t segment_size = sieve.size(); int64_t k = next_multiple; for (; k < high; k += prime * 2) { if (sieve[k - low]) { sieve.unset(k - low); cnt_update(counters, k - low, segment_size); } } next_multiple = k; } /// Calculate the contribution of the trivial leaves. /// int64_t S2_trivial(int64_t x, int64_t y, int64_t z, int64_t c, vector<int32_t>& pi, vector<int32_t>& primes) { int64_t pi_y = pi[y]; int64_t pi_sqrtz = pi[min(isqrt(z), y)]; int64_t S2_result = 0; // Find all trivial leaves: n = primes[b] * primes[l] // which satisfy phi(x / n), b - 1) = 1 for (int64_t b = max(c, pi_sqrtz + 1); b < pi_y; b++) { int64_t prime = primes[b]; S2_result += pi_y - pi[max(x / (prime * prime), prime)]; } return S2_result; } /// Calculate the contribution of the special leaves which require /// a sieve (in order to reduce the memory usage). /// int64_t S2_sieve(int64_t x, int64_t y, int64_t z, int64_t c, vector<int32_t>& pi, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu) { int64_t limit = z + 1; int64_t segment_size = next_power_of_2(isqrt(limit)); int64_t pi_sqrty = pi[isqrt(y)]; int64_t pi_sqrtz = pi[min(isqrt(z), y)]; int64_t S2_result = 0; BitSieve sieve(segment_size); vector<int32_t> counters(segment_size); vector<int64_t> next(primes.begin(), primes.end()); vector<int64_t> phi(primes.size(), 0); // Segmented sieve of Eratosthenes for (int64_t low = 1; low < limit; low += segment_size) { // Current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = 2; sieve.fill(low, high); // phi(y, b) nodes with b <= c do not contribute to S2, so we // simply sieve out the multiples of the first c primes for (; b <= c; b++) { int64_t k = next[b]; for (int64_t prime = primes[b]; k < high; k += prime * 2) sieve.unset(k - low); next[b] = k; } // Initialize special tree data structure from sieve cnt_finit(sieve, counters, segment_size); // For c + 1 <= b <= pi_sqrty // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrty; b++) { int64_t prime = primes[b]; int64_t min_m = max(x / (prime * high), y / prime); int64_t max_m = min(x / (prime * low), y); if (prime >= max_m) goto next_segment; for (int64_t m = max_m; m > min_m; m--) { if (mu[m] != 0 && prime < lpf[m]) { int64_t n = prime * m; int64_t count = cnt_query(counters, (x / n) - low); int64_t phi_xn = phi[b] + count; S2_result -= mu[m] * phi_xn; } } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } // For pi_sqrty <= b <= pi_sqrtz // Find all hard special leaves: n = primes[b] * primes[l] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrtz; b++) { int64_t prime = primes[b]; int64_t l = pi[min3(x / (prime * low), z / prime, y)]; int64_t min_hard_leaf = max3(x / (prime * high), y / prime, prime); if (prime >= primes[l]) goto next_segment; for (; primes[l] > min_hard_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; int64_t count = cnt_query(counters, xn - low); int64_t phi_xn = phi[b] + count; S2_result += phi_xn; } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } next_segment:; } return S2_result; } /// Calculate the contribution of the special leaves. /// @pre y > 0 && c > 1 /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t c, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu) { vector<int32_t> pi = generate_pi(y); int64_t S2_total = 0; S2_total += S2_trivial(x, y, z, c, pi, primes); S2_total += S2_easy(x, y, z, c, pi, primes, 1); S2_total += S2_sieve(x, y, z, c, pi, primes, lpf, mu); return S2_total; } /// alpha is a tuning factor which should grow like (log(x))^3 /// for the Deleglise-Rivat prime counting algorithm. /// double compute_alpha(int64_t x) { double d = (double) x; double alpha = log(d) * log(d) * log(d) / 1500; return in_between(1, alpha, iroot<6>(x)); } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int64_t pi_deleglise_rivat1(int64_t x) { if (x < 2) return 0; double alpha = compute_alpha(x); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = x / y; int64_t p2 = P2(x, y, 1); vector<int32_t> mu = generate_moebius(y); vector<int32_t> lpf = generate_least_prime_factors(y); vector<int32_t> primes = generate_primes(y); int64_t pi_y = primes.size() - 1; int64_t c = min(pi_y, PhiTiny::max_a()); int64_t s1 = S1(x, y, c, primes[c], lpf , mu, 1); int64_t s2 = S2(x, y, z, c, primes, lpf , mu); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount
Fix undeclared UINT64_C macro
Fix undeclared UINT64_C macro
C++
bsd-2-clause
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
06b575b0c3fe3a6883897fa4f73bba85946da1e4
CefSharp/HandlerAdapter.cpp
CefSharp/HandlerAdapter.cpp
#include "stdafx.h" #include "HandlerAdapter.h" #include "BrowserControl.h" #include "Request.h" #include "ReturnValue.h" #include "StreamAdapter.h" #include "JsResultHandler.h" namespace CefSharp { CefHandler::RetVal HandlerAdapter::HandleAfterCreated(CefRefPtr<CefBrowser> browser) { if(!browser->IsPopup()) { _browserHwnd = browser->GetWindowHandle(); _cefBrowser = browser; _browserControl->OnReady(); } return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title) { _browserControl->SetTitle(gcnew String(title.c_str())); return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& url) { _browserControl->SetAddress(gcnew String(url.c_str())); return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleBeforeBrowse(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, NavType navType, bool isRedirect) { return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) { if(!browser->IsPopup()) { Lock(); if(!frame.get()) { _browserControl->SetNavState(true, false, false); } _browserControl->AddFrame(frame); Unlock(); } return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) { if(!browser->IsPopup()) { Lock(); if(!frame.get()) { _browserControl->SetNavState(false, browser->CanGoBack(), browser->CanGoForward()); } _browserControl->FrameLoadComplete(frame); Unlock(); } return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefRequest> request, CefString& redirectUrl, CefRefPtr<CefStreamReader>& resourceStream, CefString& mimeType, int loadFlags) { IBeforeResourceLoad^ handler = _browserControl->BeforeResourceLoadHandler; if(handler != nullptr) { String^ mRedirectUrl = nullptr; Stream^ mResourceStream = nullptr; String^ mMimeType = nullptr; CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request); handler->HandleBeforeResourceLoad(_browserControl, wrapper, mRedirectUrl, mResourceStream, mMimeType, loadFlags); if(mResourceStream != nullptr) { CefRefPtr<StreamAdapter> adapter = new StreamAdapter(mResourceStream); resourceStream = CefStreamReader::CreateForHandler(static_cast<CefRefPtr<CefReadHandler>>(adapter)); pin_ptr<const wchar_t> pStr = PtrToStringChars(mMimeType); CefString str(pStr); mimeType = str; } } return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleJSBinding(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Value> object) { JsResultHandler::Bind(_browserControl, object); return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleConsoleMessage(CefRefPtr<CefBrowser> browser, const CefString& message, const CefString& source, int line) { String^ messageStr = convertToString(message); String^ sourceStr = convertToString(source); _browserControl->RaiseConsoleMessage(messageStr, sourceStr, line); return RV_CONTINUE; } }
#include "stdafx.h" #include "HandlerAdapter.h" #include "BrowserControl.h" #include "Request.h" #include "ReturnValue.h" #include "StreamAdapter.h" #include "JsResultHandler.h" namespace CefSharp { CefHandler::RetVal HandlerAdapter::HandleAfterCreated(CefRefPtr<CefBrowser> browser) { if(!browser->IsPopup()) { _browserHwnd = browser->GetWindowHandle(); _cefBrowser = browser; _browserControl->OnReady(); } return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title) { _browserControl->SetTitle(gcnew String(title.c_str())); return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& url) { if(frame->IsMain()) { _browserControl->SetAddress(gcnew String(url.c_str())); } return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleBeforeBrowse(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, NavType navType, bool isRedirect) { return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) { if(!browser->IsPopup()) { Lock(); if(!frame.get()) { _browserControl->SetNavState(true, false, false); } _browserControl->AddFrame(frame); Unlock(); } return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame) { if(!browser->IsPopup()) { Lock(); if(!frame.get()) { _browserControl->SetNavState(false, browser->CanGoBack(), browser->CanGoForward()); } _browserControl->FrameLoadComplete(frame); Unlock(); } return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefRequest> request, CefString& redirectUrl, CefRefPtr<CefStreamReader>& resourceStream, CefString& mimeType, int loadFlags) { IBeforeResourceLoad^ handler = _browserControl->BeforeResourceLoadHandler; if(handler != nullptr) { String^ mRedirectUrl = nullptr; Stream^ mResourceStream = nullptr; String^ mMimeType = nullptr; CefRequestWrapper^ wrapper = gcnew CefRequestWrapper(request); handler->HandleBeforeResourceLoad(_browserControl, wrapper, mRedirectUrl, mResourceStream, mMimeType, loadFlags); if(mResourceStream != nullptr) { CefRefPtr<StreamAdapter> adapter = new StreamAdapter(mResourceStream); resourceStream = CefStreamReader::CreateForHandler(static_cast<CefRefPtr<CefReadHandler>>(adapter)); pin_ptr<const wchar_t> pStr = PtrToStringChars(mMimeType); CefString str(pStr); mimeType = str; } } return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleJSBinding(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Value> object) { JsResultHandler::Bind(_browserControl, object); return RV_CONTINUE; } CefHandler::RetVal HandlerAdapter::HandleConsoleMessage(CefRefPtr<CefBrowser> browser, const CefString& message, const CefString& source, int line) { String^ messageStr = convertToString(message); String^ sourceStr = convertToString(source); _browserControl->RaiseConsoleMessage(messageStr, sourceStr, line); return RV_CONTINUE; } }
fix bug - Address property showing addresses of frames.
fix bug - Address property showing addresses of frames.
C++
bsd-3-clause
VioletLife/CefSharp,Octopus-ITSM/CefSharp,illfang/CefSharp,ataranto/CefSharp,rlmcneary2/CefSharp,joshvera/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,NumbersInternational/CefSharp,ITGlobal/CefSharp,windygu/CefSharp,Octopus-ITSM/CefSharp,paulcbetts/CefSharp,jamespearce2006/CefSharp,gregmartinhtc/CefSharp,windygu/CefSharp,Livit/CefSharp,dga711/CefSharp,rover886/CefSharp,AJDev77/CefSharp,Haraguroicha/CefSharp,jamespearce2006/CefSharp,ruisebastiao/CefSharp,NumbersInternational/CefSharp,Livit/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,AJDev77/CefSharp,yoder/CefSharp,wangzheng888520/CefSharp,rlmcneary2/CefSharp,twxstar/CefSharp,rover886/CefSharp,zhangjingpu/CefSharp,ruisebastiao/CefSharp,joshvera/CefSharp,zhangjingpu/CefSharp,AJDev77/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,joshvera/CefSharp,gregmartinhtc/CefSharp,ataranto/CefSharp,jamespearce2006/CefSharp,yoder/CefSharp,twxstar/CefSharp,VioletLife/CefSharp,VioletLife/CefSharp,jamespearce2006/CefSharp,illfang/CefSharp,AJDev77/CefSharp,VioletLife/CefSharp,dga711/CefSharp,rover886/CefSharp,Octopus-ITSM/CefSharp,Livit/CefSharp,dga711/CefSharp,Haraguroicha/CefSharp,ITGlobal/CefSharp,wangzheng888520/CefSharp,haozhouxu/CefSharp,Haraguroicha/CefSharp,Octopus-ITSM/CefSharp,zhangjingpu/CefSharp,wangzheng888520/CefSharp,illfang/CefSharp,yoder/CefSharp,illfang/CefSharp,ruisebastiao/CefSharp,ataranto/CefSharp,dga711/CefSharp,paulcbetts/CefSharp,NumbersInternational/CefSharp,windygu/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,battewr/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp,jamespearce2006/CefSharp,NumbersInternational/CefSharp,ITGlobal/CefSharp,Livit/CefSharp,joshvera/CefSharp,gregmartinhtc/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,twxstar/CefSharp,battewr/CefSharp,rover886/CefSharp,haozhouxu/CefSharp,gregmartinhtc/CefSharp,ataranto/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,ruisebastiao/CefSharp,rover886/CefSharp
cbeffcb44c9df3b6dd52f2949c9dfec888b84560
src/Profiling.cpp
src/Profiling.cpp
#include "Profiling.h" #include "IRMutator.h" #include "IROperator.h" #include <algorithm> #include <map> #include <string> namespace Halide { namespace Internal { namespace { const char kBufName[] = "ProfilerBuffer"; const char kToplevel[] = "$total$"; } int profiling_level() { char *trace = getenv("HL_PROFILE"); return trace ? atoi(trace) : 0; } using std::map; using std::string; using std::vector; class InjectProfiling : public IRMutator { public: InjectProfiling(string func_name) : level(profiling_level()), func_name(sanitize(func_name)) { } Stmt inject(Stmt s) { if (level >= 1) { // Add calls to the usec and timer at the start and end, // so that we can get an estimate of how long a single // tick of the profiling_timer is (since it may be dependent // on e.g. processor clock rate) { PushCallStack st(this, kToplevel, kToplevel); s = mutate(s); } s = add_ticks(kToplevel, kToplevel, s); s = add_usec(kToplevel, kToplevel, s); // Note that this is tacked on to the front of the block, since it must come // before the calls to halide_current_time_usec. Expr begin_clock_call = Call::make(Int(32), "halide_start_clock", std::vector<Expr>(), Call::Extern); Stmt begin_clock = AssertStmt::make(begin_clock_call == 0, "Failed to start clock"); s = Block::make(begin_clock, s); // Tack on code to print the counters. for (map<string, int>::const_iterator it = indices.begin(); it != indices.end(); ++it) { int idx = it->second; Expr val = Load::make(UInt(64), kBufName, idx, Buffer(), Parameter()); Stmt print_val = PrintStmt::make(it->first, vec(val)); s = Block::make(s, print_val); } // Now that we know the final size, allocate the buffer and init to zero. Expr i = Variable::make(Int(32), "i"); Stmt init = For::make("i", 0, (int)indices.size(), For::Serial, Store::make(kBufName, Cast::make(UInt(64), 0), i)); s = Block::make(init, s); s = Allocate::make(kBufName, UInt(64), (int)indices.size(), s); } else { s = mutate(s); } return s; } private: using IRMutator::visit; const int level; const string func_name; map<string, int> indices; // map name -> index in buffer. vector<string> call_stack; // names of the nodes upstream class PushCallStack { public: InjectProfiling* ip; PushCallStack(InjectProfiling* ip, const string& op_type, const string& op_name) : ip(ip) { ip->call_stack.push_back(op_type + " " + op_name); } ~PushCallStack() { ip->call_stack.pop_back(); } }; // replace all spaces with '_' static string sanitize(const string& s) { string san = s; std::replace(san.begin(), san.end(), ' ', '_'); return san; } Expr get_index(const string& s) { if (indices.find(s) == indices.end()) { int idx = indices.size(); indices[s] = idx; } return indices[s]; } Stmt add_count_and_ticks(const string& op_type, const string& op_name, Stmt s) { s = add_count(op_type, op_name, s); s = add_ticks(op_type, op_name, s); return s; } Stmt add_count(const string& op_type, const string& op_name, Stmt s) { return add_delta("count", op_type, op_name, Cast::make(UInt(64), 0), Cast::make(UInt(64), 1), s); } Stmt add_ticks(const string& op_type, const string& op_name, Stmt s) { Expr ticks = Call::make(UInt(64), Internal::Call::profiling_timer, vector<Expr>(), Call::Intrinsic); return add_delta("ticks", op_type, op_name, ticks, ticks, s); } Stmt add_usec(const string& op_type, const string& op_name, Stmt s) { Expr usec = Call::make(UInt(64), "halide_current_time_usec", std::vector<Expr>(), Call::Extern); return add_delta("usec", op_type, op_name, usec, usec, s); } Stmt add_delta(const string& metric_name, const string& op_type, const string& op_name, Expr begin_val, Expr end_val, Stmt s) { string parent_name_pair = call_stack.empty() ? "null null" : call_stack.back(); string full_name = "halide_profiler " + metric_name + " " + func_name + " " + op_type + " " + sanitize(op_name) + " " + parent_name_pair; assert(begin_val.type() == UInt(64)); assert(end_val.type() == UInt(64)); Expr idx = get_index(full_name); string begin_var_name = "begin_" + full_name; Expr begin_var = Variable::make(UInt(64), begin_var_name); Expr old_val = Load::make(UInt(64), kBufName, idx, Buffer(), Parameter()); Expr delta_val = Sub::make(end_val, begin_var); Expr new_val = Add::make(old_val, delta_val); s = Block::make(s, Store::make(kBufName, new_val, idx)); s = LetStmt::make(begin_var_name, begin_val, s); return s; } void visit(const Pipeline *op) { if (level >= 1) { Stmt produce, update, consume; { PushCallStack st(this, "produce", op->name); produce = mutate(op->produce); } { PushCallStack st(this, "update", op->name); update = op->update.defined() ? mutate(op->update) : Stmt(); } { PushCallStack st(this, "consume", op->name); consume = mutate(op->consume); } produce = add_count_and_ticks("produce", op->name, produce); update = update.defined() ? add_count_and_ticks("update", op->name, update) : Stmt(); consume = add_count_and_ticks("consume", op->name, consume); stmt = Pipeline::make(op->name, produce, update, consume); } else { IRMutator::visit(op); } } void visit(const For *op) { // We only instrument loops at profiling level 2 or higher if (level >= 2) { stmt = add_count_and_ticks("forloop", op->name, stmt); } else { IRMutator::visit(op); } } }; Stmt inject_profiling(Stmt s, string name) { InjectProfiling profiling(name); s = profiling.inject(s); return s; } } }
#include "Profiling.h" #include "IRMutator.h" #include "IROperator.h" #include <algorithm> #include <map> #include <string> namespace Halide { namespace Internal { namespace { const char kBufName[] = "ProfilerBuffer"; const char kToplevel[] = "$total$"; } int profiling_level() { char *trace = getenv("HL_PROFILE"); return trace ? atoi(trace) : 0; } using std::map; using std::string; using std::vector; class InjectProfiling : public IRMutator { public: InjectProfiling(string func_name) : level(profiling_level()), func_name(sanitize(func_name)) { } Stmt inject(Stmt s) { if (level >= 1) { // Add calls to the usec and timer at the start and end, // so that we can get an estimate of how long a single // tick of the profiling_timer is (since it may be dependent // on e.g. processor clock rate) { PushCallStack st(this, kToplevel, kToplevel); s = mutate(s); } s = add_ticks(kToplevel, kToplevel, s); s = add_usec(kToplevel, kToplevel, s); // Note that this is tacked on to the front of the block, since it must come // before the calls to halide_current_time_usec. Expr begin_clock_call = Call::make(Int(32), "halide_start_clock", std::vector<Expr>(), Call::Extern); Stmt begin_clock = AssertStmt::make(begin_clock_call == 0, "Failed to start clock"); s = Block::make(begin_clock, s); // Tack on code to print the counters. for (map<string, int>::const_iterator it = indices.begin(); it != indices.end(); ++it) { int idx = it->second; Expr val = Load::make(UInt(64), kBufName, idx, Buffer(), Parameter()); Stmt print_val = PrintStmt::make(it->first, vec(val)); s = Block::make(s, print_val); } // Now that we know the final size, allocate the buffer and init to zero. Expr i = Variable::make(Int(32), "i"); Stmt init = For::make("i", 0, (int)indices.size(), For::Serial, Store::make(kBufName, Cast::make(UInt(64), 0), i)); s = Block::make(init, s); s = Allocate::make(kBufName, UInt(64), (int)indices.size(), s); } else { s = mutate(s); } return s; } private: using IRMutator::visit; const int level; const string func_name; map<string, int> indices; // map name -> index in buffer. vector<string> call_stack; // names of the nodes upstream class PushCallStack { public: InjectProfiling* ip; PushCallStack(InjectProfiling* ip, const string& op_type, const string& op_name) : ip(ip) { ip->call_stack.push_back(op_type + " " + op_name); } ~PushCallStack() { ip->call_stack.pop_back(); } }; // replace all spaces with '_' static string sanitize(const string& s) { string san = s; std::replace(san.begin(), san.end(), ' ', '_'); return san; } Expr get_index(const string& s) { if (indices.find(s) == indices.end()) { int idx = indices.size(); indices[s] = idx; } return indices[s]; } Stmt add_count_and_ticks(const string& op_type, const string& op_name, Stmt s) { s = add_count(op_type, op_name, s); s = add_ticks(op_type, op_name, s); return s; } Stmt add_count(const string& op_type, const string& op_name, Stmt s) { return add_delta("count", op_type, op_name, Cast::make(UInt(64), 0), Cast::make(UInt(64), 1), s); } Stmt add_ticks(const string& op_type, const string& op_name, Stmt s) { Expr ticks = Call::make(UInt(64), Internal::Call::profiling_timer, vector<Expr>(), Call::Intrinsic); return add_delta("ticks", op_type, op_name, ticks, ticks, s); } Stmt add_usec(const string& op_type, const string& op_name, Stmt s) { Expr usec = Call::make(UInt(64), "halide_current_time_usec", std::vector<Expr>(), Call::Extern); return add_delta("usec", op_type, op_name, usec, usec, s); } Stmt add_delta(const string& metric_name, const string& op_type, const string& op_name, Expr begin_val, Expr end_val, Stmt s) { string parent_name_pair = call_stack.empty() ? "null null" : call_stack.back(); string full_name = "halide_profiler " + metric_name + " " + func_name + " " + op_type + " " + sanitize(op_name) + " " + parent_name_pair; assert(begin_val.type() == UInt(64)); assert(end_val.type() == UInt(64)); Expr idx = get_index(full_name); string begin_var_name = "begin_" + full_name; // variable name doesn't matter at all, but de-spacing // makes the Stmt output easier to read std::replace(begin_var_name.begin(), begin_var_name.end(), ' ', '_'); Expr begin_var = Variable::make(UInt(64), begin_var_name); Expr old_val = Load::make(UInt(64), kBufName, idx, Buffer(), Parameter()); Expr delta_val = Sub::make(end_val, begin_var); Expr new_val = Add::make(old_val, delta_val); s = Block::make(s, Store::make(kBufName, new_val, idx)); s = LetStmt::make(begin_var_name, begin_val, s); return s; } void visit(const Pipeline *op) { if (level >= 1) { Stmt produce, update, consume; { PushCallStack st(this, "produce", op->name); produce = mutate(op->produce); } { PushCallStack st(this, "update", op->name); update = op->update.defined() ? mutate(op->update) : Stmt(); } { PushCallStack st(this, "consume", op->name); consume = mutate(op->consume); } produce = add_count_and_ticks("produce", op->name, produce); update = update.defined() ? add_count_and_ticks("update", op->name, update) : Stmt(); consume = add_count_and_ticks("consume", op->name, consume); stmt = Pipeline::make(op->name, produce, update, consume); } else { IRMutator::visit(op); } } void visit(const For *op) { IRMutator::visit(op); if (level >= 1) { if (op->for_type == For::Parallel) { assert(false && "Halide Profiler does not yet support parallel schedules. " "try removing parallel() schedules and re-running."); } } // We only instrument loops at profiling level 2 or higher if (level >= 2) { stmt = add_count_and_ticks("forloop", op->name, stmt); } } }; Stmt inject_profiling(Stmt s, string name) { InjectProfiling profiling(name); s = profiling.inject(s); return s; } } }
Fix instrumentation of For loops in HL_PROFILE; disallow instrumentation of parallel For loops; clean up Stmt output of temp profiling instrumentation vars
Fix instrumentation of For loops in HL_PROFILE; disallow instrumentation of parallel For loops; clean up Stmt output of temp profiling instrumentation vars Former-commit-id: f1dc63d63057ec48d1ba5c73a5b3002f078f3f3e
C++
mit
darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide
1c4284f4191c43aa3bc0a2123e57afd15a102b20
src/WebserviceWindow.cpp
src/WebserviceWindow.cpp
#include <QDebug> #include <QFile> #include <QFileDialog> #include <QMessageBox> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QProgressDialog> #include <QStringList> #include <QTextStream> #include <AlpinoCorpus/CorpusWriter.hh> #include <WebserviceWindow.hh> #include <ui_WebserviceWindow.h> namespace ac = alpinocorpus; WebserviceWindow::WebserviceWindow(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f), d_ui(QSharedPointer<Ui::WebserviceWindow>(new Ui::WebserviceWindow)), d_accessManager(new QNetworkAccessManager), d_progressDialog(new QProgressDialog(parent)) { d_ui->setupUi(this); connect(d_progressDialog, SIGNAL(canceled()), SLOT(cancelResponse())); } WebserviceWindow::~WebserviceWindow() { delete d_progressDialog; } void WebserviceWindow::openSentencesFile() { QStringList files = QFileDialog::getOpenFileNames(this, tr("Load sentences"), QString(), tr("Text files (*.txt)")); clearSentencesField(); foreach (QString const &filename, files) loadSentencesFile(filename); } void WebserviceWindow::clearSentencesField() { d_ui->sentencesField->clear(); } void WebserviceWindow::loadSentencesFile(QString const &filename) { QFile file(filename); file.open(QIODevice::ReadOnly); QTextStream instream(&file); d_ui->sentencesField->appendPlainText(instream.readAll()); } void WebserviceWindow::parseSentences() { // Ask the user where he wants to save the parsed sentences d_corpusFilename = QFileDialog::getSaveFileName(this, tr("Save parsed sentences"), QString(), tr("Dact corpus (*.dact)")); // User cancelled choosing a save destination if (d_corpusFilename.isNull()) return; // Open corpus d_corpus = QSharedPointer<ac::CorpusWriter>( ac::CorpusWriter::open( d_corpusFilename.toUtf8().constData(), true, ac::CorpusWriter::DBXML_CORPUS_WRITER)); // Get sentences and count them for progress updates QString sentences(d_ui->sentencesField->toPlainText()); d_numberOfSentences = countSentences(sentences); d_numberOfSentencesReceived = 0; // Hide the sentences dialog hide(); // Show the progress dialog d_progressDialog->setWindowTitle(tr("Parsing sentences")); d_progressDialog->setLabelText("Sending sentences to webservice"); d_progressDialog->open(); // Send the request QNetworkRequest request(QString("http://145.100.57.148/bin/alpino")); d_reply = d_accessManager->post(request, sentences.toUtf8()); // Connect all the event handlers to the response connect(d_reply, SIGNAL(readyRead()), SLOT(readResponse())); connect(d_reply, SIGNAL(finished()), SLOT(finishResponse())); connect(d_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(errorResponse(QNetworkReply::NetworkError))); } int WebserviceWindow::countSentences(QString const &sentences) { // TODO maybe this is a bit too optimistic, and should we prune empty lines. return sentences.count('\n'); } void WebserviceWindow::readResponse() { // Peek to see if there is a complete sentence to be read // If so, read it and insert it into the corpuswriter // Update progress dialog. d_progressDialog->setLabelText(tr("Parsing sentence %1 of %2") .arg(d_numberOfSentencesReceived) .arg(d_numberOfSentences)); } void WebserviceWindow::finishResponse() { qDebug() << "finishResponse"; // Reset the reply pointer, since the request is no longer active. d_reply->deleteLater(); d_reply = 0; // Hide the dialog d_progressDialog->accept(); // Clear the sentences in the window clearSentencesField(); // Open the corpus emit parseSentencesFinished(d_corpusFilename); } void WebserviceWindow::errorResponse(QNetworkReply::NetworkError error) { // TODO show human readable error. QMessageBox box(QMessageBox::Warning, tr("Failed to receive sentences"), tr("Could not receive sentences: %1") .arg("Something something"), QMessageBox::Ok); } void WebserviceWindow::cancelResponse() { qDebug() << "cancelResponse"; if (d_reply) d_reply->abort(); }
#include <QDebug> #include <QFile> #include <QFileDialog> #include <QMessageBox> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QProgressDialog> #include <QStringList> #include <QTextStream> #include <AlpinoCorpus/CorpusWriter.hh> #include <WebserviceWindow.hh> #include <ui_WebserviceWindow.h> namespace ac = alpinocorpus; WebserviceWindow::WebserviceWindow(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f), d_ui(QSharedPointer<Ui::WebserviceWindow>(new Ui::WebserviceWindow)), d_accessManager(new QNetworkAccessManager), d_progressDialog(new QProgressDialog(parent)) { d_ui->setupUi(this); connect(d_progressDialog, SIGNAL(canceled()), SLOT(cancelResponse())); } WebserviceWindow::~WebserviceWindow() { delete d_progressDialog; } void WebserviceWindow::openSentencesFile() { QStringList files = QFileDialog::getOpenFileNames(this, tr("Load sentences"), QString(), tr("Text files (*.txt)")); clearSentencesField(); foreach (QString const &filename, files) loadSentencesFile(filename); } void WebserviceWindow::clearSentencesField() { d_ui->sentencesField->clear(); } void WebserviceWindow::loadSentencesFile(QString const &filename) { QFile file(filename); file.open(QIODevice::ReadOnly); QTextStream instream(&file); d_ui->sentencesField->appendPlainText(instream.readAll()); } void WebserviceWindow::parseSentences() { // Ask the user where he wants to save the parsed sentences d_corpusFilename = QFileDialog::getSaveFileName(this, tr("Save parsed sentences"), QString(), tr("Dact corpus (*.dact)")); // User cancelled choosing a save destination if (d_corpusFilename.isNull()) return; // Open corpus d_corpus = QSharedPointer<ac::CorpusWriter>( ac::CorpusWriter::open( d_corpusFilename.toUtf8().constData(), true, ac::CorpusWriter::DBXML_CORPUS_WRITER)); // Get sentences and count them for progress updates QString sentences(d_ui->sentencesField->toPlainText()); d_numberOfSentences = countSentences(sentences); d_numberOfSentencesReceived = 0; // Hide the sentences dialog hide(); // Show the progress dialog d_progressDialog->setWindowTitle(tr("Parsing sentences")); d_progressDialog->setLabelText("Sending sentences to webservice"); d_progressDialog->open(); // Send the request QNetworkRequest request(QString("http://145.100.57.148/bin/alpino")); d_reply = d_accessManager->post(request, sentences.toUtf8()); // Connect all the event handlers to the response connect(d_reply, SIGNAL(readyRead()), SLOT(readResponse())); connect(d_reply, SIGNAL(finished()), SLOT(finishResponse())); connect(d_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(errorResponse(QNetworkReply::NetworkError))); } int WebserviceWindow::countSentences(QString const &sentences) { // TODO maybe this is a bit too optimistic, and should we prune empty lines. return sentences.count('\n'); } void WebserviceWindow::readResponse() { // Peek to see if there is a complete sentence to be read // If so, read it and insert it into the corpuswriter // Update progress dialog. d_progressDialog->setLabelText(tr("Parsing sentence %1 of %2") .arg(d_numberOfSentencesReceived) .arg(d_numberOfSentences)); } void WebserviceWindow::finishResponse() { qDebug() << "finishResponse"; // Reset the reply pointer, since the request is no longer active. d_reply->deleteLater(); d_reply = 0; // Also close the corpus writer d_corpus.clear(); // Hide the dialog d_progressDialog->accept(); // Clear the sentences in the window clearSentencesField(); // Open the corpus emit parseSentencesFinished(d_corpusFilename); } void WebserviceWindow::errorResponse(QNetworkReply::NetworkError error) { // TODO show human readable error. QMessageBox box(QMessageBox::Warning, tr("Failed to receive sentences"), tr("Could not receive sentences: %1") .arg("Something something"), QMessageBox::Ok); } void WebserviceWindow::cancelResponse() { qDebug() << "cancelResponse"; if (d_reply) d_reply->abort(); }
Delete corpus writer when finished writing (and let it write a nice end to the file so dact won't crash while trying to read it)
Delete corpus writer when finished writing (and let it write a nice end to the file so dact won't crash while trying to read it)
C++
lgpl-2.1
evdmade01/dact,rug-compling/dact,rug-compling/dact,evdmade01/dact,evdmade01/dact
91727bc712fca3bf7f6ef289b40c82248a1a681f
tutorial01.cc
tutorial01.cc
// Include standard headers #include <stdio.h> #include <stdlib.h> #include <string> #include <fstream> #include <vector> // Include GLEW #include <GL/glew.h> // Include GLFW #include <glfw3.h> GLFWwindow* window; // Include GLM #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> using namespace glm; void error_callback(int error, const char* description) { fputs(description, stderr); } GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) { // Create the shaders GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); // Read the Vertex Shader code from the file std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); if (VertexShaderStream.is_open()) { std::string Line = ""; while (getline(VertexShaderStream, Line)) VertexShaderCode += "\n" + Line; VertexShaderStream.close(); } // Read the Fragment Shader code from the file std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); if (FragmentShaderStream.is_open()) { std::string Line = ""; while (getline(FragmentShaderStream, Line)) FragmentShaderCode += "\n" + Line; FragmentShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; // Compile Vertex Shader printf("Compiling shader : %s\n", vertex_file_path); char const* VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer, NULL); glCompileShader(VertexShaderID); // Check Vertex Shader glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> VertexShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]); // Compile Fragment Shader printf("Compiling shader : %s\n", fragment_file_path); char const* FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, NULL); glCompileShader(FragmentShaderID); // Check Fragment Shader glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> FragmentShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]); // Link the program fprintf(stdout, "Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> ProgramErrorMessage(max(InfoLogLength, int(1))); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); fprintf(stdout, "%s\n", &ProgramErrorMessage[0]); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } int main(void) { glfwSetErrorCallback(error_callback); // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context window = glfwCreateWindow(640, 480, "Tutorial 01. Or is it?", NULL, NULL); if (window == NULL) { fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are " "not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; // Initialize GLEW if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } // get version info const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string const GLubyte* version = glGetString (GL_VERSION); // version as a string printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); // tell GL to only draw onto a pixel if the shape is closer to the viewer glEnable (GL_DEPTH_TEST); // enable depth-testing glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); // Dark blue background glClearColor(.0f, .0f, 0.4f, 0.0f); GLuint VertexArrayID = 0; glGenVertexArrays (1, &VertexArrayID); glBindVertexArray (VertexArrayID); // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders("SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader"); GLuint MatrixID = glGetUniformLocation(programID, "MVP"); // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units glm::mat4 Projection = glm::perspective(60.0f, 4.0f / 3.0f, 0.1f, 100.0f); // Camera matrix glm::mat4 View = glm::lookAt( glm::vec3(4,3,3), // Camera is at (4,3,3), in World Space glm::vec3(0,0,0), // and looks at the origin glm::vec3(0,1,0) // Head is up (set to 0,-1,0 to look upside-down) ); // Model matrix : an identity matrix (model will be at the origin) glm::mat4 Model = glm::mat4(1.0f); // Changes for each model ! // Our ModelViewProjection : multiplication of our 3 matrices glm::mat4 MVP = Projection * View * Model; // Remember, matrix multiplication is the other way around // An array of 3 vectors which represents 3 vertices static const GLfloat g_vertex_buffer_data[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, -1.5f, 0.0f, }; GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);   do { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programID); // Send our transformation to the currently bound shader, // in the "MVP" uniform // For each model you render, since the MVP will be different (at least the M part) glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glBindVertexArray(VertexArrayID); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(0); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); // Cleanup VBO and shader glDeleteBuffers(1, &vertexbuffer); glDeleteProgram(programID); glDeleteVertexArrays(1, &VertexArrayID); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; }
// Include standard headers #include <stdio.h> #include <stdlib.h> #include <string> #include <fstream> #include <vector> // Include GLEW #include <GL/glew.h> // Include GLFW #include <glfw3.h> GLFWwindow* window; // Include GLM #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> using namespace glm; void error_callback(int error, const char* description) { fputs(description, stderr); } GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) { // Create the shaders GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); // Read the Vertex Shader code from the file std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); if (VertexShaderStream.is_open()) { std::string Line = ""; while (getline(VertexShaderStream, Line)) VertexShaderCode += "\n" + Line; VertexShaderStream.close(); } // Read the Fragment Shader code from the file std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); if (FragmentShaderStream.is_open()) { std::string Line = ""; while (getline(FragmentShaderStream, Line)) FragmentShaderCode += "\n" + Line; FragmentShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; // Compile Vertex Shader printf("Compiling shader : %s\n", vertex_file_path); char const* VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer, NULL); glCompileShader(VertexShaderID); // Check Vertex Shader glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> VertexShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]); // Compile Fragment Shader printf("Compiling shader : %s\n", fragment_file_path); char const* FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, NULL); glCompileShader(FragmentShaderID); // Check Fragment Shader glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> FragmentShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]); // Link the program fprintf(stdout, "Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> ProgramErrorMessage(max(InfoLogLength, int(1))); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); fprintf(stdout, "%s\n", &ProgramErrorMessage[0]); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } int main(void) { glfwSetErrorCallback(error_callback); // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); #ifdef __APPLE__ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif // Open a window and create its OpenGL context window = glfwCreateWindow(640, 480, "Tutorial 01. Or is it?", NULL, NULL); if (window == NULL) { fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are " "not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; // Initialize GLEW if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } // get version info const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string const GLubyte* version = glGetString (GL_VERSION); // version as a string printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); // tell GL to only draw onto a pixel if the shape is closer to the viewer glEnable (GL_DEPTH_TEST); // enable depth-testing glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); // Dark blue background glClearColor(.0f, .0f, 0.4f, 0.0f); GLuint VertexArrayID = 0; glGenVertexArrays (1, &VertexArrayID); glBindVertexArray (VertexArrayID); // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders("SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader"); GLuint MatrixID = glGetUniformLocation(programID, "MVP"); // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units glm::mat4 Projection = glm::perspective(60.0f, 4.0f / 3.0f, 0.1f, 100.0f); // Camera matrix glm::mat4 View = glm::lookAt( glm::vec3(4,3,3), // Camera is at (4,3,3), in World Space glm::vec3(0,0,0), // and looks at the origin glm::vec3(0,1,0) // Head is up (set to 0,-1,0 to look upside-down) ); // Model matrix : an identity matrix (model will be at the origin) glm::mat4 Model = glm::mat4(1.0f); // Changes for each model ! // Our ModelViewProjection : multiplication of our 3 matrices glm::mat4 MVP = Projection * View * Model; // Remember, matrix multiplication is the other way around // An array of 3 vectors which represents 3 vertices static const GLfloat g_vertex_buffer_data[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, -1.5f, 0.0f, }; GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); do { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programID); // Send our transformation to the currently bound shader, // in the "MVP" uniform // For each model you render, since the MVP will be different (at least the M part) glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glBindVertexArray(VertexArrayID); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(0); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); // Cleanup VBO and shader glDeleteBuffers(1, &vertexbuffer); glDeleteProgram(programID); glDeleteVertexArrays(1, &VertexArrayID); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; }
Put Mac-specific GLFW code under ifdef
Put Mac-specific GLFW code under ifdef
C++
apache-2.0
aam/opengl
c06b037629433b8c1fbc80c3dc4351bc56666160
source/synchronization/SignalsReceiverControlBlock.cpp
source/synchronization/SignalsReceiverControlBlock.cpp
/** * \file * \brief SignalsReceiverControlBlock class implementation * * \author Copyright (C) 2015-2017 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/. */ #include "distortos/internal/synchronization/SignalsReceiverControlBlock.hpp" #include "distortos/internal/scheduler/getScheduler.hpp" #include "distortos/internal/scheduler/Scheduler.hpp" #include "distortos/assert.h" #include "distortos/InterruptMaskingLock.hpp" #include "distortos/SignalsCatcher.hpp" #include "distortos/SignalInformationQueueWrapper.hpp" #include <cerrno> namespace distortos { namespace internal { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ SignalsReceiverControlBlock::SignalsReceiverControlBlock(SignalInformationQueueWrapper* const signalInformationQueueWrapper, SignalsCatcher* const signalsCatcher) : pendingSignalSet_{SignalSet::empty}, waitingSignalSet_{}, signalsCatcherControlBlock_{signalsCatcher != nullptr ? &signalsCatcher->signalsCatcherControlBlock_ : nullptr}, signalInformationQueue_ { signalInformationQueueWrapper != nullptr ? &signalInformationQueueWrapper->signalInformationQueue_ : nullptr } { } std::pair<int, SignalInformation> SignalsReceiverControlBlock::acceptPendingSignal(const uint8_t signalNumber) { if (signalInformationQueue_ != nullptr) { const auto acceptQueuedSignalResult = signalInformationQueue_->acceptQueuedSignal(signalNumber); if (acceptQueuedSignalResult.first != EAGAIN) // signal was accepted or fatal error? return acceptQueuedSignalResult; } const auto testResult = pendingSignalSet_.test(signalNumber); if (testResult.first != 0) return {testResult.first, SignalInformation{uint8_t{}, SignalInformation::Code{}, sigval{}}}; if (testResult.second == false) return {EAGAIN, SignalInformation{uint8_t{}, SignalInformation::Code{}, sigval{}}}; const auto ret = pendingSignalSet_.remove(signalNumber); return {ret, SignalInformation{signalNumber, SignalInformation::Code::generated, sigval{}}}; } int SignalsReceiverControlBlock::deliveryOfSignalsStartedHook() const { if (signalsCatcherControlBlock_ == nullptr) return ENOTSUP; signalsCatcherControlBlock_->deliveryOfSignalsStartedHook(); return 0; } int SignalsReceiverControlBlock::generateSignal(const uint8_t signalNumber, ThreadControlBlock& threadControlBlock) { { const InterruptMaskingLock interruptMaskingLock; const auto isSignalIgnoredResult = isSignalIgnored(signalNumber); if (isSignalIgnoredResult.first != 0) return isSignalIgnoredResult.first; if (isSignalIgnoredResult.second == true) // is signal ignored? return 0; { const auto ret = beforeGenerateQueue(signalNumber, threadControlBlock); if (ret != 0) return ret; } pendingSignalSet_.add(signalNumber); // signal number is valid (checked above) { const auto ret = afterGenerateQueueLocked(signalNumber, threadControlBlock); if (ret != 0) return ret; } } afterGenerateQueueUnlocked(signalNumber, threadControlBlock); return 0; } SignalSet SignalsReceiverControlBlock::getPendingSignalSet() const { const auto pendingSignalSet = pendingSignalSet_; if (signalInformationQueue_ == nullptr) return pendingSignalSet; const auto queuedSignalSet = signalInformationQueue_->getQueuedSignalSet(); return SignalSet{pendingSignalSet.getBitset() | queuedSignalSet.getBitset()}; } std::pair<int, SignalAction> SignalsReceiverControlBlock::getSignalAction(const uint8_t signalNumber) const { if (signalsCatcherControlBlock_ == nullptr) return {ENOTSUP, {}}; return signalsCatcherControlBlock_->getAssociation(signalNumber); } SignalSet SignalsReceiverControlBlock::getSignalMask() const { if (signalsCatcherControlBlock_ == nullptr) return SignalSet{SignalSet::full}; return signalsCatcherControlBlock_->getSignalMask(); } int SignalsReceiverControlBlock::queueSignal(const uint8_t signalNumber, const sigval value, ThreadControlBlock& threadControlBlock) const { if (signalInformationQueue_ == nullptr) return ENOTSUP; { const InterruptMaskingLock interruptMaskingLock; const auto isSignalIgnoredResult = isSignalIgnored(signalNumber); if (isSignalIgnoredResult.first != 0) return isSignalIgnoredResult.first; if (isSignalIgnoredResult.second == true) // is signal ignored? return 0; { const auto ret = beforeGenerateQueue(signalNumber, threadControlBlock); if (ret != 0) return ret; } { const auto ret = signalInformationQueue_->queueSignal(signalNumber, value); if (ret != 0) return ret; } { const auto ret = afterGenerateQueueLocked(signalNumber, threadControlBlock); if (ret != 0) return ret; } } afterGenerateQueueUnlocked(signalNumber, threadControlBlock); return 0; } std::pair<int, SignalAction> SignalsReceiverControlBlock::setSignalAction(const uint8_t signalNumber, const SignalAction& signalAction) { if (signalsCatcherControlBlock_ == nullptr) return {ENOTSUP, {}}; if (signalAction.getHandler() == SignalAction{}.getHandler()) // new signal action is to ignore the signal? { int ret; // discard all pending signals // this can be done before the signal is actually changed, because clearing association (changing signal action // to "ignore") may not fail (if the signal number is valid) while (std::tie(ret, std::ignore) = acceptPendingSignal(signalNumber), ret == 0); if (ret != EAGAIN) // fatal error? return {ret, {}}; } return signalsCatcherControlBlock_->setAssociation(signalNumber, signalAction); } int SignalsReceiverControlBlock::setSignalMask(const SignalSet signalMask, const bool deliver) { if (signalsCatcherControlBlock_ == nullptr) return ENOTSUP; signalsCatcherControlBlock_->setSignalMask(signalMask, deliver == true ? this : nullptr); return 0; } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ int SignalsReceiverControlBlock::afterGenerateQueueLocked(const uint8_t signalNumber, ThreadControlBlock& threadControlBlock) const { assert(signalNumber < SignalSet::Bitset{}.size() && "Invalid signal number!"); if (signalsCatcherControlBlock_ != nullptr) { const auto signalMask = signalsCatcherControlBlock_->getSignalMask(); const auto testResult = signalMask.test(signalNumber); if (testResult.second == false) // signal is not masked? return signalsCatcherControlBlock_->afterGenerateQueueLocked(signalNumber, threadControlBlock); } if (waitingSignalSet_ == nullptr) return 0; const auto testResult = waitingSignalSet_->test(signalNumber); if (testResult.second == false) // signalNumber is not "waited for"? return 0; getScheduler().unblock(ThreadList::iterator{threadControlBlock}); return 0; } void SignalsReceiverControlBlock::afterGenerateQueueUnlocked(uint8_t, ThreadControlBlock&) const { } int SignalsReceiverControlBlock::beforeGenerateQueue(uint8_t, ThreadControlBlock&) const { return 0; } std::pair<int, bool> SignalsReceiverControlBlock::isSignalIgnored(const uint8_t signalNumber) const { if (signalNumber >= SignalSet::Bitset{}.size()) return {EINVAL, {}}; if (signalsCatcherControlBlock_ == nullptr) return {{}, false}; SignalAction signalAction; // this will never fail, because signal number is valid (checked above) std::tie(std::ignore, signalAction) = signalsCatcherControlBlock_->getAssociation(signalNumber); // default handler == signal is ignored return {{}, signalAction.getHandler() == SignalAction{}.getHandler() ? true : false}; } } // namespace internal } // namespace distortos
/** * \file * \brief SignalsReceiverControlBlock class implementation * * \author Copyright (C) 2015-2017 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/. */ #include "distortos/internal/synchronization/SignalsReceiverControlBlock.hpp" #include "distortos/internal/scheduler/getScheduler.hpp" #include "distortos/internal/scheduler/Scheduler.hpp" #include "distortos/assert.h" #include "distortos/InterruptMaskingLock.hpp" #include "distortos/SignalsCatcher.hpp" #include "distortos/SignalInformationQueueWrapper.hpp" #include <cerrno> namespace distortos { namespace internal { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ SignalsReceiverControlBlock::SignalsReceiverControlBlock(SignalInformationQueueWrapper* const signalInformationQueueWrapper, SignalsCatcher* const signalsCatcher) : pendingSignalSet_{SignalSet::empty}, waitingSignalSet_{}, signalsCatcherControlBlock_{signalsCatcher != nullptr ? &signalsCatcher->signalsCatcherControlBlock_ : nullptr}, signalInformationQueue_ { signalInformationQueueWrapper != nullptr ? &signalInformationQueueWrapper->signalInformationQueue_ : nullptr } { } std::pair<int, SignalInformation> SignalsReceiverControlBlock::acceptPendingSignal(const uint8_t signalNumber) { if (signalInformationQueue_ != nullptr) { const auto acceptQueuedSignalResult = signalInformationQueue_->acceptQueuedSignal(signalNumber); if (acceptQueuedSignalResult.first != EAGAIN) // signal was accepted or fatal error? return acceptQueuedSignalResult; } const auto testResult = pendingSignalSet_.test(signalNumber); if (testResult.first != 0) return {testResult.first, SignalInformation{uint8_t{}, SignalInformation::Code{}, sigval{}}}; if (testResult.second == false) return {EAGAIN, SignalInformation{uint8_t{}, SignalInformation::Code{}, sigval{}}}; const auto ret = pendingSignalSet_.remove(signalNumber); return {ret, SignalInformation{signalNumber, SignalInformation::Code::generated, sigval{}}}; } int SignalsReceiverControlBlock::deliveryOfSignalsStartedHook() const { if (signalsCatcherControlBlock_ == nullptr) return ENOTSUP; signalsCatcherControlBlock_->deliveryOfSignalsStartedHook(); return 0; } int SignalsReceiverControlBlock::generateSignal(const uint8_t signalNumber, ThreadControlBlock& threadControlBlock) { { const InterruptMaskingLock interruptMaskingLock; const auto isSignalIgnoredResult = isSignalIgnored(signalNumber); if (isSignalIgnoredResult.first != 0) return isSignalIgnoredResult.first; if (isSignalIgnoredResult.second == true) // is signal ignored? return 0; { const auto ret = beforeGenerateQueue(signalNumber, threadControlBlock); if (ret != 0) return ret; } pendingSignalSet_.add(signalNumber); // signal number is valid (checked above) { const auto ret = afterGenerateQueueLocked(signalNumber, threadControlBlock); if (ret != 0) return ret; } } afterGenerateQueueUnlocked(signalNumber, threadControlBlock); return 0; } SignalSet SignalsReceiverControlBlock::getPendingSignalSet() const { const auto pendingSignalSet = pendingSignalSet_; if (signalInformationQueue_ == nullptr) return pendingSignalSet; const auto queuedSignalSet = signalInformationQueue_->getQueuedSignalSet(); return SignalSet{pendingSignalSet.getBitset() | queuedSignalSet.getBitset()}; } std::pair<int, SignalAction> SignalsReceiverControlBlock::getSignalAction(const uint8_t signalNumber) const { if (signalsCatcherControlBlock_ == nullptr) return {ENOTSUP, {}}; return signalsCatcherControlBlock_->getAssociation(signalNumber); } SignalSet SignalsReceiverControlBlock::getSignalMask() const { if (signalsCatcherControlBlock_ == nullptr) return SignalSet{SignalSet::full}; return signalsCatcherControlBlock_->getSignalMask(); } int SignalsReceiverControlBlock::queueSignal(const uint8_t signalNumber, const sigval value, ThreadControlBlock& threadControlBlock) const { if (signalInformationQueue_ == nullptr) return ENOTSUP; { const InterruptMaskingLock interruptMaskingLock; const auto isSignalIgnoredResult = isSignalIgnored(signalNumber); if (isSignalIgnoredResult.first != 0) return isSignalIgnoredResult.first; if (isSignalIgnoredResult.second == true) // is signal ignored? return 0; { const auto ret = beforeGenerateQueue(signalNumber, threadControlBlock); if (ret != 0) return ret; } { const auto ret = signalInformationQueue_->queueSignal(signalNumber, value); if (ret != 0) return ret; } { const auto ret = afterGenerateQueueLocked(signalNumber, threadControlBlock); if (ret != 0) return ret; } } afterGenerateQueueUnlocked(signalNumber, threadControlBlock); return 0; } std::pair<int, SignalAction> SignalsReceiverControlBlock::setSignalAction(const uint8_t signalNumber, const SignalAction& signalAction) { if (signalsCatcherControlBlock_ == nullptr) return {ENOTSUP, {}}; if (signalAction.getHandler() == SignalAction{}.getHandler()) // new signal action is to ignore the signal? { int ret; // discard all pending signals // this can be done before the signal is actually changed, because clearing association (changing signal action // to "ignore") may not fail (if the signal number is valid) while (std::tie(ret, std::ignore) = acceptPendingSignal(signalNumber), ret == 0); if (ret != EAGAIN) // fatal error? return {ret, {}}; } return signalsCatcherControlBlock_->setAssociation(signalNumber, signalAction); } int SignalsReceiverControlBlock::setSignalMask(const SignalSet signalMask, const bool deliver) { if (signalsCatcherControlBlock_ == nullptr) return ENOTSUP; signalsCatcherControlBlock_->setSignalMask(signalMask, deliver == true ? this : nullptr); return 0; } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ int SignalsReceiverControlBlock::afterGenerateQueueLocked(const uint8_t signalNumber, ThreadControlBlock& threadControlBlock) const { assert(signalNumber < SignalSet::Bitset{}.size() && "Invalid signal number!"); if (signalsCatcherControlBlock_ != nullptr) { const auto signalMask = signalsCatcherControlBlock_->getSignalMask(); const auto testResult = signalMask.test(signalNumber); if (testResult.second == false) // signal is not masked? return signalsCatcherControlBlock_->afterGenerateQueueLocked(signalNumber, threadControlBlock); } if (waitingSignalSet_ == nullptr) return 0; const auto testResult = waitingSignalSet_->test(signalNumber); if (testResult.second == false) // signalNumber is not "waited for"? return 0; getScheduler().unblock(ThreadList::iterator{threadControlBlock}); return 0; } void SignalsReceiverControlBlock::afterGenerateQueueUnlocked(const uint8_t signalNumber, ThreadControlBlock& threadControlBlock) const { assert(signalNumber < SignalSet::Bitset{}.size() && "Invalid signal number!"); if (signalsCatcherControlBlock_ == nullptr) return; const auto testResult = signalsCatcherControlBlock_->getSignalMask().test(signalNumber); if (testResult.second == true) // signal is masked? return; signalsCatcherControlBlock_->afterGenerateQueueUnlocked(threadControlBlock); } int SignalsReceiverControlBlock::beforeGenerateQueue(uint8_t, ThreadControlBlock&) const { return 0; } std::pair<int, bool> SignalsReceiverControlBlock::isSignalIgnored(const uint8_t signalNumber) const { if (signalNumber >= SignalSet::Bitset{}.size()) return {EINVAL, {}}; if (signalsCatcherControlBlock_ == nullptr) return {{}, false}; SignalAction signalAction; // this will never fail, because signal number is valid (checked above) std::tie(std::ignore, signalAction) = signalsCatcherControlBlock_->getAssociation(signalNumber); // default handler == signal is ignored return {{}, signalAction.getHandler() == SignalAction{}.getHandler() ? true : false}; } } // namespace internal } // namespace distortos
Add calls to SignalsCatcherControlBlock::afterGenerateQueueUnlocked()
Add calls to SignalsCatcherControlBlock::afterGenerateQueueUnlocked() Call SignalsCatcherControlBlock::afterGenerateQueueUnlocked() in SignalsReceiverControlBlock::afterGenerateQueueUnlocked().
C++
mpl-2.0
DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,jasmin-j/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,jasmin-j/distortos,CezaryGapinski/distortos
2b5bba496bc4c21c8e3d7d8ad94b08185041b6ad
src/base/file_utils.cc
src/base/file_utils.cc
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/ext/base/file_utils.h" #include <sys/stat.h> #include <sys/types.h> #include <algorithm> #include <deque> #include <string> #include <vector> #include "perfetto/base/build_config.h" #include "perfetto/base/logging.h" #include "perfetto/base/platform_handle.h" #include "perfetto/base/status.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/ext/base/utils.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <Windows.h> #include <direct.h> #include <io.h> #else #include <dirent.h> #include <unistd.h> #endif namespace perfetto { namespace base { namespace { constexpr size_t kBufSize = 2048; #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Wrap FindClose to: (1) make the return unix-style; (2) deal with stdcall. int CloseFindHandle(HANDLE h) { return FindClose(h) ? 0 : -1; }; #endif } // namespace ssize_t Read(int fd, void* dst, size_t dst_size) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _read(fd, dst, static_cast<unsigned>(dst_size)); #else return PERFETTO_EINTR(read(fd, dst, dst_size)); #endif } bool ReadFileDescriptor(int fd, std::string* out) { // Do not override existing data in string. size_t i = out->size(); struct stat buf {}; if (fstat(fd, &buf) != -1) { if (buf.st_size > 0) out->resize(i + static_cast<size_t>(buf.st_size)); } ssize_t bytes_read; for (;;) { if (out->size() < i + kBufSize) out->resize(out->size() + kBufSize); bytes_read = Read(fd, &((*out)[i]), kBufSize); if (bytes_read > 0) { i += static_cast<size_t>(bytes_read); } else { out->resize(i); return bytes_read == 0; } } } bool ReadPlatformHandle(PlatformHandle h, std::string* out) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Do not override existing data in string. size_t i = out->size(); for (;;) { if (out->size() < i + kBufSize) out->resize(out->size() + kBufSize); DWORD bytes_read = 0; auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr); if (res && bytes_read > 0) { i += static_cast<size_t>(bytes_read); } else { out->resize(i); const bool is_eof = res && bytes_read == 0; auto err = res ? 0 : GetLastError(); // The "Broken pipe" error on Windows is slighly different than Unix: // On Unix: a "broken pipe" error can happen only on the writer side. On // the reader there is no broken pipe, just a EOF. // On windows: the reader also sees a broken pipe error. // Here we normalize on the Unix behavior, treating broken pipe as EOF. return is_eof || err == ERROR_BROKEN_PIPE; } } #else return ReadFileDescriptor(h, out); #endif } bool ReadFileStream(FILE* f, std::string* out) { return ReadFileDescriptor(fileno(f), out); } bool ReadFile(const std::string& path, std::string* out) { base::ScopedFile fd = base::OpenFile(path, O_RDONLY); if (!fd) return false; return ReadFileDescriptor(*fd, out); } ssize_t WriteAll(int fd, const void* buf, size_t count) { size_t written = 0; while (written < count) { // write() on windows takes an unsigned int size. uint32_t bytes_left = static_cast<uint32_t>( std::min(count - written, static_cast<size_t>(UINT32_MAX))); ssize_t wr = PERFETTO_EINTR( write(fd, static_cast<const char*>(buf) + written, bytes_left)); if (wr == 0) break; if (wr < 0) return wr; written += static_cast<size_t>(wr); } return static_cast<ssize_t>(written); } ssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) DWORD wsize = 0; if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) { return wsize; } else { return -1; } #else return WriteAll(h, buf, count); #endif } bool FlushFile(int fd) { PERFETTO_DCHECK(fd != 0); #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) return !PERFETTO_EINTR(fdatasync(fd)); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return !PERFETTO_EINTR(_commit(fd)); #else return !PERFETTO_EINTR(fsync(fd)); #endif } bool Mkdir(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _mkdir(path.c_str()) == 0; #else return mkdir(path.c_str(), 0755) == 0; #endif } bool Rmdir(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _rmdir(path.c_str()) == 0; #else return rmdir(path.c_str()) == 0; #endif } int CloseFile(int fd) { return close(fd); } ScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) { PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid); #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Always use O_BINARY on Windows, to avoid silly EOL translations. ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode)); #else // Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec. ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode)); #endif return fd; } bool FileExists(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _access(path.c_str(), 0) == 0; #else return access(path.c_str(), F_OK) == 0; #endif } // Declared in base/platform_handle.h. int ClosePlatformHandle(PlatformHandle handle) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Make the return value UNIX-style. return CloseHandle(handle) ? 0 : -1; #else return close(handle); #endif } base::Status ListFilesRecursive(const std::string& dir_path, std::vector<std::string>& output) { std::string root_dir_path = dir_path; if (root_dir_path.back() == '\\') { root_dir_path.back() = '/'; } else if (root_dir_path.back() != '/') { root_dir_path.push_back('/'); } // dir_queue contains full paths to the directories. The paths include the // root_dir_path at the beginning and the trailing slash at the end. std::deque<std::string> dir_queue; dir_queue.push_back(root_dir_path); while (!dir_queue.empty()) { const std::string cur_dir = std::move(dir_queue.front()); dir_queue.pop_front(); #if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL) return base::ErrStatus("ListFilesRecursive not supported yet"); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) std::string glob_path = cur_dir + "*"; // + 1 because we also have to count the NULL terminator. if (glob_path.length() + 1 > MAX_PATH) return base::ErrStatus("Directory path %s is too long", dir_path.c_str()); WIN32_FIND_DATAA ffd; base::ScopedResource<HANDLE, CloseFindHandle, nullptr, false, base::PlatformHandleChecker> hFind(FindFirstFileA(glob_path.c_str(), &ffd)); if (!hFind) { // For empty directories, there should be at least one entry '.'. // If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory // couldn't be accessed. return base::ErrStatus("Failed to open directory %s", cur_dir.c_str()); } do { if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0) continue; if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::string subdir_path = cur_dir + ffd.cFileName + '/'; dir_queue.push_back(subdir_path); } else { const std::string full_path = cur_dir + ffd.cFileName; PERFETTO_CHECK(full_path.length() > root_dir_path.length()); output.push_back(full_path.substr(root_dir_path.length())); } } while (FindNextFileA(*hFind, &ffd)); #else ScopedDir dir = ScopedDir(opendir(cur_dir.c_str())); if (!dir) { return base::ErrStatus("Failed to open directory %s", cur_dir.c_str()); } for (auto* dirent = readdir(dir.get()); dirent != nullptr; dirent = readdir(dir.get())) { if (strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0) { continue; } if (dirent->d_type == DT_DIR) { dir_queue.push_back(cur_dir + dirent->d_name + '/'); } else if (dirent->d_type == DT_REG) { const std::string full_path = cur_dir + dirent->d_name; PERFETTO_CHECK(full_path.length() > root_dir_path.length()); output.push_back(full_path.substr(root_dir_path.length())); } } #endif } return base::OkStatus(); } std::string GetFileExtension(const std::string& filename) { auto ext_idx = filename.rfind('.'); if (ext_idx == std::string::npos) return std::string(); return filename.substr(ext_idx); } base::Optional<size_t> GetFileSize(const std::string& file_path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) HANDLE file = CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return nullopt; } LARGE_INTEGER file_size; file_size.QuadPart = 0; BOOL ok = GetFileSizeEx(file, &file_size); CloseHandle(file); if (!ok) { return nullopt; } return static_cast<size_t>(file_size.QuadPart); #else base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC)); if (!fd) { return nullopt; } struct stat buf{}; if (fstat(*fd, &buf) == -1) { return nullopt; } return static_cast<size_t>(buf.st_size); #endif } } // namespace base } // namespace perfetto
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/ext/base/file_utils.h" #include <sys/stat.h> #include <sys/types.h> #include <algorithm> #include <deque> #include <string> #include <vector> #include "perfetto/base/build_config.h" #include "perfetto/base/logging.h" #include "perfetto/base/platform_handle.h" #include "perfetto/base/status.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/ext/base/utils.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <Windows.h> #include <direct.h> #include <io.h> #else #include <dirent.h> #include <unistd.h> #endif namespace perfetto { namespace base { namespace { constexpr size_t kBufSize = 2048; #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Wrap FindClose to: (1) make the return unix-style; (2) deal with stdcall. int CloseFindHandle(HANDLE h) { return FindClose(h) ? 0 : -1; } #endif } // namespace ssize_t Read(int fd, void* dst, size_t dst_size) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _read(fd, dst, static_cast<unsigned>(dst_size)); #else return PERFETTO_EINTR(read(fd, dst, dst_size)); #endif } bool ReadFileDescriptor(int fd, std::string* out) { // Do not override existing data in string. size_t i = out->size(); struct stat buf {}; if (fstat(fd, &buf) != -1) { if (buf.st_size > 0) out->resize(i + static_cast<size_t>(buf.st_size)); } ssize_t bytes_read; for (;;) { if (out->size() < i + kBufSize) out->resize(out->size() + kBufSize); bytes_read = Read(fd, &((*out)[i]), kBufSize); if (bytes_read > 0) { i += static_cast<size_t>(bytes_read); } else { out->resize(i); return bytes_read == 0; } } } bool ReadPlatformHandle(PlatformHandle h, std::string* out) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Do not override existing data in string. size_t i = out->size(); for (;;) { if (out->size() < i + kBufSize) out->resize(out->size() + kBufSize); DWORD bytes_read = 0; auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr); if (res && bytes_read > 0) { i += static_cast<size_t>(bytes_read); } else { out->resize(i); const bool is_eof = res && bytes_read == 0; auto err = res ? 0 : GetLastError(); // The "Broken pipe" error on Windows is slighly different than Unix: // On Unix: a "broken pipe" error can happen only on the writer side. On // the reader there is no broken pipe, just a EOF. // On windows: the reader also sees a broken pipe error. // Here we normalize on the Unix behavior, treating broken pipe as EOF. return is_eof || err == ERROR_BROKEN_PIPE; } } #else return ReadFileDescriptor(h, out); #endif } bool ReadFileStream(FILE* f, std::string* out) { return ReadFileDescriptor(fileno(f), out); } bool ReadFile(const std::string& path, std::string* out) { base::ScopedFile fd = base::OpenFile(path, O_RDONLY); if (!fd) return false; return ReadFileDescriptor(*fd, out); } ssize_t WriteAll(int fd, const void* buf, size_t count) { size_t written = 0; while (written < count) { // write() on windows takes an unsigned int size. uint32_t bytes_left = static_cast<uint32_t>( std::min(count - written, static_cast<size_t>(UINT32_MAX))); ssize_t wr = PERFETTO_EINTR( write(fd, static_cast<const char*>(buf) + written, bytes_left)); if (wr == 0) break; if (wr < 0) return wr; written += static_cast<size_t>(wr); } return static_cast<ssize_t>(written); } ssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) DWORD wsize = 0; if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) { return wsize; } else { return -1; } #else return WriteAll(h, buf, count); #endif } bool FlushFile(int fd) { PERFETTO_DCHECK(fd != 0); #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) return !PERFETTO_EINTR(fdatasync(fd)); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return !PERFETTO_EINTR(_commit(fd)); #else return !PERFETTO_EINTR(fsync(fd)); #endif } bool Mkdir(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _mkdir(path.c_str()) == 0; #else return mkdir(path.c_str(), 0755) == 0; #endif } bool Rmdir(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _rmdir(path.c_str()) == 0; #else return rmdir(path.c_str()) == 0; #endif } int CloseFile(int fd) { return close(fd); } ScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) { PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid); #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Always use O_BINARY on Windows, to avoid silly EOL translations. ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode)); #else // Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec. ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode)); #endif return fd; } bool FileExists(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _access(path.c_str(), 0) == 0; #else return access(path.c_str(), F_OK) == 0; #endif } // Declared in base/platform_handle.h. int ClosePlatformHandle(PlatformHandle handle) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Make the return value UNIX-style. return CloseHandle(handle) ? 0 : -1; #else return close(handle); #endif } base::Status ListFilesRecursive(const std::string& dir_path, std::vector<std::string>& output) { std::string root_dir_path = dir_path; if (root_dir_path.back() == '\\') { root_dir_path.back() = '/'; } else if (root_dir_path.back() != '/') { root_dir_path.push_back('/'); } // dir_queue contains full paths to the directories. The paths include the // root_dir_path at the beginning and the trailing slash at the end. std::deque<std::string> dir_queue; dir_queue.push_back(root_dir_path); while (!dir_queue.empty()) { const std::string cur_dir = std::move(dir_queue.front()); dir_queue.pop_front(); #if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL) return base::ErrStatus("ListFilesRecursive not supported yet"); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) std::string glob_path = cur_dir + "*"; // + 1 because we also have to count the NULL terminator. if (glob_path.length() + 1 > MAX_PATH) return base::ErrStatus("Directory path %s is too long", dir_path.c_str()); WIN32_FIND_DATAA ffd; base::ScopedResource<HANDLE, CloseFindHandle, nullptr, false, base::PlatformHandleChecker> hFind(FindFirstFileA(glob_path.c_str(), &ffd)); if (!hFind) { // For empty directories, there should be at least one entry '.'. // If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory // couldn't be accessed. return base::ErrStatus("Failed to open directory %s", cur_dir.c_str()); } do { if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0) continue; if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::string subdir_path = cur_dir + ffd.cFileName + '/'; dir_queue.push_back(subdir_path); } else { const std::string full_path = cur_dir + ffd.cFileName; PERFETTO_CHECK(full_path.length() > root_dir_path.length()); output.push_back(full_path.substr(root_dir_path.length())); } } while (FindNextFileA(*hFind, &ffd)); #else ScopedDir dir = ScopedDir(opendir(cur_dir.c_str())); if (!dir) { return base::ErrStatus("Failed to open directory %s", cur_dir.c_str()); } for (auto* dirent = readdir(dir.get()); dirent != nullptr; dirent = readdir(dir.get())) { if (strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0) { continue; } if (dirent->d_type == DT_DIR) { dir_queue.push_back(cur_dir + dirent->d_name + '/'); } else if (dirent->d_type == DT_REG) { const std::string full_path = cur_dir + dirent->d_name; PERFETTO_CHECK(full_path.length() > root_dir_path.length()); output.push_back(full_path.substr(root_dir_path.length())); } } #endif } return base::OkStatus(); } std::string GetFileExtension(const std::string& filename) { auto ext_idx = filename.rfind('.'); if (ext_idx == std::string::npos) return std::string(); return filename.substr(ext_idx); } base::Optional<size_t> GetFileSize(const std::string& file_path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) HANDLE file = CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return nullopt; } LARGE_INTEGER file_size; file_size.QuadPart = 0; BOOL ok = GetFileSizeEx(file, &file_size); CloseHandle(file); if (!ok) { return nullopt; } return static_cast<size_t>(file_size.QuadPart); #else base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC)); if (!fd) { return nullopt; } struct stat buf{}; if (fstat(*fd, &buf) == -1) { return nullopt; } return static_cast<size_t>(buf.st_size); #endif } } // namespace base } // namespace perfetto
Fix chromium windows build am: d21ed9d314 am: a73d9a39da
Fix chromium windows build am: d21ed9d314 am: a73d9a39da Original change: https://android-review.googlesource.com/c/platform/external/perfetto/+/1946875 Change-Id: I60e82f9157485f7384bd511f2b348ededd340a69
C++
apache-2.0
google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto
16cfb97ca20ae04dc1d3a87dcc24cec5bb38266c
editor/plugins/skeleton_2d_editor_plugin.cpp
editor/plugins/skeleton_2d_editor_plugin.cpp
/*************************************************************************/ /* skeleton_2d_editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "skeleton_2d_editor_plugin.h" #include "canvas_item_editor_plugin.h" #include "scene/2d/mesh_instance_2d.h" #include "scene/gui/box_container.h" #include "thirdparty/misc/clipper.hpp" void Skeleton2DEditor::_node_removed(Node *p_node) { if (p_node == node) { node = nullptr; options->hide(); } } void Skeleton2DEditor::edit(Skeleton2D *p_sprite) { node = p_sprite; } void Skeleton2DEditor::_menu_option(int p_option) { if (!node) { return; } switch (p_option) { case MENU_OPTION_MAKE_REST: { if (node->get_bone_count() == 0) { err_dialog->set_text(TTR("This skeleton has no bones, create some children Bone2D nodes.")); err_dialog->popup_centered(); return; } UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("Create Rest Pose from Bones")); for (int i = 0; i < node->get_bone_count(); i++) { Bone2D *bone = node->get_bone(i); ur->add_do_method(bone, "set_rest", bone->get_transform()); ur->add_undo_method(bone, "set_rest", bone->get_rest()); } ur->commit_action(); } break; case MENU_OPTION_SET_REST: { if (node->get_bone_count() == 0) { err_dialog->set_text(TTR("This skeleton has no bones, create some children Bone2D nodes.")); err_dialog->popup_centered(); return; } UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("Set Rest Pose to Bones")); for (int i = 0; i < node->get_bone_count(); i++) { Bone2D *bone = node->get_bone(i); ur->add_do_method(bone, "set_transform", bone->get_rest()); ur->add_undo_method(bone, "set_transform", bone->get_transform()); } ur->commit_action(); } break; } } void Skeleton2DEditor::_bind_methods() { } Skeleton2DEditor::Skeleton2DEditor() { options = memnew(MenuButton); CanvasItemEditor::get_singleton()->add_control_to_menu_panel(options); options->set_text(TTR("Skeleton2D")); options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Skeleton2D"), SNAME("EditorIcons"))); options->get_popup()->add_item(TTR("Make Rest Pose (From Bones)"), MENU_OPTION_MAKE_REST); options->get_popup()->add_separator(); options->get_popup()->add_item(TTR("Set Bones to Rest Pose"), MENU_OPTION_SET_REST); options->set_switch_on_hover(true); options->get_popup()->connect("id_pressed", callable_mp(this, &Skeleton2DEditor::_menu_option)); err_dialog = memnew(AcceptDialog); add_child(err_dialog); } void Skeleton2DEditorPlugin::edit(Object *p_object) { sprite_editor->edit(Object::cast_to<Skeleton2D>(p_object)); } bool Skeleton2DEditorPlugin::handles(Object *p_object) const { return p_object->is_class("Skeleton2D"); } void Skeleton2DEditorPlugin::make_visible(bool p_visible) { if (p_visible) { sprite_editor->options->show(); } else { sprite_editor->options->hide(); sprite_editor->edit(nullptr); } } Skeleton2DEditorPlugin::Skeleton2DEditorPlugin(EditorNode *p_node) { editor = p_node; sprite_editor = memnew(Skeleton2DEditor); editor->get_main_control()->add_child(sprite_editor); make_visible(false); //sprite_editor->options->hide(); } Skeleton2DEditorPlugin::~Skeleton2DEditorPlugin() { }
/*************************************************************************/ /* skeleton_2d_editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "skeleton_2d_editor_plugin.h" #include "canvas_item_editor_plugin.h" #include "scene/2d/mesh_instance_2d.h" #include "scene/gui/box_container.h" #include "thirdparty/misc/clipper.hpp" void Skeleton2DEditor::_node_removed(Node *p_node) { if (p_node == node) { node = nullptr; options->hide(); } } void Skeleton2DEditor::edit(Skeleton2D *p_sprite) { node = p_sprite; } void Skeleton2DEditor::_menu_option(int p_option) { if (!node) { return; } switch (p_option) { case MENU_OPTION_MAKE_REST: { if (node->get_bone_count() == 0) { err_dialog->set_text(TTR("This skeleton has no bones, create some children Bone2D nodes.")); err_dialog->popup_centered(); return; } UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("Create Rest Pose from Bones")); for (int i = 0; i < node->get_bone_count(); i++) { Bone2D *bone = node->get_bone(i); ur->add_do_method(bone, "set_rest", bone->get_transform()); ur->add_undo_method(bone, "set_rest", bone->get_rest()); } ur->commit_action(); } break; case MENU_OPTION_SET_REST: { if (node->get_bone_count() == 0) { err_dialog->set_text(TTR("This skeleton has no bones, create some children Bone2D nodes.")); err_dialog->popup_centered(); return; } UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("Set Rest Pose to Bones")); for (int i = 0; i < node->get_bone_count(); i++) { Bone2D *bone = node->get_bone(i); ur->add_do_method(bone, "set_transform", bone->get_rest()); ur->add_undo_method(bone, "set_transform", bone->get_transform()); } ur->commit_action(); } break; } } void Skeleton2DEditor::_bind_methods() { } Skeleton2DEditor::Skeleton2DEditor() { options = memnew(MenuButton); CanvasItemEditor::get_singleton()->add_control_to_menu_panel(options); options->set_text(TTR("Skeleton2D")); options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Skeleton2D"), SNAME("EditorIcons"))); options->get_popup()->add_item(TTR("Reset to Rest Pose"), MENU_OPTION_MAKE_REST); options->get_popup()->add_separator(); // Use the "Overwrite" word to highlight that this is a destructive operation. options->get_popup()->add_item(TTR("Overwrite Rest Pose"), MENU_OPTION_SET_REST); options->set_switch_on_hover(true); options->get_popup()->connect("id_pressed", callable_mp(this, &Skeleton2DEditor::_menu_option)); err_dialog = memnew(AcceptDialog); add_child(err_dialog); } void Skeleton2DEditorPlugin::edit(Object *p_object) { sprite_editor->edit(Object::cast_to<Skeleton2D>(p_object)); } bool Skeleton2DEditorPlugin::handles(Object *p_object) const { return p_object->is_class("Skeleton2D"); } void Skeleton2DEditorPlugin::make_visible(bool p_visible) { if (p_visible) { sprite_editor->options->show(); } else { sprite_editor->options->hide(); sprite_editor->edit(nullptr); } } Skeleton2DEditorPlugin::Skeleton2DEditorPlugin(EditorNode *p_node) { editor = p_node; sprite_editor = memnew(Skeleton2DEditor); editor->get_main_control()->add_child(sprite_editor); make_visible(false); //sprite_editor->options->hide(); } Skeleton2DEditorPlugin::~Skeleton2DEditorPlugin() { }
Tweak skeleton editor texts "Make Rest Pose" and "Set Bones to Rest Pose"
Tweak skeleton editor texts "Make Rest Pose" and "Set Bones to Rest Pose" The new terms are more descriptive of each button's actual function.
C++
mit
godotengine/godot,Faless/godot,BastiaanOlij/godot,vnen/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,akien-mga/godot,Valentactive/godot,josempans/godot,Shockblast/godot,sanikoyes/godot,guilhermefelipecgs/godot,vkbsb/godot,Valentactive/godot,vkbsb/godot,guilhermefelipecgs/godot,Zylann/godot,BastiaanOlij/godot,DmitriySalnikov/godot,BastiaanOlij/godot,sanikoyes/godot,sanikoyes/godot,guilhermefelipecgs/godot,firefly2442/godot,josempans/godot,godotengine/godot,guilhermefelipecgs/godot,pkowal1982/godot,ZuBsPaCe/godot,firefly2442/godot,vkbsb/godot,Zylann/godot,Faless/godot,godotengine/godot,pkowal1982/godot,BastiaanOlij/godot,ZuBsPaCe/godot,akien-mga/godot,godotengine/godot,josempans/godot,ZuBsPaCe/godot,akien-mga/godot,josempans/godot,vnen/godot,vkbsb/godot,vkbsb/godot,Faless/godot,akien-mga/godot,Zylann/godot,Valentactive/godot,Faless/godot,pkowal1982/godot,sanikoyes/godot,BastiaanOlij/godot,sanikoyes/godot,Shockblast/godot,Valentactive/godot,BastiaanOlij/godot,Faless/godot,Shockblast/godot,BastiaanOlij/godot,Valentactive/godot,Shockblast/godot,guilhermefelipecgs/godot,vkbsb/godot,josempans/godot,guilhermefelipecgs/godot,guilhermefelipecgs/godot,Valentactive/godot,vnen/godot,pkowal1982/godot,Shockblast/godot,Faless/godot,firefly2442/godot,akien-mga/godot,Faless/godot,firefly2442/godot,godotengine/godot,Faless/godot,josempans/godot,DmitriySalnikov/godot,akien-mga/godot,sanikoyes/godot,firefly2442/godot,Zylann/godot,Valentactive/godot,BastiaanOlij/godot,Valentactive/godot,pkowal1982/godot,pkowal1982/godot,josempans/godot,Shockblast/godot,sanikoyes/godot,sanikoyes/godot,godotengine/godot,vnen/godot,vnen/godot,akien-mga/godot,DmitriySalnikov/godot,vnen/godot,godotengine/godot,firefly2442/godot,godotengine/godot,Zylann/godot,Zylann/godot,pkowal1982/godot,akien-mga/godot,Zylann/godot,DmitriySalnikov/godot,Shockblast/godot,ZuBsPaCe/godot,Shockblast/godot,vnen/godot,Zylann/godot,guilhermefelipecgs/godot,firefly2442/godot,pkowal1982/godot,ZuBsPaCe/godot,firefly2442/godot,ZuBsPaCe/godot,ZuBsPaCe/godot,vnen/godot,josempans/godot,vkbsb/godot,DmitriySalnikov/godot,DmitriySalnikov/godot,vkbsb/godot
dd1944c3827426ad32108fa1d8e710f3dfbf9794
src/activemasternode.cpp
src/activemasternode.cpp
// Copyright (c) 2014-2017 The Helium Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "masternode.h" #include "masternode-sync.h" #include "masternodeman.h" #include "protocol.h" extern CWallet* pwalletMain; // Keep track of the active Masternode CActiveMasternode activeMasternode; void CActiveMasternode::ManageState() { LogPrint("masternode", "CActiveMasternode::ManageState -- Start\n"); if(!fMasterNode) { LogPrint("masternode", "CActiveMasternode::ManageState -- Not a masternode, returning\n"); return; } if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS; LogPrintf("CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus()); return; } if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) { nState = ACTIVE_MASTERNODE_INITIAL; } LogPrint("masternode", "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); if(eType == MASTERNODE_UNKNOWN) { ManageStateInitial(); } if(eType == MASTERNODE_REMOTE) { ManageStateRemote(); } else if(eType == MASTERNODE_LOCAL) { // Try Remote Start first so the started local masternode can be restarted without recreate masternode broadcast. ManageStateRemote(); if(nState != ACTIVE_MASTERNODE_STARTED) ManageStateLocal(); } SendMasternodePing(); } std::string CActiveMasternode::GetStateString() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "INITIAL"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "SYNC_IN_PROCESS"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return "INPUT_TOO_NEW"; case ACTIVE_MASTERNODE_NOT_CAPABLE: return "NOT_CAPABLE"; case ACTIVE_MASTERNODE_STARTED: return "STARTED"; default: return "UNKNOWN"; } } std::string CActiveMasternode::GetStatus() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations); case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason; case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started"; default: return "Unknown"; } } std::string CActiveMasternode::GetTypeString() const { std::string strType; switch(eType) { case MASTERNODE_UNKNOWN: strType = "UNKNOWN"; break; case MASTERNODE_REMOTE: strType = "REMOTE"; break; case MASTERNODE_LOCAL: strType = "LOCAL"; break; default: strType = "UNKNOWN"; break; } return strType; } bool CActiveMasternode::SendMasternodePing() { if(!fPingerEnabled) { LogPrint("masternode", "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString()); return false; } if(!mnodeman.Has(vin)) { strNotCapableReason = "Masternode not in masternode list"; nState = ACTIVE_MASTERNODE_NOT_CAPABLE; LogPrintf("CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason); return false; } CMasternodePing mnp(vin); if(!mnp.Sign(keyMasternode, pubKeyMasternode)) { LogPrintf("CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n"); return false; } // Update lastPing for our masternode in Masternode list if(mnodeman.IsMasternodePingedWithin(vin, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { LogPrintf("CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n"); return false; } mnodeman.SetMasternodeLastPing(vin, mnp); LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", vin.ToString()); mnp.Relay(); return true; } void CActiveMasternode::ManageStateInitial() { LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); // Check that our local network configuration is correct if (!fListen) { // listen option is probably overwritten by smth else, no good nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter."; LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } bool fFoundLocal = false; { LOCK(cs_vNodes); // First try to find whatever local address is specified by externalip option fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service); if(!fFoundLocal) { // nothing and no live connections, can't do anything for now if (vNodes.empty()) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available."; LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // We have some peers, let's try to find our local address from one of them BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->fSuccessfullyConnected && pnode->addr.IsIPv4()) { fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service); if(fFoundLocal) break; } } } } if(!fFoundLocal) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only."; LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(service.GetPort() != mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } } else if(service.GetPort() == mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } LogPrintf("CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString()); if(!ConnectNode((CAddress)service, NULL, true)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Could not connect to " + service.ToString(); LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // Default to REMOTE eType = MASTERNODE_REMOTE; // Check if wallet funds are available if(!pwalletMain) { LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet not available\n", GetStateString()); return; } if(pwalletMain->IsLocked()) { LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet is locked\n", GetStateString()); return; } if(pwalletMain->GetBalance() < 1000*COIN) { LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet balance is < 1000 HELIUM\n", GetStateString()); return; } // Choose coins to use CPubKey pubKeyCollateral; CKey keyCollateral; // If collateral is found switch to LOCAL mode if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) { eType = MASTERNODE_LOCAL; } LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); } void CActiveMasternode::ManageStateRemote() { LogPrint("masternode", "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n", GetStatus(), fPingerEnabled, GetTypeString(), pubKeyMasternode.GetID().ToString()); mnodeman.CheckMasternode(pubKeyMasternode); masternode_info_t infoMn = mnodeman.GetMasternodeInfo(pubKeyMasternode); if(infoMn.fInfoValid) { if(infoMn.nProtocolVersion != PROTOCOL_VERSION) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Invalid protocol version"; LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(service != infoMn.addr) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently."; LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState)); LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(nState != ACTIVE_MASTERNODE_STARTED) { LogPrintf("CActiveMasternode::ManageStateRemote -- STARTED!\n"); vin = infoMn.vin; service = infoMn.addr; fPingerEnabled = true; nState = ACTIVE_MASTERNODE_STARTED; } } else { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode not in masternode list"; LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); } } void CActiveMasternode::ManageStateLocal() { LogPrint("masternode", "CActiveMasternode::ManageStateLocal -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); if(nState == ACTIVE_MASTERNODE_STARTED) { return; } // Choose coins to use CPubKey pubKeyCollateral; CKey keyCollateral; if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) { int nInputAge = GetInputAge(vin); if(nInputAge < Params().GetConsensus().nMasternodeMinimumConfirmations){ nState = ACTIVE_MASTERNODE_INPUT_TOO_NEW; strNotCapableReason = strprintf(_("%s - %d confirmations"), GetStatus(), nInputAge); LogPrintf("CActiveMasternode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason); return; } { LOCK(pwalletMain->cs_wallet); pwalletMain->LockCoin(vin.prevout); } CMasternodeBroadcast mnb; std::string strError; if(!CMasternodeBroadcast::Create(vin, service, keyCollateral, pubKeyCollateral, keyMasternode, pubKeyMasternode, strError, mnb)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Error creating mastenode broadcast: " + strError; LogPrintf("CActiveMasternode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason); return; } fPingerEnabled = true; nState = ACTIVE_MASTERNODE_STARTED; //update to masternode list LogPrintf("CActiveMasternode::ManageStateLocal -- Update Masternode List\n"); mnodeman.UpdateMasternodeList(mnb); mnodeman.NotifyMasternodeUpdates(); //send to all peers LogPrintf("CActiveMasternode::ManageStateLocal -- Relay broadcast, vin=%s\n", vin.ToString()); mnb.Relay(); } }
// Copyright (c) 2014-2017 The Helium Core developers // Copyright (c) 2014-2017 The DASH Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "masternode.h" #include "masternode-sync.h" #include "masternodeman.h" #include "protocol.h" extern CWallet* pwalletMain; // Keep track of the active Masternode CActiveMasternode activeMasternode; void CActiveMasternode::ManageState() { LogPrint("masternode", "CActiveMasternode::ManageState -- Start\n"); if(!fMasterNode) { LogPrint("masternode", "CActiveMasternode::ManageState -- Not a masternode, returning\n"); return; } if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS; LogPrintf("CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus()); return; } if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) { nState = ACTIVE_MASTERNODE_INITIAL; } LogPrint("masternode", "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); if(eType == MASTERNODE_UNKNOWN) { ManageStateInitial(); } if(eType == MASTERNODE_REMOTE) { ManageStateRemote(); } else if(eType == MASTERNODE_LOCAL) { // Try Remote Start first so the started local masternode can be restarted without recreate masternode broadcast. ManageStateRemote(); if(nState != ACTIVE_MASTERNODE_STARTED) ManageStateLocal(); } SendMasternodePing(); } std::string CActiveMasternode::GetStateString() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "INITIAL"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "SYNC_IN_PROCESS"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return "INPUT_TOO_NEW"; case ACTIVE_MASTERNODE_NOT_CAPABLE: return "NOT_CAPABLE"; case ACTIVE_MASTERNODE_STARTED: return "STARTED"; default: return "UNKNOWN"; } } std::string CActiveMasternode::GetStatus() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations); case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason; case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started"; default: return "Unknown"; } } std::string CActiveMasternode::GetTypeString() const { std::string strType; switch(eType) { case MASTERNODE_UNKNOWN: strType = "UNKNOWN"; break; case MASTERNODE_REMOTE: strType = "REMOTE"; break; case MASTERNODE_LOCAL: strType = "LOCAL"; break; default: strType = "UNKNOWN"; break; } return strType; } bool CActiveMasternode::SendMasternodePing() { if(!fPingerEnabled) { LogPrint("masternode", "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString()); return false; } if(!mnodeman.Has(vin)) { strNotCapableReason = "Masternode not in masternode list"; nState = ACTIVE_MASTERNODE_NOT_CAPABLE; LogPrintf("CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason); return false; } CMasternodePing mnp(vin); if(!mnp.Sign(keyMasternode, pubKeyMasternode)) { LogPrintf("CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n"); return false; } // Update lastPing for our masternode in Masternode list if(mnodeman.IsMasternodePingedWithin(vin, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { LogPrintf("CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n"); return false; } mnodeman.SetMasternodeLastPing(vin, mnp); LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", vin.ToString()); mnp.Relay(); return true; } void CActiveMasternode::ManageStateInitial() { LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); // Check that our local network configuration is correct if (!fListen) { // listen option is probably overwritten by smth else, no good nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter."; LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } bool fFoundLocal = false; { LOCK(cs_vNodes); // First try to find whatever local address is specified by externalip option fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service); if(!fFoundLocal) { // nothing and no live connections, can't do anything for now if (vNodes.empty()) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available."; LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // We have some peers, let's try to find our local address from one of them BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->fSuccessfullyConnected && pnode->addr.IsIPv4()) { fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service); if(fFoundLocal) break; } } } } if(!fFoundLocal) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only."; LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(service.GetPort() != mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } } else if(service.GetPort() == mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } LogPrintf("CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString()); if(!ConnectNode((CAddress)service, NULL, true)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Could not connect to " + service.ToString(); LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // Default to REMOTE eType = MASTERNODE_REMOTE; // Check if wallet funds are available if(!pwalletMain) { LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet not available\n", GetStateString()); return; } if(pwalletMain->IsLocked()) { LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet is locked\n", GetStateString()); return; } if(pwalletMain->GetBalance() < 1000*COIN) { LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet balance is < 1000 HELIUM\n", GetStateString()); return; } // Choose coins to use CPubKey pubKeyCollateral; CKey keyCollateral; // If collateral is found switch to LOCAL mode if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) { eType = MASTERNODE_LOCAL; } LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); } void CActiveMasternode::ManageStateRemote() { LogPrint("masternode", "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n", GetStatus(), fPingerEnabled, GetTypeString(), pubKeyMasternode.GetID().ToString()); mnodeman.CheckMasternode(pubKeyMasternode); masternode_info_t infoMn = mnodeman.GetMasternodeInfo(pubKeyMasternode); if(infoMn.fInfoValid) { if(infoMn.nProtocolVersion != PROTOCOL_VERSION) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Invalid protocol version"; LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(service != infoMn.addr) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently."; LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState)); LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(nState != ACTIVE_MASTERNODE_STARTED) { LogPrintf("CActiveMasternode::ManageStateRemote -- STARTED!\n"); vin = infoMn.vin; service = infoMn.addr; fPingerEnabled = true; nState = ACTIVE_MASTERNODE_STARTED; } } else { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode not in masternode list"; LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); } } void CActiveMasternode::ManageStateLocal() { LogPrint("masternode", "CActiveMasternode::ManageStateLocal -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); if(nState == ACTIVE_MASTERNODE_STARTED) { return; } // Choose coins to use CPubKey pubKeyCollateral; CKey keyCollateral; if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) { int nInputAge = GetInputAge(vin); if(nInputAge < Params().GetConsensus().nMasternodeMinimumConfirmations){ nState = ACTIVE_MASTERNODE_INPUT_TOO_NEW; strNotCapableReason = strprintf(_("%s - %d confirmations"), GetStatus(), nInputAge); LogPrintf("CActiveMasternode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason); return; } { LOCK(pwalletMain->cs_wallet); pwalletMain->LockCoin(vin.prevout); } CMasternodeBroadcast mnb; std::string strError; if(!CMasternodeBroadcast::Create(vin, service, keyCollateral, pubKeyCollateral, keyMasternode, pubKeyMasternode, strError, mnb)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Error creating mastenode broadcast: " + strError; LogPrintf("CActiveMasternode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason); return; } fPingerEnabled = true; nState = ACTIVE_MASTERNODE_STARTED; //update to masternode list LogPrintf("CActiveMasternode::ManageStateLocal -- Update Masternode List\n"); mnodeman.UpdateMasternodeList(mnb); mnodeman.NotifyMasternodeUpdates(); //send to all peers LogPrintf("CActiveMasternode::ManageStateLocal -- Relay broadcast, vin=%s\n", vin.ToString()); mnb.Relay(); } }
Update activemasternode.cpp
Update activemasternode.cpp
C++
mit
HeliumGas/helium,HeliumGas/helium,HeliumGas/helium,HeliumGas/helium,HeliumGas/helium,HeliumGas/helium
6a902634408c0cd591a696a0b6069666d9f63112
src/app/dependencies.cpp
src/app/dependencies.cpp
/* This file is part of Zanshin Copyright 2014 Kevin Ottens <[email protected]> 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "dependencies.h" #include "akonadi/akonadiartifactqueries.h" #include "akonadi/akonadicontextqueries.h" #include "akonadi/akonadicontextrepository.h" #include "akonadi/akonadidatasourcequeries.h" #include "akonadi/akonadidatasourcerepository.h" #include "akonadi/akonadinotequeries.h" #include "akonadi/akonadinoterepository.h" #include "akonadi/akonadiprojectqueries.h" #include "akonadi/akonadiprojectrepository.h" #include "akonadi/akonaditagqueries.h" #include "akonadi/akonaditagrepository.h" #include "akonadi/akonaditaskqueries.h" #include "akonadi/akonaditaskrepository.h" #include "presentation/applicationmodel.h" #include "utils/dependencymanager.h" void App::initializeDependencies() { auto &deps = Utils::DependencyManager::globalInstance(); deps.add<Domain::ArtifactQueries, Akonadi::ArtifactQueries>(); deps.add<Domain::ContextQueries, Akonadi::ContextQueries>(); deps.add<Domain::ContextRepository, Akonadi::ContextRepository>(); deps.add<Domain::DataSourceQueries, Akonadi::DataSourceQueries>(); deps.add<Domain::DataSourceRepository, Akonadi::DataSourceRepository>(); deps.add<Domain::NoteQueries, Akonadi::NoteQueries>(); deps.add<Domain::NoteRepository, Akonadi::NoteRepository>(); deps.add<Domain::ProjectQueries, Akonadi::ProjectQueries>(); deps.add<Domain::ProjectRepository, Akonadi::ProjectRepository>(); deps.add<Domain::TagQueries, Akonadi::TagQueries>(); deps.add<Domain::TagRepository, Akonadi::TagRepository>(); deps.add<Domain::TaskQueries, Akonadi::TaskQueries>(); deps.add<Domain::TaskRepository, Akonadi::TaskRepository>(); deps.add<Presentation::ApplicationModel, Presentation::ApplicationModel(Domain::ArtifactQueries*, Domain::ProjectQueries*, Domain::ProjectRepository*, Domain::ContextQueries*, Domain::ContextRepository*, Domain::DataSourceQueries*, Domain::DataSourceRepository*, Domain::TaskQueries*, Domain::TaskRepository*, Domain::NoteRepository*, Domain::TagQueries*, Domain::TagRepository*)>(); }
/* This file is part of Zanshin Copyright 2014 Kevin Ottens <[email protected]> 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "dependencies.h" #include "akonadi/akonadiartifactqueries.h" #include "akonadi/akonadicontextqueries.h" #include "akonadi/akonadicontextrepository.h" #include "akonadi/akonadidatasourcequeries.h" #include "akonadi/akonadidatasourcerepository.h" #include "akonadi/akonadinotequeries.h" #include "akonadi/akonadinoterepository.h" #include "akonadi/akonadiprojectqueries.h" #include "akonadi/akonadiprojectrepository.h" #include "akonadi/akonaditagqueries.h" #include "akonadi/akonaditagrepository.h" #include "akonadi/akonaditaskqueries.h" #include "akonadi/akonaditaskrepository.h" #include "akonadi/akonadimessaging.h" #include "akonadi/akonadimonitorimpl.h" #include "akonadi/akonadiserializer.h" #include "akonadi/akonadistorage.h" #include "presentation/applicationmodel.h" #include "utils/dependencymanager.h" void App::initializeDependencies() { auto &deps = Utils::DependencyManager::globalInstance(); deps.add<Akonadi::MessagingInterface, Akonadi::Messaging>(); deps.add<Akonadi::MonitorInterface, Akonadi::MonitorImpl>(); deps.add<Akonadi::SerializerInterface, Akonadi::Serializer>(); deps.add<Akonadi::StorageInterface, Akonadi::Storage>(); deps.add<Domain::ArtifactQueries, Akonadi::ArtifactQueries(Akonadi::StorageInterface*, Akonadi::SerializerInterface*, Akonadi::MonitorInterface*)>(); deps.add<Domain::ContextQueries, Akonadi::ContextQueries(Akonadi::StorageInterface*, Akonadi::SerializerInterface*, Akonadi::MonitorInterface*)>(); deps.add<Domain::ContextRepository, Akonadi::ContextRepository(Akonadi::StorageInterface*, Akonadi::SerializerInterface*)>(); deps.add<Domain::DataSourceQueries, Akonadi::DataSourceQueries(Akonadi::StorageInterface*, Akonadi::SerializerInterface*, Akonadi::MonitorInterface*)>(); deps.add<Domain::DataSourceRepository, Akonadi::DataSourceRepository(Akonadi::StorageInterface*, Akonadi::SerializerInterface*)>(); deps.add<Domain::NoteQueries, Akonadi::NoteQueries(Akonadi::StorageInterface*, Akonadi::SerializerInterface*, Akonadi::MonitorInterface*)>(); deps.add<Domain::NoteRepository, Akonadi::NoteRepository(Akonadi::StorageInterface*, Akonadi::SerializerInterface*)>(); deps.add<Domain::ProjectQueries, Akonadi::ProjectQueries(Akonadi::StorageInterface*, Akonadi::SerializerInterface*, Akonadi::MonitorInterface*)>(); deps.add<Domain::ProjectRepository, Akonadi::ProjectRepository(Akonadi::StorageInterface*, Akonadi::SerializerInterface*)>(); deps.add<Domain::TagQueries, Akonadi::TagQueries(Akonadi::StorageInterface*, Akonadi::SerializerInterface*, Akonadi::MonitorInterface*)>(); deps.add<Domain::TagRepository, Akonadi::TagRepository(Akonadi::StorageInterface*, Akonadi::SerializerInterface*)>(); deps.add<Domain::TaskQueries, Akonadi::TaskQueries(Akonadi::StorageInterface*, Akonadi::SerializerInterface*, Akonadi::MonitorInterface*)>(); deps.add<Domain::TaskRepository, Akonadi::TaskRepository(Akonadi::StorageInterface*, Akonadi::SerializerInterface*, Akonadi::MessagingInterface*)>(); deps.add<Presentation::ApplicationModel, Presentation::ApplicationModel(Domain::ArtifactQueries*, Domain::ProjectQueries*, Domain::ProjectRepository*, Domain::ContextQueries*, Domain::ContextRepository*, Domain::DataSourceQueries*, Domain::DataSourceRepository*, Domain::TaskQueries*, Domain::TaskRepository*, Domain::NoteRepository*, Domain::TagQueries*, Domain::TagRepository*)>(); }
Create Storage, Serializer, Monitor and Messaging through dependencies
Create Storage, Serializer, Monitor and Messaging through dependencies
C++
lgpl-2.1
sandsmark/zanshin,sandsmark/zanshin,sandsmark/zanshin
3bad224f58f0f5f9fd274a960003615ac5b75772
test/array.cpp
test/array.cpp
#include "array.h" #include "test.h" namespace array { TEST(array_default_constructor) { dense_array<int, 1> a(make_dense_shape(10)); for (int x = 0; x < 10; x++) { ASSERT_EQ(a(x), 0); } dense_array<int, 2> b({7, 3}); for (int y = 0; y < 3; y++) { for (int x = 0; x < 7; x++) { ASSERT_EQ(b(x, y), 0); } } dense_array<int, 3> c({5, 9, 3}); for (int z = 0; z < 3; z++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 5; x++) { ASSERT_EQ(c(x, y, z), 0); } } } auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); array<int, shape<dim<>, dim<>>> sparse(sparse_shape); for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 0); } } sparse.clear(); ASSERT(sparse.empty()); sparse.clear(); } TEST(array_fill_constructor) { dense_array<int, 1> a(make_dense_shape(10), 3); for (int x = 0; x < 10; x++) { ASSERT_EQ(a(x), 3); } dense_array<int, 2> b({7, 3}, 5); for (int y = 0; y < 3; y++) { for (int x = 0; x < 7; x++) { ASSERT_EQ(b(x, y), 5); } } dense_array<int, 3> c({5, 9, 3}, 7); for (int z = 0; z < 3; z++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 5; x++) { ASSERT_EQ(c(x, y, z), 7); } } } auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); array<int, shape<dim<>, dim<>>> sparse(sparse_shape, 13); for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 13); } } } TEST(array_fill_assign) { dense_array<int, 1> a; a.assign(make_dense_shape(10), 3); for (int x = 0; x < 10; x++) { ASSERT_EQ(a(x), 3); } dense_array<int, 2> b; b.assign({7, 3}, 5); for (int y = 0; y < 3; y++) { for (int x = 0; x < 7; x++) { ASSERT_EQ(b(x, y), 5); } } dense_array<int, 3> c; c.assign({5, 9, 3}, 7); for (int z = 0; z < 3; z++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 5; x++) { ASSERT_EQ(c(x, y, z), 7); } } } array<int, shape<dim<>, dim<>>> sparse; auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10)); ASSERT(sparse_shape.flat_extent() > sparse_shape.size()); sparse.assign(sparse_shape, 13); for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 13); } } } TEST(sparse_array) { auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10)); ASSERT(sparse_shape.flat_extent() > sparse_shape.size()); array<int, shape<dim<>, dim<>>> sparse(sparse_shape); // Fill the storage with a constant. for (int i = 0; i < sparse_shape.flat_extent(); i++) { sparse.data()[i] = 7; } // Assign a different constant. sparse.assign(sparse_shape, 3); // Check that we assigned all of the elements of the array. for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 3); } } // Check that only the elements of the array were assigned. int sevens = 0; for (int i = 0; i < sparse_shape.flat_extent(); i++) { if (sparse.data()[i] == 7) { sevens++; } } ASSERT_EQ(sevens, sparse_shape.flat_extent() - sparse.size()); } struct lifetime_counter { static int default_constructs; static int copy_constructs; static int move_constructs; static int copy_assigns; static int move_assigns; static int destructs; static void reset() { default_constructs = 0; copy_constructs = 0; move_constructs = 0; copy_assigns = 0; move_assigns = 0; destructs = 0; } static int constructs() { return default_constructs + copy_constructs + move_constructs; } static int assigns() { return copy_assigns + move_assigns; } static int copies() { return copy_constructs + copy_assigns; } static int moves() { return move_constructs + move_assigns; } lifetime_counter() { default_constructs++; } lifetime_counter(const lifetime_counter&) { copy_constructs++; } lifetime_counter(lifetime_counter&&) { move_constructs++; } ~lifetime_counter() { destructs++; } lifetime_counter& operator=(const lifetime_counter&) { copy_assigns++; return *this; } lifetime_counter& operator=(lifetime_counter&&) { move_assigns++; return *this; } }; int lifetime_counter::default_constructs = 0; int lifetime_counter::copy_constructs = 0; int lifetime_counter::move_constructs = 0; int lifetime_counter::copy_assigns = 0; int lifetime_counter::move_assigns = 0; int lifetime_counter::destructs = 0; typedef shape<dim<>, dim<>> LifetimeShape; auto lifetime_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); TEST(array_default_init_lifetime) { lifetime_counter::reset(); { array<lifetime_counter, LifetimeShape> default_init(lifetime_shape); } ASSERT_EQ(lifetime_counter::default_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } TEST(array_copy_init_lifetime) { lifetime_counter::reset(); { array<lifetime_counter, LifetimeShape> copy_init(lifetime_shape, lifetime_counter()); } ASSERT_EQ(lifetime_counter::copy_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size() + 1); } TEST(array_copy_lifetime) { { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> copy(source); } ASSERT_EQ(lifetime_counter::copy_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size() * 2); } TEST(array_move_lifetime) { { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> move(std::move(source)); } // This should have moved the whole array. ASSERT_EQ(lifetime_counter::constructs(), 0); ASSERT_EQ(lifetime_counter::moves(), 0); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } TEST(array_move_alloc_lifetime) { { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> move(std::move(source), std::allocator<lifetime_counter>()); } // This should have moved the whole array. ASSERT_EQ(lifetime_counter::constructs(), 0); ASSERT_EQ(lifetime_counter::moves(), 0); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } // TODO: Test move with incompatible allocator. TEST(array_copy_assign_lifetime) { { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> assign; assign = source; } ASSERT_EQ(lifetime_counter::copy_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size() * 2); } TEST(array_move_assign_lifetime) { { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> assign; assign = std::move(source); } // This should have moved the whole array. ASSERT_EQ(lifetime_counter::constructs(), 0); ASSERT_EQ(lifetime_counter::moves(), 0); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } // TODO: Test move with incompatible allocator. TEST(array_clear_lifetime) { lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> default_init(lifetime_shape); default_init.clear(); ASSERT_EQ(lifetime_counter::default_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } } // namespace array
#include "array.h" #include "test.h" namespace array { TEST(array_default_constructor) { dense_array<int, 1> a(make_dense_shape(10)); for (int x = 0; x < 10; x++) { ASSERT_EQ(a(x), 0); } dense_array<int, 2> b({7, 3}); for (int y = 0; y < 3; y++) { for (int x = 0; x < 7; x++) { ASSERT_EQ(b(x, y), 0); } } dense_array<int, 3> c({5, 9, 3}); for (int z = 0; z < 3; z++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 5; x++) { ASSERT_EQ(c(x, y, z), 0); } } } auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); array<int, shape<dim<>, dim<>>> sparse(sparse_shape); for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 0); } } sparse.clear(); ASSERT(sparse.empty()); sparse.clear(); } TEST(array_fill_constructor) { dense_array<int, 1> a(make_dense_shape(10), 3); for (int x = 0; x < 10; x++) { ASSERT_EQ(a(x), 3); } dense_array<int, 2> b({7, 3}, 5); for (int y = 0; y < 3; y++) { for (int x = 0; x < 7; x++) { ASSERT_EQ(b(x, y), 5); } } dense_array<int, 3> c({5, 9, 3}, 7); for (int z = 0; z < 3; z++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 5; x++) { ASSERT_EQ(c(x, y, z), 7); } } } auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); array<int, shape<dim<>, dim<>>> sparse(sparse_shape, 13); for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 13); } } } TEST(array_fill_assign) { dense_array<int, 1> a; a.assign(make_dense_shape(10), 3); for (int x = 0; x < 10; x++) { ASSERT_EQ(a(x), 3); } dense_array<int, 2> b; b.assign({7, 3}, 5); for (int y = 0; y < 3; y++) { for (int x = 0; x < 7; x++) { ASSERT_EQ(b(x, y), 5); } } dense_array<int, 3> c; c.assign({5, 9, 3}, 7); for (int z = 0; z < 3; z++) { for (int y = 0; y < 9; y++) { for (int x = 0; x < 5; x++) { ASSERT_EQ(c(x, y, z), 7); } } } array<int, shape<dim<>, dim<>>> sparse; auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10)); ASSERT(sparse_shape.flat_extent() > sparse_shape.size()); sparse.assign(sparse_shape, 13); for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 13); } } } TEST(sparse_array) { auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10)); ASSERT(sparse_shape.flat_extent() > sparse_shape.size()); array<int, shape<dim<>, dim<>>> sparse(sparse_shape); // Fill the storage with a constant. for (int i = 0; i < sparse_shape.flat_extent(); i++) { sparse.data()[i] = 7; } // Assign a different constant. sparse.assign(sparse_shape, 3); // Check that we assigned all of the elements of the array. for (int y = 4; y < 14; y++) { for (int x = -2; x < 3; x++) { ASSERT_EQ(sparse(x, y), 3); } } // Check that only the elements of the array were assigned. int sevens = 0; for (int i = 0; i < sparse_shape.flat_extent(); i++) { if (sparse.data()[i] == 7) { sevens++; } } ASSERT_EQ(sevens, sparse_shape.flat_extent() - sparse.size()); } struct lifetime_counter { static int default_constructs; static int copy_constructs; static int move_constructs; static int copy_assigns; static int move_assigns; static int destructs; static void reset() { default_constructs = 0; copy_constructs = 0; move_constructs = 0; copy_assigns = 0; move_assigns = 0; destructs = 0; } static int constructs() { return default_constructs + copy_constructs + move_constructs; } static int assigns() { return copy_assigns + move_assigns; } static int copies() { return copy_constructs + copy_assigns; } static int moves() { return move_constructs + move_assigns; } lifetime_counter() { default_constructs++; } lifetime_counter(const lifetime_counter&) { copy_constructs++; } lifetime_counter(lifetime_counter&&) { move_constructs++; } ~lifetime_counter() { destructs++; } lifetime_counter& operator=(const lifetime_counter&) { copy_assigns++; return *this; } lifetime_counter& operator=(lifetime_counter&&) { move_assigns++; return *this; } }; int lifetime_counter::default_constructs = 0; int lifetime_counter::copy_constructs = 0; int lifetime_counter::move_constructs = 0; int lifetime_counter::copy_assigns = 0; int lifetime_counter::move_assigns = 0; int lifetime_counter::destructs = 0; typedef shape<dim<>, dim<>> LifetimeShape; auto lifetime_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20)); TEST(array_default_init_lifetime) { lifetime_counter::reset(); { array<lifetime_counter, LifetimeShape> default_init(lifetime_shape); } ASSERT_EQ(lifetime_counter::default_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } TEST(array_copy_init_lifetime) { lifetime_counter::reset(); { array<lifetime_counter, LifetimeShape> copy_init(lifetime_shape, lifetime_counter()); } ASSERT_EQ(lifetime_counter::copy_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size() + 1); } TEST(array_copy_lifetime) { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); { array<lifetime_counter, LifetimeShape> copy(source); } ASSERT_EQ(lifetime_counter::copy_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } TEST(array_move_lifetime) { { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> move(std::move(source)); } // This should have moved the whole array. ASSERT_EQ(lifetime_counter::constructs(), 0); ASSERT_EQ(lifetime_counter::moves(), 0); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } TEST(array_move_alloc_lifetime) { { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> move(std::move(source), std::allocator<lifetime_counter>()); } // This should have moved the whole array. ASSERT_EQ(lifetime_counter::constructs(), 0); ASSERT_EQ(lifetime_counter::moves(), 0); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } // TODO: Test move with incompatible allocator. TEST(array_copy_assign_lifetime) { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); { array<lifetime_counter, LifetimeShape> assign; assign = source; } ASSERT_EQ(lifetime_counter::copy_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } TEST(array_move_assign_lifetime) { { array<lifetime_counter, LifetimeShape> source(lifetime_shape); lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> assign; assign = std::move(source); } // This should have moved the whole array. ASSERT_EQ(lifetime_counter::constructs(), 0); ASSERT_EQ(lifetime_counter::moves(), 0); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } // TODO: Test move with incompatible allocator. TEST(array_clear_lifetime) { lifetime_counter::reset(); array<lifetime_counter, LifetimeShape> default_init(lifetime_shape); default_init.clear(); ASSERT_EQ(lifetime_counter::default_constructs, lifetime_shape.size()); ASSERT_EQ(lifetime_counter::destructs, lifetime_shape.size()); } } // namespace array
Improve tests of copy construction/assignment.
Improve tests of copy construction/assignment.
C++
apache-2.0
dsharlet/array
629e09deda50885ea1e16a429f7a879d02d76027
src/application/main.cpp
src/application/main.cpp
/* * Copyright 2016, Simula Research Laboratory * * 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 <fstream> #include <sstream> #include <string> #include <cmath> #include <iomanip> #include <stdlib.h> #include <getopt.h> #include <boost/filesystem.hpp> #include <popsift/popsift.h> #include <popsift/sift_conf.h> #include <popsift/common/device_prop.h> #include "pgmread.h" using namespace std; static void validate( const char* appName, popsift::Config& config ); static void usage( const char* argv ) { cout << argv << " [options] <filename>" << endl << endl << "* Options *" << endl << " --help / -h / -? Print usage" << endl << " --verbose / -v" << endl << " --log / -l Write debugging files" << endl << " --print-info / -p Print info about GPUs" << endl << endl << "* Parameters *" << endl << " --octaves=<int> Number of octaves" << endl << " --levels=<int> Number of levels per octave" << endl << " --sigma=<float> Initial sigma value" << endl << " --threshold=<float> Constrast threshold" << endl << " --edge-threshold=<float> or" << endl << " --edge-limit=<float> On-edge threshold" << endl << " --downsampling=<float> Downscale width and height of input by 2^N (default N=-1)" << endl << " --initial-blur=<float> Assume initial blur, subtract when blurring first time" << endl << endl << "* Modes *" << endl << " --popsift-mode (default) During the initial upscale, shift pixels by 1." << endl << " In extrema refinement, steps up to 0.6," << endl << " do not reject points when reaching max iterations," << endl << " first contrast threshold is .8 * peak thresh." << endl << " Shift feature coords octave 0 back to original pos." << endl << " --vlfeat-mode During the initial upscale, shift pixels by 1." << endl << " That creates a sharper upscaled image. " << endl << " In extrema refinement, steps up to 0.6, levels remain unchanged," << endl << " do not reject points when reaching max iterations," << endl << " first contrast threshold is .8 * peak thresh." << endl << " --opencv-mode During the initial upscale, shift pixels by 0.5." << endl << " In extrema refinement, steps up to 0.5," << endl << " reject points when reaching max iterations," << endl << " first contrast threshold is floor(.5 * peak thresh)." << endl << " Computed filter width are lower than VLFeat/PopSift" << endl << " --dp-off Switch all CUDA Dynamic Parallelism off" << endl << " --dp-ori-off Switch DP off for orientation computation" << endl << " --dp-desc-off Switch DP off for descriptor computation" << endl << endl << "* Informational *" << endl << " --print-gauss-tables A debug output printing Gauss filter size and tables" << endl << " --print-dev-info A debug output printing CUDA device information" << endl << " --print-time-info A debug output printing image processing time after load()" << endl << " --test-direct-scaling Direct each octave from upscaled orig instead of blurred level." << endl << " Does not work yet." << endl << " --group-gauss=<int> Gauss-filter N levels at once (N=2, 3 or 8)" << endl << " 3 is accurate for default sigmas of VLFeat and OpenCV mode" << endl << " Does not work yet." << endl << endl; exit(0); } static struct option longopts[] = { { "help", no_argument, NULL, 'h' }, { "verbose", no_argument, NULL, 'v' }, { "log", no_argument, NULL, 'l' }, { "print-info", no_argument, NULL, 'p' }, { "octaves", required_argument, NULL, 1000 }, { "levels", required_argument, NULL, 1001 }, { "downsampling", required_argument, NULL, 1002 }, { "threshold", required_argument, NULL, 1003 }, { "edge-threshold", required_argument, NULL, 1004 }, { "edge-limit", required_argument, NULL, 1004 }, { "sigma", required_argument, NULL, 1005 }, { "initial-blur", required_argument, NULL, 1006 }, { "vlfeat-mode", no_argument, NULL, 1100 }, { "opencv-mode", no_argument, NULL, 1101 }, { "popsift-mode", no_argument, NULL, 1102 }, { "test-direct-scaling", no_argument, NULL, 1103 }, { "group-gauss", required_argument, NULL, 1104 }, { "dp-off", no_argument, NULL, 1105 }, { "dp-ori-off", no_argument, NULL, 1106 }, { "dp-desc-off", no_argument, NULL, 1107 }, { "print-gauss-tables", no_argument, NULL, 1200 }, { "print-dev-info", no_argument, NULL, 1201 }, { "print-time-info", no_argument, NULL, 1202 }, { NULL, 0, NULL, 0 } }; static bool print_dev_info = false; static bool print_time_info = false; static void parseargs( int argc, char**argv, popsift::Config& config, string& inputFile ) { const char* appName = argv[0]; if( argc == 0 ) usage( "<program>" ); if( argc == 1 ) usage( argv[0] ); int opt; bool applySigma = false; float sigma; while( (opt = getopt_long(argc, argv, "?hvlp", longopts, NULL)) != -1 ) { switch (opt) { case '?' : case 'h' : usage( appName ); break; case 'v' : config.setVerbose(); break; case 'l' : config.setLogMode( popsift::Config::All ); break; case 1000 : config.setOctaves( strtol( optarg, NULL, 0 ) ); break; case 1001 : config.setLevels( strtol( optarg, NULL, 0 ) ); break; case 1002 : config.setDownsampling( strtof( optarg, NULL ) ); break; case 1003 : config.setThreshold( strtof( optarg, NULL ) ); break; case 1004 : config.setEdgeLimit( strtof( optarg, NULL ) ); break; case 1005 : applySigma = true; sigma = strtof( optarg, NULL ); break; case 1006 : config.setInitialBlur( strtof( optarg, NULL ) ); break; case 1100 : config.setMode( popsift::Config::VLFeat ); break; case 1101 : config.setMode( popsift::Config::OpenCV ); break; case 1102 : config.setMode( popsift::Config::PopSift ); break; case 1103 : config.setScalingMode( popsift::Config::ScaleDirect ); break; case 1104 : config.setGaussGroup( strtol( optarg, NULL, 0 ) ); break; case 1105 : config.setDPOrientation( false ); config.setDPDescriptors( false ); break; case 1106 : config.setDPOrientation( false ); break; case 1107 : config.setDPDescriptors( false ); break; case 1200 : config.setPrintGaussTables( ); break; case 1201 : print_dev_info = true; break; case 1202 : print_time_info = true; break; default : usage( appName ); } } if( applySigma ) config.setSigma( sigma ); validate( appName, config ); argc -= optind; argv += optind; if( argc == 0 ) usage( appName ); inputFile = argv[0]; } int main(int argc, char **argv) { cudaDeviceReset(); popsift::Config config; string inputFile = ""; const char* appName = argv[0]; parseargs( argc, argv, config, inputFile ); // Parse command line if( inputFile == "" ) { cerr << "No input filename given" << endl; usage( appName ); } int w; int h; unsigned char* image_data = readPGMfile( inputFile, w, h ); if( image_data == 0 ) { exit( -1 ); } // cerr << "Input image size: " // << w << "X" << h // << " filename: " << boost::filesystem::path(inputFile).filename() << endl; popsift::cuda::device_prop_t deviceInfo; deviceInfo.set( 0, print_dev_info ); if( print_dev_info ) deviceInfo.print( ); PopSift PopSift( config ); PopSift.init( 0, w, h, print_time_info ); popsift::Features* feature_list = PopSift.execute( 0, image_data, print_time_info ); PopSift.uninit( 0 ); std::ofstream of( "output-features.txt" ); of << *feature_list; delete feature_list; delete [] image_data; return 0; } static void validate( const char* appName, popsift::Config& config ) { switch( config.getGaussGroup() ) { case 1 : case 2 : case 3 : case 8 : break; default : cerr << "Only 2, 3 or 8 Gauss levels can be combined at this time" << endl; usage( appName ); exit( -1 ); } }
/* * Copyright 2016, Simula Research Laboratory * * 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 <fstream> #include <sstream> #include <string> #include <cmath> #include <iomanip> #include <stdlib.h> #include <getopt.h> #include <boost/filesystem.hpp> #include <popsift/popsift.h> #include <popsift/sift_conf.h> #include <popsift/common/device_prop.h> #include "pgmread.h" using namespace std; static void validate( const char* appName, popsift::Config& config ); static void usage( const char* argv ) { cout << argv << " [options] <filename>" << endl << endl << "* Options *" << endl << " --help / -h / -? Print usage" << endl << " --verbose / -v" << endl << " --log / -l Write debugging files" << endl << endl << "* Parameters *" << endl << " --octaves=<int> Number of octaves" << endl << " --levels=<int> Number of levels per octave" << endl << " --sigma=<float> Initial sigma value" << endl << " --threshold=<float> Constrast threshold" << endl << " --edge-threshold=<float> or" << endl << " --edge-limit=<float> On-edge threshold" << endl << " --downsampling=<float> Downscale width and height of input by 2^N (default N=-1)" << endl << " --initial-blur=<float> Assume initial blur, subtract when blurring first time" << endl << endl << "* Modes *" << endl << " --popsift-mode (default) During the initial upscale, shift pixels by 1." << endl << " In extrema refinement, steps up to 0.6," << endl << " do not reject points when reaching max iterations," << endl << " first contrast threshold is .8 * peak thresh." << endl << " Shift feature coords octave 0 back to original pos." << endl << " --vlfeat-mode During the initial upscale, shift pixels by 1." << endl << " That creates a sharper upscaled image. " << endl << " In extrema refinement, steps up to 0.6, levels remain unchanged," << endl << " do not reject points when reaching max iterations," << endl << " first contrast threshold is .8 * peak thresh." << endl << " --opencv-mode During the initial upscale, shift pixels by 0.5." << endl << " In extrema refinement, steps up to 0.5," << endl << " reject points when reaching max iterations," << endl << " first contrast threshold is floor(.5 * peak thresh)." << endl << " Computed filter width are lower than VLFeat/PopSift" << endl << " --dp-off Switch all CUDA Dynamic Parallelism off" << endl << " --dp-ori-off Switch DP off for orientation computation" << endl << " --dp-desc-off Switch DP off for descriptor computation" << endl << endl << "* Informational *" << endl << " --print-gauss-tables A debug output printing Gauss filter size and tables" << endl << " --print-dev-info A debug output printing CUDA device information" << endl << " --print-time-info A debug output printing image processing time after load()" << endl #if 0 << " --test-direct-scaling Direct each octave from upscaled orig instead of blurred level." << endl << " Does not work yet." << endl << " --group-gauss=<int> Gauss-filter N levels at once (N=2, 3 or 8)" << endl << " 3 is accurate for default sigmas of VLFeat and OpenCV mode" << endl << " Does not work yet." << endl #endif << endl; exit(0); } static struct option longopts[] = { { "help", no_argument, NULL, 'h' }, { "verbose", no_argument, NULL, 'v' }, { "log", no_argument, NULL, 'l' }, { "print-info", no_argument, NULL, 'p' }, { "octaves", required_argument, NULL, 1000 }, { "levels", required_argument, NULL, 1001 }, { "downsampling", required_argument, NULL, 1002 }, { "threshold", required_argument, NULL, 1003 }, { "edge-threshold", required_argument, NULL, 1004 }, { "edge-limit", required_argument, NULL, 1004 }, { "sigma", required_argument, NULL, 1005 }, { "initial-blur", required_argument, NULL, 1006 }, { "vlfeat-mode", no_argument, NULL, 1100 }, { "opencv-mode", no_argument, NULL, 1101 }, { "popsift-mode", no_argument, NULL, 1102 }, { "test-direct-scaling", no_argument, NULL, 1103 }, { "group-gauss", required_argument, NULL, 1104 }, { "dp-off", no_argument, NULL, 1105 }, { "dp-ori-off", no_argument, NULL, 1106 }, { "dp-desc-off", no_argument, NULL, 1107 }, { "print-gauss-tables", no_argument, NULL, 1200 }, { "print-dev-info", no_argument, NULL, 1201 }, { "print-time-info", no_argument, NULL, 1202 }, { NULL, 0, NULL, 0 } }; static bool print_dev_info = false; static bool print_time_info = false; static void parseargs( int argc, char**argv, popsift::Config& config, string& inputFile ) { const char* appName = argv[0]; if( argc == 0 ) usage( "<program>" ); if( argc == 1 ) usage( argv[0] ); int opt; bool applySigma = false; float sigma; while( (opt = getopt_long(argc, argv, "?hvlp", longopts, NULL)) != -1 ) { switch (opt) { case '?' : case 'h' : usage( appName ); break; case 'v' : config.setVerbose(); break; case 'l' : config.setLogMode( popsift::Config::All ); break; case 1000 : config.setOctaves( strtol( optarg, NULL, 0 ) ); break; case 1001 : config.setLevels( strtol( optarg, NULL, 0 ) ); break; case 1002 : config.setDownsampling( strtof( optarg, NULL ) ); break; case 1003 : config.setThreshold( strtof( optarg, NULL ) ); break; case 1004 : config.setEdgeLimit( strtof( optarg, NULL ) ); break; case 1005 : applySigma = true; sigma = strtof( optarg, NULL ); break; case 1006 : config.setInitialBlur( strtof( optarg, NULL ) ); break; case 1100 : config.setMode( popsift::Config::VLFeat ); break; case 1101 : config.setMode( popsift::Config::OpenCV ); break; case 1102 : config.setMode( popsift::Config::PopSift ); break; case 1103 : config.setScalingMode( popsift::Config::ScaleDirect ); break; case 1104 : config.setGaussGroup( strtol( optarg, NULL, 0 ) ); break; case 1105 : config.setDPOrientation( false ); config.setDPDescriptors( false ); break; case 1106 : config.setDPOrientation( false ); break; case 1107 : config.setDPDescriptors( false ); break; case 1200 : config.setPrintGaussTables( ); break; case 1201 : print_dev_info = true; break; case 1202 : print_time_info = true; break; default : usage( appName ); } } if( applySigma ) config.setSigma( sigma ); validate( appName, config ); argc -= optind; argv += optind; if( argc == 0 ) usage( appName ); inputFile = argv[0]; } int main(int argc, char **argv) { cudaDeviceReset(); popsift::Config config; string inputFile = ""; const char* appName = argv[0]; parseargs( argc, argv, config, inputFile ); // Parse command line if( inputFile == "" ) { cerr << "No input filename given" << endl; usage( appName ); } int w; int h; unsigned char* image_data = readPGMfile( inputFile, w, h ); if( image_data == 0 ) { exit( -1 ); } // cerr << "Input image size: " // << w << "X" << h // << " filename: " << boost::filesystem::path(inputFile).filename() << endl; popsift::cuda::device_prop_t deviceInfo; deviceInfo.set( 0, print_dev_info ); if( print_dev_info ) deviceInfo.print( ); PopSift PopSift( config ); PopSift.init( 0, w, h, print_time_info ); popsift::Features* feature_list = PopSift.execute( 0, image_data, print_time_info ); PopSift.uninit( 0 ); std::ofstream of( "output-features.txt" ); of << *feature_list; delete feature_list; delete [] image_data; return 0; } static void validate( const char* appName, popsift::Config& config ) { switch( config.getGaussGroup() ) { case 1 : case 2 : case 3 : case 8 : break; default : cerr << "Only 2, 3 or 8 Gauss levels can be combined at this time" << endl; usage( appName ); exit( -1 ); } }
remove test/debug command line options
remove test/debug command line options
C++
mpl-2.0
alicevision/popsift,poparteu/popsift,alicevision/popsift,poparteu/popsift,alicevision/popsift
cfcd5bb616484b6c1d34e6ea8f4cd3e2d7774824
src/arch/mips/utility.hh
src/arch/mips/utility.hh
/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of 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 * Korey Sewell */ #ifndef __ARCH_MIPS_UTILITY_HH__ #define __ARCH_MIPS_UTILITY_HH__ #include "arch/mips/types.hh" #include "arch/mips/isa_traits.hh" #include "base/misc.hh" #include "config/full_system.hh" //XXX This is needed for size_t. We should use something other than size_t //#include "kern/linux/linux.hh" #include "sim/host.hh" #include "cpu/thread_context.hh" class ThreadContext; namespace MipsISA { uint64_t getArgument(ThreadContext *tc, bool fp) { panic("getArgument() not implemented for MIPS\n"); } //Floating Point Utility Functions uint64_t fpConvert(ConvertType cvt_type, double fp_val); double roundFP(double val, int digits); double truncFP(double val); bool getCondCode(uint32_t fcsr, int cc); uint32_t genCCVector(uint32_t fcsr, int num, uint32_t cc_val); uint32_t genInvalidVector(uint32_t fcsr); bool isNan(void *val_ptr, int size); bool isQnan(void *val_ptr, int size); bool isSnan(void *val_ptr, int size); /** * Function to insure ISA semantics about 0 registers. * @param tc The thread context. */ template <class TC> void zeroRegisters(TC *tc); void startupCPU(ThreadContext *tc, int cpuId); // Instruction address compression hooks static inline Addr realPCToFetchPC(const Addr &addr) { return addr; } static inline Addr fetchPCToRealPC(const Addr &addr) { return addr; } // the size of "fetched" instructions (not necessarily the size // of real instructions for PISA) static inline size_t fetchInstSize() { return sizeof(MachInst); } static inline MachInst makeRegisterCopy(int dest, int src) { panic("makeRegisterCopy not implemented"); return 0; } static inline ExtMachInst makeExtMI(MachInst inst, ThreadContext * xc) { #if FULL_SYSTEM ExtMachInst ext_inst = inst; if (xc->readPC() && 0x1) return ext_inst|=(static_cast<ExtMachInst>(xc->readPC() & 0x1) << 32); else return ext_inst; #else return ExtMachInst(inst); #endif } }; #endif
/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of 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 * Korey Sewell */ #ifndef __ARCH_MIPS_UTILITY_HH__ #define __ARCH_MIPS_UTILITY_HH__ #include "arch/mips/types.hh" #include "arch/mips/isa_traits.hh" #include "base/misc.hh" #include "config/full_system.hh" //XXX This is needed for size_t. We should use something other than size_t //#include "kern/linux/linux.hh" #include "sim/host.hh" #include "cpu/thread_context.hh" class ThreadContext; namespace MipsISA { inline uint64_t getArgument(ThreadContext *tc, bool fp) { panic("getArgument() not implemented for MIPS\n"); } //Floating Point Utility Functions uint64_t fpConvert(ConvertType cvt_type, double fp_val); double roundFP(double val, int digits); double truncFP(double val); bool getCondCode(uint32_t fcsr, int cc); uint32_t genCCVector(uint32_t fcsr, int num, uint32_t cc_val); uint32_t genInvalidVector(uint32_t fcsr); bool isNan(void *val_ptr, int size); bool isQnan(void *val_ptr, int size); bool isSnan(void *val_ptr, int size); /** * Function to insure ISA semantics about 0 registers. * @param tc The thread context. */ template <class TC> void zeroRegisters(TC *tc); void startupCPU(ThreadContext *tc, int cpuId); // Instruction address compression hooks static inline Addr realPCToFetchPC(const Addr &addr) { return addr; } static inline Addr fetchPCToRealPC(const Addr &addr) { return addr; } // the size of "fetched" instructions (not necessarily the size // of real instructions for PISA) static inline size_t fetchInstSize() { return sizeof(MachInst); } static inline MachInst makeRegisterCopy(int dest, int src) { panic("makeRegisterCopy not implemented"); return 0; } static inline ExtMachInst makeExtMI(MachInst inst, ThreadContext * xc) { #if FULL_SYSTEM ExtMachInst ext_inst = inst; if (xc->readPC() && 0x1) return ext_inst|=(static_cast<ExtMachInst>(xc->readPC() & 0x1) << 32); else return ext_inst; #else return ExtMachInst(inst); #endif } }; #endif
make getArgument inline so mips will link properly
mips: make getArgument inline so mips will link properly
C++
bsd-3-clause
vovojh/gem5,vovojh/gem5,hoangt/tpzsimul.gem5,vovojh/gem5,hoangt/tpzsimul.gem5,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,vovojh/gem5,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,hoangt/tpzsimul.gem5,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-
503ebb7102045c679fd56a6068eeefffdfa2b6b4
Dep/common/lexical_cast.hpp
Dep/common/lexical_cast.hpp
//C++ 11ʵֵlexical_castΪ˰boost //: https://github.com/qicosmos/cosmos #ifndef CPP_11_LEXICAL_CAST_HPP #define CPP_11_LEXICAL_CAST_HPP #include <type_traits> #include <string> #include <cstdlib> #include <algorithm> #include <stdexcept> #include <cctype> #include <cstring> using namespace std; namespace detail { static const char* strue = "true"; static const char* sfalse = "false"; template <typename To, typename From> struct Converter { }; //to numeric template <typename From> struct Converter<int, From> { static int convert(const string& from) { return std::atoi(from.c_str()); } static int convert(const char* from) { return std::atoi(from); } }; template <typename From> struct Converter<long, From> { static long convert(const string& from) { return std::atol(from.c_str()); } static long convert(const char* from) { return std::atol(from); } }; template <typename From> struct Converter<long long, From> { static long long convert(const string& from) { return std::atoll(from.c_str()); } static long long convert(const char* from) { return std::atoll(from); } }; template <typename From> struct Converter<double, From> { static double convert(const string& from) { return std::atof(from.c_str()); } static double convert(const char* from) { return std::atof(from); } }; template <typename From> struct Converter<float, From> { static float convert(const string& from) { return (float)std::atof(from.c_str()); } static float convert(const char* from) { return (float)std::atof(from); } }; //to bool template <typename From> struct Converter<bool, From> { static typename std::enable_if<std::is_integral<From>::value, bool>::type convert(From from) { return !!from; } }; static bool checkbool(const char* from, const size_t len, const char* s) { for(size_t i = 0; i < len; i++) { if(from[i] != s[i]) { return false; } } return true; } static bool convert(const char* from) { const unsigned int len = strlen(from); if(len != 4 && len != 5) throw std::invalid_argument("argument is invalid"); bool r = true; if(len == 4) { //"true" r = checkbool(from, len, strue); if(r) return true; } else if(len == 5) { //"false" r = checkbool(from, len, sfalse); if(r) return false; } else { // תΪbool int value = Converter<int, const char*>::convert(from); return (value > 0); } throw std::invalid_argument("argument is invalid"); } template <> struct Converter<bool, string> { static bool convert(const string& from) { return detail::convert(from.c_str()); } }; template <> struct Converter<bool, const char*> { static bool convert(const char* from) { return detail::convert(from); } }; template <> struct Converter<bool, char*> { static bool convert(char* from) { return detail::convert(from); } }; template <unsigned N> struct Converter<bool, const char[N]> { static bool convert(const char(&from)[N]) { return detail::convert(from); } }; template <unsigned N> struct Converter<bool, char[N]> { static bool convert(const char(&from)[N]) { return detail::convert(from); } }; //to string template <typename From> struct Converter<string, From> { static string convert(const From& from) { return std::to_string(from); } }; } template <typename To, typename From> typename std::enable_if < !std::is_same<To, From>::value, To >::type lexical_cast(const From& from) { return detail::Converter<To, From>::convert(from); } template <typename To, typename From> typename std::enable_if<std::is_same<To, From>::value, To>::type lexical_cast(const From& from) { return from; } template<typename ValueTYPE> bool ValueFromString(const std::string& strValue, ValueTYPE& nValue) { try { nValue = lexical_cast<ValueTYPE>(strValue); return true; } catch(...) { return false; } return false; } template<typename ValueTYPE> bool ValueToString(const ValueTYPE& nValue, std::string& strData) { try { strData = lexical_cast<std::string>(nValue); return true; } catch(...) { return false; } return false; } #endif //!CPP_11_LEXICAL_CAST_HPP
//C++ 11ʵֵlexical_castΪ˰boost //: https://github.com/qicosmos/cosmos #ifndef CPP_11_LEXICAL_CAST_HPP #define CPP_11_LEXICAL_CAST_HPP #include <type_traits> #include <string> #include <cstdlib> #include <algorithm> #include <stdexcept> #include <cctype> #include <cstring> using namespace std; namespace detail { static const char* strue = "true"; static const char* sfalse = "false"; template <typename To, typename From> struct Converter { }; //to numeric template <typename From> struct Converter<int, From> { static int convert(const string& from) { return std::atoi(from.c_str()); } static int convert(const char* from) { return std::atoi(from); } }; template <typename From> struct Converter<long, From> { static long convert(const string& from) { return std::atol(from.c_str()); } static long convert(const char* from) { return std::atol(from); } }; template <typename From> struct Converter<long long, From> { static long long convert(const string& from) { return std::atoll(from.c_str()); } static long long convert(const char* from) { return std::atoll(from); } }; template <typename From> struct Converter<double, From> { static double convert(const string& from) { return std::atof(from.c_str()); } static double convert(const char* from) { return std::atof(from); } }; template <typename From> struct Converter<float, From> { static float convert(const string& from) { return (float)std::atof(from.c_str()); } static float convert(const char* from) { return (float)std::atof(from); } }; //to bool template <typename From> struct Converter<bool, From> { static typename std::enable_if<std::is_integral<From>::value, bool>::type convert(From from) { return !!from; } }; static bool checkbool(const char* from, const size_t len, const char* s) { for(size_t i = 0; i < len; i++) { if(from[i] != s[i]) { return false; } } return true; } static bool convert(const char* from) { const unsigned int len = strlen(from); //if(len != 4 && len != 5) // throw std::invalid_argument("argument is invalid"); bool r = true; if(len == 4) { //"true" r = checkbool(from, len, strue); if(r) return true; } else if(len == 5) { //"false" r = checkbool(from, len, sfalse); if(r) return false; } else { // תΪbool int value = Converter<int, const char*>::convert(from); return (value > 0); } throw std::invalid_argument("argument is invalid"); } template <> struct Converter<bool, string> { static bool convert(const string& from) { return detail::convert(from.c_str()); } }; template <> struct Converter<bool, const char*> { static bool convert(const char* from) { return detail::convert(from); } }; template <> struct Converter<bool, char*> { static bool convert(char* from) { return detail::convert(from); } }; template <unsigned N> struct Converter<bool, const char[N]> { static bool convert(const char(&from)[N]) { return detail::convert(from); } }; template <unsigned N> struct Converter<bool, char[N]> { static bool convert(const char(&from)[N]) { return detail::convert(from); } }; //to string template <typename From> struct Converter<string, From> { static string convert(const From& from) { return std::to_string(from); } }; } template <typename To, typename From> typename std::enable_if < !std::is_same<To, From>::value, To >::type lexical_cast(const From& from) { return detail::Converter<To, From>::convert(from); } template <typename To, typename From> typename std::enable_if<std::is_same<To, From>::value, To>::type lexical_cast(const From& from) { return from; } template<typename ValueTYPE> bool ValueFromString(const std::string& strValue, ValueTYPE& nValue) { try { nValue = lexical_cast<ValueTYPE>(strValue); return true; } catch(...) { return false; } return false; } template<typename ValueTYPE> bool ValueToString(const ValueTYPE& nValue, std::string& strData) { try { strData = lexical_cast<std::string>(nValue); return true; } catch(...) { return false; } return false; } #endif //!CPP_11_LEXICAL_CAST_HPP
fix lexical_cast bug when convert number string to boolean
fix lexical_cast bug when convert number string to boolean Former-commit-id: 40008d34ece1d2adc224ce6afb6d922b389cc1d6 [formerly 806da0701024c9ed223092b1262454d617132407] [formerly 603c83caa66d7248f1dc44246747a8500e17c3ee [formerly 4950b5fc80d7abb590eb8f01e06feee042a8275c]] Former-commit-id: a25025f922cb7337b44aa33d368f2551337192f7 [formerly bcd5130e498bcc25e682e834393e55ce0d6ad45b] Former-commit-id: 9178c2c5aae767e904af5e0736233f38aef603e3 Former-commit-id: 0494f5a3f463e1e2d962eb2bd7dd597c58ed369c
C++
apache-2.0
ArkGame/ArkGameFrame,ArkGame/ArkGameFrame,ArkGame/ArkGameFrame,ArkGame/ArkGameFrame,ArkGame/ArkGameFrame,ArkGame/ArkGameFrame,ArkGame/ArkGameFrame
6fcca1cc874c2b374b05399be92c5c1ea2086cc0
lib/Analysis/PHITransAddr.cpp
lib/Analysis/PHITransAddr.cpp
//===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PHITransAddr class. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/PHITransAddr.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/InstructionSimplify.h" using namespace llvm; /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true /// if we have some hope of doing it. This should be used as a filter to /// avoid calling PHITranslateValue in hopeless situations. bool PHITransAddr::IsPotentiallyPHITranslatable() const { // If the input value is not an instruction, or if it is not defined in CurBB, // then we don't need to phi translate it. Instruction *Inst = dyn_cast<Instruction>(Addr); if (isa<PHINode>(Inst) || isa<BitCastInst>(Inst) || isa<GetElementPtrInst>(Inst) || (Inst->getOpcode() == Instruction::And && isa<ConstantInt>(Inst->getOperand(1)))) return true; // cerr << "MEMDEP: Could not PHI translate: " << *Pointer; // if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst)) // cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0); return false; } Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB, BasicBlock *PredBB) { // If this is a non-instruction value, it can't require PHI translation. Instruction *Inst = dyn_cast<Instruction>(V); if (Inst == 0) return V; // Determine whether 'Inst' is an input to our PHI translatable expression. bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst); // If 'Inst' is not defined in this block, it is either an input, or an // intermediate result. if (Inst->getParent() != CurBB) { // If it is an input, then it remains an input. if (isInput) return Inst; // Otherwise, it must be an intermediate result. See if its operands need // to be phi translated, and if so, reconstruct it. if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) { Value *PHIIn = PHITranslateSubExpr(BC->getOperand(0), CurBB, PredBB); if (PHIIn == 0) return 0; if (PHIIn == BC->getOperand(0)) return BC; // Find an available version of this cast. // Constants are trivial to find. if (Constant *C = dyn_cast<Constant>(PHIIn)) return ConstantExpr::getBitCast(C, BC->getType()); // Otherwise we have to see if a bitcasted version of the incoming pointer // is available. If so, we can use it, otherwise we have to fail. for (Value::use_iterator UI = PHIIn->use_begin(), E = PHIIn->use_end(); UI != E; ++UI) { if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) if (BCI->getType() == BC->getType()) return BCI; } return 0; } // Handle getelementptr with at least one PHI translatable operand. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) { SmallVector<Value*, 8> GEPOps; BasicBlock *CurBB = GEP->getParent(); bool AnyChanged = false; for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) { Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB); if (GEPOp == 0) return 0; AnyChanged = GEPOp != GEP->getOperand(i); GEPOps.push_back(GEPOp); } if (!AnyChanged) return GEP; // Simplify the GEP to handle 'gep x, 0' -> x etc. if (Value *V = SimplifyGEPInst(&GEPOps[0], GEPOps.size(), TD)) return V; // Scan to see if we have this GEP available. Value *APHIOp = GEPOps[0]; for (Value::use_iterator UI = APHIOp->use_begin(), E = APHIOp->use_end(); UI != E; ++UI) { if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) if (GEPI->getType() == GEP->getType() && GEPI->getNumOperands() == GEPOps.size() && GEPI->getParent()->getParent() == CurBB->getParent()) { bool Mismatch = false; for (unsigned i = 0, e = GEPOps.size(); i != e; ++i) if (GEPI->getOperand(i) != GEPOps[i]) { Mismatch = true; break; } if (!Mismatch) return GEPI; } } return 0; } // Handle add with a constant RHS. if (Inst->getOpcode() == Instruction::Add && isa<ConstantInt>(Inst->getOperand(1))) { // PHI translate the LHS. Constant *RHS = cast<ConstantInt>(Inst->getOperand(1)); bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap(); bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap(); Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB); if (LHS == 0) return 0; // If the PHI translated LHS is an add of a constant, fold the immediates. if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS)) if (BOp->getOpcode() == Instruction::Add) if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) { LHS = BOp->getOperand(0); RHS = ConstantExpr::getAdd(RHS, CI); isNSW = isNUW = false; } // See if the add simplifies away. if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD)) return Res; // Otherwise, see if we have this add available somewhere. for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end(); UI != E; ++UI) { if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*UI)) if (BO->getOperand(0) == LHS && BO->getOperand(1) == RHS && BO->getParent()->getParent() == CurBB->getParent()) return BO; } return 0; } // Otherwise, we failed. return 0; } // Otherwise, it is defined in this block. It must be an input and must be // phi translated. assert(isInput && "Instruction defined in block must be an input"); abort(); // unimplemented so far. } /// PHITranslateValue - PHI translate the current address up the CFG from /// CurBB to Pred, updating our state the reflect any needed changes. This /// returns true on failure. bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB) { Addr = PHITranslateSubExpr(Addr, CurBB, PredBB); return Addr == 0; } /// GetAvailablePHITranslatedSubExpr - Return the value computed by /// PHITranslateSubExpr if it dominates PredBB, otherwise return null. Value *PHITransAddr:: GetAvailablePHITranslatedSubExpr(Value *V, BasicBlock *CurBB,BasicBlock *PredBB, const DominatorTree &DT) { // See if PHI translation succeeds. V = PHITranslateSubExpr(V, CurBB, PredBB); // Make sure the value is live in the predecessor. if (Instruction *Inst = dyn_cast_or_null<Instruction>(V)) if (!DT.dominates(Inst->getParent(), PredBB)) return 0; return V; } /// PHITranslateWithInsertion - PHI translate this value into the specified /// predecessor block, inserting a computation of the value if it is /// unavailable. /// /// All newly created instructions are added to the NewInsts list. This /// returns null on failure. /// Value *PHITransAddr:: PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree &DT, SmallVectorImpl<Instruction*> &NewInsts) { unsigned NISize = NewInsts.size(); // Attempt to PHI translate with insertion. Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts); // If successful, return the new value. if (Addr) return Addr; // If not, destroy any intermediate instructions inserted. while (NewInsts.size() != NISize) NewInsts.pop_back_val()->eraseFromParent(); return 0; } /// InsertPHITranslatedPointer - Insert a computation of the PHI translated /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB /// block. All newly created instructions are added to the NewInsts list. /// This returns null on failure. /// Value *PHITransAddr:: InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree &DT, SmallVectorImpl<Instruction*> &NewInsts) { // See if we have a version of this value already available and dominating // PredBB. If so, there is no need to insert a new instance of it. if (Value *Res = GetAvailablePHITranslatedSubExpr(InVal, CurBB, PredBB, DT)) return Res; // If we don't have an available version of this value, it must be an // instruction. Instruction *Inst = cast<Instruction>(InVal); // Handle bitcast of PHI translatable value. if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) { Value *OpVal = InsertPHITranslatedSubExpr(BC->getOperand(0), CurBB, PredBB, DT, NewInsts); if (OpVal == 0) return 0; // Otherwise insert a bitcast at the end of PredBB. BitCastInst *New = new BitCastInst(OpVal, InVal->getType(), InVal->getName()+".phi.trans.insert", PredBB->getTerminator()); NewInsts.push_back(New); return New; } // Handle getelementptr with at least one PHI operand. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) { SmallVector<Value*, 8> GEPOps; BasicBlock *CurBB = GEP->getParent(); for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) { Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i), CurBB, PredBB, DT, NewInsts); if (OpVal == 0) return 0; GEPOps.push_back(OpVal); } GetElementPtrInst *Result = GetElementPtrInst::Create(GEPOps[0], GEPOps.begin()+1, GEPOps.end(), InVal->getName()+".phi.trans.insert", PredBB->getTerminator()); Result->setIsInBounds(GEP->isInBounds()); NewInsts.push_back(Result); return Result; } #if 0 // FIXME: This code works, but it is unclear that we actually want to insert // a big chain of computation in order to make a value available in a block. // This needs to be evaluated carefully to consider its cost trade offs. // Handle add with a constant RHS. if (Inst->getOpcode() == Instruction::Add && isa<ConstantInt>(Inst->getOperand(1))) { // PHI translate the LHS. Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0), CurBB, PredBB, DT, NewInsts); if (OpVal == 0) return 0; BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1), InVal->getName()+".phi.trans.insert", PredBB->getTerminator()); Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap()); Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap()); NewInsts.push_back(Res); return Res; } #endif return 0; }
//===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PHITransAddr class. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/PHITransAddr.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/InstructionSimplify.h" using namespace llvm; static bool CanPHITrans(Instruction *Inst) { if (isa<PHINode>(Inst) || isa<BitCastInst>(Inst) || isa<GetElementPtrInst>(Inst)) return true; if (Inst->getOpcode() == Instruction::And && isa<ConstantInt>(Inst->getOperand(1))) return true; // cerr << "MEMDEP: Could not PHI translate: " << *Pointer; // if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst)) // cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0); return false; } /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true /// if we have some hope of doing it. This should be used as a filter to /// avoid calling PHITranslateValue in hopeless situations. bool PHITransAddr::IsPotentiallyPHITranslatable() const { // If the input value is not an instruction, or if it is not defined in CurBB, // then we don't need to phi translate it. Instruction *Inst = dyn_cast<Instruction>(Addr); return Inst == 0 || CanPHITrans(Inst); } Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB, BasicBlock *PredBB) { // If this is a non-instruction value, it can't require PHI translation. Instruction *Inst = dyn_cast<Instruction>(V); if (Inst == 0) return V; // If 'Inst' is defined in this block, it must be an input that needs to be // phi translated or an intermediate expression that needs to be incorporated // into the expression. if (Inst->getParent() == CurBB) { assert(std::count(InstInputs.begin(), InstInputs.end(), Inst) && "Not an input?"); // If this is a PHI, go ahead and translate it. if (PHINode *PN = dyn_cast<PHINode>(Inst)) return PN->getIncomingValueForBlock(PredBB); // If this is a non-phi value, and it is analyzable, we can incorporate it // into the expression by making all instruction operands be inputs. if (!CanPHITrans(Inst)) return 0; // Okay, we can incorporate it, this instruction is no longer an input. InstInputs.erase(std::find(InstInputs.begin(), InstInputs.end(), Inst)); // All instruction operands are now inputs (and of course, they may also be // defined in this block, so they may need to be phi translated themselves. for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i))) InstInputs.push_back(Op); } else { // Determine whether 'Inst' is an input to our PHI translatable expression. bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst); // If it is an input defined in a different block, then it remains an input. if (isInput) return Inst; } // Ok, it must be an intermediate result (either because it started that way // or because we just incorporated it into the expression). See if its // operands need to be phi translated, and if so, reconstruct it. if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) { Value *PHIIn = PHITranslateSubExpr(BC->getOperand(0), CurBB, PredBB); if (PHIIn == 0) return 0; if (PHIIn == BC->getOperand(0)) return BC; // Find an available version of this cast. // Constants are trivial to find. if (Constant *C = dyn_cast<Constant>(PHIIn)) return ConstantExpr::getBitCast(C, BC->getType()); // Otherwise we have to see if a bitcasted version of the incoming pointer // is available. If so, we can use it, otherwise we have to fail. for (Value::use_iterator UI = PHIIn->use_begin(), E = PHIIn->use_end(); UI != E; ++UI) { if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) if (BCI->getType() == BC->getType()) return BCI; } return 0; } // Handle getelementptr with at least one PHI translatable operand. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) { SmallVector<Value*, 8> GEPOps; BasicBlock *CurBB = GEP->getParent(); bool AnyChanged = false; for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) { Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB); if (GEPOp == 0) return 0; AnyChanged = GEPOp != GEP->getOperand(i); GEPOps.push_back(GEPOp); } if (!AnyChanged) return GEP; // Simplify the GEP to handle 'gep x, 0' -> x etc. if (Value *V = SimplifyGEPInst(&GEPOps[0], GEPOps.size(), TD)) return V; // Scan to see if we have this GEP available. Value *APHIOp = GEPOps[0]; for (Value::use_iterator UI = APHIOp->use_begin(), E = APHIOp->use_end(); UI != E; ++UI) { if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) if (GEPI->getType() == GEP->getType() && GEPI->getNumOperands() == GEPOps.size() && GEPI->getParent()->getParent() == CurBB->getParent()) { bool Mismatch = false; for (unsigned i = 0, e = GEPOps.size(); i != e; ++i) if (GEPI->getOperand(i) != GEPOps[i]) { Mismatch = true; break; } if (!Mismatch) return GEPI; } } return 0; } // Handle add with a constant RHS. if (Inst->getOpcode() == Instruction::Add && isa<ConstantInt>(Inst->getOperand(1))) { // PHI translate the LHS. Constant *RHS = cast<ConstantInt>(Inst->getOperand(1)); bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap(); bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap(); Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB); if (LHS == 0) return 0; // If the PHI translated LHS is an add of a constant, fold the immediates. if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS)) if (BOp->getOpcode() == Instruction::Add) if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) { LHS = BOp->getOperand(0); RHS = ConstantExpr::getAdd(RHS, CI); isNSW = isNUW = false; } // See if the add simplifies away. if (Value *Res = SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD)) return Res; // Otherwise, see if we have this add available somewhere. for (Value::use_iterator UI = LHS->use_begin(), E = LHS->use_end(); UI != E; ++UI) { if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*UI)) if (BO->getOperand(0) == LHS && BO->getOperand(1) == RHS && BO->getParent()->getParent() == CurBB->getParent()) return BO; } return 0; } // Otherwise, we failed. return 0; } /// PHITranslateValue - PHI translate the current address up the CFG from /// CurBB to Pred, updating our state the reflect any needed changes. This /// returns true on failure. bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB) { Addr = PHITranslateSubExpr(Addr, CurBB, PredBB); return Addr == 0; } /// GetAvailablePHITranslatedSubExpr - Return the value computed by /// PHITranslateSubExpr if it dominates PredBB, otherwise return null. Value *PHITransAddr:: GetAvailablePHITranslatedSubExpr(Value *V, BasicBlock *CurBB,BasicBlock *PredBB, const DominatorTree &DT) { // See if PHI translation succeeds. V = PHITranslateSubExpr(V, CurBB, PredBB); // Make sure the value is live in the predecessor. if (Instruction *Inst = dyn_cast_or_null<Instruction>(V)) if (!DT.dominates(Inst->getParent(), PredBB)) return 0; return V; } /// PHITranslateWithInsertion - PHI translate this value into the specified /// predecessor block, inserting a computation of the value if it is /// unavailable. /// /// All newly created instructions are added to the NewInsts list. This /// returns null on failure. /// Value *PHITransAddr:: PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree &DT, SmallVectorImpl<Instruction*> &NewInsts) { unsigned NISize = NewInsts.size(); // Attempt to PHI translate with insertion. Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts); // If successful, return the new value. if (Addr) return Addr; // If not, destroy any intermediate instructions inserted. while (NewInsts.size() != NISize) NewInsts.pop_back_val()->eraseFromParent(); return 0; } /// InsertPHITranslatedPointer - Insert a computation of the PHI translated /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB /// block. All newly created instructions are added to the NewInsts list. /// This returns null on failure. /// Value *PHITransAddr:: InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree &DT, SmallVectorImpl<Instruction*> &NewInsts) { // See if we have a version of this value already available and dominating // PredBB. If so, there is no need to insert a new instance of it. if (Value *Res = GetAvailablePHITranslatedSubExpr(InVal, CurBB, PredBB, DT)) return Res; // If we don't have an available version of this value, it must be an // instruction. Instruction *Inst = cast<Instruction>(InVal); // Handle bitcast of PHI translatable value. if (BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) { Value *OpVal = InsertPHITranslatedSubExpr(BC->getOperand(0), CurBB, PredBB, DT, NewInsts); if (OpVal == 0) return 0; // Otherwise insert a bitcast at the end of PredBB. BitCastInst *New = new BitCastInst(OpVal, InVal->getType(), InVal->getName()+".phi.trans.insert", PredBB->getTerminator()); NewInsts.push_back(New); return New; } // Handle getelementptr with at least one PHI operand. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) { SmallVector<Value*, 8> GEPOps; BasicBlock *CurBB = GEP->getParent(); for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) { Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i), CurBB, PredBB, DT, NewInsts); if (OpVal == 0) return 0; GEPOps.push_back(OpVal); } GetElementPtrInst *Result = GetElementPtrInst::Create(GEPOps[0], GEPOps.begin()+1, GEPOps.end(), InVal->getName()+".phi.trans.insert", PredBB->getTerminator()); Result->setIsInBounds(GEP->isInBounds()); NewInsts.push_back(Result); return Result; } #if 0 // FIXME: This code works, but it is unclear that we actually want to insert // a big chain of computation in order to make a value available in a block. // This needs to be evaluated carefully to consider its cost trade offs. // Handle add with a constant RHS. if (Inst->getOpcode() == Instruction::Add && isa<ConstantInt>(Inst->getOperand(1))) { // PHI translate the LHS. Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0), CurBB, PredBB, DT, NewInsts); if (OpVal == 0) return 0; BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1), InVal->getName()+".phi.trans.insert", PredBB->getTerminator()); Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap()); Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap()); NewInsts.push_back(Res); return Res; } #endif return 0; }
add support for phi translation and incorpation of new expression.
add support for phi translation and incorpation of new expression. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@90782 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap
e5f62e81c2245a5ad26be6efa5b4e5855064c1ee
lib/CodeGen/CGObjCRuntime.cpp
lib/CodeGen/CGObjCRuntime.cpp
//==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This abstract class defines the interface for Objective-C runtime-specific // code generation. It provides some concrete helper methods for functionality // shared between all (or most) of the Objective-C runtimes supported by clang. // //===----------------------------------------------------------------------===// #include "CGObjCRuntime.h" #include "CGCleanup.h" #include "CGRecordLayout.h" #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/StmtObjC.h" #include "clang/CodeGen/CGFunctionInfo.h" #include "llvm/IR/CallSite.h" using namespace clang; using namespace CodeGen; static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) { const ObjCInterfaceDecl *Container = Ivar->getContainingInterface(); // FIXME: We should eliminate the need to have ObjCImplementationDecl passed // in here; it should never be necessary because that should be the lexical // decl context for the ivar. // If we know have an implementation (and the ivar is in it) then // look up in the implementation layout. const ASTRecordLayout *RL; if (ID && declaresSameEntity(ID->getClassInterface(), Container)) RL = &CGM.getContext().getASTObjCImplementationLayout(ID); else RL = &CGM.getContext().getASTObjCInterfaceLayout(Container); // Compute field index. // // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is // implemented. This should be fixed to get the information from the layout // directly. unsigned Index = 0; for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { if (Ivar == IVD) break; ++Index; } assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!"); return RL->getFieldOffset(Index); } uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) { return LookupFieldBitOffset(CGM, OID, nullptr, Ivar) / CGM.getContext().getCharWidth(); } uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, const ObjCImplementationDecl *OID, const ObjCIvarDecl *Ivar) { return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / CGM.getContext().getCharWidth(); } unsigned CGObjCRuntime::ComputeBitfieldBitOffset( CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar) { return LookupFieldBitOffset(CGM, ID, ID->getImplementation(), Ivar); } LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF, const ObjCInterfaceDecl *OID, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers, llvm::Value *Offset) { // Compute (type*) ( (char *) BaseValue + Offset) QualType IvarTy = Ivar->getType(); llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy); llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy); V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr"); if (!Ivar->isBitField()) { V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy)); LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy); LV.getQuals().addCVRQualifiers(CVRQualifiers); return LV; } // We need to compute an access strategy for this bit-field. We are given the // offset to the first byte in the bit-field, the sub-byte offset is taken // from the original layout. We reuse the normal bit-field access strategy by // treating this as an access to a struct where the bit-field is in byte 0, // and adjust the containing type size as appropriate. // // FIXME: Note that currently we make a very conservative estimate of the // alignment of the bit-field, because (a) it is not clear what guarantees the // runtime makes us, and (b) we don't have a way to specify that the struct is // at an alignment plus offset. // // Note, there is a subtle invariant here: we can only call this routine on // non-synthesized ivars but we may be called for synthesized ivars. However, // a synthesized ivar can never be a bit-field, so this is safe. uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, nullptr, Ivar); uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth(); uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign(); uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext()); CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits( llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits)); CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits); // Allocate a new CGBitFieldInfo object to describe this access. // // FIXME: This is incredibly wasteful, these should be uniqued or part of some // layout object. However, this is blocked on other cleanups to the // Objective-C code, so for now we just live with allocating a bunch of these // objects. CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo( CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize, CGF.CGM.getContext().toBits(StorageSize), CharUnits::fromQuantity(0))); Address Addr(V, Alignment); Addr = CGF.Builder.CreateElementBitCast(Addr, llvm::Type::getIntNTy(CGF.getLLVMContext(), Info->StorageSize)); return LValue::MakeBitfield(Addr, *Info, IvarTy.withCVRQualifiers(CVRQualifiers), AlignmentSource::Decl); } namespace { struct CatchHandler { const VarDecl *Variable; const Stmt *Body; llvm::BasicBlock *Block; llvm::Constant *TypeInfo; }; struct CallObjCEndCatch final : EHScopeStack::Cleanup { CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) : MightThrow(MightThrow), Fn(Fn) {} bool MightThrow; llvm::Value *Fn; void Emit(CodeGenFunction &CGF, Flags flags) override { if (!MightThrow) { CGF.Builder.CreateCall(Fn)->setDoesNotThrow(); return; } CGF.EmitRuntimeCallOrInvoke(Fn); } }; } void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S, llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, llvm::Constant *exceptionRethrowFn) { // Jump destination for falling out of catch bodies. CodeGenFunction::JumpDest Cont; if (S.getNumCatchStmts()) Cont = CGF.getJumpDestInCurrentScope("eh.cont"); CodeGenFunction::FinallyInfo FinallyInfo; if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) FinallyInfo.enter(CGF, Finally->getFinallyBody(), beginCatchFn, endCatchFn, exceptionRethrowFn); SmallVector<CatchHandler, 8> Handlers; // Enter the catch, if there is one. if (S.getNumCatchStmts()) { for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) { const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I); const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); Handlers.push_back(CatchHandler()); CatchHandler &Handler = Handlers.back(); Handler.Variable = CatchDecl; Handler.Body = CatchStmt->getCatchBody(); Handler.Block = CGF.createBasicBlock("catch"); // @catch(...) always matches. if (!CatchDecl) { Handler.TypeInfo = nullptr; // catch-all // Don't consider any other catches. break; } Handler.TypeInfo = GetEHType(CatchDecl->getType()); } EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size()); for (unsigned I = 0, E = Handlers.size(); I != E; ++I) Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block); } // Emit the try body. CGF.EmitStmt(S.getTryBody()); // Leave the try. if (S.getNumCatchStmts()) CGF.popCatchScope(); // Remember where we were. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); // Emit the handlers. for (unsigned I = 0, E = Handlers.size(); I != E; ++I) { CatchHandler &Handler = Handlers[I]; CGF.EmitBlock(Handler.Block); llvm::Value *RawExn = CGF.getExceptionFromSlot(); // Enter the catch. llvm::Value *Exn = RawExn; if (beginCatchFn) { Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted"); cast<llvm::CallInst>(Exn)->setDoesNotThrow(); } CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange()); if (endCatchFn) { // Add a cleanup to leave the catch. bool EndCatchMightThrow = (Handler.Variable == nullptr); CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup, EndCatchMightThrow, endCatchFn); } // Bind the catch parameter if it exists. if (const VarDecl *CatchParam = Handler.Variable) { llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType()); llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType); CGF.EmitAutoVarDecl(*CatchParam); EmitInitOfCatchParam(CGF, CastExn, CatchParam); } CGF.ObjCEHValueStack.push_back(Exn); CGF.EmitStmt(Handler.Body); CGF.ObjCEHValueStack.pop_back(); // Leave any cleanups associated with the catch. cleanups.ForceCleanup(); CGF.EmitBranchThroughCleanup(Cont); } // Go back to the try-statement fallthrough. CGF.Builder.restoreIP(SavedIP); // Pop out of the finally. if (S.getFinallyStmt()) FinallyInfo.exit(CGF); if (Cont.isValid()) CGF.EmitBlock(Cont.getBlock()); } void CGObjCRuntime::EmitInitOfCatchParam(CodeGenFunction &CGF, llvm::Value *exn, const VarDecl *paramDecl) { Address paramAddr = CGF.GetAddrOfLocalVar(paramDecl); switch (paramDecl->getType().getQualifiers().getObjCLifetime()) { case Qualifiers::OCL_Strong: exn = CGF.EmitARCRetainNonBlock(exn); // fallthrough case Qualifiers::OCL_None: case Qualifiers::OCL_ExplicitNone: case Qualifiers::OCL_Autoreleasing: CGF.Builder.CreateStore(exn, paramAddr); return; case Qualifiers::OCL_Weak: CGF.EmitARCInitWeak(paramAddr, exn); return; } llvm_unreachable("invalid ownership qualifier"); } namespace { struct CallSyncExit final : EHScopeStack::Cleanup { llvm::Value *SyncExitFn; llvm::Value *SyncArg; CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg) : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {} void Emit(CodeGenFunction &CGF, Flags flags) override { CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow(); } }; } void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S, llvm::Function *syncEnterFn, llvm::Function *syncExitFn) { CodeGenFunction::RunCleanupsScope cleanups(CGF); // Evaluate the lock operand. This is guaranteed to dominate the // ARC release and lock-release cleanups. const Expr *lockExpr = S.getSynchExpr(); llvm::Value *lock; if (CGF.getLangOpts().ObjCAutoRefCount) { lock = CGF.EmitARCRetainScalarExpr(lockExpr); lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock); } else { lock = CGF.EmitScalarExpr(lockExpr); } lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy); // Acquire the lock. CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow(); // Register an all-paths cleanup to release the lock. CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock); // Emit the body of the statement. CGF.EmitStmt(S.getSynchBody()); } /// Compute the pointer-to-function type to which a message send /// should be casted in order to correctly call the given method /// with the given arguments. /// /// \param method - may be null /// \param resultType - the result type to use if there's no method /// \param callArgs - the actual arguments, including implicit ones CGObjCRuntime::MessageSendInfo CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method, QualType resultType, CallArgList &callArgs) { // If there's a method, use information from that. if (method) { const CGFunctionInfo &signature = CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty); llvm::PointerType *signatureType = CGM.getTypes().GetFunctionType(signature)->getPointerTo(); const CGFunctionInfo &signatureForCall = CGM.getTypes().arrangeCall(signature, callArgs); return MessageSendInfo(signatureForCall, signatureType); } // There's no method; just use a default CC. const CGFunctionInfo &argsInfo = CGM.getTypes().arrangeUnprototypedObjCMessageSend(resultType, callArgs); // Derive the signature to call from that. llvm::PointerType *signatureType = CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo(); return MessageSendInfo(argsInfo, signatureType); }
//==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This abstract class defines the interface for Objective-C runtime-specific // code generation. It provides some concrete helper methods for functionality // shared between all (or most) of the Objective-C runtimes supported by clang. // //===----------------------------------------------------------------------===// #include "CGObjCRuntime.h" #include "CGCleanup.h" #include "CGRecordLayout.h" #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/StmtObjC.h" #include "clang/CodeGen/CGFunctionInfo.h" #include "llvm/IR/CallSite.h" using namespace clang; using namespace CodeGen; static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) { const ObjCInterfaceDecl *Container = Ivar->getContainingInterface(); // FIXME: We should eliminate the need to have ObjCImplementationDecl passed // in here; it should never be necessary because that should be the lexical // decl context for the ivar. // If we know have an implementation (and the ivar is in it) then // look up in the implementation layout. const ASTRecordLayout *RL; if (ID && declaresSameEntity(ID->getClassInterface(), Container)) RL = &CGM.getContext().getASTObjCImplementationLayout(ID); else RL = &CGM.getContext().getASTObjCInterfaceLayout(Container); // Compute field index. // // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is // implemented. This should be fixed to get the information from the layout // directly. unsigned Index = 0; for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { if (Ivar == IVD) break; ++Index; } assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!"); return RL->getFieldOffset(Index); } uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) { return LookupFieldBitOffset(CGM, OID, nullptr, Ivar) / CGM.getContext().getCharWidth(); } uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, const ObjCImplementationDecl *OID, const ObjCIvarDecl *Ivar) { return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / CGM.getContext().getCharWidth(); } unsigned CGObjCRuntime::ComputeBitfieldBitOffset( CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar) { return LookupFieldBitOffset(CGM, ID, ID->getImplementation(), Ivar); } LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF, const ObjCInterfaceDecl *OID, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers, llvm::Value *Offset) { // Compute (type*) ( (char *) BaseValue + Offset) QualType IvarTy = Ivar->getType().withCVRQualifiers(CVRQualifiers); llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy); llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy); V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr"); if (!Ivar->isBitField()) { V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy)); LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy); return LV; } // We need to compute an access strategy for this bit-field. We are given the // offset to the first byte in the bit-field, the sub-byte offset is taken // from the original layout. We reuse the normal bit-field access strategy by // treating this as an access to a struct where the bit-field is in byte 0, // and adjust the containing type size as appropriate. // // FIXME: Note that currently we make a very conservative estimate of the // alignment of the bit-field, because (a) it is not clear what guarantees the // runtime makes us, and (b) we don't have a way to specify that the struct is // at an alignment plus offset. // // Note, there is a subtle invariant here: we can only call this routine on // non-synthesized ivars but we may be called for synthesized ivars. However, // a synthesized ivar can never be a bit-field, so this is safe. uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, nullptr, Ivar); uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth(); uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign(); uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext()); CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits( llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits)); CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits); // Allocate a new CGBitFieldInfo object to describe this access. // // FIXME: This is incredibly wasteful, these should be uniqued or part of some // layout object. However, this is blocked on other cleanups to the // Objective-C code, so for now we just live with allocating a bunch of these // objects. CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo( CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize, CGF.CGM.getContext().toBits(StorageSize), CharUnits::fromQuantity(0))); Address Addr(V, Alignment); Addr = CGF.Builder.CreateElementBitCast(Addr, llvm::Type::getIntNTy(CGF.getLLVMContext(), Info->StorageSize)); return LValue::MakeBitfield(Addr, *Info, IvarTy, AlignmentSource::Decl); } namespace { struct CatchHandler { const VarDecl *Variable; const Stmt *Body; llvm::BasicBlock *Block; llvm::Constant *TypeInfo; }; struct CallObjCEndCatch final : EHScopeStack::Cleanup { CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) : MightThrow(MightThrow), Fn(Fn) {} bool MightThrow; llvm::Value *Fn; void Emit(CodeGenFunction &CGF, Flags flags) override { if (!MightThrow) { CGF.Builder.CreateCall(Fn)->setDoesNotThrow(); return; } CGF.EmitRuntimeCallOrInvoke(Fn); } }; } void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S, llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, llvm::Constant *exceptionRethrowFn) { // Jump destination for falling out of catch bodies. CodeGenFunction::JumpDest Cont; if (S.getNumCatchStmts()) Cont = CGF.getJumpDestInCurrentScope("eh.cont"); CodeGenFunction::FinallyInfo FinallyInfo; if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) FinallyInfo.enter(CGF, Finally->getFinallyBody(), beginCatchFn, endCatchFn, exceptionRethrowFn); SmallVector<CatchHandler, 8> Handlers; // Enter the catch, if there is one. if (S.getNumCatchStmts()) { for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) { const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I); const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); Handlers.push_back(CatchHandler()); CatchHandler &Handler = Handlers.back(); Handler.Variable = CatchDecl; Handler.Body = CatchStmt->getCatchBody(); Handler.Block = CGF.createBasicBlock("catch"); // @catch(...) always matches. if (!CatchDecl) { Handler.TypeInfo = nullptr; // catch-all // Don't consider any other catches. break; } Handler.TypeInfo = GetEHType(CatchDecl->getType()); } EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size()); for (unsigned I = 0, E = Handlers.size(); I != E; ++I) Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block); } // Emit the try body. CGF.EmitStmt(S.getTryBody()); // Leave the try. if (S.getNumCatchStmts()) CGF.popCatchScope(); // Remember where we were. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); // Emit the handlers. for (unsigned I = 0, E = Handlers.size(); I != E; ++I) { CatchHandler &Handler = Handlers[I]; CGF.EmitBlock(Handler.Block); llvm::Value *RawExn = CGF.getExceptionFromSlot(); // Enter the catch. llvm::Value *Exn = RawExn; if (beginCatchFn) { Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted"); cast<llvm::CallInst>(Exn)->setDoesNotThrow(); } CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange()); if (endCatchFn) { // Add a cleanup to leave the catch. bool EndCatchMightThrow = (Handler.Variable == nullptr); CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup, EndCatchMightThrow, endCatchFn); } // Bind the catch parameter if it exists. if (const VarDecl *CatchParam = Handler.Variable) { llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType()); llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType); CGF.EmitAutoVarDecl(*CatchParam); EmitInitOfCatchParam(CGF, CastExn, CatchParam); } CGF.ObjCEHValueStack.push_back(Exn); CGF.EmitStmt(Handler.Body); CGF.ObjCEHValueStack.pop_back(); // Leave any cleanups associated with the catch. cleanups.ForceCleanup(); CGF.EmitBranchThroughCleanup(Cont); } // Go back to the try-statement fallthrough. CGF.Builder.restoreIP(SavedIP); // Pop out of the finally. if (S.getFinallyStmt()) FinallyInfo.exit(CGF); if (Cont.isValid()) CGF.EmitBlock(Cont.getBlock()); } void CGObjCRuntime::EmitInitOfCatchParam(CodeGenFunction &CGF, llvm::Value *exn, const VarDecl *paramDecl) { Address paramAddr = CGF.GetAddrOfLocalVar(paramDecl); switch (paramDecl->getType().getQualifiers().getObjCLifetime()) { case Qualifiers::OCL_Strong: exn = CGF.EmitARCRetainNonBlock(exn); // fallthrough case Qualifiers::OCL_None: case Qualifiers::OCL_ExplicitNone: case Qualifiers::OCL_Autoreleasing: CGF.Builder.CreateStore(exn, paramAddr); return; case Qualifiers::OCL_Weak: CGF.EmitARCInitWeak(paramAddr, exn); return; } llvm_unreachable("invalid ownership qualifier"); } namespace { struct CallSyncExit final : EHScopeStack::Cleanup { llvm::Value *SyncExitFn; llvm::Value *SyncArg; CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg) : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {} void Emit(CodeGenFunction &CGF, Flags flags) override { CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow(); } }; } void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S, llvm::Function *syncEnterFn, llvm::Function *syncExitFn) { CodeGenFunction::RunCleanupsScope cleanups(CGF); // Evaluate the lock operand. This is guaranteed to dominate the // ARC release and lock-release cleanups. const Expr *lockExpr = S.getSynchExpr(); llvm::Value *lock; if (CGF.getLangOpts().ObjCAutoRefCount) { lock = CGF.EmitARCRetainScalarExpr(lockExpr); lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock); } else { lock = CGF.EmitScalarExpr(lockExpr); } lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy); // Acquire the lock. CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow(); // Register an all-paths cleanup to release the lock. CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock); // Emit the body of the statement. CGF.EmitStmt(S.getSynchBody()); } /// Compute the pointer-to-function type to which a message send /// should be casted in order to correctly call the given method /// with the given arguments. /// /// \param method - may be null /// \param resultType - the result type to use if there's no method /// \param callArgs - the actual arguments, including implicit ones CGObjCRuntime::MessageSendInfo CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method, QualType resultType, CallArgList &callArgs) { // If there's a method, use information from that. if (method) { const CGFunctionInfo &signature = CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty); llvm::PointerType *signatureType = CGM.getTypes().GetFunctionType(signature)->getPointerTo(); const CGFunctionInfo &signatureForCall = CGM.getTypes().arrangeCall(signature, callArgs); return MessageSendInfo(signatureForCall, signatureType); } // There's no method; just use a default CC. const CGFunctionInfo &argsInfo = CGM.getTypes().arrangeUnprototypedObjCMessageSend(resultType, callArgs); // Derive the signature to call from that. llvm::PointerType *signatureType = CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo(); return MessageSendInfo(argsInfo, signatureType); }
Make the LValue created in EmitValueForIvarAtOffset have the same Qualifiers in the LValue as the QualType in the LValue. No functionality change intended.
Make the LValue created in EmitValueForIvarAtOffset have the same Qualifiers in the LValue as the QualType in the LValue. No functionality change intended. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@283795 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang
c3ef917b3c44a32aa3240382f5c32b6ab1615c28
tests/auto/symbian/qmediaobject_s60/tst_qmediaobject_s60.cpp
tests/auto/symbian/qmediaobject_s60/tst_qmediaobject_s60.cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QtCore/qtimer.h> #include <qmediaobject.h> #include <qmediaservice.h> #include <qmediaplayer.h> QT_USE_NAMESPACE class tst_QMediaObject : public QObject { Q_OBJECT public slots: void initTestCase_data(); void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); private slots: void isMetaDataAvailable(); void isWritable(); void metaData(); void availableMetaData(); void extendedMetaData(); void availableExtendedMetaData(); private: QString metaDataKeyAsString(QtMultimedia::MetaData key) const; }; void tst_QMediaObject::initTestCase_data() { QTest::addColumn<bool>("valid"); //QTest::addColumn<QMediaPlayer::State>("state"); //QTest::addColumn<QMediaPlayer::MediaStatus>("status"); QTest::addColumn<QMediaContent>("mediaContent"); QTest::addColumn<bool>("metaDataAvailable"); QTest::addColumn<bool>("metaDataWritable"); // Is this needed ??? //QTest::addColumn<int>("bufferStatus"); //QTest::addColumn<qreal>("playbackRate"); //QTest::addColumn<QMediaPlayer::Error>("error"); //QTest::addColumn<QString>("errorString"); QTest::newRow("TestDataNull") << false // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent() // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString /* QTest::newRow("test_3gp.3gp") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_3gp.3gp")) // mediaContent << qint64(-1) // duration << qint64(0) // position << false // seekable << 0 // volume << false // muted << false; // videoAvailable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString */ QTest::newRow("test_amr.amr") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_amr.amr")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_flash_video.flv") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_flash_video.flv")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_invalid_extension_mp4.xyz") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_invalid_extension_mp4.xyz")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_invalid_extension_wav.xyz") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_invalid_extension_wav.xyz")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_mp3.mp3") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_mp3.mp3")) // mediaContent #if !defined(__WINS__) || !defined(__WINSCW__) << true // metaDataAvailable #else << false // metaDataAvailable #endif // !defined(__WINS__) || defined(__WINSCW__) << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_mp3_no_metadata.mp3") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_mp3_no_metadata.mp3")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_mp4.mp4") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_mp4.mp4")) // mediaContent #if defined(__WINS__) || defined(__WINSCW__) << true // metaDataAvailable #else << false // metaDataAvailable #endif // !defined(__WINS__) || defined(__WINSCW__) << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_wav.wav") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_wav.wav")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_wmv9.wmv") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_wmv9.wmv")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test youtube stream") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("rtsp://v3.cache4.c.youtube.com/CkgLENy73wIaPwlU2rm7yu8PFhMYESARFEIJbXYtZ29vZ2xlSARSB3JlbGF0ZWRaDkNsaWNrVGh1bWJuYWlsYPi6_IXT2rvpSgw=/0/0/0/video.3gp")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString } void tst_QMediaObject::initTestCase() { } void tst_QMediaObject::cleanupTestCase() { } void tst_QMediaObject::init() { qRegisterMetaType<QMediaContent>("QMediaContent"); } void tst_QMediaObject::cleanup() { } void tst_QMediaObject::isMetaDataAvailable() { QFETCH_GLOBAL(bool, metaDataAvailable); QFETCH_GLOBAL(QMediaContent, mediaContent); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); QVERIFY(player.isMetaDataAvailable() == metaDataAvailable); } void tst_QMediaObject::metaData() { QFETCH_GLOBAL(QMediaContent, mediaContent); QFETCH_GLOBAL(bool, metaDataAvailable); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); const QString artist(QLatin1String("Artist")); const QString title(QLatin1String("Title")); if (player.isMetaDataAvailable()) { QEXPECT_FAIL("", "player.metaData(QtMultimedia::AlbumArtist) failed: ", Continue); QCOMPARE(player.metaData(QtMultimedia::AlbumArtist).toString(), artist); QEXPECT_FAIL("", "player.metaData(QtMultimedia::Title) failed: ", Continue); QCOMPARE(player.metaData(QtMultimedia::Title).toString(), title); } } void tst_QMediaObject::availableMetaData() { QFETCH_GLOBAL(QMediaContent, mediaContent); QFETCH_GLOBAL(bool, metaDataAvailable); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); if (player.isMetaDataAvailable()) { QList<QtMultimedia::MetaData> metaDataKeys = player.availableMetaData(); QEXPECT_FAIL("", "metaDataKeys.count() failed: ", Continue); QVERIFY(metaDataKeys.count() > 0); // qWarning() << "metaDataKeys.count: " << metaDataKeys.count(); QEXPECT_FAIL("", "metaDataKeys.contains(QtMultimedia::AlbumArtist) failed: ", Continue); QVERIFY(metaDataKeys.contains(QtMultimedia::AlbumArtist)); QEXPECT_FAIL("", "metaDataKeys.contains(QtMultimedia::Title) failed: ", Continue); QVERIFY(metaDataKeys.contains(QtMultimedia::Title)); } } void tst_QMediaObject::extendedMetaData() { QFETCH_GLOBAL(QMediaContent, mediaContent); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); const QString artist(QLatin1String("Artist")); const QString title(QLatin1String("Title")); if (player.isMetaDataAvailable()) { QEXPECT_FAIL("", "player.extendedMetaData(QtMultimedia::AlbumArtist) failed: ", Continue); QCOMPARE(player.extendedMetaData(metaDataKeyAsString(QtMultimedia::AlbumArtist)).toString(), artist); QEXPECT_FAIL("", "player.extendedMetaData(QtMultimedia::Title) failed: ", Continue); QCOMPARE(player.extendedMetaData(metaDataKeyAsString(QtMultimedia::Title)).toString(), title); } } void tst_QMediaObject::availableExtendedMetaData() { QFETCH_GLOBAL(QMediaContent, mediaContent); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); const QString artist(QLatin1String("Artist")); const QString title(QLatin1String("Title")); if (player.isMetaDataAvailable()) { QStringList metaDataKeys = player.availableExtendedMetaData(); QVERIFY(metaDataKeys.count() > 0); /* qWarning() << "metaDataKeys.count: " << metaDataKeys.count(); int count = metaDataKeys.count(); count = count-1; int i = 0; while(count >= i) { qWarning() << "metaDataKeys " << i <<". " << metaDataKeys.at(i); i++; }*/ QEXPECT_FAIL("", "metaDataKeys.contains(QtMultimedia::AlbumArtist) failed: ", Continue); QVERIFY(metaDataKeys.contains(metaDataKeyAsString(QtMultimedia::AlbumArtist))); QEXPECT_FAIL("", "metaDataKeys.contains(QtMultimedia::AlbumArtist) failed: ", Continue); QVERIFY(metaDataKeys.contains(metaDataKeyAsString(QtMultimedia::Title))); } } QString tst_QMediaObject::metaDataKeyAsString(QtMultimedia::MetaData key) const { switch(key) { case QtMultimedia::Title: return "title"; case QtMultimedia::AlbumArtist: return "artist"; case QtMultimedia::Comment: return "comment"; case QtMultimedia::Genre: return "genre"; case QtMultimedia::Year: return "year"; case QtMultimedia::Copyright: return "copyright"; case QtMultimedia::AlbumTitle: return "album"; case QtMultimedia::Composer: return "composer"; case QtMultimedia::TrackNumber: return "albumtrack"; case QtMultimedia::AudioBitRate: return "audiobitrate"; case QtMultimedia::VideoBitRate: return "videobitrate"; case QtMultimedia::Duration: return "duration"; case QtMultimedia::MediaType: return "contenttype"; case QtMultimedia::SubTitle: // TODO: Find the matching metadata keys case QtMultimedia::Description: case QtMultimedia::Category: case QtMultimedia::Date: case QtMultimedia::UserRating: case QtMultimedia::Keywords: case QtMultimedia::Language: case QtMultimedia::Publisher: case QtMultimedia::ParentalRating: case QtMultimedia::RatingOrganisation: case QtMultimedia::Size: case QtMultimedia::AudioCodec: case QtMultimedia::AverageLevel: case QtMultimedia::ChannelCount: case QtMultimedia::PeakValue: case QtMultimedia::SampleRate: case QtMultimedia::Author: case QtMultimedia::ContributingArtist: case QtMultimedia::Conductor: case QtMultimedia::Lyrics: case QtMultimedia::Mood: case QtMultimedia::TrackCount: case QtMultimedia::CoverArtUrlSmall: case QtMultimedia::CoverArtUrlLarge: case QtMultimedia::Resolution: case QtMultimedia::PixelAspectRatio: case QtMultimedia::VideoFrameRate: case QtMultimedia::VideoCodec: case QtMultimedia::PosterUrl: case QtMultimedia::ChapterNumber: case QtMultimedia::Director: case QtMultimedia::LeadPerformer: case QtMultimedia::Writer: case QtMultimedia::CameraManufacturer: case QtMultimedia::CameraModel: case QtMultimedia::Event: case QtMultimedia::Subject: default: break; } return QString(); } QTEST_MAIN(tst_QMediaObject) #include "tst_qmediaobject_s60.moc"
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QtCore/qtimer.h> #include <qmediaobject.h> #include <qmediaservice.h> #include <qmediaplayer.h> QT_USE_NAMESPACE class tst_QMediaObject : public QObject { Q_OBJECT public slots: void initTestCase_data(); void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); private slots: void isMetaDataAvailable(); void metaData(); void availableMetaData(); void extendedMetaData(); void availableExtendedMetaData(); private: QString metaDataKeyAsString(QtMultimedia::MetaData key) const; }; void tst_QMediaObject::initTestCase_data() { QTest::addColumn<bool>("valid"); //QTest::addColumn<QMediaPlayer::State>("state"); //QTest::addColumn<QMediaPlayer::MediaStatus>("status"); QTest::addColumn<QMediaContent>("mediaContent"); QTest::addColumn<bool>("metaDataAvailable"); QTest::addColumn<bool>("metaDataWritable"); // Is this needed ??? //QTest::addColumn<int>("bufferStatus"); //QTest::addColumn<qreal>("playbackRate"); //QTest::addColumn<QMediaPlayer::Error>("error"); //QTest::addColumn<QString>("errorString"); QTest::newRow("TestDataNull") << false // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent() // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString /* QTest::newRow("test_3gp.3gp") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_3gp.3gp")) // mediaContent << qint64(-1) // duration << qint64(0) // position << false // seekable << 0 // volume << false // muted << false; // videoAvailable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString */ QTest::newRow("test_amr.amr") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_amr.amr")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_flash_video.flv") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_flash_video.flv")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_invalid_extension_mp4.xyz") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_invalid_extension_mp4.xyz")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_invalid_extension_wav.xyz") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_invalid_extension_wav.xyz")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_mp3.mp3") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_mp3.mp3")) // mediaContent #if !defined(__WINS__) || !defined(__WINSCW__) << true // metaDataAvailable #else << false // metaDataAvailable #endif // !defined(__WINS__) || defined(__WINSCW__) << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_mp3_no_metadata.mp3") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_mp3_no_metadata.mp3")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_mp4.mp4") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_mp4.mp4")) // mediaContent #if defined(__WINS__) || defined(__WINSCW__) << true // metaDataAvailable #else << false // metaDataAvailable #endif // !defined(__WINS__) || defined(__WINSCW__) << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_wav.wav") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_wav.wav")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test_wmv9.wmv") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("file:///C:/data/testfiles/test_wmv9.wmv")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString QTest::newRow("test youtube stream") << true // valid //<< QMediaPlayer::StoppedState // state //<< QMediaPlayer::UnknownMediaStatus // status << QMediaContent(QUrl("rtsp://v3.cache4.c.youtube.com/CkgLENy73wIaPwlU2rm7yu8PFhMYESARFEIJbXYtZ29vZ2xlSARSB3JlbGF0ZWRaDkNsaWNrVGh1bWJuYWlsYPi6_IXT2rvpSgw=/0/0/0/video.3gp")) // mediaContent << false // metaDataAvailable << false; // metaDataWritable //<< 0 // bufferStatus //<< qreal(0) // playbackRate //<< QMediaPlayer::NoError // error //<< QString(); // errorString } void tst_QMediaObject::initTestCase() { } void tst_QMediaObject::cleanupTestCase() { } void tst_QMediaObject::init() { qRegisterMetaType<QMediaContent>("QMediaContent"); } void tst_QMediaObject::cleanup() { } void tst_QMediaObject::isMetaDataAvailable() { QFETCH_GLOBAL(bool, metaDataAvailable); QFETCH_GLOBAL(QMediaContent, mediaContent); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); QVERIFY(player.isMetaDataAvailable() == metaDataAvailable); } void tst_QMediaObject::metaData() { QFETCH_GLOBAL(QMediaContent, mediaContent); QFETCH_GLOBAL(bool, metaDataAvailable); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); const QString artist(QLatin1String("Artist")); const QString title(QLatin1String("Title")); if (player.isMetaDataAvailable()) { QEXPECT_FAIL("", "player.metaData(QtMultimedia::AlbumArtist) failed: ", Continue); QCOMPARE(player.metaData(QtMultimedia::AlbumArtist).toString(), artist); QEXPECT_FAIL("", "player.metaData(QtMultimedia::Title) failed: ", Continue); QCOMPARE(player.metaData(QtMultimedia::Title).toString(), title); } } void tst_QMediaObject::availableMetaData() { QFETCH_GLOBAL(QMediaContent, mediaContent); QFETCH_GLOBAL(bool, metaDataAvailable); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); if (player.isMetaDataAvailable()) { QList<QtMultimedia::MetaData> metaDataKeys = player.availableMetaData(); QEXPECT_FAIL("", "metaDataKeys.count() failed: ", Continue); QVERIFY(metaDataKeys.count() > 0); // qWarning() << "metaDataKeys.count: " << metaDataKeys.count(); QEXPECT_FAIL("", "metaDataKeys.contains(QtMultimedia::AlbumArtist) failed: ", Continue); QVERIFY(metaDataKeys.contains(QtMultimedia::AlbumArtist)); QEXPECT_FAIL("", "metaDataKeys.contains(QtMultimedia::Title) failed: ", Continue); QVERIFY(metaDataKeys.contains(QtMultimedia::Title)); } } void tst_QMediaObject::extendedMetaData() { QFETCH_GLOBAL(QMediaContent, mediaContent); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); const QString artist(QLatin1String("Artist")); const QString title(QLatin1String("Title")); if (player.isMetaDataAvailable()) { QEXPECT_FAIL("", "player.extendedMetaData(QtMultimedia::AlbumArtist) failed: ", Continue); QCOMPARE(player.extendedMetaData(metaDataKeyAsString(QtMultimedia::AlbumArtist)).toString(), artist); QEXPECT_FAIL("", "player.extendedMetaData(QtMultimedia::Title) failed: ", Continue); QCOMPARE(player.extendedMetaData(metaDataKeyAsString(QtMultimedia::Title)).toString(), title); } } void tst_QMediaObject::availableExtendedMetaData() { QFETCH_GLOBAL(QMediaContent, mediaContent); // qWarning() << mediaContent.canonicalUrl(); QMediaPlayer player; player.setMedia(mediaContent); QTest::qWait(700); const QString artist(QLatin1String("Artist")); const QString title(QLatin1String("Title")); if (player.isMetaDataAvailable()) { QStringList metaDataKeys = player.availableExtendedMetaData(); QVERIFY(metaDataKeys.count() > 0); /* qWarning() << "metaDataKeys.count: " << metaDataKeys.count(); int count = metaDataKeys.count(); count = count-1; int i = 0; while(count >= i) { qWarning() << "metaDataKeys " << i <<". " << metaDataKeys.at(i); i++; }*/ QEXPECT_FAIL("", "metaDataKeys.contains(QtMultimedia::AlbumArtist) failed: ", Continue); QVERIFY(metaDataKeys.contains(metaDataKeyAsString(QtMultimedia::AlbumArtist))); QEXPECT_FAIL("", "metaDataKeys.contains(QtMultimedia::AlbumArtist) failed: ", Continue); QVERIFY(metaDataKeys.contains(metaDataKeyAsString(QtMultimedia::Title))); } } QString tst_QMediaObject::metaDataKeyAsString(QtMultimedia::MetaData key) const { switch(key) { case QtMultimedia::Title: return "title"; case QtMultimedia::AlbumArtist: return "artist"; case QtMultimedia::Comment: return "comment"; case QtMultimedia::Genre: return "genre"; case QtMultimedia::Year: return "year"; case QtMultimedia::Copyright: return "copyright"; case QtMultimedia::AlbumTitle: return "album"; case QtMultimedia::Composer: return "composer"; case QtMultimedia::TrackNumber: return "albumtrack"; case QtMultimedia::AudioBitRate: return "audiobitrate"; case QtMultimedia::VideoBitRate: return "videobitrate"; case QtMultimedia::Duration: return "duration"; case QtMultimedia::MediaType: return "contenttype"; case QtMultimedia::SubTitle: // TODO: Find the matching metadata keys case QtMultimedia::Description: case QtMultimedia::Category: case QtMultimedia::Date: case QtMultimedia::UserRating: case QtMultimedia::Keywords: case QtMultimedia::Language: case QtMultimedia::Publisher: case QtMultimedia::ParentalRating: case QtMultimedia::RatingOrganisation: case QtMultimedia::Size: case QtMultimedia::AudioCodec: case QtMultimedia::AverageLevel: case QtMultimedia::ChannelCount: case QtMultimedia::PeakValue: case QtMultimedia::SampleRate: case QtMultimedia::Author: case QtMultimedia::ContributingArtist: case QtMultimedia::Conductor: case QtMultimedia::Lyrics: case QtMultimedia::Mood: case QtMultimedia::TrackCount: case QtMultimedia::CoverArtUrlSmall: case QtMultimedia::CoverArtUrlLarge: case QtMultimedia::Resolution: case QtMultimedia::PixelAspectRatio: case QtMultimedia::VideoFrameRate: case QtMultimedia::VideoCodec: case QtMultimedia::PosterUrl: case QtMultimedia::ChapterNumber: case QtMultimedia::Director: case QtMultimedia::LeadPerformer: case QtMultimedia::Writer: case QtMultimedia::CameraManufacturer: case QtMultimedia::CameraModel: case QtMultimedia::Event: case QtMultimedia::Subject: default: break; } return QString(); } QTEST_MAIN(tst_QMediaObject) #include "tst_qmediaobject_s60.moc"
fix isWritable() function symbol not found - Seems the isWritable() function body has been removed so remove function definition
symbian:tests: fix isWritable() function symbol not found - Seems the isWritable() function body has been removed so remove function definition
C++
lgpl-2.1
enthought/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,tmcguire/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility
5342617b3866588c4a972f36231b8686aac98daa
tntnet/framework/common/httpmessage.cpp
tntnet/framework/common/httpmessage.cpp
/* httpmessage.cpp * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <tnt/httpmessage.h> #include <cxxtools/log.h> #include <cxxtools/thread.h> #include <list> #include <sstream> namespace tnt { size_t HttpMessage::maxRequestSize = 0; //////////////////////////////////////////////////////////////////////// // HttpMessage // log_define("tntnet.httpmessage") void HttpMessage::clear() { method.clear(); url.clear(); queryString.clear(); header.clear(); body.clear(); majorVersion = 1; minorVersion = 0; contentSize = 0; } std::string HttpMessage::getHeader(const std::string& key, const std::string& def) const { header_type::const_iterator i = header.find(key); return i == header.end() ? def : i->second; } void HttpMessage::setHeader(const std::string& key, const std::string& value) { log_debug("HttpMessage::setHeader(\"" << key << "\", \"" << value << "\")"); std::string k = key; if (k.size() > 0 && k.at(k.size() - 1) != ':') k += ':'; header.insert(header_type::value_type(k, value)); } std::string HttpMessage::dumpHeader() const { std::ostringstream h; dumpHeader(h); return h.str(); } void HttpMessage::dumpHeader(std::ostream& out) const { for (header_type::const_iterator it = header.begin(); it != header.end(); ++it) out << it->first << ' ' << it->second << '\n'; } std::string HttpMessage::htdate(time_t t) { struct ::tm tm; gmtime_r(&t, &tm); return htdate(&tm); } std::string HttpMessage::htdate(struct ::tm* tm) { const char* wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; const char* monthn[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; char buffer[80]; sprintf(buffer, "%s, %02d %s %d %02d:%02d:%02d GMT", wday[tm->tm_wday], tm->tm_mday, monthn[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); return buffer; } std::string HttpMessage::htdateCurrent() { static struct ::tm lastTm; static time_t lastDay = 0; static cxxtools::Mutex mutex; /* * we cache the last split tm-struct here, because it is pretty expensive * to calculate the date with gmtime_r. */ time_t t; struct ::tm tm; // get current time time(&t); time_t day = t / (24*60*60); // check lastDay if (day == lastDay) { // We can use the cached tm-struct and calculate hour, minute and // seconds. No locking was needed at all. This is the common case. memcpy(&tm, &lastTm, sizeof(struct ::tm)); tm.tm_sec = t % 60; t /= 60; tm.tm_min = t % 60; t /= 24; tm.tm_hour = t % 24; } // We recheck the last day here to ensure, our lastTm was valid even // after the check. There is a small chance, that the day has changed // and someone was just setting the lastTm. if (day != lastDay) { // Day differs, we calculate new date. cxxtools::MutexLock lock(mutex); // Check again with lock. Another thread might have computed it already. if (day != lastDay) { // still differs // We set lastDay to zero first, so that other threads will reach // the lock above. That way we avoid racing-conditions when accessing // lastTm without locking in the normal case. lastDay = 0; gmtime_r(&t, &tm); memcpy(&lastTm, &tm, sizeof(struct ::tm)); lastDay = day; } } return htdate(&tm); } namespace { class Pstr { const char* start; const char* end; public: typedef size_t size_type; Pstr(const char* s, const char* e) : start(s), end(e) { } void setStart(const char* s) { start = s; } void setEnd(const char* e) { end = e; } size_type size() const { return end - start; } bool empty() const { return start == end; } bool operator== (const Pstr& s) const { return size() == s.size() && std::equal(start, end, s.start); } bool operator== (const char* str) const { size_type i; for (i = 0; i < size() && str[i] != '\0'; ++i) if (start[i] != str[i]) return false; return i == size() && str[i] == '\0'; } }; } bool HttpMessage::checkUrl(const std::string& url) { unsigned level = 0; const char* p = url.data(); const char* e = p + url.size(); Pstr str(p, p); for (; p != e; ++p) { if (*p == '/') { str.setEnd(p); if (!str.empty()) { if (str == ".") ; else if (str == "..") { if (level == 0) return false; --level; } else ++level; } str.setStart(p + 1); } } if (level == 0 && (str.setEnd(p), str == "..")) return false; return true; } }
/* httpmessage.cpp * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <tnt/httpmessage.h> #include <cxxtools/log.h> #include <cxxtools/thread.h> #include <list> #include <sstream> namespace tnt { size_t HttpMessage::maxRequestSize = 0; //////////////////////////////////////////////////////////////////////// // HttpMessage // log_define("tntnet.httpmessage") void HttpMessage::clear() { method.clear(); url.clear(); queryString.clear(); header.clear(); body.clear(); majorVersion = 1; minorVersion = 0; contentSize = 0; } std::string HttpMessage::getHeader(const std::string& key, const std::string& def) const { header_type::const_iterator i = header.find(key); return i == header.end() ? def : i->second; } void HttpMessage::setHeader(const std::string& key, const std::string& value) { log_debug("HttpMessage::setHeader(\"" << key << "\", \"" << value << "\")"); std::string k = key; if (k.size() > 0 && k.at(k.size() - 1) != ':') k += ':'; header.insert(header_type::value_type(k, value)); } std::string HttpMessage::dumpHeader() const { std::ostringstream h; dumpHeader(h); return h.str(); } void HttpMessage::dumpHeader(std::ostream& out) const { for (header_type::const_iterator it = header.begin(); it != header.end(); ++it) out << it->first << ' ' << it->second << '\n'; } std::string HttpMessage::htdate(time_t t) { struct ::tm tm; gmtime_r(&t, &tm); return htdate(&tm); } std::string HttpMessage::htdate(struct ::tm* tm) { static const char* wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; static const char* monthn[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; char buffer[80]; sprintf(buffer, "%s, %02d %s %d %02d:%02d:%02d GMT", wday[tm->tm_wday], tm->tm_mday, monthn[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); return buffer; } std::string HttpMessage::htdateCurrent() { static struct ::tm lastTm; static time_t lastDay = 0; static cxxtools::Mutex mutex; cxxtools::MutexLock lock(mutex, false); /* * we cache the last split tm-struct here, because it is pretty expensive * to calculate the date with gmtime_r. */ time_t t; struct ::tm tm; time(&t); time_t day = t / (24*60*60); if (day != lastDay) { // Day differs, we calculate new date. lock.lock(); // Check again with lock. Another thread might have computed it already. if (day != lastDay) { // still differs // We set lastDay to zero first, so that other threads will reach // the lock above. That way we avoid racing-conditions when accessing // lastTm without locking in the normal case. lastDay = 0; gmtime_r(&t, &lastTm); lastDay = day; } } // We can use the cached tm-struct and calculate hour, minute and // seconds. No locking was needed at all. This is the common case. memcpy(&tm, &lastTm, sizeof(struct ::tm)); tm.tm_sec = t % 60; t /= 60; tm.tm_min = t % 60; t /= 24; tm.tm_hour = t % 24; return htdate(&tm); } namespace { class Pstr { const char* start; const char* end; public: typedef size_t size_type; Pstr(const char* s, const char* e) : start(s), end(e) { } void setStart(const char* s) { start = s; } void setEnd(const char* e) { end = e; } size_type size() const { return end - start; } bool empty() const { return start == end; } bool operator== (const Pstr& s) const { return size() == s.size() && std::equal(start, end, s.start); } bool operator== (const char* str) const { size_type i; for (i = 0; i < size() && str[i] != '\0'; ++i) if (start[i] != str[i]) return false; return i == size() && str[i] == '\0'; } }; } bool HttpMessage::checkUrl(const std::string& url) { unsigned level = 0; const char* p = url.data(); const char* e = p + url.size(); Pstr str(p, p); for (; p != e; ++p) { if (*p == '/') { str.setEnd(p); if (!str.empty()) { if (str == ".") ; else if (str == "..") { if (level == 0) return false; --level; } else ++level; } str.setStart(p + 1); } } if (level == 0 && (str.setEnd(p), str == "..")) return false; return true; } }
fix http-date-generation
fix http-date-generation git-svn-id: cc913a7f7b4e3b8bac01cff72f0fc87362e4d502@816 8dd45c8f-be11-0410-86c3-e0da43b70fc1
C++
lgpl-2.1
maekitalo/tntnet,OlafRadicke/tntnet,maekitalo/tntnet,OlafRadicke/tntnet,OlafRadicke/tntnet,OlafRadicke/tntnet,OlafRadicke/tntnet,maekitalo/tntnet,maekitalo/tntnet,maekitalo/tntnet,maekitalo/tntnet
e9e32ecc39ac80aad3ff62408858929a6bb9573b
tests/http/qdjangofastcgiserver/tst_qdjangofastcgiserver.cpp
tests/http/qdjangofastcgiserver/tst_qdjangofastcgiserver.cpp
/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango 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 <QLocalSocket> #include <QTcpSocket> #include <QtTest> #include <QUrl> #include "QDjangoFastCgiServer.h" #include "QDjangoFastCgiServer_p.h" #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoFastCgiServer.h" #include "QDjangoUrlResolver.h" #define ERROR_DATA QByteArray("Status: 500 Internal Server Error\r\n" \ "Content-Length: 107\r\n" \ "Content-Type: text/html; charset=utf-8\r\n" \ "\r\n" \ "<html><head><title>Error</title></head><body><p>An internal server error was encountered.</p></body></html>") #define NOT_FOUND_DATA QByteArray("Status: 404 Not Found\r\n" \ "Content-Length: 107\r\n" \ "Content-Type: text/html; charset=utf-8\r\n" \ "\r\n" \ "<html><head><title>Error</title></head><body><p>The document you requested was not found.</p></body></html>") #define ROOT_DATA QByteArray("Status: 200 OK\r\n" \ "Content-Length: 17\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "method=GET|path=/") #define QUERY_STRING_DATA QByteArray("Status: 200 OK\r\n" \ "Content-Length: 25\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "method=GET|path=/|get=bar") class QDjangoFastCgiReply : public QObject { Q_OBJECT public: QDjangoFastCgiReply(QObject *parent = 0) : QObject(parent) {}; QByteArray data; signals: void finished(); }; class QDjangoFastCgiClient : public QObject { Q_OBJECT public: QDjangoFastCgiClient(QIODevice *socket); QDjangoFastCgiReply* get(const QUrl &url); QDjangoFastCgiReply* post(const QUrl &url, const QByteArray &data); private slots: void _q_readyRead(); private: QDjangoFastCgiReply* request(const QByteArray &method, const QUrl &url, const QByteArray &data); QIODevice *m_device; QMap<quint16, QDjangoFastCgiReply*> m_replies; quint16 m_requestId; }; QDjangoFastCgiClient::QDjangoFastCgiClient(QIODevice *socket) : m_device(socket) , m_requestId(0) { connect(socket, SIGNAL(readyRead()), this, SLOT(_q_readyRead())); }; QDjangoFastCgiReply* QDjangoFastCgiClient::get(const QUrl &url) { return request("GET", url, QByteArray()); } QDjangoFastCgiReply* QDjangoFastCgiClient::post(const QUrl &url, const QByteArray &data) { return request("POST", url, data); } QDjangoFastCgiReply* QDjangoFastCgiClient::request(const QByteArray &method, const QUrl &url, const QByteArray &data) { const quint16 requestId = ++m_requestId; QDjangoFastCgiReply *reply = new QDjangoFastCgiReply(this); m_replies[requestId] = reply; QByteArray headerBuffer(FCGI_HEADER_LEN, '\0'); FCGI_Header *header = (FCGI_Header*)headerBuffer.data(); QByteArray ba; // BEGIN REQUEST ba = QByteArray("\x01\x00\x00\x00\x00\x00\x00\x00", 8); header->version = 1; FCGI_Header_setRequestId(header, requestId); header->type = FCGI_BEGIN_REQUEST; FCGI_Header_setContentLength(header, ba.size()); m_device->write(headerBuffer + ba); QMap<QByteArray, QByteArray> params; params["PATH_INFO"] = url.path().toUtf8(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) params["QUERY_STRING"] = url.query().toUtf8(); #else params["QUERY_STRING"] = url.encodedQuery(); #endif params["REQUEST_URI"] = url.toString().toUtf8(); params["REQUEST_METHOD"] = method; ba.clear(); foreach (const QByteArray &key, params.keys()) { const QByteArray value = params.value(key); ba.append(char(key.size())); ba.append(char(value.size())); ba.append(key); ba.append(value); } // FAST CGI PARAMS header->type = FCGI_PARAMS; FCGI_Header_setContentLength(header, ba.size()); m_device->write(headerBuffer + ba); // STDIN if (data.size() > 0) { header->type = FCGI_STDIN; FCGI_Header_setContentLength(header, data.size()); m_device->write(headerBuffer + data); } header->type = FCGI_STDIN; FCGI_Header_setContentLength(header, 0); m_device->write(headerBuffer); return reply; } void QDjangoFastCgiClient::_q_readyRead() { char inputBuffer[FCGI_RECORD_SIZE]; FCGI_Header *header = (FCGI_Header*)inputBuffer; while (m_device->bytesAvailable()) { if (m_device->read(inputBuffer, FCGI_HEADER_LEN) != FCGI_HEADER_LEN) { qWarning("header read fail"); return; } const quint16 contentLength = FCGI_Header_contentLength(header); const quint16 requestId = FCGI_Header_requestId(header); const quint16 bodyLength = contentLength + header->paddingLength; if (m_device->read(inputBuffer + FCGI_HEADER_LEN, bodyLength) != bodyLength) { qWarning("body read fail"); return; } if (!m_replies.contains(requestId)) { qWarning() << "unknown request" << requestId; return; } if (header->type == FCGI_STDOUT) { const QByteArray data = QByteArray(inputBuffer + FCGI_HEADER_LEN, contentLength); m_replies[requestId]->data += data; } else if (header->type == FCGI_END_REQUEST) { QMetaObject::invokeMethod(m_replies[requestId], "finished"); } } } /** Test QDjangoFastCgiServer class. */ class tst_QDjangoFastCgiServer : public QObject { Q_OBJECT private slots: void cleanup(); void init(); void testLocal_data(); void testLocal(); void testPost(); void testTcp_data(); void testTcp(); QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request); private: QDjangoFastCgiServer *server; }; void tst_QDjangoFastCgiServer::cleanup() { server->close(); delete server; } void tst_QDjangoFastCgiServer::init() { server = new QDjangoFastCgiServer; server->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index"); server->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error"); } void tst_QDjangoFastCgiServer::testLocal_data() { QTest::addColumn<QString>("path"); QTest::addColumn<QByteArray>("data"); QTest::newRow("root") << "/" << ROOT_DATA; QTest::newRow("query-string") << "/?message=bar" << QUERY_STRING_DATA; QTest::newRow("not-found") << "/not-found" << NOT_FOUND_DATA; QTest::newRow("internal-server-error") << "/internal-server-error" << ERROR_DATA; } void tst_QDjangoFastCgiServer::testLocal() { QFETCH(QString, path); QFETCH(QByteArray, data); const QString name("/tmp/qdjangofastcgi.socket"); QCOMPARE(server->listen(name), true); QLocalSocket socket; socket.connectToServer(name); QEventLoop loop; QDjangoFastCgiClient client(&socket); // check socket is connected QCOMPARE(socket.state(), QLocalSocket::ConnectedState); // wait for reply QDjangoFastCgiReply *reply = client.get(path); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::ConnectedState); QCOMPARE(reply->data, data); // wait for connection to close QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::UnconnectedState); } void tst_QDjangoFastCgiServer::testPost() { const QString name("/tmp/qdjangofastcgi.socket"); QCOMPARE(server->listen(name), true); QLocalSocket socket; socket.connectToServer(name); QCOMPARE(socket.state(), QLocalSocket::ConnectedState); QEventLoop loop; QDjangoFastCgiClient client(&socket); // wait for reply QDjangoFastCgiReply *reply = client.post(QUrl("/"), QByteArray("message=bar")); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::ConnectedState); QCOMPARE(reply->data, QByteArray("Status: 200 OK\r\n" \ "Content-Length: 27\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "method=POST|path=/|post=bar")); // wait for connection to close QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::UnconnectedState); } void tst_QDjangoFastCgiServer::testTcp_data() { QTest::addColumn<QString>("path"); QTest::addColumn<QByteArray>("data"); QTest::newRow("root") << "/" << ROOT_DATA; QTest::newRow("query-string") << "/?message=bar" << QUERY_STRING_DATA; QTest::newRow("not-found") << "/not-found" << NOT_FOUND_DATA; QTest::newRow("internal-server-error") << "/internal-server-error" << ERROR_DATA; } void tst_QDjangoFastCgiServer::testTcp() { QFETCH(QString, path); QFETCH(QByteArray, data); QCOMPARE(server->listen(QHostAddress::LocalHost, 8123), true); QTcpSocket socket; socket.connectToHost("127.0.0.1", 8123); QEventLoop loop; QDjangoFastCgiClient client(&socket); // wait for socket to connect QObject::connect(&socket, SIGNAL(connected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QAbstractSocket::ConnectedState); // wait for reply QDjangoFastCgiReply *reply = client.get(path); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QAbstractSocket::ConnectedState); QCOMPARE(reply->data, data); // wait for connection to close QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QAbstractSocket::UnconnectedState); } QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_index(const QDjangoHttpRequest &request) { QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); QString output = QLatin1String("method=") + request.method(); output += QLatin1String("|path=") + request.path(); const QString getValue = request.get(QLatin1String("message")); if (!getValue.isEmpty()) output += QLatin1String("|get=") + getValue; const QString postValue = request.post(QLatin1String("message")); if (!postValue.isEmpty()) output += QLatin1String("|post=") + postValue; response->setBody(output.toUtf8()); return response; } QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_error(const QDjangoHttpRequest &request) { Q_UNUSED(request); return QDjangoHttpController::serveInternalServerError(request); } QTEST_MAIN(tst_QDjangoFastCgiServer) #include "tst_qdjangofastcgiserver.moc"
/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango 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 <QLocalSocket> #include <QTcpSocket> #include <QtTest> #include <QUrl> #include "QDjangoFastCgiServer.h" #include "QDjangoFastCgiServer_p.h" #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoFastCgiServer.h" #include "QDjangoUrlResolver.h" #define ERROR_DATA QByteArray("Status: 500 Internal Server Error\r\n" \ "Content-Length: 107\r\n" \ "Content-Type: text/html; charset=utf-8\r\n" \ "\r\n" \ "<html><head><title>Error</title></head><body><p>An internal server error was encountered.</p></body></html>") #define NOT_FOUND_DATA QByteArray("Status: 404 Not Found\r\n" \ "Content-Length: 107\r\n" \ "Content-Type: text/html; charset=utf-8\r\n" \ "\r\n" \ "<html><head><title>Error</title></head><body><p>The document you requested was not found.</p></body></html>") #define POST_DATA QByteArray("Status: 200 OK\r\n" \ "Content-Length: 27\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "method=POST|path=/|post=bar") #define ROOT_DATA QByteArray("Status: 200 OK\r\n" \ "Content-Length: 17\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "method=GET|path=/") #define QUERY_STRING_DATA QByteArray("Status: 200 OK\r\n" \ "Content-Length: 25\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "method=GET|path=/|get=bar") class QDjangoFastCgiReply : public QObject { Q_OBJECT public: QDjangoFastCgiReply(QObject *parent = 0) : QObject(parent) {}; QByteArray data; signals: void finished(); }; class QDjangoFastCgiClient : public QObject { Q_OBJECT public: QDjangoFastCgiClient(QIODevice *socket); QDjangoFastCgiReply* request(const QString &method, const QUrl &url, const QByteArray &data); private slots: void _q_readyRead(); private: QIODevice *m_device; QMap<quint16, QDjangoFastCgiReply*> m_replies; quint16 m_requestId; }; QDjangoFastCgiClient::QDjangoFastCgiClient(QIODevice *socket) : m_device(socket) , m_requestId(0) { connect(socket, SIGNAL(readyRead()), this, SLOT(_q_readyRead())); }; QDjangoFastCgiReply* QDjangoFastCgiClient::request(const QString &method, const QUrl &url, const QByteArray &data) { const quint16 requestId = ++m_requestId; QDjangoFastCgiReply *reply = new QDjangoFastCgiReply(this); m_replies[requestId] = reply; QByteArray headerBuffer(FCGI_HEADER_LEN, '\0'); FCGI_Header *header = (FCGI_Header*)headerBuffer.data(); QByteArray ba; // BEGIN REQUEST ba = QByteArray("\x01\x00\x00\x00\x00\x00\x00\x00", 8); header->version = 1; FCGI_Header_setRequestId(header, requestId); header->type = FCGI_BEGIN_REQUEST; FCGI_Header_setContentLength(header, ba.size()); m_device->write(headerBuffer + ba); QMap<QByteArray, QByteArray> params; params["PATH_INFO"] = url.path().toUtf8(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) params["QUERY_STRING"] = url.query().toUtf8(); #else params["QUERY_STRING"] = url.encodedQuery(); #endif params["REQUEST_URI"] = url.toString().toUtf8(); params["REQUEST_METHOD"] = method.toUtf8(); ba.clear(); foreach (const QByteArray &key, params.keys()) { const QByteArray value = params.value(key); ba.append(char(key.size())); ba.append(char(value.size())); ba.append(key); ba.append(value); } // FAST CGI PARAMS header->type = FCGI_PARAMS; FCGI_Header_setContentLength(header, ba.size()); m_device->write(headerBuffer + ba); // STDIN if (data.size() > 0) { header->type = FCGI_STDIN; FCGI_Header_setContentLength(header, data.size()); m_device->write(headerBuffer + data); } header->type = FCGI_STDIN; FCGI_Header_setContentLength(header, 0); m_device->write(headerBuffer); return reply; } void QDjangoFastCgiClient::_q_readyRead() { char inputBuffer[FCGI_RECORD_SIZE]; FCGI_Header *header = (FCGI_Header*)inputBuffer; while (m_device->bytesAvailable()) { if (m_device->read(inputBuffer, FCGI_HEADER_LEN) != FCGI_HEADER_LEN) { qWarning("header read fail"); return; } const quint16 contentLength = FCGI_Header_contentLength(header); const quint16 requestId = FCGI_Header_requestId(header); const quint16 bodyLength = contentLength + header->paddingLength; if (m_device->read(inputBuffer + FCGI_HEADER_LEN, bodyLength) != bodyLength) { qWarning("body read fail"); return; } if (!m_replies.contains(requestId)) { qWarning() << "unknown request" << requestId; return; } if (header->type == FCGI_STDOUT) { const QByteArray data = QByteArray(inputBuffer + FCGI_HEADER_LEN, contentLength); m_replies[requestId]->data += data; } else if (header->type == FCGI_END_REQUEST) { QMetaObject::invokeMethod(m_replies[requestId], "finished"); } } } /** Test QDjangoFastCgiServer class. */ class tst_QDjangoFastCgiServer : public QObject { Q_OBJECT private slots: void cleanup(); void init(); void testLocal_data(); void testLocal(); void testTcp_data(); void testTcp(); QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request); private: QDjangoFastCgiServer *server; }; void tst_QDjangoFastCgiServer::cleanup() { server->close(); delete server; } void tst_QDjangoFastCgiServer::init() { server = new QDjangoFastCgiServer; server->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index"); server->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error"); } void tst_QDjangoFastCgiServer::testLocal_data() { QTest::addColumn<QString>("method"); QTest::addColumn<QString>("path"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<QByteArray>("response"); QTest::newRow("root") << "GET" << "/" << QByteArray() << ROOT_DATA; QTest::newRow("query-string") << "GET" << "/?message=bar" << QByteArray() << QUERY_STRING_DATA; QTest::newRow("not-found") << "GET" << "/not-found" << QByteArray() << NOT_FOUND_DATA; QTest::newRow("internal-server-error") << "GET" << "/internal-server-error" << QByteArray() << ERROR_DATA; QTest::newRow("post") << "POST" << "/" << QByteArray("message=bar") << POST_DATA; } void tst_QDjangoFastCgiServer::testLocal() { QFETCH(QString, method); QFETCH(QString, path); QFETCH(QByteArray, data); QFETCH(QByteArray, response); const QString name("/tmp/qdjangofastcgi.socket"); QCOMPARE(server->listen(name), true); QLocalSocket socket; socket.connectToServer(name); QEventLoop loop; QDjangoFastCgiClient client(&socket); // check socket is connected QCOMPARE(socket.state(), QLocalSocket::ConnectedState); // wait for reply QDjangoFastCgiReply *reply = client.request(method, path, data); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::ConnectedState); QCOMPARE(reply->data, response); // wait for connection to close QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::UnconnectedState); } void tst_QDjangoFastCgiServer::testTcp_data() { QTest::addColumn<QString>("method"); QTest::addColumn<QString>("path"); QTest::addColumn<QByteArray>("data"); QTest::addColumn<QByteArray>("response"); QTest::newRow("root") << "GET" << "/" << QByteArray() << ROOT_DATA; QTest::newRow("query-string") << "GET" << "/?message=bar" << QByteArray() << QUERY_STRING_DATA; QTest::newRow("not-found") << "GET" << "/not-found" << QByteArray() << NOT_FOUND_DATA; QTest::newRow("internal-server-error") << "GET" << "/internal-server-error" << QByteArray() << ERROR_DATA; QTest::newRow("post") << "POST" << "/" << QByteArray("message=bar") << POST_DATA; } void tst_QDjangoFastCgiServer::testTcp() { QFETCH(QString, method); QFETCH(QString, path); QFETCH(QByteArray, data); QFETCH(QByteArray, response); QCOMPARE(server->listen(QHostAddress::LocalHost, 8123), true); QTcpSocket socket; socket.connectToHost("127.0.0.1", 8123); QEventLoop loop; QDjangoFastCgiClient client(&socket); // wait for socket to connect QObject::connect(&socket, SIGNAL(connected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QAbstractSocket::ConnectedState); // wait for reply QDjangoFastCgiReply *reply = client.request(method, path, data); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QAbstractSocket::ConnectedState); QCOMPARE(reply->data, response); // wait for connection to close QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QAbstractSocket::UnconnectedState); } QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_index(const QDjangoHttpRequest &request) { QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); QString output = QLatin1String("method=") + request.method(); output += QLatin1String("|path=") + request.path(); const QString getValue = request.get(QLatin1String("message")); if (!getValue.isEmpty()) output += QLatin1String("|get=") + getValue; const QString postValue = request.post(QLatin1String("message")); if (!postValue.isEmpty()) output += QLatin1String("|post=") + postValue; response->setBody(output.toUtf8()); return response; } QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_error(const QDjangoHttpRequest &request) { Q_UNUSED(request); return QDjangoHttpController::serveInternalServerError(request); } QTEST_MAIN(tst_QDjangoFastCgiServer) #include "tst_qdjangofastcgiserver.moc"
test POST over fastcgi (local + tcp)
test POST over fastcgi (local + tcp)
C++
lgpl-2.1
paradoxon82/qdjango,jlaine/qdjango,ericLemanissier/qdjango,jlaine/qdjango,ericLemanissier/qdjango,paradoxon82/qdjango,jlaine/qdjango,paradoxon82/qdjango,jlaine/qdjango,jlaine/qdjango,paradoxon82/qdjango,ericLemanissier/qdjango,ericLemanissier/qdjango,paradoxon82/qdjango,ericLemanissier/qdjango
92198ceefad53fa165f848652788301726dddc95
src/bp/session/Write.cxx
src/bp/session/Write.cxx
/* * Copyright 2007-2022 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "Write.hxx" #include "File.hxx" #include "Session.hxx" #include "io/BufferedOutputStream.hxx" #include "util/SpanCast.hxx" #include <stdexcept> #include <stdint.h> namespace { class SessionSerializerError final : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class FileWriter { BufferedOutputStream &os; public: explicit FileWriter(BufferedOutputStream &_os) noexcept :os(_os) {} void WriteBuffer(const void *buffer, size_t size) { os.Write(buffer, size); } template<typename T> void WriteT(T &value) { os.WriteT<T>(value); } void WriteBool(const bool &value) { WriteT(value); } void Write16(const uint16_t &value) { WriteT(value); } void Write32(const uint32_t &value) { WriteT(value); } void Write64(const uint64_t &value) { WriteT(value); } void Write(const Expiry &value) { WriteT(value); } void Write(const char *s) { if (s == nullptr) { Write16((uint16_t)-1); return; } uint32_t length = strlen(s); if (length >= (uint16_t)-1) throw SessionSerializerError("String is too long"); Write16(length); WriteBuffer(s, length); } void Write(std::span<const std::byte> buffer) { if (buffer.data() == nullptr) { Write16((uint16_t)-1); return; } if (buffer.size() >= (uint16_t)-1) throw SessionSerializerError("Buffer is too long"); Write16(buffer.size()); WriteBuffer(buffer.data(), buffer.size()); } void Write(std::string_view s) { Write(AsBytes(s)); } }; } void session_write_magic(BufferedOutputStream &os, uint32_t magic) { FileWriter file(os); file.Write32(magic); } void session_write_file_header(BufferedOutputStream &os) { FileWriter file(os); file.Write32(MAGIC_FILE); file.Write32(sizeof(Session)); } void session_write_file_tail(BufferedOutputStream &file) { session_write_magic(file, MAGIC_END_OF_LIST); } static void WriteWidgetSessions(FileWriter &file, const WidgetSession::Set &widgets); static void WriteWidgetSession(FileWriter &file, const WidgetSession &session) { file.Write(session.id); WriteWidgetSessions(file, session.children); file.Write(session.path_info); file.Write(session.query_string); file.Write32(MAGIC_END_OF_RECORD); } static void WriteWidgetSessions(FileWriter &file, const WidgetSession::Set &widgets) { for (const auto &ws : widgets) { file.Write32(MAGIC_WIDGET_SESSION); WriteWidgetSession(file, ws); } file.Write32(MAGIC_END_OF_LIST); } static void WriteCookie(FileWriter &file, const Cookie &cookie) { file.Write(cookie.name); file.Write(cookie.value); file.Write(cookie.domain); file.Write(cookie.path); file.Write(cookie.expires); file.Write32(MAGIC_END_OF_RECORD); } static void WriteCookieJar(FileWriter &file, const CookieJar &jar) { for (const auto &cookie : jar.cookies) { file.Write32(MAGIC_COOKIE); WriteCookie(file, cookie); } file.Write32(MAGIC_END_OF_LIST); } static void WriteRealmSession(FileWriter &file, const RealmSession &session) { file.Write(session.realm); file.Write(session.site); file.Write(session.user); file.Write(session.user_expires); WriteWidgetSessions(file, session.widgets); WriteCookieJar(file, session.cookies); file.WriteT(session.session_cookie_same_site); file.Write32(MAGIC_END_OF_RECORD); } void session_write(BufferedOutputStream &os, const Session *session) { FileWriter file(os); file.WriteT(session->id); file.Write(session->expires); file.WriteT(session->counter); file.WriteBool(session->cookie_received); file.Write(session->translate); file.Write(session->language); for (const auto &realm : session->realms) { file.Write32(MAGIC_REALM_SESSION); WriteRealmSession(file, realm); } file.Write32(MAGIC_END_OF_LIST); file.Write32(MAGIC_END_OF_RECORD); }
/* * Copyright 2007-2022 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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 "Write.hxx" #include "File.hxx" #include "Session.hxx" #include "io/BufferedOutputStream.hxx" #include "util/SpanCast.hxx" #include <cstdint> #include <stdexcept> namespace { class SessionSerializerError final : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class FileWriter { BufferedOutputStream &os; public: explicit FileWriter(BufferedOutputStream &_os) noexcept :os(_os) {} void WriteBuffer(const void *buffer, size_t size) { os.Write(buffer, size); } template<typename T> void WriteT(T &value) { os.WriteT<T>(value); } void WriteBool(const bool &value) { WriteT(value); } void Write16(const uint16_t &value) { WriteT(value); } void Write32(const uint32_t &value) { WriteT(value); } void Write64(const uint64_t &value) { WriteT(value); } void Write(const Expiry &value) { WriteT(value); } void Write(const char *s) { if (s == nullptr) { Write16(UINT16_MAX); return; } uint32_t length = strlen(s); if (length >= UINT16_MAX) throw SessionSerializerError("String is too long"); Write16(length); WriteBuffer(s, length); } void Write(std::span<const std::byte> buffer) { if (buffer.data() == nullptr) { Write16(UINT16_MAX); return; } if (buffer.size() >= UINT16_MAX) throw SessionSerializerError("Buffer is too long"); Write16(buffer.size()); WriteBuffer(buffer.data(), buffer.size()); } void Write(std::string_view s) { Write(AsBytes(s)); } }; } void session_write_magic(BufferedOutputStream &os, uint32_t magic) { FileWriter file(os); file.Write32(magic); } void session_write_file_header(BufferedOutputStream &os) { FileWriter file(os); file.Write32(MAGIC_FILE); file.Write32(sizeof(Session)); } void session_write_file_tail(BufferedOutputStream &file) { session_write_magic(file, MAGIC_END_OF_LIST); } static void WriteWidgetSessions(FileWriter &file, const WidgetSession::Set &widgets); static void WriteWidgetSession(FileWriter &file, const WidgetSession &session) { file.Write(session.id); WriteWidgetSessions(file, session.children); file.Write(session.path_info); file.Write(session.query_string); file.Write32(MAGIC_END_OF_RECORD); } static void WriteWidgetSessions(FileWriter &file, const WidgetSession::Set &widgets) { for (const auto &ws : widgets) { file.Write32(MAGIC_WIDGET_SESSION); WriteWidgetSession(file, ws); } file.Write32(MAGIC_END_OF_LIST); } static void WriteCookie(FileWriter &file, const Cookie &cookie) { file.Write(cookie.name); file.Write(cookie.value); file.Write(cookie.domain); file.Write(cookie.path); file.Write(cookie.expires); file.Write32(MAGIC_END_OF_RECORD); } static void WriteCookieJar(FileWriter &file, const CookieJar &jar) { for (const auto &cookie : jar.cookies) { file.Write32(MAGIC_COOKIE); WriteCookie(file, cookie); } file.Write32(MAGIC_END_OF_LIST); } static void WriteRealmSession(FileWriter &file, const RealmSession &session) { file.Write(session.realm); file.Write(session.site); file.Write(session.user); file.Write(session.user_expires); WriteWidgetSessions(file, session.widgets); WriteCookieJar(file, session.cookies); file.WriteT(session.session_cookie_same_site); file.Write32(MAGIC_END_OF_RECORD); } void session_write(BufferedOutputStream &os, const Session *session) { FileWriter file(os); file.WriteT(session->id); file.Write(session->expires); file.WriteT(session->counter); file.WriteBool(session->cookie_received); file.Write(session->translate); file.Write(session->language); for (const auto &realm : session->realms) { file.Write32(MAGIC_REALM_SESSION); WriteRealmSession(file, realm); } file.Write32(MAGIC_END_OF_LIST); file.Write32(MAGIC_END_OF_RECORD); }
use UINT16_MAX
bp/session/Write: use UINT16_MAX
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
81a085a2598a877a02dbedf9d91e7bf899fb2f02
lib/Support/FileUtilities.cpp
lib/Support/FileUtilities.cpp
//===- Support/FileUtilities.cpp - File System Utilities ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a family of utility functions which are useful for doing // various things with files. // //===----------------------------------------------------------------------===// #include "Support/FileUtilities.h" #include "Config/unistd.h" #include "Config/sys/stat.h" #include "Config/sys/types.h" #include <fstream> #include <iostream> #include <cstdio> using namespace llvm; /// CheckMagic - Returns true IFF the file named FN begins with Magic. FN must /// name a readable file. /// bool llvm::CheckMagic(const std::string &FN, const std::string &Magic) { char buf[1 + Magic.size ()]; std::ifstream f (FN.c_str ()); f.read (buf, Magic.size ()); buf[Magic.size ()] = '\0'; return Magic == buf; } /// IsArchive - Returns true IFF the file named FN appears to be a "ar" library /// archive. The file named FN must exist. /// bool llvm::IsArchive(const std::string &FN) { // Inspect the beginning of the file to see if it contains the "ar" // library archive format magic string. return CheckMagic (FN, "!<arch>\012"); } /// IsBytecode - Returns true IFF the file named FN appears to be an LLVM /// bytecode file. The file named FN must exist. /// bool llvm::IsBytecode(const std::string &FN) { // Inspect the beginning of the file to see if it contains the LLVM // bytecode format magic string. return CheckMagic (FN, "llvm"); } /// IsSharedObject - Returns trus IFF the file named FN appears to be a shared /// object with an ELF header. The file named FN must exist. /// bool llvm::IsSharedObject(const std::string &FN) { // Inspect the beginning of the file to see if it contains the ELF shared // object magic string. static const char elfMagic[] = { 0x7f, 'E', 'L', 'F', '\0' }; return CheckMagic(FN, elfMagic); } /// FileOpenable - Returns true IFF Filename names an existing regular /// file which we can successfully open. /// bool llvm::FileOpenable(const std::string &Filename) { struct stat s; if (stat (Filename.c_str (), &s) == -1) return false; // Cannot stat file if (!S_ISREG (s.st_mode)) return false; // File is not a regular file std::ifstream FileStream (Filename.c_str ()); if (!FileStream) return false; // File is not openable return true; } /// DiffFiles - Compare the two files specified, returning true if they are /// different or if there is a file error. If you specify a string to fill in /// for the error option, it will set the string to an error message if an error /// occurs, allowing the caller to distinguish between a failed diff and a file /// system error. /// bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB, std::string *Error) { std::ifstream FileAStream(FileA.c_str()); if (!FileAStream) { if (Error) *Error = "Couldn't open file '" + FileA + "'"; return true; } std::ifstream FileBStream(FileB.c_str()); if (!FileBStream) { if (Error) *Error = "Couldn't open file '" + FileB + "'"; return true; } // Compare the two files... int C1, C2; do { C1 = FileAStream.get(); C2 = FileBStream.get(); if (C1 != C2) return true; } while (C1 != EOF); return false; } /// MoveFileOverIfUpdated - If the file specified by New is different than Old, /// or if Old does not exist, move the New file over the Old file. Otherwise, /// remove the New file. /// void llvm::MoveFileOverIfUpdated(const std::string &New, const std::string &Old) { if (DiffFiles(New, Old)) { if (std::rename(New.c_str(), Old.c_str())) std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n"; } else { std::remove(New.c_str()); } } /// removeFile - Delete the specified file /// void llvm::removeFile(const std::string &Filename) { std::remove(Filename.c_str()); } /// getUniqueFilename - Return a filename with the specified prefix. If the /// file does not exist yet, return it, otherwise add a suffix to make it /// unique. /// std::string llvm::getUniqueFilename(const std::string &FilenameBase) { if (!std::ifstream(FilenameBase.c_str())) return FilenameBase; // Couldn't open the file? Use it! // Create a pattern for mkstemp... char *FNBuffer = new char[FilenameBase.size()+8]; strcpy(FNBuffer, FilenameBase.c_str()); strcpy(FNBuffer+FilenameBase.size(), "-XXXXXX"); // Agree on a temporary file name to use.... int TempFD; if ((TempFD = mkstemp(FNBuffer)) == -1) { std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current " << " directory!\n"; exit(1); } // We don't need to hold the temp file descriptor... we will trust that no one // will overwrite/delete the file while we are working on it... close(TempFD); std::string Result(FNBuffer); delete[] FNBuffer; return Result; } static bool AddPermissionsBits (const std::string &Filename, mode_t bits) { // Get the umask value from the operating system. We want to use it // when changing the file's permissions. Since calling umask() sets // the umask and returns its old value, we must call it a second // time to reset it to the user's preference. mode_t mask = umask (0777); // The arg. to umask is arbitrary... umask (mask); // Get the file's current mode. struct stat st; if ((stat (Filename.c_str(), &st)) == -1) return false; // Change the file to have whichever permissions bits from 'bits' // that the umask would not disable. if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1) return false; return true; } /// MakeFileExecutable - Make the file named Filename executable by /// setting whichever execute permissions bits the process's current /// umask would allow. Filename must name an existing file or /// directory. Returns true on success, false on error. /// bool llvm::MakeFileExecutable(const std::string &Filename) { return AddPermissionsBits(Filename, 0111); } /// MakeFileReadable - Make the file named Filename readable by /// setting whichever read permissions bits the process's current /// umask would allow. Filename must name an existing file or /// directory. Returns true on success, false on error. /// bool llvm::MakeFileReadable(const std::string &Filename) { return AddPermissionsBits(Filename, 0444); } /// getFileSize - Return the size of the specified file in bytes, or -1 if the /// file cannot be read or does not exist. long long llvm::getFileSize(const std::string &Filename) { struct stat StatBuf; if (stat(Filename.c_str(), &StatBuf) == -1) return -1; return StatBuf.st_size; } //===----------------------------------------------------------------------===// // FDHandle class implementation // FDHandle::~FDHandle() throw() { if (FD != -1) close(FD); } FDHandle &FDHandle::operator=(int fd) throw() { if (FD != -1) close(FD); FD = fd; return *this; }
//===- Support/FileUtilities.cpp - File System Utilities ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a family of utility functions which are useful for doing // various things with files. // //===----------------------------------------------------------------------===// #include "Support/FileUtilities.h" #include "Config/unistd.h" #include "Config/sys/stat.h" #include "Config/sys/types.h" #include <fstream> #include <iostream> #include <cstdio> using namespace llvm; /// CheckMagic - Returns true IFF the file named FN begins with Magic. FN must /// name a readable file. /// bool llvm::CheckMagic(const std::string &FN, const std::string &Magic) { char buf[1 + Magic.size ()]; std::ifstream f (FN.c_str ()); f.read (buf, Magic.size ()); buf[Magic.size ()] = '\0'; return Magic == buf; } /// IsArchive - Returns true IFF the file named FN appears to be a "ar" library /// archive. The file named FN must exist. /// bool llvm::IsArchive(const std::string &FN) { // Inspect the beginning of the file to see if it contains the "ar" // library archive format magic string. return CheckMagic (FN, "!<arch>\012"); } /// IsBytecode - Returns true IFF the file named FN appears to be an LLVM /// bytecode file. The file named FN must exist. /// bool llvm::IsBytecode(const std::string &FN) { // Inspect the beginning of the file to see if it contains the LLVM // bytecode format magic string. return CheckMagic (FN, "llvm"); } /// IsSharedObject - Returns trus IFF the file named FN appears to be a shared /// object with an ELF header. The file named FN must exist. /// bool llvm::IsSharedObject(const std::string &FN) { // Inspect the beginning of the file to see if it contains the ELF shared // object magic string. static const char elfMagic[] = { 0x7f, 'E', 'L', 'F', '\0' }; return CheckMagic(FN, elfMagic); } /// FileOpenable - Returns true IFF Filename names an existing regular /// file which we can successfully open. /// bool llvm::FileOpenable(const std::string &Filename) { struct stat s; if (stat (Filename.c_str (), &s) == -1) return false; // Cannot stat file if (!S_ISREG (s.st_mode)) return false; // File is not a regular file std::ifstream FileStream (Filename.c_str ()); if (!FileStream) return false; // File is not openable return true; } /// DiffFiles - Compare the two files specified, returning true if they are /// different or if there is a file error. If you specify a string to fill in /// for the error option, it will set the string to an error message if an error /// occurs, allowing the caller to distinguish between a failed diff and a file /// system error. /// bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB, std::string *Error) { std::ifstream FileAStream(FileA.c_str()); if (!FileAStream) { if (Error) *Error = "Couldn't open file '" + FileA + "'"; return true; } std::ifstream FileBStream(FileB.c_str()); if (!FileBStream) { if (Error) *Error = "Couldn't open file '" + FileB + "'"; return true; } // Compare the two files... int C1, C2; do { C1 = FileAStream.get(); C2 = FileBStream.get(); if (C1 != C2) return true; } while (C1 != EOF); return false; } /// MoveFileOverIfUpdated - If the file specified by New is different than Old, /// or if Old does not exist, move the New file over the Old file. Otherwise, /// remove the New file. /// void llvm::MoveFileOverIfUpdated(const std::string &New, const std::string &Old) { if (DiffFiles(New, Old)) { if (std::rename(New.c_str(), Old.c_str())) std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n"; } else { std::remove(New.c_str()); } } /// removeFile - Delete the specified file /// void llvm::removeFile(const std::string &Filename) { std::remove(Filename.c_str()); } /// getUniqueFilename - Return a filename with the specified prefix. If the /// file does not exist yet, return it, otherwise add a suffix to make it /// unique. /// std::string llvm::getUniqueFilename(const std::string &FilenameBase) { if (!std::ifstream(FilenameBase.c_str())) return FilenameBase; // Couldn't open the file? Use it! // Create a pattern for mkstemp... char *FNBuffer = new char[FilenameBase.size()+8]; strcpy(FNBuffer, FilenameBase.c_str()); strcpy(FNBuffer+FilenameBase.size(), "-XXXXXX"); // Agree on a temporary file name to use.... int TempFD; if ((TempFD = mkstemp(FNBuffer)) == -1) { std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current " << " directory!\n"; exit(1); } // We don't need to hold the temp file descriptor... we will trust that no one // will overwrite/delete the file while we are working on it... close(TempFD); std::string Result(FNBuffer); delete[] FNBuffer; return Result; } static bool AddPermissionsBits (const std::string &Filename, mode_t bits) { // Get the umask value from the operating system. We want to use it // when changing the file's permissions. Since calling umask() sets // the umask and returns its old value, we must call it a second // time to reset it to the user's preference. mode_t mask = umask (0777); // The arg. to umask is arbitrary... umask (mask); // Get the file's current mode. struct stat st; if ((stat (Filename.c_str(), &st)) == -1) return false; // Change the file to have whichever permissions bits from 'bits' // that the umask would not disable. if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1) return false; return true; } /// MakeFileExecutable - Make the file named Filename executable by /// setting whichever execute permissions bits the process's current /// umask would allow. Filename must name an existing file or /// directory. Returns true on success, false on error. /// bool llvm::MakeFileExecutable(const std::string &Filename) { return AddPermissionsBits(Filename, 0111); } /// MakeFileReadable - Make the file named Filename readable by /// setting whichever read permissions bits the process's current /// umask would allow. Filename must name an existing file or /// directory. Returns true on success, false on error. /// bool llvm::MakeFileReadable(const std::string &Filename) { return AddPermissionsBits(Filename, 0444); } /// getFileSize - Return the size of the specified file in bytes, or -1 if the /// file cannot be read or does not exist. long long llvm::getFileSize(const std::string &Filename) { struct stat StatBuf; if (stat(Filename.c_str(), &StatBuf) == -1) return -1; return StatBuf.st_size; } /// getFileTimestamp - Get the last modified time for the specified file in an /// unspecified format. This is useful to allow checking to see if a file was /// updated since that last time the timestampt was aquired. If the file does /// not exist or there is an error getting the time-stamp, zero is returned. unsigned long long llvm::getFileTimestamp(const std::string &Filename) { struct stat StatBuf; if (stat(Filename.c_str(), &StatBuf) == -1) return 0; return StatBuf.st_mtime; } //===----------------------------------------------------------------------===// // FDHandle class implementation // FDHandle::~FDHandle() throw() { if (FD != -1) close(FD); } FDHandle &FDHandle::operator=(int fd) throw() { if (FD != -1) close(FD); FD = fd; return *this; }
Add new function
Add new function git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@10664 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap
4cba69e7edac2ab98d48198fda118d4c97084edf
Tournament/SadisticShooter.hpp
Tournament/SadisticShooter.hpp
// SadisticShooter by muddyfish // PPCG: http://codegolf.stackexchange.com/a/104947/11933 // SadisticShooter.hpp // A very sad person. He likes to shoot people. #ifndef __SAD_SHOOTER_PLAYER_HPP__ #define __SAD_SHOOTER_PLAYER_HPP__ #include <cstdlib> #include "Player.hpp" // #include <iostream> class SadisticShooter final : public Player { public: SadisticShooter(size_t opponent = -1) : Player(opponent) {} private: bool historySame(std::vector<Action> history, int elements) { if (history.size() < elements) return false; std::vector<Action> lastElements(history.end() - elements, history.end()); for (Action const &action : lastElements) if (action != lastElements[0]) return false; return true; } public: virtual Action fight() { int my_ammo = getAmmo(); int opponent_ammo = getAmmoOpponent(); int turn_number = getTurn(); //std::cout << " :: Turn " << turn_number << " ammo: " << my_ammo << " oppo: " << opponent_ammo << std::endl; if (turn_number == 90) { // Getting impatient return load(); } if (my_ammo == 0 && opponent_ammo == 0) { // It would be idiotic not to load here return load(); } if (my_ammo >= 2 && historySame(getHistoryOpponent(), 3)) { if (getHistoryOpponent()[turn_number - 1] == THERMAL) return bullet(); if (getHistoryOpponent()[turn_number - 1] == METAL) return thermal(); } if (my_ammo < 2 && opponent_ammo == 1) { // I'd rather not die thank you very much return metal(); } if (my_ammo == 1) { if (opponent_ammo == 0) { // You think I would just shoot you? return load(); } if (turn_number == 2) { return thermal(); } return bullet(); } if (opponent_ammo >= 2) { // Your plasma weapon doesn't scare me return thermal(); } if (my_ammo >= 2) { // 85% more bullet per bullet if (turn_number == 4) return bullet(); return plasma(); } // Just load the gun already return load(); } }; #endif // !__SAD_SHOOTER_PLAYER_HPP__
// SadisticShooter by muddyfish // PPCG: http://codegolf.stackexchange.com/a/104947/11933 // SadisticShooter.hpp // A very sad person. He likes to shoot people. #ifndef __SAD_SHOOTER_PLAYER_HPP__ #define __SAD_SHOOTER_PLAYER_HPP__ #include <cstdlib> #include "Player.hpp" // #include <iostream> class SadisticShooter final : public Player { public: SadisticShooter(size_t opponent = -1) : Player(opponent) {} private: bool historySame(std::vector<Action> const &history, int elements) { if (history.size() < elements) return false; std::vector<Action> lastElements(history.end() - elements, history.end()); for (Action const &action : lastElements) if (action != lastElements[0]) return false; return true; } public: virtual Action fight() { int my_ammo = getAmmo(); int opponent_ammo = getAmmoOpponent(); int turn_number = getTurn(); //std::cout << " :: Turn " << turn_number << " ammo: " << my_ammo << " oppo: " << opponent_ammo << std::endl; if (turn_number == 90) { // Getting impatient return load(); } if (my_ammo == 0 && opponent_ammo == 0) { // It would be idiotic not to load here return load(); } if (my_ammo >= 2 && historySame(getHistoryOpponent(), 3)) { if (getHistoryOpponent()[turn_number - 1] == THERMAL) return bullet(); if (getHistoryOpponent()[turn_number - 1] == METAL) return thermal(); } if (my_ammo < 2 && opponent_ammo == 1) { // I'd rather not die thank you very much return metal(); } if (my_ammo == 1) { if (opponent_ammo == 0) { // You think I would just shoot you? return load(); } if (turn_number == 2) { return thermal(); } return bullet(); } if (opponent_ammo >= 2) { // Your plasma weapon doesn't scare me return thermal(); } if (my_ammo >= 2) { // 85% more bullet per bullet if (turn_number == 4) return bullet(); return plasma(); } // Just load the gun already return load(); } }; #endif // !__SAD_SHOOTER_PLAYER_HPP__
Update historySame method
Update historySame method
C++
mit
FYPetro/GunDuel,FYPetro/GunDuel
19ebefff62dcee9feb777dec027ab35dd0b32f76
quantities/quantities_test.cpp
quantities/quantities_test.cpp
 #include <string> #include "glog/logging.h" #include "gtest/gtest.h" #include "quantities/astronomy.hpp" #include "quantities/BIPM.hpp" #include "quantities/constants.hpp" #include "quantities/elementary_functions.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" #include "quantities/uk.hpp" #include "testing_utilities/algebra.hpp" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/explicit_operators.hpp" #include "testing_utilities/numerics.hpp" using principia::astronomy::EarthMass; using principia::astronomy::JulianYear; using principia::astronomy::JupiterMass; using principia::astronomy::LightYear; using principia::astronomy::LunarDistance; using principia::astronomy::Parsec; using principia::astronomy::SolarMass; using principia::constants::ElectronMass; using principia::constants::GravitationalConstant; using principia::constants::SpeedOfLight; using principia::constants::StandardGravity; using principia::constants::VacuumPermeability; using principia::constants::VacuumPermittivity; using principia::si::Ampere; using principia::si::AstronomicalUnit; using principia::si::Candela; using principia::si::Cycle; using principia::si::Day; using principia::si::Degree; using principia::si::Hour; using principia::si::Kelvin; using principia::si::Kilogram; using principia::si::Mega; using principia::si::Metre; using principia::si::Mole; using principia::si::Radian; using principia::si::Second; using principia::si::Steradian; using principia::testing_utilities::AbsoluteError; using principia::testing_utilities::AlmostEquals; using principia::testing_utilities::RelativeError; using principia::testing_utilities::Times; using principia::uk::Foot; using principia::uk::Furlong; using principia::uk::Mile; using principia::uk::Rood; using testing::Lt; namespace principia { namespace quantities { class QuantitiesTest : public testing::Test { protected: }; TEST_F(QuantitiesTest, AbsoluteValue) { EXPECT_EQ(Abs(-1729), 1729); EXPECT_EQ(Abs(1729), 1729); } TEST_F(QuantitiesTest, DimensionfulComparisons) { testing_utilities::TestOrder(EarthMass, JupiterMass); testing_utilities::TestOrder(LightYear, Parsec); testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight); testing_utilities::TestOrder(SpeedOfLight * Day, LightYear); } TEST_F(QuantitiesTest, DimensionlfulOperations) { testing_utilities::TestVectorSpace( 0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour, -340.29 * Metre / Second, 0.0, 1.0, -2 * π, 1729.0, 2); // Dimensionful multiplication is a tensor product, see [Tao 2012]. testing_utilities::TestBilinearMap( Times<Product<Mass, Speed>, Mass, Speed>, SolarMass, ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 2); } TEST_F(QuantitiesTest, DimensionlessExponentiation) { double const number = π - 42; double positivePower = 1; double negativePower = 1; EXPECT_EQ(positivePower, Pow<0>(number)); positivePower *= number; negativePower /= number; EXPECT_EQ(positivePower, Pow<1>(number)); EXPECT_EQ(negativePower, Pow<-1>(number)); positivePower *= number; negativePower /= number; EXPECT_EQ(positivePower, Pow<2>(number)); EXPECT_EQ(negativePower, Pow<-2>(number)); positivePower *= number; negativePower /= number; EXPECT_EQ(positivePower, Pow<3>(number)); EXPECT_EQ(negativePower, Pow<-3>(number)); positivePower *= number; negativePower /= number; // This one calls |std::pow|. EXPECT_THAT(positivePower, AlmostEquals(Pow<4>(number))); EXPECT_THAT(negativePower, AlmostEquals(Pow<-4>(number))); } // The Greek letters cause a warning when stringified by the macros, because // apparently Visual Studio doesn't encode strings in UTF-8 by default. #pragma warning(disable: 4566) TEST_F(QuantitiesTest, Formatting) { auto const allTheUnits = 1 * Metre * Kilogram * Second * Ampere * Kelvin / (Mole * Candela * Cycle * Radian * Steradian); std::string const expected = std::string("1e+000 m kg s A K mol^-1") + " cd^-1 cycle^-1 rad^-1 sr^-1"; std::string const actual = DebugString(allTheUnits, 0); EXPECT_EQ(expected, actual); std::string π16 = "3.1415926535897931e+000"; EXPECT_EQ(DebugString(π), π16); } TEST_F(QuantitiesTest, PhysicalConstants) { // By definition. EXPECT_THAT(1 / Pow<2>(SpeedOfLight), AlmostEquals(VacuumPermittivity * VacuumPermeability, 2)); // The Keplerian approximation for the mass of the Sun // is fairly accurate. EXPECT_THAT(RelativeError( 4 * Pow<2>(π) * Pow<3>(AstronomicalUnit) / (GravitationalConstant * Pow<2>(JulianYear)), SolarMass), Lt(4E-5)); EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6)); // The Keplerian approximation for the mass of the Earth // is pretty bad, but the error is still only 1%. EXPECT_THAT(RelativeError( 4 * Pow<2>(π) * Pow<3>(LunarDistance) / (GravitationalConstant * Pow<2>(27.321582 * Day)), EarthMass), Lt(1E-2)); EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4)); // Delambre & Méchain. EXPECT_THAT(RelativeError( GravitationalConstant * EarthMass / Pow<2>(40 * Mega(Metre) / (2 * π)), StandardGravity), Lt(4E-3)); // Talleyrand. EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second), Lt(4E-3)); } #pragma warning(default: 4566) TEST_F(QuantitiesTest, TrigonometricFunctions) { EXPECT_EQ(Cos(0 * Degree), 1); EXPECT_EQ(Sin(0 * Degree), 0); EXPECT_THAT(AbsoluteError(Cos(90 * Degree), 0), Lt(1E-16)); EXPECT_EQ(Sin(90 * Degree), 1); EXPECT_EQ(Cos(180 * Degree), -1); EXPECT_THAT(AbsoluteError(Sin(180 * Degree), 0), Lt(1E-15)); EXPECT_THAT(AbsoluteError(Cos(-90 * Degree), 0), Lt(1E-16)); EXPECT_EQ(Sin(-90 * Degree), -1); for (int k = 1; k < 360; ++k) { // Don't test for multiples of 90 degrees as zeros lead to horrible // conditioning. if (k % 90 != 0) { EXPECT_THAT(Cos((90 - k) * Degree), AlmostEquals(Sin(k * Degree), 50)); EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree), AlmostEquals(Tan(k * Degree), 2)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)), 80)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit, Cos(k * Degree) * AstronomicalUnit), 80)); EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))), AlmostEquals(Cos(k * Degree), 10)); EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))), AlmostEquals(Sin(k * Degree), 1)); } } // Horribly conditioned near 0, so not in the loop above. EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree)); } TEST_F(QuantitiesTest, HyperbolicFunctions) { EXPECT_EQ(Sinh(0 * Radian), 0); EXPECT_EQ(Cosh(0 * Radian), 1); EXPECT_EQ(Tanh(0 * Radian), 0); // Limits: EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian)); EXPECT_EQ(Tanh(20 * Radian), 1); EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian)); EXPECT_EQ(Tanh(-20 * Radian), -1); EXPECT_EQ(Sinh(2 * Radian) / Cosh(2 * Radian), Tanh(2 * Radian)); EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)), AlmostEquals(-10 * Degree, 2)); EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)), AlmostEquals(10 * Degree, 20)); EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)), AlmostEquals(-10 * Degree, 1)); } TEST_F(QuantitiesTest, ExpLogAndSqrt) {; EXPECT_THAT(std::exp(std::log(2) / 2), AlmostEquals(Sqrt(2), 1)); EXPECT_EQ(std::exp(std::log(Rood / Pow<2>(Foot)) / 2) * Foot, Sqrt(Rood)); } } // namespace quantities } // namespace principia
 #include <string> #include "glog/logging.h" #include "gtest/gtest.h" #include "quantities/astronomy.hpp" #include "quantities/BIPM.hpp" #include "quantities/constants.hpp" #include "quantities/elementary_functions.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" #include "quantities/uk.hpp" #include "testing_utilities/algebra.hpp" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/explicit_operators.hpp" #include "testing_utilities/numerics.hpp" using principia::astronomy::EarthMass; using principia::astronomy::JulianYear; using principia::astronomy::JupiterMass; using principia::astronomy::LightYear; using principia::astronomy::LunarDistance; using principia::astronomy::Parsec; using principia::astronomy::SolarMass; using principia::constants::ElectronMass; using principia::constants::GravitationalConstant; using principia::constants::SpeedOfLight; using principia::constants::StandardGravity; using principia::constants::VacuumPermeability; using principia::constants::VacuumPermittivity; using principia::si::Ampere; using principia::si::AstronomicalUnit; using principia::si::Candela; using principia::si::Cycle; using principia::si::Day; using principia::si::Degree; using principia::si::Hour; using principia::si::Kelvin; using principia::si::Kilogram; using principia::si::Mega; using principia::si::Metre; using principia::si::Mole; using principia::si::Radian; using principia::si::Second; using principia::si::Steradian; using principia::testing_utilities::AbsoluteError; using principia::testing_utilities::AlmostEquals; using principia::testing_utilities::RelativeError; using principia::testing_utilities::Times; using principia::uk::Foot; using principia::uk::Furlong; using principia::uk::Mile; using principia::uk::Rood; using testing::Lt; namespace principia { namespace quantities { class QuantitiesTest : public testing::Test { protected: }; TEST_F(QuantitiesTest, AbsoluteValue) { EXPECT_EQ(Abs(-1729), 1729); EXPECT_EQ(Abs(1729), 1729); } TEST_F(QuantitiesTest, DimensionfulComparisons) { testing_utilities::TestOrder(EarthMass, JupiterMass); testing_utilities::TestOrder(LightYear, Parsec); testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight); testing_utilities::TestOrder(SpeedOfLight * Day, LightYear); } TEST_F(QuantitiesTest, DimensionlfulOperations) { testing_utilities::TestVectorSpace( 0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour, -340.29 * Metre / Second, 0.0, 1.0, -2 * π, 1729.0, 2); // Dimensionful multiplication is a tensor product, see [Tao 2012]. testing_utilities::TestBilinearMap( Times<Product<Mass, Speed>, Mass, Speed>, SolarMass, ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 2); } TEST_F(QuantitiesTest, DimensionlessExponentiation) { double const number = π - 42; double positivePower = 1; double negativePower = 1; EXPECT_EQ(positivePower, Pow<0>(number)); positivePower *= number; negativePower /= number; EXPECT_EQ(positivePower, Pow<1>(number)); EXPECT_EQ(negativePower, Pow<-1>(number)); positivePower *= number; negativePower /= number; EXPECT_EQ(positivePower, Pow<2>(number)); EXPECT_EQ(negativePower, Pow<-2>(number)); positivePower *= number; negativePower /= number; EXPECT_EQ(positivePower, Pow<3>(number)); EXPECT_EQ(negativePower, Pow<-3>(number)); positivePower *= number; negativePower /= number; // This one calls |std::pow|. EXPECT_THAT(positivePower, AlmostEquals(Pow<4>(number))); EXPECT_THAT(negativePower, AlmostEquals(Pow<-4>(number))); } // The Greek letters cause a warning when stringified by the macros, because // apparently Visual Studio doesn't encode strings in UTF-8 by default. #pragma warning(disable: 4566) TEST_F(QuantitiesTest, Formatting) { auto const allTheUnits = 1 * Metre * Kilogram * Second * Ampere * Kelvin / (Mole * Candela * Cycle * Radian * Steradian); #ifdef _MSC_VER std::string const expected = std::string("1e+000 m kg s A K mol^-1") + " cd^-1 cycle^-1 rad^-1 sr^-1"; #else std::string const expected = std::string("1e+00 m kg s A K mol^-1") + " cd^-1 cycle^-1 rad^-1 sr^-1"; #endif std::string const actual = DebugString(allTheUnits, 0); EXPECT_EQ(expected, actual); #ifdef _MSC_VER std::string π16 = "3.1415926535897931e+000"; #else std::string π16 = "3.1415926535897931e+00"; #endif EXPECT_EQ(DebugString(π), π16); } TEST_F(QuantitiesTest, PhysicalConstants) { // By definition. EXPECT_THAT(1 / Pow<2>(SpeedOfLight), AlmostEquals(VacuumPermittivity * VacuumPermeability, 2)); // The Keplerian approximation for the mass of the Sun // is fairly accurate. EXPECT_THAT(RelativeError( 4 * Pow<2>(π) * Pow<3>(AstronomicalUnit) / (GravitationalConstant * Pow<2>(JulianYear)), SolarMass), Lt(4E-5)); EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6)); // The Keplerian approximation for the mass of the Earth // is pretty bad, but the error is still only 1%. EXPECT_THAT(RelativeError( 4 * Pow<2>(π) * Pow<3>(LunarDistance) / (GravitationalConstant * Pow<2>(27.321582 * Day)), EarthMass), Lt(1E-2)); EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4)); // Delambre & Méchain. EXPECT_THAT(RelativeError( GravitationalConstant * EarthMass / Pow<2>(40 * Mega(Metre) / (2 * π)), StandardGravity), Lt(4E-3)); // Talleyrand. EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second), Lt(4E-3)); } #pragma warning(default: 4566) TEST_F(QuantitiesTest, TrigonometricFunctions) { EXPECT_EQ(Cos(0 * Degree), 1); EXPECT_EQ(Sin(0 * Degree), 0); EXPECT_THAT(AbsoluteError(Cos(90 * Degree), 0), Lt(1E-16)); EXPECT_EQ(Sin(90 * Degree), 1); EXPECT_EQ(Cos(180 * Degree), -1); EXPECT_THAT(AbsoluteError(Sin(180 * Degree), 0), Lt(1E-15)); EXPECT_THAT(AbsoluteError(Cos(-90 * Degree), 0), Lt(1E-16)); EXPECT_EQ(Sin(-90 * Degree), -1); for (int k = 1; k < 360; ++k) { // Don't test for multiples of 90 degrees as zeros lead to horrible // conditioning. if (k % 90 != 0) { EXPECT_THAT(Cos((90 - k) * Degree), AlmostEquals(Sin(k * Degree), 50)); EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree), AlmostEquals(Tan(k * Degree), 2)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)), 80)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit, Cos(k * Degree) * AstronomicalUnit), 80)); EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))), AlmostEquals(Cos(k * Degree), 10)); EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))), AlmostEquals(Sin(k * Degree), 1)); } } // Horribly conditioned near 0, so not in the loop above. EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree)); } TEST_F(QuantitiesTest, HyperbolicFunctions) { EXPECT_EQ(Sinh(0 * Radian), 0); EXPECT_EQ(Cosh(0 * Radian), 1); EXPECT_EQ(Tanh(0 * Radian), 0); // Limits: EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian)); EXPECT_EQ(Tanh(20 * Radian), 1); EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian)); EXPECT_EQ(Tanh(-20 * Radian), -1); EXPECT_EQ(Sinh(2 * Radian) / Cosh(2 * Radian), Tanh(2 * Radian)); EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)), AlmostEquals(-10 * Degree, 2)); EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)), AlmostEquals(10 * Degree, 20)); EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)), AlmostEquals(-10 * Degree, 1)); } TEST_F(QuantitiesTest, ExpLogAndSqrt) {; EXPECT_THAT(std::exp(std::log(2) / 2), AlmostEquals(Sqrt(2), 1)); EXPECT_EQ(std::exp(std::log(Rood / Pow<2>(Foot)) / 2) * Foot, Sqrt(Rood)); } } // namespace quantities } // namespace principia
Fix test
Fix test
C++
mit
eggrobin/Principia,pleroy/Principia,pleroy/Principia,Norgg/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,pleroy/Principia,eggrobin/Principia,mockingbirdnest/Principia,pleroy/Principia,Norgg/Principia,Norgg/Principia,mockingbirdnest/Principia,eggrobin/Principia,Norgg/Principia
993afe142b7dc11a00c0b0f823edbd340e836ef4
src/cbang/log/Logger.cpp
src/cbang/log/Logger.cpp
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2017, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland [email protected] \******************************************************************************/ #include "Logger.h" #include "LogDevice.h" #include <cbang/Exception.h> #include <cbang/String.h> #include <cbang/time/Time.h> #include <cbang/iostream/NullDevice.h> #include <cbang/os/SystemUtilities.h> #include <cbang/os/ThreadLocalStorage.h> #include <cbang/config/Options.h> #include <cbang/config/OptionActionSet.h> #include <cbang/util/SmartLock.h> #include <iostream> #include <stdio.h> // for freopen() #include <boost/ref.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/tee.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/filtering_stream.hpp> namespace io = boost::iostreams; using namespace std; using namespace cb; Logger::Logger(Inaccessible) : verbosity(DEFAULT_VERBOSITY), logCRLF(false), #ifdef DEBUG logDebug(true), #else logDebug(false), #endif logTime(true), logDate(false), logDatePeriodically(0), logShortLevel(false), logLevel(true), logThreadPrefix(false), logDomain(false), logSimpleDomains(true), logThreadID(false), logHeader(true), logNoInfoHeader(false), logColor(true), logToScreen(true), logTrunc(false), logRedirect(false), logRotate(true), logRotateMax(0), logRotateDir("logs"), threadIDStorage(new ThreadLocalStorage<unsigned long>), threadPrefixStorage(new ThreadLocalStorage<string>), screenStream(SmartPointer<ostream>::Phony(&cout)), idWidth(1), lastDate(Time::now()) { #ifdef _WIN32 logCRLF = true; logColor = false; // Windows does not handle ANSI color codes well #endif } void Logger::addOptions(Options &options) { options.pushCategory("Logging"); options.add("log", "Set log file."); options.addTarget("verbosity", verbosity, "Set logging level for INFO " #ifdef DEBUG "and DEBUG " #endif "messages."); options.addTarget("log-crlf", logCRLF, "Print carriage return and line feed " "at end of log lines."); #ifdef DEBUG options.addTarget("log-debug", logDebug, "Disable or enable debugging info."); #endif options.addTarget("log-time", logTime, "Print time information with log entries."); options.addTarget("log-date", logDate, "Print date information with log entries."); options.addTarget("log-date-periodically", logDatePeriodically, "Print date to log before new log entries if so many " "seconds have passed since the last date was printed."); options.addTarget("log-short-level", logShortLevel, "Print shortened level " "information with log entries."); options.addTarget("log-level", logLevel, "Print level information with log entries."); options.addTarget("log-thread-prefix", logThreadPrefix, "Print thread prefixes, if set, with log entries."); options.addTarget("log-domain", logDomain, "Print domain information with log entries."); options.addTarget("log-simple-domains", logSimpleDomains, "Remove any " "leading directories and trailing file extensions from " "domains so that source code file names can be easily used " "as log domains."); options.add("log-domain-levels", 0, new OptionAction<Logger>(this, &Logger::domainLevelsAction), "Set log levels by domain. Format is:\n" "\t<domain>[:i|d|t]:<level> ...\n" "Entries are separated by white-space and or commas.\n" "\ti - info\n" #ifdef DEBUG "\td - debug\n" #endif #ifdef HAVE_DEBUGGER "\tt - enable traces\n" #endif "For example: server:i:3 module:6\n" "Set 'server' domain info messages to level 3 and 'module' info " #ifdef DEBUG "and debug " #endif "messages to level 6. All other domains will follow " "the system wide log verbosity level.\n" "If <level> is negative it is relative to the system wide " "verbosity." )->setType(Option::STRINGS_TYPE); options.addTarget("log-thread-id", logThreadID, "Print id with log entries."); options.addTarget("log-header", logHeader, "Enable log message headers."); options.addTarget("log-no-info-header", logNoInfoHeader, "Don't print 'INFO(#):' in header."); options.addTarget("log-color", logColor, "Print log messages with ANSI color coding."); options.addTarget("log-to-screen", logToScreen, "Log to screen."); options.addTarget("log-truncate", logTrunc, "Truncate log file."); options.addTarget("log-redirect", logRedirect, "Redirect all output to log " "file. Implies !log-to-screen."); options.addTarget("log-rotate", logRotate, "Rotate log files on each run."); options.addTarget("log-rotate-dir", logRotateDir, "Put rotated logs in this directory."); options.addTarget("log-rotate-max", logRotateMax, "Maximum number of rotated logs to keep."); options.popCategory(); } void Logger::setOptions(Options &options) { if (options["log"].hasValue()) startLogFile(options["log"]); } int Logger::domainLevelsAction(Option &option) { setLogDomainLevels(option); return 0; } void Logger::setScreenStream(ostream &stream) { setScreenStream(SmartPointer<ostream>::Phony(&stream)); } void Logger::setScreenStream(const SmartPointer<std::ostream> &stream) { screenStream = stream; } void Logger::startLogFile(const string &filename) { // Rotate log if (logRotate) SystemUtilities::rotate(filename, logRotateDir, logRotateMax); logFile = SystemUtilities::open(filename, ios::out | (logTrunc ? ios::trunc : ios::app)); *logFile << String::bar(SSTR("Log Started " << Time())) << (logCRLF ? "\r\n" : "\n"); logFile->flush(); lastDate = Time::now(); if (logRedirect) { setLogToScreen(false); SystemUtilities::open(filename, ios::app | ios::out); // Test filename // Redirect standard error and out if (!freopen(filename.c_str(), "a", stdout) || !freopen(filename.c_str(), "a", stderr)) THROWS("Redirecting output to '" << filename << "'"); } } void Logger::setLogDomainLevels(const string &levels) { Option::strings_t entries; String::tokenize(levels, entries, Option::DEFAULT_DELIMS + ","); for (unsigned i = 0; i < entries.size(); i++) { vector<string> tokens; String::tokenize(entries[i], tokens, ":"); bool invalid = false; if (tokens.size() == 3) { int level = String::parseS32(tokens[2]); for (unsigned j = 0; j < tokens[1].size(); j++) switch (tokens[1][j]) { case 'i': infoDomainLevels[tokens[0]] = level; break; case 'd': debugDomainLevels[tokens[0]] = level; break; #ifdef HAVE_DEBUGGER case 't': domainTraces.insert(tokens[0]); break; #endif default: invalid = true; } } else if (tokens.size() == 2) { int level = String::parseS32(tokens[1]); infoDomainLevels[tokens[0]] = level; debugDomainLevels[tokens[0]] = level; } else invalid = true; if (invalid) THROWS("Invalid log domain level entry " << (i + 1) << " '" << entries[i] << "'"); } } unsigned Logger::getHeaderWidth() const { return getHeader("", LOG_INFO_LEVEL(10)).size(); } void Logger::setThreadID(unsigned long id) {threadIDStorage->set(id);} unsigned long Logger::getThreadID() const { return threadIDStorage->isSet() ? threadIDStorage->get() : 0; } void Logger::setThreadPrefix(const string &prefix) { threadPrefixStorage->set(prefix); } string Logger::getThreadPrefix() const { return threadPrefixStorage->isSet() ? threadPrefixStorage->get() : string(); } string Logger::simplifyDomain(const string &domain) const { if (!logSimpleDomains) return domain; size_t pos = domain.find_last_of(SystemUtilities::path_separators); size_t start = pos == string::npos ? 0 : pos + 1; size_t end = domain.find_last_of('.'); size_t len = end == string::npos ? end : end - start; return len ? domain.substr(start, len) : domain; } int Logger::domainVerbosity(const string &domain, int level) const { string dom = simplifyDomain(domain); domain_levels_t::const_iterator it; if ((level == LEVEL_DEBUG && (it = debugDomainLevels.find(dom)) != debugDomainLevels.end()) || (level == LEVEL_INFO && (it = infoDomainLevels.find(dom)) != infoDomainLevels.end())) { int verbosity = it->second; // If verbosity < 0 then it is relative to Logger::verbosity if (verbosity < 0) verbosity += this->verbosity; return verbosity; } return verbosity; } string Logger::getHeader(const string &domain, int level) const { string header; if (!logHeader || level == LEVEL_RAW) return header; int verbosity = level >> 8; level &= LEVEL_MASK; // Thread ID if (logThreadID) { string idStr = String::printf("%0*ld:", idWidth - 1, getThreadID()); if (idWidth < idStr.length()) { lock(); idWidth = idStr.length(); unlock(); } header += idStr; } // Date & Time if (logDate || logTime) { uint64_t now = Time::now(); // Must be the same time for both if (logDate) header += Time(now, "%Y-%m-%d:").toString(); if (logTime) header += Time(now, "%H:%M:%S:").toString(); } // Level if (logShortLevel) { switch (level) { case LEVEL_ERROR: header += "E"; break; case LEVEL_CRITICAL: header += "C"; break; case LEVEL_WARNING: header += "W"; break; case LEVEL_INFO: header += "I"; break; case LEVEL_DEBUG: header += "D"; break; default: THROWS("Unknown log level " << level); } // Verbosity if (level >= LEVEL_INFO && verbosity) header += String(verbosity); else header += ' '; header += ':'; } else if (logLevel) { switch (level) { case LEVEL_ERROR: header += "ERROR"; break; case LEVEL_CRITICAL: header += "CRITICAL"; break; case LEVEL_WARNING: header += "WARNING"; break; case LEVEL_INFO: if (!logNoInfoHeader) header += "INFO"; break; case LEVEL_DEBUG: header += "DEBUG"; break; default: THROWS("Unknown log level " << level); } if (!logNoInfoHeader || level != LEVEL_INFO) { // Verbosity if (level >= LEVEL_INFO && verbosity) header += string("(") + String(verbosity) + ")"; header += ':'; } } // Domain if (logDomain && domain != "") header += string(domain) + ':'; // Thread Prefix if (logThreadPrefix) header += getThreadPrefix(); return header; } const char *Logger::startColor(int level) const { if (!logColor) return ""; switch (level & LEVEL_MASK) { case LEVEL_ERROR: return "\033[91m"; case LEVEL_CRITICAL: return "\033[31m"; case LEVEL_WARNING: return "\033[93m"; case LEVEL_DEBUG: return "\033[92m"; default: return ""; } } const char *Logger::endColor(int level) const { if (!logColor) return ""; switch (level & LEVEL_MASK) { case LEVEL_ERROR: case LEVEL_CRITICAL: case LEVEL_WARNING: case LEVEL_DEBUG: return "\033[0m"; default: return ""; } } bool Logger::enabled(const string &domain, int level) const { unsigned verbosity = level >> 8; level &= LEVEL_MASK; if (!logDebug && level == LEVEL_DEBUG) return false; if (level >= LEVEL_INFO && domainVerbosity(domain, level) < (int)verbosity) return false; // All other log levels are always enabled return true; } Logger::LogStream Logger::createStream(const string &_domain, int level, const std::string &_prefix) { string domain = simplifyDomain(_domain); if (!enabled(domain, level)) return new NullStream<>; // Log date periodically if (logDatePeriodically && lastDate + logDatePeriodically <= Time::now()) { lastDate = Time::now(); write(String::bar(Time(lastDate, "Date: %Y-%m-%d").toString()) + (logCRLF ? "\r\n" : "\n")); } string prefix = startColor(level) + getHeader(domain, level) + _prefix; string suffix = endColor(level); string trailer; #ifdef HAVE_DEBUGGER if (domainTraces.find(domain) != domainTraces.end()) { StackTrace trace; Debugger::instance().getStackTrace(trace); for (int i = 0; i < 3; i++) trace.pop_front(); trailer = SSTR(trace); } #endif return new cb::LogStream(prefix, suffix, trailer); } streamsize Logger::write(const char *s, streamsize n) { if (!logFile.isNull()) logFile->write(s, n); if (logToScreen) screenStream->write(s, n); return n; } void Logger::write(const string &s) {write(s.c_str(), s.length());} bool Logger::flush() { if (!logFile.isNull()) logFile->flush(); if (logToScreen) screenStream->flush(); return true; }
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2017, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland [email protected] \******************************************************************************/ #include "Logger.h" #include "LogDevice.h" #include <cbang/Exception.h> #include <cbang/String.h> #include <cbang/time/Time.h> #include <cbang/iostream/NullDevice.h> #include <cbang/os/SystemUtilities.h> #include <cbang/os/ThreadLocalStorage.h> #include <cbang/config/Options.h> #include <cbang/config/OptionActionSet.h> #include <cbang/util/SmartLock.h> #include <iostream> #include <stdio.h> // for freopen() #include <boost/ref.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/tee.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/filtering_stream.hpp> namespace io = boost::iostreams; using namespace std; using namespace cb; Logger::Logger(Inaccessible) : verbosity(DEFAULT_VERBOSITY), logCRLF(false), #ifdef DEBUG logDebug(true), #else logDebug(false), #endif logTime(true), logDate(false), logDatePeriodically(0), logShortLevel(false), logLevel(true), logThreadPrefix(false), logDomain(false), logSimpleDomains(true), logThreadID(false), logHeader(true), logNoInfoHeader(false), logColor(true), logToScreen(true), logTrunc(false), logRedirect(false), logRotate(true), logRotateMax(0), logRotateDir("logs"), threadIDStorage(new ThreadLocalStorage<unsigned long>), threadPrefixStorage(new ThreadLocalStorage<string>), screenStream(SmartPointer<ostream>::Phony(&cout)), idWidth(1), lastDate(Time::now()) { #ifdef _WIN32 logCRLF = true; logColor = false; // Windows does not handle ANSI color codes well #endif } void Logger::addOptions(Options &options) { options.pushCategory("Logging"); options.add("log", "Set log file."); options.addTarget("verbosity", verbosity, "Set logging level for INFO " #ifdef DEBUG "and DEBUG " #endif "messages."); options.addTarget("log-crlf", logCRLF, "Print carriage return and line feed " "at end of log lines."); #ifdef DEBUG options.addTarget("log-debug", logDebug, "Disable or enable debugging info."); #endif options.addTarget("log-time", logTime, "Print time information with log entries."); options.addTarget("log-date", logDate, "Print date information with log entries."); options.addTarget("log-date-periodically", logDatePeriodically, "Print date to log before new log entries if so many " "seconds have passed since the last date was printed."); options.addTarget("log-short-level", logShortLevel, "Print shortened level " "information with log entries."); options.addTarget("log-level", logLevel, "Print level information with log entries."); options.addTarget("log-thread-prefix", logThreadPrefix, "Print thread prefixes, if set, with log entries."); options.addTarget("log-domain", logDomain, "Print domain information with log entries."); options.addTarget("log-simple-domains", logSimpleDomains, "Remove any " "leading directories and trailing file extensions from " "domains so that source code file names can be easily used " "as log domains."); options.add("log-domain-levels", 0, new OptionAction<Logger>(this, &Logger::domainLevelsAction), "Set log levels by domain. Format is:\n" "\t<domain>[:i|d|t]:<level> ...\n" "Entries are separated by white-space and or commas.\n" "\ti - info\n" #ifdef DEBUG "\td - debug\n" #endif #ifdef HAVE_DEBUGGER "\tt - enable traces\n" #endif "For example: server:i:3 module:6\n" "Set 'server' domain info messages to level 3 and 'module' info " #ifdef DEBUG "and debug " #endif "messages to level 6. All other domains will follow " "the system wide log verbosity level.\n" "If <level> is negative it is relative to the system wide " "verbosity." )->setType(Option::STRINGS_TYPE); options.addTarget("log-thread-id", logThreadID, "Print id with log entries."); options.addTarget("log-header", logHeader, "Enable log message headers."); options.addTarget("log-no-info-header", logNoInfoHeader, "Don't print 'INFO(#):' in header."); options.addTarget("log-color", logColor, "Print log messages with ANSI color coding."); options.addTarget("log-to-screen", logToScreen, "Log to screen."); options.addTarget("log-truncate", logTrunc, "Truncate log file."); options.addTarget("log-redirect", logRedirect, "Redirect all output to log " "file. Implies !log-to-screen."); options.addTarget("log-rotate", logRotate, "Rotate log files on each run."); options.addTarget("log-rotate-dir", logRotateDir, "Put rotated logs in this directory."); options.addTarget("log-rotate-max", logRotateMax, "Maximum number of rotated logs to keep."); options.popCategory(); } void Logger::setOptions(Options &options) { if (options["log"].hasValue()) startLogFile(options["log"]); } int Logger::domainLevelsAction(Option &option) { setLogDomainLevels(option); return 0; } void Logger::setScreenStream(ostream &stream) { setScreenStream(SmartPointer<ostream>::Phony(&stream)); } void Logger::setScreenStream(const SmartPointer<std::ostream> &stream) { screenStream = stream; } void Logger::startLogFile(const string &filename) { // Rotate log if (logRotate) SystemUtilities::rotate(filename, logRotateDir, logRotateMax); logFile = SystemUtilities::open(filename, ios::out | (logTrunc ? ios::trunc : ios::app)); *logFile << String::bar(SSTR("Log Started " << Time())) << (logCRLF ? "\r\n" : "\n"); logFile->flush(); lastDate = Time::now(); if (logRedirect) { setLogToScreen(false); SystemUtilities::open(filename, ios::app | ios::out); // Test filename // Redirect standard error and out if (!freopen(filename.c_str(), "a", stdout) || !freopen(filename.c_str(), "a", stderr)) THROWS("Redirecting output to '" << filename << "'"); } } void Logger::setLogDomainLevels(const string &levels) { Option::strings_t entries; String::tokenize(levels, entries, Option::DEFAULT_DELIMS + ","); for (unsigned i = 0; i < entries.size(); i++) { vector<string> tokens; String::tokenize(entries[i], tokens, ":"); bool invalid = false; if (tokens.size() == 3) { int level = String::parseS32(tokens[2]); for (unsigned j = 0; j < tokens[1].size(); j++) switch (tokens[1][j]) { case 'i': infoDomainLevels[tokens[0]] = level; break; case 'd': debugDomainLevels[tokens[0]] = level; break; #ifdef HAVE_DEBUGGER case 't': domainTraces.insert(tokens[0]); break; #endif default: invalid = true; } } else if (tokens.size() == 2) { int level = String::parseS32(tokens[1]); infoDomainLevels[tokens[0]] = level; debugDomainLevels[tokens[0]] = level; } else invalid = true; if (invalid) THROWS("Invalid log domain level entry " << (i + 1) << " '" << entries[i] << "'"); } } unsigned Logger::getHeaderWidth() const { return getHeader("", LOG_INFO_LEVEL(10)).size(); } void Logger::setThreadID(unsigned long id) {threadIDStorage->set(id);} unsigned long Logger::getThreadID() const { return threadIDStorage->isSet() ? threadIDStorage->get() : 0; } void Logger::setThreadPrefix(const string &prefix) { threadPrefixStorage->set(prefix); } string Logger::getThreadPrefix() const { return threadPrefixStorage->isSet() ? threadPrefixStorage->get() : string(); } string Logger::simplifyDomain(const string &domain) const { if (!logSimpleDomains) return domain; size_t pos = domain.find_last_of(SystemUtilities::path_separators); size_t start = pos == string::npos ? 0 : pos + 1; size_t end = domain.find_last_of('.'); size_t len = end == string::npos ? end : end - start; return len ? domain.substr(start, len) : domain; } int Logger::domainVerbosity(const string &domain, int level) const { string dom = simplifyDomain(domain); domain_levels_t::const_iterator it; if ((level == LEVEL_DEBUG && (it = debugDomainLevels.find(dom)) != debugDomainLevels.end()) || (level == LEVEL_INFO && (it = infoDomainLevels.find(dom)) != infoDomainLevels.end())) { int verbosity = it->second; // If verbosity < 0 then it is relative to Logger::verbosity if (verbosity < 0) verbosity += this->verbosity; return verbosity; } return verbosity; } string Logger::getHeader(const string &domain, int level) const { string header; if (!logHeader || level == LEVEL_RAW) return header; int verbosity = level >> 8; level &= LEVEL_MASK; // Thread ID if (logThreadID) { string idStr = String::printf("%0*ld:", idWidth - 1, getThreadID()); if (idWidth < idStr.length()) { lock(); idWidth = idStr.length(); unlock(); } header += idStr; } // Date & Time if (logDate || logTime) { uint64_t now = Time::now(); // Must be the same time for both if (logDate) header += Time(now, "%Y-%m-%d:").toString(); if (logTime) header += Time(now, "%H:%M:%S:").toString(); } // Level if (logShortLevel) { switch (level) { case LEVEL_ERROR: header += "E"; break; case LEVEL_CRITICAL: header += "C"; break; case LEVEL_WARNING: header += "W"; break; case LEVEL_INFO: header += "I"; break; case LEVEL_DEBUG: header += "D"; break; default: THROWS("Unknown log level " << level); } // Verbosity if (level >= LEVEL_INFO && verbosity) header += String(verbosity); else header += ' '; header += ':'; } else if (logLevel) { switch (level) { case LEVEL_ERROR: header += "ERROR"; break; case LEVEL_CRITICAL: header += "CRITICAL"; break; case LEVEL_WARNING: header += "WARNING"; break; case LEVEL_INFO: if (!logNoInfoHeader) header += "INFO"; break; case LEVEL_DEBUG: header += "DEBUG"; break; default: THROWS("Unknown log level " << level); } if (!logNoInfoHeader || level != LEVEL_INFO) { // Verbosity if (level >= LEVEL_INFO && verbosity) header += string("(") + String(verbosity) + ")"; header += ':'; } } // Domain if (logDomain && domain != "") header += string(domain) + ':'; // Thread Prefix if (logThreadPrefix) header += getThreadPrefix(); return header; } const char *Logger::startColor(int level) const { if (!logColor) return ""; switch (level & LEVEL_MASK) { case LEVEL_ERROR: return "\033[91m"; case LEVEL_CRITICAL: return "\033[31m"; case LEVEL_WARNING: return "\033[93m"; case LEVEL_DEBUG: return "\033[92m"; default: return ""; } } const char *Logger::endColor(int level) const { if (!logColor) return ""; switch (level & LEVEL_MASK) { case LEVEL_ERROR: case LEVEL_CRITICAL: case LEVEL_WARNING: case LEVEL_DEBUG: return "\033[0m"; default: return ""; } } bool Logger::enabled(const string &domain, int level) const { unsigned verbosity = level >> 8; level &= LEVEL_MASK; if (!logDebug && level == LEVEL_DEBUG) return false; if (level >= LEVEL_INFO && domainVerbosity(domain, level) < (int)verbosity) return false; // All other log levels are always enabled return true; } Logger::LogStream Logger::createStream(const string &_domain, int level, const std::string &_prefix) { string domain = simplifyDomain(_domain); if (!enabled(domain, level)) return new NullStream<>; // Log date periodically if (logDatePeriodically && lastDate + logDatePeriodically <= Time::now()) { lastDate = Time::now(); write(String::bar(Time(lastDate, "Date: %Y-%m-%d").toString()) + (logCRLF ? "\r\n" : "\n")); } string prefix = startColor(level) + getHeader(domain, level) + _prefix; string suffix = endColor(level); string trailer; #ifdef HAVE_DEBUGGER if (domainTraces.find(domain) != domainTraces.end()) { StackTrace trace; Debugger::instance().getStackTrace(trace); for (int i = 0; i < 3; i++) trace.pop_front(); trailer = SSTR(trace); } #endif return new cb::LogStream(prefix, suffix, trailer); } streamsize Logger::write(const char *s, streamsize n) { if (!logFile.isNull()) logFile->write(s, n); if (logToScreen && !screenStream.isNull()) screenStream->write(s, n); return n; } void Logger::write(const string &s) {write(s.c_str(), s.length());} bool Logger::flush() { if (!logFile.isNull()) logFile->flush(); if (logToScreen && !screenStream.isNull()) screenStream->flush(); return true; }
Check for null log screen stream
Check for null log screen stream
C++
lgpl-2.1
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
ac9e84bd4c8a872e9743f625cec197ffe650d684
X10_Project/Classes/Bullet.cpp
X10_Project/Classes/Bullet.cpp
#include "stdafx.h" #include "Bullet.h" #include "Explosion.h" //Base Class of All Bullets bool Bullet::init() { if (!Node::init()) { return false; } Director* director = Director::getInstance(); m_screen = director->getVisibleSize(); m_speed = 0; m_direction = Vec2::ZERO; m_isFlying = false; m_shouldExplode = false; m_toBeErased = false; m_stopAction = false; m_lifeTime = 5.0; m_lifeDecrease = 1.0 / director->getFrameRate(); m_speedSetRatio = 0.01f; m_speedDecreaseRatio = 1 - (10/BULLET_REDUCTIONSPEEDTIME) / director->getFrameRate(); m_body = MakeBody(); addChild(m_body); return true; } Sprite* Bullet::MakeBody() { Sprite* body = Sprite::create(); float scale = Director::getInstance()->getContentScaleFactor(); Size fireSize(BULLET_WIDTH /scale , BULLET_HEIGHT /scale); int frameCut = BULLET_FRAMES; Vector<SpriteFrame*> animFrames; animFrames.reserve(frameCut); for (int i = 0; i < frameCut; i++) { SpriteFrame* frame = SpriteFrame::create(FILE_NAME, Rect(Point(fireSize.width*i, 0), fireSize)); animFrames.pushBack(frame); } Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f); Animate* animate = Animate::create(animation); RepeatForever *aniAction = RepeatForever::create(animate); body->runAction(aniAction); body->setScale(BULLET_RATIO); return body; } bool Bullet::NotShooted() { CCLOG("m_lifeTime: %d", m_lifeTime); if (m_shouldExplode) CCLOG("ex: true"); else CCLOG("ex: false"); if (m_lifeTime > 0 && !m_isFlying) return true; return false; } void Bullet::Act() { if (m_stopAction) { return; } if (m_lifeTime > BULLET_EXPLODETIME) { Move(); DecreaseLife(); if (m_lifeTime < BULLET_REDUCTIONSPEEDTIME) { ReduceSpeed(); } } else { Explode(); TimeUp(); } } void Bullet::Move() { const Vec2 delta = m_speed * m_direction; const Vec2 curPos = getPosition(); Vec2 newPos; if (curPos.x + delta.x < 0) { newPos = Vec2(curPos.x + delta.x + m_screen.width, delta.y + curPos.y); } else if (curPos.x + delta.x > m_screen.width) { newPos = Vec2(curPos.x + delta.x - m_screen.width, delta.y + curPos.y); } else { newPos = curPos + delta; } setPosition(newPos); } Explosion* Bullet::GetExplosion() { Explosion* explosion = Explosion::create(); explosion->setPosition(getPosition()); explosion->setRotation(getRotation()); Exploded(); return explosion; } void Bullet::DecreaseLife() { m_lifeTime -= m_lifeDecrease; } void Bullet::ReduceSpeed() { m_speed *= m_speedDecreaseRatio; } void Bullet::Crashed() { m_lifeTime = BULLET_EXPLODETIME; } void Bullet::TimeUp() { removeFromParent(); m_isFlying = false; m_toBeErased = true; } const Rect& Bullet::GetBoundingArea() { return Rect(this->getPosition(), m_body->getContentSize()*BULLET_RATIO); }
#include "stdafx.h" #include "Bullet.h" #include "Explosion.h" //Base Class of All Bullets bool Bullet::init() { if (!Node::init()) { return false; } Director* director = Director::getInstance(); m_screen = director->getVisibleSize(); m_speed = 0; m_direction = Vec2::ZERO; m_isFlying = false; m_shouldExplode = false; m_toBeErased = false; m_stopAction = false; m_lifeTime = 5.0; m_lifeDecrease = 1.0 / director->getFrameRate(); m_speedSetRatio = 0.01f; m_speedDecreaseRatio = 1 - (10.0f/BULLET_REDUCTIONSPEEDTIME) / director->getFrameRate(); m_body = MakeBody(); addChild(m_body); return true; } Sprite* Bullet::MakeBody() { Sprite* body = Sprite::create(); float scale = Director::getInstance()->getContentScaleFactor(); Size fireSize(BULLET_WIDTH /scale , BULLET_HEIGHT /scale); int frameCut = BULLET_FRAMES; Vector<SpriteFrame*> animFrames; animFrames.reserve(frameCut); for (int i = 0; i < frameCut; i++) { SpriteFrame* frame = SpriteFrame::create(FILE_NAME, Rect(Point(fireSize.width*i, 0), fireSize)); animFrames.pushBack(frame); } Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f); Animate* animate = Animate::create(animation); RepeatForever *aniAction = RepeatForever::create(animate); body->runAction(aniAction); body->setScale(BULLET_RATIO); return body; } bool Bullet::NotShooted() { CCLOG("m_lifeTime: %d", m_lifeTime); if (m_shouldExplode) CCLOG("ex: true"); else CCLOG("ex: false"); if (m_lifeTime > 0 && !m_isFlying) return true; return false; } void Bullet::Act() { if (m_stopAction) { return; } if (m_lifeTime > BULLET_EXPLODETIME) { Move(); DecreaseLife(); if (m_lifeTime < BULLET_REDUCTIONSPEEDTIME) { ReduceSpeed(); } } else { Explode(); TimeUp(); } } void Bullet::Move() { const Vec2 delta = m_speed * m_direction; const Vec2 curPos = getPosition(); Vec2 newPos; if (curPos.x + delta.x < 0) { newPos = Vec2(curPos.x + delta.x + m_screen.width, delta.y + curPos.y); } else if (curPos.x + delta.x > m_screen.width) { newPos = Vec2(curPos.x + delta.x - m_screen.width, delta.y + curPos.y); } else { newPos = curPos + delta; } setPosition(newPos); } Explosion* Bullet::GetExplosion() { Explosion* explosion = Explosion::create(); explosion->setPosition(getPosition()); explosion->setRotation(getRotation()); Exploded(); return explosion; } void Bullet::DecreaseLife() { m_lifeTime -= m_lifeDecrease; } void Bullet::ReduceSpeed() { m_speed *= m_speedDecreaseRatio; } void Bullet::Crashed() { m_lifeTime = BULLET_EXPLODETIME; } void Bullet::TimeUp() { removeFromParent(); m_isFlying = false; m_toBeErased = true; } const Rect& Bullet::GetBoundingArea() { return Rect(this->getPosition(), m_body->getContentSize()*BULLET_RATIO); }
fix bug of Bullet speed reduction 10 -> 10.0f (int->float)
fix bug of Bullet speed reduction 10 -> 10.0f (int->float)
C++
mit
kimsin3003/X10,kimsin3003/X10,kimsin3003/X10,kimsin3003/X10,kimsin3003/X10
75a7d9a28465539f952155c4d59416e17c3814d8
lib/afsm/include/afsm/fsm.hpp
lib/afsm/include/afsm/fsm.hpp
/* * fsm.hpp * * Created on: 25 мая 2016 г. * Author: sergey.fedorov */ #ifndef AFSM_FSM_HPP_ #define AFSM_FSM_HPP_ #include <afsm/detail/base_states.hpp> #include <afsm/detail/observer.hpp> #include <deque> namespace afsm { //---------------------------------------------------------------------------- // State //---------------------------------------------------------------------------- template < typename T, typename FSM > class state : public detail::state_base< T > { public: using enclosing_fsm_type = FSM; public: state(enclosing_fsm_type& fsm) : state::state_type{}, fsm_{&fsm} {} state(state const& rhs) = default; state(state&& rhs) = default; state(enclosing_fsm_type& fsm, state const& rhs) : state::state_type{static_cast<typename state::state_type const&>(rhs)}, fsm_{&fsm} {} state(enclosing_fsm_type& fsm, state&& rhs) : state::state_type{static_cast<typename state::state_type&&>(rhs)}, fsm_{&fsm} {} state& operator = (state const& rhs) { state{rhs}.swap(*this); return *this; } state& operator = (state&& rhs) { swap(rhs); return *this; } void swap(state& rhs) noexcept { static_cast<typename state::state_type&>(*this).swap(rhs); } template < typename Event > actions::event_process_result process_event( Event&& evt ) { return process_event_impl(::std::forward<Event>(evt), detail::event_process_selector< Event, typename state::internal_events, typename state::deferred_events>{} ); } enclosing_fsm_type& enclosing_fsm() { return *fsm_; } enclosing_fsm_type const& enclosing_fsm() const { return *fsm_; } void enclosing_fsm(enclosing_fsm_type& fsm) { fsm_ = &fsm; } template < typename Event > void state_enter(Event&&) {} template < typename Event > void state_exit(Event&&) {} private: template < typename Event > actions::event_process_result process_event_impl(Event&& evt, detail::process_type<actions::event_process_result::process> const&) { return actions::handle_in_state_event(::std::forward<Event>(evt), *fsm_, *this); } template < typename Event > constexpr actions::event_process_result process_event_impl(Event&&, detail::process_type<actions::event_process_result::defer> const&) const { return actions::event_process_result::defer; } template < typename Event > constexpr actions::event_process_result process_event_impl(Event&&, detail::process_type<actions::event_process_result::refuse> const&) const { return actions::event_process_result::refuse; } private: enclosing_fsm_type* fsm_; }; //---------------------------------------------------------------------------- // Inner state machine //---------------------------------------------------------------------------- template < typename T, typename FSM > class inner_state_machine : public detail::state_machine_base< T, none, inner_state_machine<T, FSM> > { public: using enclosing_fsm_type = FSM; using this_type = inner_state_machine<T, FSM>; using base_machine_type = detail::state_machine_base< T, none, this_type >; public: inner_state_machine(enclosing_fsm_type& fsm) : base_machine_type{this}, fsm_{&fsm} {} inner_state_machine(inner_state_machine const& rhs) : base_machine_type{this, rhs}, fsm_{rhs.fsm_} {} inner_state_machine(inner_state_machine&& rhs) : base_machine_type{this, ::std::move(rhs)}, fsm_{rhs.fsm_} { } inner_state_machine(enclosing_fsm_type& fsm, inner_state_machine const& rhs) : base_machine_type{static_cast<base_machine_type const&>(rhs)}, fsm_{&fsm} {} inner_state_machine(enclosing_fsm_type& fsm, inner_state_machine&& rhs) : base_machine_type{static_cast<base_machine_type&&>(rhs)}, fsm_{&fsm} {} void swap(inner_state_machine& rhs) noexcept { using ::std::swap; static_cast<base_machine_type&>(*this).swap(rhs); swap(fsm_, rhs.fsm_); } inner_state_machine& operator = (inner_state_machine const& rhs) { inner_state_machine tmp{rhs}; swap(tmp); return *this; } inner_state_machine& operator = (inner_state_machine&& rhs) { swap(rhs); return *this; } template < typename Event > actions::event_process_result process_event( Event&& event ) { return process_event_impl(*fsm_, ::std::forward<Event>(event), detail::event_process_selector< Event, typename inner_state_machine::handled_events, typename inner_state_machine::deferred_events>{} ); } enclosing_fsm_type& enclosing_fsm() { return *fsm_; } enclosing_fsm_type const& enclosing_fsm() const { return *fsm_; } void enclosing_fsm(enclosing_fsm_type& fsm) { fsm_ = &fsm; } private: using base_machine_type::process_event_impl; private: enclosing_fsm_type* fsm_; }; //---------------------------------------------------------------------------- // State machine //---------------------------------------------------------------------------- template < typename T, typename Mutex, typename Observer, template<typename> class ObserverWrapper > class state_machine : public detail::state_machine_base< T, Mutex, state_machine<T, Mutex, Observer> >, public ObserverWrapper<Observer> { public: static_assert( ::psst::meta::is_empty< typename T::deferred_events >::value, "Outer state machine cannot defer events" ); using this_type = state_machine<T, Mutex, Observer>; using base_machine_type = detail::state_machine_base< T, Mutex, this_type >; using mutex_type = Mutex; using lock_guard = typename detail::lock_guard_type<mutex_type>::type; using observer_wrapper = ObserverWrapper<Observer>; using event_invokation = ::std::function< actions::event_process_result() >; using event_queue = ::std::deque< event_invokation >; public: state_machine() : base_machine_type{this}, stack_size_{0}, mutex_{}, queued_events_{}, queue_size_{0}, deferred_mutex_{}, deferred_events_{} {} template<typename ... Args> explicit state_machine(Args&& ... args) : base_machine_type(this, ::std::forward<Args>(args)...), stack_size_{0}, mutex_{}, queued_events_{}, queue_size_{0}, deferred_mutex_{}, deferred_events_{} {} template < typename Event > actions::event_process_result process_event( Event&& event ) { if (!stack_size_++) { auto res = process_event_dispatch(::std::forward<Event>(event)); --stack_size_; // Process enqueued events process_event_queue(); return res; } else { --stack_size_; // Enqueue event enqueue_event(::std::forward<Event>(event)); return actions::event_process_result::defer; } } private: template < typename Event > actions::event_process_result process_event_dispatch( Event&& event ) { return process_event_impl(::std::forward<Event>(event), detail::event_process_selector< Event, typename state_machine::handled_events>{} ); } template < typename Event > actions::event_process_result process_event_impl(Event&& event, detail::process_type<actions::event_process_result::process> const& sel) { using actions::event_process_result; observer_wrapper::start_process_event(*this, ::std::forward<Event>(event)); auto res = base_machine_type::process_event_impl(*this, ::std::forward<Event>(event), sel ); switch (res) { case event_process_result::process: observer_wrapper::state_changed(*this); // Changed state. Process deferred events process_deferred_queue(); break; case event_process_result::process_in_state: observer_wrapper::processed_in_state(*this, ::std::forward<Event>(event)); break; case event_process_result::defer: // Add event to deferred queue defer_event(::std::forward<Event>(event)); break; case event_process_result::refuse: // The event cannot be processed in current state observer_wrapper::reject_event(*this, ::std::forward<Event>(event)); break; default: break; } return res; } template < typename Event > actions::event_process_result process_event_impl(Event&&, detail::process_type<actions::event_process_result::refuse> const&) { static_assert( detail::event_process_selector< Event, typename state_machine::handled_events, typename state_machine::deferred_events>::value != actions::event_process_result::refuse, "Event type is not handled by this state machine" ); return actions::event_process_result::refuse; } template < typename Event > void enqueue_event(Event&& event) { { lock_guard lock{mutex_}; ++queue_size_; observer_wrapper::enqueue_event(*this, ::std::forward<Event>(event)); Event evt = event; queued_events_.emplace_back([&, evt]() mutable { return process_event_dispatch(::std::move(evt)); }); } // Process enqueued events in case we've been waiting for queue // mutex release process_event_queue(); } void lock_and_swap_queue(event_queue& queue) { lock_guard lock{mutex_}; ::std::swap(queued_events_, queue); queue_size_ -= queue.size(); } void process_event_queue() { // TODO replace those if's with atomic compare and swap if (stack_size_) return; if (stack_size_++) { --stack_size_; return; } observer_wrapper::start_process_events_queue(*this); while (queue_size_ > 0) { event_queue postponed; lock_and_swap_queue(postponed); for (auto const& event : postponed) { event(); } } --stack_size_; observer_wrapper::end_process_events_queue(*this); if (queue_size_ > 0) { process_event_queue(); } } template < typename Event > void defer_event(Event&& event) { lock_guard lock{deferred_mutex_}; observer_wrapper::defer_event(*this, ::std::forward<Event>(event)); Event evt = event; deferred_events_.emplace_back([&, evt]() mutable { return process_event_dispatch(::std::move(evt)); }); } void process_deferred_queue() { using actions::event_process_result; if (stack_size_++ <= 1) { event_queue deferred; { lock_guard lock{deferred_mutex_}; ::std::swap(deferred_events_, deferred); } while (!deferred.empty()) { observer_wrapper::start_process_deferred_queue(*this); auto res = event_process_result::refuse; while (!deferred.empty()) { auto event = deferred.front(); deferred.pop_front(); res = event(); if (res == event_process_result::process) break; } { lock_guard lock{deferred_mutex_}; deferred_events_.insert(deferred_events_.end(), deferred.begin(), deferred.end()); deferred.clear(); } if (res == event_process_result::process) { ::std::swap(deferred_events_, deferred); } observer_wrapper::end_process_deferred_queue(*this); } } --stack_size_; } private: using atomic_counter = ::std::atomic< ::std::size_t >; atomic_counter stack_size_; mutex_type mutex_; event_queue queued_events_; atomic_counter queue_size_; mutex_type deferred_mutex_; event_queue deferred_events_; }; } /* namespace afsm */ #endif /* AFSM_FSM_HPP_ */
/* * fsm.hpp * * Created on: 25 мая 2016 г. * Author: sergey.fedorov */ #ifndef AFSM_FSM_HPP_ #define AFSM_FSM_HPP_ #include <afsm/detail/base_states.hpp> #include <afsm/detail/observer.hpp> #include <deque> namespace afsm { //---------------------------------------------------------------------------- // State //---------------------------------------------------------------------------- template < typename T, typename FSM > class state : public detail::state_base< T > { public: using enclosing_fsm_type = FSM; public: state(enclosing_fsm_type& fsm) : state::state_type{}, fsm_{&fsm} {} state(state const& rhs) = default; state(state&& rhs) = default; state(enclosing_fsm_type& fsm, state const& rhs) : state::state_type{static_cast<typename state::state_type const&>(rhs)}, fsm_{&fsm} {} state(enclosing_fsm_type& fsm, state&& rhs) : state::state_type{static_cast<typename state::state_type&&>(rhs)}, fsm_{&fsm} {} state& operator = (state const& rhs) { state{rhs}.swap(*this); return *this; } state& operator = (state&& rhs) { swap(rhs); return *this; } void swap(state& rhs) noexcept { static_cast<typename state::state_type&>(*this).swap(rhs); } template < typename Event > actions::event_process_result process_event( Event&& evt ) { return process_event_impl(::std::forward<Event>(evt), detail::event_process_selector< Event, typename state::internal_events, typename state::deferred_events>{} ); } enclosing_fsm_type& enclosing_fsm() { return *fsm_; } enclosing_fsm_type const& enclosing_fsm() const { return *fsm_; } void enclosing_fsm(enclosing_fsm_type& fsm) { fsm_ = &fsm; } template < typename Event > void state_enter(Event&&) {} template < typename Event > void state_exit(Event&&) {} private: template < typename Event > actions::event_process_result process_event_impl(Event&& evt, detail::process_type<actions::event_process_result::process> const&) { return actions::handle_in_state_event(::std::forward<Event>(evt), *fsm_, *this); } template < typename Event > constexpr actions::event_process_result process_event_impl(Event&&, detail::process_type<actions::event_process_result::defer> const&) const { return actions::event_process_result::defer; } template < typename Event > constexpr actions::event_process_result process_event_impl(Event&&, detail::process_type<actions::event_process_result::refuse> const&) const { return actions::event_process_result::refuse; } private: enclosing_fsm_type* fsm_; }; //---------------------------------------------------------------------------- // Inner state machine //---------------------------------------------------------------------------- template < typename T, typename FSM > class inner_state_machine : public detail::state_machine_base< T, none, inner_state_machine<T, FSM> > { public: using enclosing_fsm_type = FSM; using this_type = inner_state_machine<T, FSM>; using base_machine_type = detail::state_machine_base< T, none, this_type >; public: inner_state_machine(enclosing_fsm_type& fsm) : base_machine_type{this}, fsm_{&fsm} {} inner_state_machine(inner_state_machine const& rhs) : base_machine_type{this, rhs}, fsm_{rhs.fsm_} {} inner_state_machine(inner_state_machine&& rhs) : base_machine_type{this, ::std::move(rhs)}, fsm_{rhs.fsm_} { } inner_state_machine(enclosing_fsm_type& fsm, inner_state_machine const& rhs) : base_machine_type{static_cast<base_machine_type const&>(rhs)}, fsm_{&fsm} {} inner_state_machine(enclosing_fsm_type& fsm, inner_state_machine&& rhs) : base_machine_type{static_cast<base_machine_type&&>(rhs)}, fsm_{&fsm} {} void swap(inner_state_machine& rhs) noexcept { using ::std::swap; static_cast<base_machine_type&>(*this).swap(rhs); swap(fsm_, rhs.fsm_); } inner_state_machine& operator = (inner_state_machine const& rhs) { inner_state_machine tmp{rhs}; swap(tmp); return *this; } inner_state_machine& operator = (inner_state_machine&& rhs) { swap(rhs); return *this; } template < typename Event > actions::event_process_result process_event( Event&& event ) { return process_event_impl(*fsm_, ::std::forward<Event>(event), detail::event_process_selector< Event, typename inner_state_machine::handled_events, typename inner_state_machine::deferred_events>{} ); } enclosing_fsm_type& enclosing_fsm() { return *fsm_; } enclosing_fsm_type const& enclosing_fsm() const { return *fsm_; } void enclosing_fsm(enclosing_fsm_type& fsm) { fsm_ = &fsm; } private: using base_machine_type::process_event_impl; private: enclosing_fsm_type* fsm_; }; //---------------------------------------------------------------------------- // State machine //---------------------------------------------------------------------------- template < typename T, typename Mutex, typename Observer, template<typename> class ObserverWrapper > class state_machine : public detail::state_machine_base< T, Mutex, state_machine<T, Mutex, Observer> >, public ObserverWrapper<Observer> { public: static_assert( ::psst::meta::is_empty< typename T::deferred_events >::value, "Outer state machine cannot defer events" ); using this_type = state_machine<T, Mutex, Observer>; using base_machine_type = detail::state_machine_base< T, Mutex, this_type >; using mutex_type = Mutex; using lock_guard = typename detail::lock_guard_type<mutex_type>::type; using observer_wrapper = ObserverWrapper<Observer>; using event_invokation = ::std::function< actions::event_process_result() >; using event_queue = ::std::deque< event_invokation >; public: state_machine() : base_machine_type{this}, is_top_{}, mutex_{}, queued_events_{}, queue_size_{0}, deferred_mutex_{}, deferred_events_{} {} template<typename ... Args> explicit state_machine(Args&& ... args) : base_machine_type(this, ::std::forward<Args>(args)...), is_top_{}, mutex_{}, queued_events_{}, queue_size_{0}, deferred_mutex_{}, deferred_events_{} {} template < typename Event > actions::event_process_result process_event( Event&& event ) { if (!is_top_.test_and_set()) { auto res = process_event_dispatch(::std::forward<Event>(event)); is_top_.clear(); // Process enqueued events process_event_queue(); return res; } else { // Enqueue event enqueue_event(::std::forward<Event>(event)); return actions::event_process_result::defer; } } private: template < typename Event > actions::event_process_result process_event_dispatch( Event&& event ) { return process_event_impl(::std::forward<Event>(event), detail::event_process_selector< Event, typename state_machine::handled_events>{} ); } template < typename Event > actions::event_process_result process_event_impl(Event&& event, detail::process_type<actions::event_process_result::process> const& sel) { using actions::event_process_result; observer_wrapper::start_process_event(*this, ::std::forward<Event>(event)); auto res = base_machine_type::process_event_impl(*this, ::std::forward<Event>(event), sel ); switch (res) { case event_process_result::process: observer_wrapper::state_changed(*this); // Changed state. Process deferred events process_deferred_queue(); break; case event_process_result::process_in_state: observer_wrapper::processed_in_state(*this, ::std::forward<Event>(event)); break; case event_process_result::defer: // Add event to deferred queue defer_event(::std::forward<Event>(event)); break; case event_process_result::refuse: // The event cannot be processed in current state observer_wrapper::reject_event(*this, ::std::forward<Event>(event)); break; default: break; } return res; } template < typename Event > actions::event_process_result process_event_impl(Event&&, detail::process_type<actions::event_process_result::refuse> const&) { static_assert( detail::event_process_selector< Event, typename state_machine::handled_events, typename state_machine::deferred_events>::value != actions::event_process_result::refuse, "Event type is not handled by this state machine" ); return actions::event_process_result::refuse; } template < typename Event > void enqueue_event(Event&& event) { { lock_guard lock{mutex_}; ++queue_size_; observer_wrapper::enqueue_event(*this, ::std::forward<Event>(event)); Event evt = event; queued_events_.emplace_back([&, evt]() mutable { return process_event_dispatch(::std::move(evt)); }); } // Process enqueued events in case we've been waiting for queue // mutex release process_event_queue(); } void lock_and_swap_queue(event_queue& queue) { lock_guard lock{mutex_}; ::std::swap(queued_events_, queue); queue_size_ -= queue.size(); } void process_event_queue() { while (queue_size_ > 0 && !is_top_.test_and_set()) { observer_wrapper::start_process_events_queue(*this); while (queue_size_ > 0) { event_queue postponed; lock_and_swap_queue(postponed); for (auto const& event : postponed) { event(); } } observer_wrapper::end_process_events_queue(*this); is_top_.clear(); } } template < typename Event > void defer_event(Event&& event) { lock_guard lock{deferred_mutex_}; observer_wrapper::defer_event(*this, ::std::forward<Event>(event)); Event evt = event; deferred_events_.emplace_back([&, evt]() mutable { return process_event_dispatch(::std::move(evt)); }); } void process_deferred_queue() { using actions::event_process_result; event_queue deferred; { lock_guard lock{deferred_mutex_}; ::std::swap(deferred_events_, deferred); } while (!deferred.empty()) { observer_wrapper::start_process_deferred_queue(*this); auto res = event_process_result::refuse; while (!deferred.empty()) { auto event = deferred.front(); deferred.pop_front(); res = event(); if (res == event_process_result::process) break; } { lock_guard lock{deferred_mutex_}; deferred_events_.insert(deferred_events_.end(), deferred.begin(), deferred.end()); deferred.clear(); } if (res == event_process_result::process) { ::std::swap(deferred_events_, deferred); } observer_wrapper::end_process_deferred_queue(*this); } } private: using atomic_counter = ::std::atomic< ::std::size_t >; ::std::atomic_flag is_top_; mutex_type mutex_; event_queue queued_events_; atomic_counter queue_size_; mutex_type deferred_mutex_; event_queue deferred_events_; }; } /* namespace afsm */ #endif /* AFSM_FSM_HPP_ */
Replace atomic counter with atomic flag.
Replace atomic counter with atomic flag.
C++
artistic-2.0
zmij/pg_async
3a6009a18716eb9fe2bdabec01aa74ac9ff4b1a8
src/client/bfs_client.cc
src/client/bfs_client.cc
// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: [email protected] #include <gflags/gflags.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <string> #include <unistd.h> #include <stdlib.h> #include <common/util.h> #include <common/timer.h> #include "sdk/bfs.h" DECLARE_string(flagfile); DECLARE_string(nameserver); DECLARE_string(nameserver_port); void print_usage() { printf("Use:\nbfs_client <commond> path\n"); printf("\t commond:\n"); printf("\t ls <path> : list the directory\n"); printf("\t cat <path> : cat the file\n"); printf("\t mkdir <path> : make director\n"); printf("\t mv <srcpath> <destpath> : rename director or file\n"); printf("\t touchz <path> : create a new file\n"); printf("\t rm <path> : remove a file\n"); printf("\t get <bfsfile> <localfile> : copy file to local\n"); printf("\t put <localfile> <bfsfile> : copy file from local to bfs\n"); printf("\t rmdir <path> : remove empty directory\n"); printf("\t rmr <path> : remove directory recursively\n"); printf("\t change_replica_num <bfsfile> <num>: change replica num of <bfsfile> to <num>\n"); printf("\t du <path> : count disk usage for path\n"); printf("\t stat : list current stat of the file system\n"); } int BfsMkdir(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 1) { print_usage(); return 1; } bool ret = fs->CreateDirectory(argv[0]); if (!ret) { fprintf(stderr, "Create dir %s fail\n", argv[0]); return 1; } return 0; } int BfsRename(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 2) { print_usage(); return 1; } bool ret = fs->Rename(argv[0], argv[1]); if (!ret) { fprintf(stderr, "Rename %s to %s fail\n", argv[0], argv[1]); return 1; } return 0; } int BfsCat(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 1) { print_usage(); return 1; } int64_t bytes = 0; int32_t len; for (int i = 0; i < argc; i++) { baidu::bfs::File* file; if (!fs->OpenFile(argv[i], O_RDONLY, &file)) { fprintf(stderr, "Can't Open bfs file %s\n", argv[0]); return 1; } char buf[10240]; len = 0; while (1) { len = file->Read(buf, sizeof(buf)); if (len <= 0) { if (len < 0) { fprintf(stderr, "Read from %s fail.\n", argv[0]); } break; } bytes += len; write(1, buf, len); } delete file; } return len; } int BfsGet(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 1) { print_usage(); return 1; } std::string source = argv[0]; std::string target; if (argc >= 2) { target = argv[1]; } std::vector<std::string> src_elements; bool src_isdir = false; if (!baidu::common::util::SplitPath(source, &src_elements, &src_isdir) || src_isdir || src_elements.empty()) { fprintf(stderr, "Bad file path %s\n", source.c_str()); return 1; } std::string src_file_name = src_elements[src_elements.size() - 1]; if (target.empty() || target[target.size() - 1] == '/') { target += src_file_name; } baidu::common::timer::AutoTimer at(0, "BfsGet", argv[0]); baidu::bfs::File* file; if (!fs->OpenFile(source.c_str(), O_RDONLY, &file)) { fprintf(stderr, "Can't Open bfs file %s\n", source.c_str()); return 1; } FILE* fp = fopen(target.c_str(), "wb"); if (fp == NULL) { fprintf(stderr, "Open local file %s fail\n", target.c_str()); delete file; return -1; } char buf[10240]; int64_t bytes = 0; int32_t len = 0; while (1) { len = file->Read(buf, sizeof(buf)); if (len <= 0) { if (len < 0) { fprintf(stderr, "Read from %s fail.\n", source.c_str()); } break; } bytes += len; fwrite(buf, len, 1, fp); } printf("Read %ld bytes from %s\n", bytes, source.c_str()); delete file; fclose(fp); return len; } int BfsPut(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc != 4) { print_usage(); return 0; } std::string source = argv[2]; std::string target = argv[3]; if (source.empty() || source[source.size() - 1] == '/' || target.empty()) { fprintf(stderr, "Bad file path: %s or %s\n", source.c_str(), target.c_str()); return 1; } std::string src_file_name; size_t pos = source.rfind('/'); if (pos == std::string::npos) { src_file_name = source; } else { src_file_name = source.substr(pos+1); } if (target[target.size() - 1] == '/') { target += src_file_name; } int ret = 0; baidu::common::timer::AutoTimer at(0, "BfsPut", target.c_str()); FILE* fp = fopen(source.c_str(), "rb"); if (fp == NULL) { fprintf(stderr, "Can't open local file %s\n", argv[2]); return 1; } baidu::bfs::File* file; ///TODO: Use the same mode as the source file. if (!fs->OpenFile(target.c_str(), O_WRONLY | O_TRUNC, 0644, -1, &file)) { fprintf(stderr, "Can't Open bfs file %s\n", target.c_str()); fclose(fp); return 1; } char buf[10240]; int64_t len = 0; int32_t bytes = 0; while ( (bytes = fread(buf, 1, sizeof(buf), fp)) > 0) { int32_t write_bytes = file->Write(buf, bytes); if (write_bytes < bytes) { fprintf(stderr, "Write fail: [%s:%ld]\n", target.c_str(), len); return 1; } len += bytes; } if (!file->Close()) { fprintf(stderr, "close fail: %s\n", target.c_str()); ret = 1; } delete file; fclose(fp); printf("Put file to bfs %s %ld bytes\n", target.c_str(), len); return ret; } int64_t BfsDuRecursive(baidu::bfs::FS* fs, const std::string& path) { int64_t ret = 0; std::string pad; if (path[path.size() - 1] != '/') { pad = "/"; } baidu::bfs::BfsFileInfo* files = NULL; int num = 0; if (!fs->ListDirectory(path.c_str(), &files, &num)) { fprintf(stderr, "List directory fail: %s\n", path.c_str()); return ret; } for (int i = 0; i < num; i++) { std::string file_path = path + pad + files[i].name; int32_t type = files[i].mode; if (type & (1<<9)) { ret += BfsDuRecursive(fs, file_path); continue; } baidu::bfs::BfsFileInfo fileinfo; if (fs->Stat(file_path.c_str(), &fileinfo)) { ret += fileinfo.size; printf("%s\t %ld\n", file_path.c_str(), fileinfo.size); } } delete files; return ret; } int BfsDu(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc != 1) { print_usage(); return 1; } int64_t du = BfsDuRecursive(fs, argv[0]); printf("Total:\t%ld\n", du); return 0; } int BfsList(baidu::bfs::FS* fs, int argc, char* argv[]) { std::string path("/"); if (argc == 3) { path = argv[2]; if (path.size() && path[path.size()-1] != '/') { path.append("/"); } } baidu::bfs::BfsFileInfo* files = NULL; int num; bool ret = fs->ListDirectory(path.c_str(), &files, &num); if (!ret) { fprintf(stderr, "List dir %s fail\n", path.c_str()); return 1; } printf("Found %d items\n", num); for (int i = 0; i < num; i++) { int32_t type = files[i].mode; char statbuf[16] = "drwxrwxrwx"; for (int j = 0; j < 10; j++) { if ((type & (1<<(9-j))) == 0) { statbuf[j] = '-'; } } char timestr[64]; struct tm stm; time_t ctime = files[i].ctime; localtime_r(&ctime, &stm); snprintf(timestr, sizeof(timestr), "%4d-%02d-%02d %2d:%02d", stm.tm_year+1900, stm.tm_mon+1, stm.tm_mday, stm.tm_hour, stm.tm_min); printf("%s\t%s %s%s\n", statbuf, timestr, path.c_str(), files[i].name); } delete files; return 0; } int BfsRmdir(baidu::bfs::FS* fs, int argc, char* argv[], bool recursive) { if (argc < 1) { print_usage(); return 1; } bool ret = fs->DeleteDirectory(argv[0], recursive); if (!ret) { fprintf(stderr, "Remove dir %s fail\n", argv[0]); return 1; } return 0; } int BfsChangeReplicaNum(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 2) { print_usage(); return 1; } char* file_name = argv[0]; int32_t replica_num = atoi(argv[1]); bool ret = fs->ChangeReplicaNum(file_name, replica_num); if (!ret) { fprintf(stderr, "Change %s replica num to %d fail\n", file_name, replica_num); return 1; } return 0; } int BfsStat(baidu::bfs::FS* fs, int argc, char* argv[]) { std::string stat_name("Stat"); if (argc && 0 == strcmp(argv[0], "-a")) { stat_name = "StatAll"; } std::string result; bool ret = fs->SysStat(stat_name, &result); if (!ret) { fprintf(stderr, "SysStat fail\n"); return 1; } printf("%s\n", result.c_str()); return 0; } /// bfs client main int main(int argc, char* argv[]) { FLAGS_flagfile = "./bfs.flag"; int gflags_argc = 1; ::google::ParseCommandLineFlags(&gflags_argc, &argv, false); if (argc < 2) { print_usage(); return 0; } baidu::bfs::FS* fs; std::string ns_address = FLAGS_nameserver + ":" + FLAGS_nameserver_port; if (!baidu::bfs::FS::OpenFileSystem(ns_address.c_str(), &fs)) { fprintf(stderr, "Open filesytem %s fail\n", ns_address.c_str()); return 1; } int ret = 1; if (strcmp(argv[1], "touchz") == 0) { if (argc != 3) { print_usage(); return ret; } baidu::bfs::File* file; if (!fs->OpenFile(argv[2], O_WRONLY, 644, 0, &file)) { fprintf(stderr, "Open %s fail\n", argv[2]); } else { ret = 0; } } else if (strcmp(argv[1], "rm") == 0) { if (argc != 3) { print_usage(); return ret; } if (fs->DeleteFile(argv[2])) { printf("%s Removed\n", argv[2]); ret = 0; } else { fprintf(stderr, "Remove file fail: %s\n", argv[2]); } } else if (strcmp(argv[1], "mkdir") == 0) { ret = BfsMkdir(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "mv") == 0) { ret = BfsRename(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "put") == 0) { ret = BfsPut(fs, argc, argv); } else if (strcmp(argv[1], "get") == 0 ) { ret = BfsGet(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "cat") == 0) { ret = BfsCat(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "ls") == 0) { ret = BfsList(fs, argc, argv); } else if (strcmp(argv[1], "rmdir") == 0) { ret = BfsRmdir(fs, argc - 2, argv + 2, false); } else if (strcmp(argv[1], "rmr") == 0) { ret = BfsRmdir(fs, argc - 2, argv + 2, true); } else if (strcmp(argv[1], "change_replica_num") == 0) { ret = BfsChangeReplicaNum(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "du") == 0) { ret = BfsDu(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "stat") == 0) { ret = BfsStat(fs, argc - 2, argv + 2); } else { fprintf(stderr, "Unknow common: %s\n", argv[1]); } return ret; } /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: [email protected] #include <gflags/gflags.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <string> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <common/util.h> #include <common/timer.h> #include "sdk/bfs.h" DECLARE_string(flagfile); DECLARE_string(nameserver); DECLARE_string(nameserver_port); void print_usage() { printf("Use:\nbfs_client <commond> path\n"); printf("\t commond:\n"); printf("\t ls <path> : list the directory\n"); printf("\t cat <path> : cat the file\n"); printf("\t mkdir <path> : make director\n"); printf("\t mv <srcpath> <destpath> : rename director or file\n"); printf("\t touchz <path> : create a new file\n"); printf("\t rm <path> : remove a file\n"); printf("\t get <bfsfile> <localfile> : copy file to local\n"); printf("\t put <localfile> <bfsfile> : copy file from local to bfs\n"); printf("\t rmdir <path> : remove empty directory\n"); printf("\t rmr <path> : remove directory recursively\n"); printf("\t change_replica_num <bfsfile> <num>: change replica num of <bfsfile> to <num>\n"); printf("\t du <path> : count disk usage for path\n"); printf("\t stat : list current stat of the file system\n"); } int BfsMkdir(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 1) { print_usage(); return 1; } bool ret = fs->CreateDirectory(argv[0]); if (!ret) { fprintf(stderr, "Create dir %s fail\n", argv[0]); return 1; } return 0; } int BfsRename(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 2) { print_usage(); return 1; } bool ret = fs->Rename(argv[0], argv[1]); if (!ret) { fprintf(stderr, "Rename %s to %s fail\n", argv[0], argv[1]); return 1; } return 0; } int BfsCat(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 1) { print_usage(); return 1; } int64_t bytes = 0; int32_t len; for (int i = 0; i < argc; i++) { baidu::bfs::File* file; if (!fs->OpenFile(argv[i], O_RDONLY, &file)) { fprintf(stderr, "Can't Open bfs file %s\n", argv[0]); return 1; } char buf[10240]; len = 0; while (1) { len = file->Read(buf, sizeof(buf)); if (len <= 0) { if (len < 0) { fprintf(stderr, "Read from %s fail.\n", argv[0]); } break; } bytes += len; write(1, buf, len); } delete file; } return len; } int BfsGet(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 1) { print_usage(); return 1; } std::string source = argv[0]; std::string target; if (argc >= 2) { target = argv[1]; } std::vector<std::string> src_elements; bool src_isdir = false; if (!baidu::common::util::SplitPath(source, &src_elements, &src_isdir) || src_isdir || src_elements.empty()) { fprintf(stderr, "Bad file path %s\n", source.c_str()); return 1; } std::string src_file_name = src_elements[src_elements.size() - 1]; if (target.empty() || target[target.size() - 1] == '/') { target += src_file_name; } baidu::common::timer::AutoTimer at(0, "BfsGet", argv[0]); baidu::bfs::File* file; if (!fs->OpenFile(source.c_str(), O_RDONLY, &file)) { fprintf(stderr, "Can't Open bfs file %s\n", source.c_str()); return 1; } FILE* fp = fopen(target.c_str(), "wb"); if (fp == NULL) { fprintf(stderr, "Open local file %s fail\n", target.c_str()); delete file; return -1; } char buf[10240]; int64_t bytes = 0; int32_t len = 0; while (1) { len = file->Read(buf, sizeof(buf)); if (len <= 0) { if (len < 0) { fprintf(stderr, "Read from %s fail.\n", source.c_str()); } break; } bytes += len; fwrite(buf, len, 1, fp); } printf("Read %ld bytes from %s\n", bytes, source.c_str()); delete file; fclose(fp); return len; } int BfsPut(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc != 4) { print_usage(); return 0; } std::string source = argv[2]; std::string target = argv[3]; if (source.empty() || source[source.size() - 1] == '/' || target.empty()) { fprintf(stderr, "Bad file path: %s or %s\n", source.c_str(), target.c_str()); return 1; } std::string src_file_name; size_t pos = source.rfind('/'); if (pos == std::string::npos) { src_file_name = source; } else { src_file_name = source.substr(pos+1); } if (target[target.size() - 1] == '/') { target += src_file_name; } int ret = 0; baidu::common::timer::AutoTimer at(0, "BfsPut", target.c_str()); FILE* fp = fopen(source.c_str(), "rb"); if (fp == NULL) { fprintf(stderr, "Can't open local file %s\n", argv[2]); return 1; } struct stat st; if (stat(source.c_str(), &st)) { fprintf(stderr, "Can't get file stat info %s\n", source.c_str()); return 1; } baidu::bfs::File* file; if (!fs->OpenFile(target.c_str(), O_WRONLY | O_TRUNC, st.st_mode, -1, &file)) { fprintf(stderr, "Can't Open bfs file %s\n", target.c_str()); fclose(fp); return 1; } char buf[10240]; int64_t len = 0; int32_t bytes = 0; while ( (bytes = fread(buf, 1, sizeof(buf), fp)) > 0) { int32_t write_bytes = file->Write(buf, bytes); if (write_bytes < bytes) { fprintf(stderr, "Write fail: [%s:%ld]\n", target.c_str(), len); return 1; } len += bytes; } if (!file->Close()) { fprintf(stderr, "close fail: %s\n", target.c_str()); ret = 1; } delete file; fclose(fp); printf("Put file to bfs %s %ld bytes\n", target.c_str(), len); return ret; } int64_t BfsDuRecursive(baidu::bfs::FS* fs, const std::string& path) { int64_t ret = 0; std::string pad; if (path[path.size() - 1] != '/') { pad = "/"; } baidu::bfs::BfsFileInfo* files = NULL; int num = 0; if (!fs->ListDirectory(path.c_str(), &files, &num)) { fprintf(stderr, "List directory fail: %s\n", path.c_str()); return ret; } for (int i = 0; i < num; i++) { std::string file_path = path + pad + files[i].name; int32_t type = files[i].mode; if (type & (1<<9)) { ret += BfsDuRecursive(fs, file_path); continue; } baidu::bfs::BfsFileInfo fileinfo; if (fs->Stat(file_path.c_str(), &fileinfo)) { ret += fileinfo.size; printf("%s\t %ld\n", file_path.c_str(), fileinfo.size); } } delete files; return ret; } int BfsDu(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc != 1) { print_usage(); return 1; } int64_t du = BfsDuRecursive(fs, argv[0]); printf("Total:\t%ld\n", du); return 0; } int BfsList(baidu::bfs::FS* fs, int argc, char* argv[]) { std::string path("/"); if (argc == 3) { path = argv[2]; if (path.size() && path[path.size()-1] != '/') { path.append("/"); } } baidu::bfs::BfsFileInfo* files = NULL; int num; bool ret = fs->ListDirectory(path.c_str(), &files, &num); if (!ret) { fprintf(stderr, "List dir %s fail\n", path.c_str()); return 1; } printf("Found %d items\n", num); for (int i = 0; i < num; i++) { int32_t type = files[i].mode; char statbuf[16] = "drwxrwxrwx"; for (int j = 0; j < 10; j++) { if ((type & (1<<(9-j))) == 0) { statbuf[j] = '-'; } } char timestr[64]; struct tm stm; time_t ctime = files[i].ctime; localtime_r(&ctime, &stm); snprintf(timestr, sizeof(timestr), "%4d-%02d-%02d %2d:%02d", stm.tm_year+1900, stm.tm_mon+1, stm.tm_mday, stm.tm_hour, stm.tm_min); printf("%s\t%s %s%s\n", statbuf, timestr, path.c_str(), files[i].name); } delete files; return 0; } int BfsRmdir(baidu::bfs::FS* fs, int argc, char* argv[], bool recursive) { if (argc < 1) { print_usage(); return 1; } bool ret = fs->DeleteDirectory(argv[0], recursive); if (!ret) { fprintf(stderr, "Remove dir %s fail\n", argv[0]); return 1; } return 0; } int BfsChangeReplicaNum(baidu::bfs::FS* fs, int argc, char* argv[]) { if (argc < 2) { print_usage(); return 1; } char* file_name = argv[0]; int32_t replica_num = atoi(argv[1]); bool ret = fs->ChangeReplicaNum(file_name, replica_num); if (!ret) { fprintf(stderr, "Change %s replica num to %d fail\n", file_name, replica_num); return 1; } return 0; } int BfsStat(baidu::bfs::FS* fs, int argc, char* argv[]) { std::string stat_name("Stat"); if (argc && 0 == strcmp(argv[0], "-a")) { stat_name = "StatAll"; } std::string result; bool ret = fs->SysStat(stat_name, &result); if (!ret) { fprintf(stderr, "SysStat fail\n"); return 1; } printf("%s\n", result.c_str()); return 0; } /// bfs client main int main(int argc, char* argv[]) { FLAGS_flagfile = "./bfs.flag"; int gflags_argc = 1; ::google::ParseCommandLineFlags(&gflags_argc, &argv, false); if (argc < 2) { print_usage(); return 0; } baidu::bfs::FS* fs; std::string ns_address = FLAGS_nameserver + ":" + FLAGS_nameserver_port; if (!baidu::bfs::FS::OpenFileSystem(ns_address.c_str(), &fs)) { fprintf(stderr, "Open filesytem %s fail\n", ns_address.c_str()); return 1; } int ret = 1; if (strcmp(argv[1], "touchz") == 0) { if (argc != 3) { print_usage(); return ret; } baidu::bfs::File* file; if (!fs->OpenFile(argv[2], O_WRONLY, 644, 0, &file)) { fprintf(stderr, "Open %s fail\n", argv[2]); } else { ret = 0; } } else if (strcmp(argv[1], "rm") == 0) { if (argc != 3) { print_usage(); return ret; } if (fs->DeleteFile(argv[2])) { printf("%s Removed\n", argv[2]); ret = 0; } else { fprintf(stderr, "Remove file fail: %s\n", argv[2]); } } else if (strcmp(argv[1], "mkdir") == 0) { ret = BfsMkdir(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "mv") == 0) { ret = BfsRename(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "put") == 0) { ret = BfsPut(fs, argc, argv); } else if (strcmp(argv[1], "get") == 0 ) { ret = BfsGet(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "cat") == 0) { ret = BfsCat(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "ls") == 0) { ret = BfsList(fs, argc, argv); } else if (strcmp(argv[1], "rmdir") == 0) { ret = BfsRmdir(fs, argc - 2, argv + 2, false); } else if (strcmp(argv[1], "rmr") == 0) { ret = BfsRmdir(fs, argc - 2, argv + 2, true); } else if (strcmp(argv[1], "change_replica_num") == 0) { ret = BfsChangeReplicaNum(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "du") == 0) { ret = BfsDu(fs, argc - 2, argv + 2); } else if (strcmp(argv[1], "stat") == 0) { ret = BfsStat(fs, argc - 2, argv + 2); } else { fprintf(stderr, "Unknow common: %s\n", argv[1]); } return ret; } /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
Use original mask when create file
Use original mask when create file
C++
bsd-3-clause
linyvxiang/dfs,yvxiang/dfs,lylei/dfs,yvxiang/coverage_for_bfs,bluebore/dfs,myawan/bfs-1,lylei/dfs,lylei/dfs,00k/ToyDFS,bluebore/dfs,00k/ToyDFS,yvxiang/coverage_for_bfs,baidu/bfs,bluebore/bfs,baidu/bfs,yvxiang/coverage_for_bfs,bluebore/bfs,imotai/bfs,bluebore/bfs,yvxiang/dfs,linyvxiang/dfs,imotai/bfs,yvxiang/dfs,baidu/bfs,myawan/bfs-1,yvxiang/dfs,bluebore/dfs,imotai/bfs,myawan/bfs-1,yvxiang/coverage_for_bfs,linyvxiang/dfs,myawan/bfs-1,lylei/dfs,baidu/bfs
e0e101daff1db918463976907a47ccbe57cc3d50
vespalib/src/vespa/vespalib/util/threadstackexecutorbase.cpp
vespalib/src/vespa/vespalib/util/threadstackexecutorbase.cpp
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "threadstackexecutorbase.h" #include <vespa/fastos/thread.h> namespace vespalib { namespace thread { struct ThreadInit : public FastOS_Runnable { Runnable &worker; ThreadStackExecutorBase::init_fun_t init_fun; explicit ThreadInit(Runnable &worker_in, ThreadStackExecutorBase::init_fun_t init_fun_in) : worker(worker_in), init_fun(std::move(init_fun_in)) {} void Run(FastOS_ThreadInterface *, void *) override; }; void ThreadInit::Run(FastOS_ThreadInterface *, void *) { init_fun(worker); } } ThreadStackExecutorBase::Worker::Worker() : lock(), cond(), idleTracker(), pre_guard(0xaaaaaaaa), idle(true), post_guard(0x55555555), task() {} void ThreadStackExecutorBase::Worker::verify(bool expect_idle) const { (void) expect_idle; assert(pre_guard == 0xaaaaaaaa); assert(post_guard == 0x55555555); assert(idle == expect_idle); assert(!task.task == expect_idle); } void ThreadStackExecutorBase::BlockedThread::wait() const { unique_lock guard(lock); while (blocked) { cond.wait(guard); } } void ThreadStackExecutorBase::BlockedThread::unblock() { unique_lock guard(lock); blocked = false; cond.notify_one(); } //----------------------------------------------------------------------------- thread_local ThreadStackExecutorBase *ThreadStackExecutorBase::_master = nullptr; //----------------------------------------------------------------------------- void ThreadStackExecutorBase::block_thread(const unique_lock &, BlockedThread &blocked_thread) { auto pos = _blocked.begin(); while ((pos != _blocked.end()) && ((*pos)->wait_task_count < blocked_thread.wait_task_count)) { ++pos; } _blocked.insert(pos, &blocked_thread); } void ThreadStackExecutorBase::unblock_threads(const unique_lock &) { while (!_blocked.empty() && (_taskCount <= _blocked.back()->wait_task_count)) { BlockedThread &blocked_thread = *(_blocked.back()); _blocked.pop_back(); blocked_thread.unblock(); } } void ThreadStackExecutorBase::assignTask(TaggedTask task, Worker &worker) { unique_lock guard(worker.lock); worker.verify(/* idle: */ true); worker.idle = false; worker.task = std::move(task); worker.cond.notify_one(); } bool ThreadStackExecutorBase::obtainTask(Worker &worker) { { unique_lock guard(_lock); if (!worker.idle) { assert(_taskCount != 0); --_taskCount; wakeup(guard, _cond); _barrier.completeEvent(worker.task.token); worker.idle = true; } worker.verify(/* idle: */ true); unblock_threads(guard); if (!_tasks.empty()) { worker.task = std::move(_tasks.front()); worker.idle = false; _tasks.pop(); return true; } if (_closed) { return false; } _workers.push(&worker); worker.idleTracker.set_idle(steady_clock::now()); } { unique_lock guard(worker.lock); while (worker.idle) { worker.cond.wait(guard); } } worker.idle = !worker.task.task; return !worker.idle; } void ThreadStackExecutorBase::run() { Worker worker; _master = this; worker.verify(/* idle: */ true); while (obtainTask(worker)) { worker.verify(/* idle: */ false); worker.task.task->run(); worker.task.task.reset(); } _executorCompletion.await(); // to allow unsafe signaling worker.verify(/* idle: */ true); _master = nullptr; } //----------------------------------------------------------------------------- ThreadStackExecutorBase::ThreadStackExecutorBase(uint32_t stackSize, uint32_t taskLimit, init_fun_t init_fun) : SyncableThreadExecutor(), Runnable(), _pool(std::make_unique<FastOS_ThreadPool>(stackSize)), _lock(), _cond(), _stats(), _idleTracker(steady_clock::now()), _executorCompletion(), _tasks(), _workers(), _barrier(), _taskCount(0), _taskLimit(taskLimit), _closed(false), _thread_init(std::make_unique<thread::ThreadInit>(*this, std::move(init_fun))) { assert(taskLimit > 0); } void ThreadStackExecutorBase::start(uint32_t threads) { assert(threads > 0); _idleTracker.reset(steady_clock::now(), threads); for (uint32_t i = 0; i < threads; ++i) { FastOS_ThreadInterface *thread = _pool->NewThread(_thread_init.get()); assert(thread != nullptr); (void)thread; } } size_t ThreadStackExecutorBase::getNumThreads() const { return _pool->GetNumStartedThreads(); } void ThreadStackExecutorBase::setTaskLimit(uint32_t taskLimit) { internalSetTaskLimit(taskLimit); } uint32_t ThreadStackExecutorBase::getTaskLimit() const { unique_lock guard(_lock); return _taskLimit; } void ThreadStackExecutorBase::wakeup() { // Nothing to do here as workers are always attentive. } void ThreadStackExecutorBase::internalSetTaskLimit(uint32_t taskLimit) { unique_lock guard(_lock); if (!_closed) { _taskLimit = taskLimit; wakeup(guard, _cond); } } size_t ThreadStackExecutorBase::num_idle_workers() const { std::unique_lock guard(_lock); return _workers.size(); } ExecutorStats ThreadStackExecutorBase::getStats() { std::unique_lock guard(_lock); ExecutorStats stats = _stats; steady_time now = steady_clock::now(); for (size_t i(0); i < _workers.size(); i++) { _idleTracker.was_idle(_workers.access(i)->idleTracker.reset(now)); } size_t numThreads = getNumThreads(); stats.setUtil(numThreads, _idleTracker.reset(now, numThreads)); _stats = ExecutorStats(); _stats.queueSize.add(_taskCount); return stats; } ThreadStackExecutorBase::Task::UP ThreadStackExecutorBase::execute(Task::UP task) { unique_lock guard(_lock); if (acceptNewTask(guard, _cond)) { TaggedTask taggedTask(std::move(task), _barrier.startEvent()); ++_taskCount; ++_stats.acceptedTasks; _stats.queueSize.add(_taskCount); if (!_workers.empty()) { Worker *worker = _workers.back(); _workers.popBack(); _idleTracker.was_idle(worker->idleTracker.set_active(steady_clock::now())); _stats.wakeupCount++; guard.unlock(); // <- UNLOCK assignTask(std::move(taggedTask), *worker); } else { _tasks.push(std::move(taggedTask)); } } else { ++_stats.rejectedTasks; } return task; } ThreadStackExecutorBase & ThreadStackExecutorBase::shutdown() { ArrayQueue<Worker*> idle; { unique_lock guard(_lock); _closed = true; _taskLimit = 0; idle.swap(_workers); assert(idle.empty() || _tasks.empty()); // idle -> empty queue wakeup(guard, _cond); } while (!idle.empty()) { assignTask(TaggedTask(), *idle.back()); idle.popBack(); } return *this; } ThreadStackExecutorBase & ThreadStackExecutorBase::sync() { BarrierCompletion barrierCompletion; { std::unique_lock guard(_lock); if (!_barrier.startBarrier(barrierCompletion)) { return *this; } } barrierCompletion.gate.await(); return *this; } void ThreadStackExecutorBase::wait_for_task_count(uint32_t task_count) { std::unique_lock guard(_lock); if (_taskCount <= task_count) { return; } BlockedThread self(task_count); block_thread(guard, self); guard.unlock(); // <- UNLOCK self.wait(); } void ThreadStackExecutorBase::cleanup() { shutdown().sync(); _executorCompletion.countDown(); _pool->Close(); } ThreadStackExecutorBase::~ThreadStackExecutorBase() { assert(_pool->isClosed()); assert(_taskCount == 0); assert(_blocked.empty()); } } // namespace vespalib
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "threadstackexecutorbase.h" #include <vespa/fastos/thread.h> namespace vespalib { namespace thread { struct ThreadInit : public FastOS_Runnable { Runnable &worker; ThreadStackExecutorBase::init_fun_t init_fun; explicit ThreadInit(Runnable &worker_in, ThreadStackExecutorBase::init_fun_t init_fun_in) : worker(worker_in), init_fun(std::move(init_fun_in)) {} void Run(FastOS_ThreadInterface *, void *) override; }; void ThreadInit::Run(FastOS_ThreadInterface *, void *) { init_fun(worker); } } ThreadStackExecutorBase::Worker::Worker() : lock(), cond(), idleTracker(), pre_guard(0xaaaaaaaa), idle(true), post_guard(0x55555555), task() {} void ThreadStackExecutorBase::Worker::verify(bool expect_idle) const { (void) expect_idle; assert(pre_guard == 0xaaaaaaaa); assert(post_guard == 0x55555555); assert(idle == expect_idle); assert(!task.task == expect_idle); } void ThreadStackExecutorBase::BlockedThread::wait() const { unique_lock guard(lock); while (blocked) { cond.wait(guard); } } void ThreadStackExecutorBase::BlockedThread::unblock() { unique_lock guard(lock); blocked = false; cond.notify_one(); } //----------------------------------------------------------------------------- thread_local ThreadStackExecutorBase *ThreadStackExecutorBase::_master = nullptr; //----------------------------------------------------------------------------- void ThreadStackExecutorBase::block_thread(const unique_lock &, BlockedThread &blocked_thread) { auto pos = _blocked.begin(); while ((pos != _blocked.end()) && ((*pos)->wait_task_count < blocked_thread.wait_task_count)) { ++pos; } _blocked.insert(pos, &blocked_thread); } void ThreadStackExecutorBase::unblock_threads(const unique_lock &) { while (!_blocked.empty() && (_taskCount <= _blocked.back()->wait_task_count)) { BlockedThread &blocked_thread = *(_blocked.back()); _blocked.pop_back(); blocked_thread.unblock(); } } void ThreadStackExecutorBase::assignTask(TaggedTask task, Worker &worker) { unique_lock guard(worker.lock); worker.verify(/* idle: */ true); worker.idle = false; worker.task = std::move(task); worker.cond.notify_one(); } bool ThreadStackExecutorBase::obtainTask(Worker &worker) { { unique_lock guard(_lock); if (!worker.idle) { assert(_taskCount != 0); --_taskCount; wakeup(guard, _cond); _barrier.completeEvent(worker.task.token); worker.idle = true; } worker.verify(/* idle: */ true); unblock_threads(guard); if (!_tasks.empty()) { worker.task = std::move(_tasks.front()); worker.idle = false; _tasks.pop(); return true; } if (_closed) { return false; } _workers.push(&worker); worker.idleTracker.set_idle(steady_clock::now()); } { unique_lock guard(worker.lock); while (worker.idle) { worker.cond.wait(guard); } } worker.idle = !worker.task.task; return !worker.idle; } void ThreadStackExecutorBase::run() { Worker worker; _master = this; worker.verify(/* idle: */ true); while (obtainTask(worker)) { worker.verify(/* idle: */ false); worker.task.task->run(); worker.task.task.reset(); } _executorCompletion.await(); // to allow unsafe signaling worker.verify(/* idle: */ true); _master = nullptr; } //----------------------------------------------------------------------------- ThreadStackExecutorBase::ThreadStackExecutorBase(uint32_t stackSize, uint32_t taskLimit, init_fun_t init_fun) : SyncableThreadExecutor(), Runnable(), _pool(std::make_unique<FastOS_ThreadPool>(stackSize)), _lock(), _cond(), _stats(), _idleTracker(steady_clock::now()), _executorCompletion(), _tasks(), _workers(), _barrier(), _taskCount(0), _taskLimit(taskLimit), _closed(false), _thread_init(std::make_unique<thread::ThreadInit>(*this, std::move(init_fun))) { assert(taskLimit > 0); } void ThreadStackExecutorBase::start(uint32_t threads) { assert(threads > 0); for (uint32_t i = 0; i < threads; ++i) { FastOS_ThreadInterface *thread = _pool->NewThread(_thread_init.get()); assert(thread != nullptr); (void)thread; } } size_t ThreadStackExecutorBase::getNumThreads() const { return _pool->GetNumStartedThreads(); } void ThreadStackExecutorBase::setTaskLimit(uint32_t taskLimit) { internalSetTaskLimit(taskLimit); } uint32_t ThreadStackExecutorBase::getTaskLimit() const { unique_lock guard(_lock); return _taskLimit; } void ThreadStackExecutorBase::wakeup() { // Nothing to do here as workers are always attentive. } void ThreadStackExecutorBase::internalSetTaskLimit(uint32_t taskLimit) { unique_lock guard(_lock); if (!_closed) { _taskLimit = taskLimit; wakeup(guard, _cond); } } size_t ThreadStackExecutorBase::num_idle_workers() const { std::unique_lock guard(_lock); return _workers.size(); } ExecutorStats ThreadStackExecutorBase::getStats() { std::unique_lock guard(_lock); ExecutorStats stats = _stats; steady_time now = steady_clock::now(); for (size_t i(0); i < _workers.size(); i++) { _idleTracker.was_idle(_workers.access(i)->idleTracker.reset(now)); } size_t numThreads = getNumThreads(); stats.setUtil(numThreads, _idleTracker.reset(now, numThreads)); _stats = ExecutorStats(); _stats.queueSize.add(_taskCount); return stats; } ThreadStackExecutorBase::Task::UP ThreadStackExecutorBase::execute(Task::UP task) { unique_lock guard(_lock); if (acceptNewTask(guard, _cond)) { TaggedTask taggedTask(std::move(task), _barrier.startEvent()); ++_taskCount; ++_stats.acceptedTasks; _stats.queueSize.add(_taskCount); if (!_workers.empty()) { Worker *worker = _workers.back(); _workers.popBack(); _idleTracker.was_idle(worker->idleTracker.set_active(steady_clock::now())); _stats.wakeupCount++; guard.unlock(); // <- UNLOCK assignTask(std::move(taggedTask), *worker); } else { _tasks.push(std::move(taggedTask)); } } else { ++_stats.rejectedTasks; } return task; } ThreadStackExecutorBase & ThreadStackExecutorBase::shutdown() { ArrayQueue<Worker*> idle; { unique_lock guard(_lock); _closed = true; _taskLimit = 0; idle.swap(_workers); assert(idle.empty() || _tasks.empty()); // idle -> empty queue wakeup(guard, _cond); } while (!idle.empty()) { assignTask(TaggedTask(), *idle.back()); idle.popBack(); } return *this; } ThreadStackExecutorBase & ThreadStackExecutorBase::sync() { BarrierCompletion barrierCompletion; { std::unique_lock guard(_lock); if (!_barrier.startBarrier(barrierCompletion)) { return *this; } } barrierCompletion.gate.await(); return *this; } void ThreadStackExecutorBase::wait_for_task_count(uint32_t task_count) { std::unique_lock guard(_lock); if (_taskCount <= task_count) { return; } BlockedThread self(task_count); block_thread(guard, self); guard.unlock(); // <- UNLOCK self.wait(); } void ThreadStackExecutorBase::cleanup() { shutdown().sync(); _executorCompletion.countDown(); _pool->Close(); } ThreadStackExecutorBase::~ThreadStackExecutorBase() { assert(_pool->isClosed()); assert(_taskCount == 0); assert(_blocked.empty()); } } // namespace vespalib
Remove reset of idletracker in start() method as it is protected.
Remove reset of idletracker in start() method as it is protected.
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
43ed174452edeb01fe71c49228b8474c351d992e
dune/gdt/functionals/default.hh
dune/gdt/functionals/default.hh
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_FUNCTIONALS_DEFAULT_HH #define DUNE_GDT_FUNCTIONALS_DEFAULT_HH #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/grid/walker/apply-on.hh> #include <dune/stuff/la/container/vector-interface.hh> #include <dune/gdt/assembler/wrapper.hh> #include <dune/gdt/assembler/system.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/localfunctional/interfaces.hh> #include <dune/gdt/spaces/interface.hh> #include "interfaces.hh" namespace Dune { namespace GDT { // forward, required for the traits template <class V, class S, class GV = typename S::GridViewType, class F = typename V::RealType> class VectorFunctionalDefault; namespace internal { template <class VectorImp, class SpaceImp, class GridViewImp, class FieldImp> class VectorFunctionalDefaultTraits { static_assert(Stuff::LA::is_vector<VectorImp>::value, "VectorType has to be derived from Stuff::LA::vectorInterface!"); static_assert(is_space<SpaceImp>::value, "SpaceType has to be derived from SpaceInterface!"); static_assert(std::is_same<typename SpaceImp::GridViewType::template Codim<0>::Entity, typename GridViewImp::template Codim<0>::Entity>::value, "SpaceType and GridViewType have to match!"); public: typedef VectorFunctionalDefault<VectorImp, SpaceImp, GridViewImp, FieldImp> derived_type; typedef FieldImp FieldType; }; } // namespace internal /** * \note Does a const_cast in apply(), not sure yet if this is fine. */ template <class VectorImp, class SpaceImp, class GridViewImp, class FieldImp> class VectorFunctionalDefault : public FunctionalInterface<internal::VectorFunctionalDefaultTraits<VectorImp, SpaceImp, GridViewImp, FieldImp>>, public SystemAssembler<SpaceImp, GridViewImp> { typedef FunctionalInterface<internal::VectorFunctionalDefaultTraits<VectorImp, SpaceImp, GridViewImp, FieldImp>> BaseFunctionalType; typedef SystemAssembler<SpaceImp, GridViewImp> BaseAssemblerType; typedef VectorFunctionalDefault<VectorImp, SpaceImp, GridViewImp, FieldImp> ThisType; public: typedef internal::VectorFunctionalDefaultTraits<VectorImp, SpaceImp, GridViewImp, FieldImp> Traits; typedef typename BaseAssemblerType::AnsatzSpaceType SpaceType; using typename BaseAssemblerType::GridViewType; typedef VectorImp VectorType; using typename BaseFunctionalType::FieldType; using typename BaseFunctionalType::derived_type; public: template <class... Args> explicit VectorFunctionalDefault(VectorType& vec, Args&&... args) : BaseAssemblerType(std::forward<Args>(args)...) , vector_(vec) { if (vector_.access().size() != this->space().mapper().size()) DUNE_THROW(Stuff::Exceptions::shapes_do_not_match, "vector.size(): " << vector_.access().size() << "\n" << "space().mapper().size(): " << this->space().mapper().size()); } // VectorFunctionalDefault(...) template <class... Args> explicit VectorFunctionalDefault(Args&&... args) : BaseAssemblerType(std::forward<Args>(args)...) , vector_(new VectorType(this->space().mapper().size(), 0.0)) { } VectorFunctionalDefault(ThisType&& source) = default; const VectorType& vector() const { return vector_.access(); } VectorType& vector() { return vector_.access(); } const SpaceType& space() const { return this->ansatz_space(); } using BaseAssemblerType::add; template <class F> void add(const LocalVolumeFunctionalInterface<F>& local_volume_functional, const DSG::ApplyOn::WhichEntity<GridViewType>* where = new DSG::ApplyOn::AllEntities<GridViewType>()) { typedef internal::LocalVolumeFunctionalWrapper<ThisType, typename LocalVolumeFunctionalInterface<F>::derived_type, VectorType> WrapperType; this->codim0_functors_.emplace_back( new WrapperType(this->test_space_, where, local_volume_functional.as_imp(), vector_.access())); } template <class S> FieldType apply(const Stuff::LA::VectorInterface<S>& source) const { const_cast<ThisType&>(*this).assemble(); return vector().dot(source.as_imp()); } template <class S> void apply(const ConstDiscreteFunction<SpaceType, S>& source) const { return apply(source.vector()); } private: DSC::StorageProvider<VectorType> vector_; }; // class VectorFunctionalDefault } // namespace GDT } // namespace Dune #endif // DUNE_GDT_FUNCTIONALS_DEFAULT_HH
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_FUNCTIONALS_DEFAULT_HH #define DUNE_GDT_FUNCTIONALS_DEFAULT_HH #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/grid/walker/apply-on.hh> #include <dune/stuff/la/container/vector-interface.hh> #include <dune/gdt/assembler/wrapper.hh> #include <dune/gdt/assembler/system.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/localfunctional/interfaces.hh> #include <dune/gdt/spaces/interface.hh> #include "interfaces.hh" namespace Dune { namespace GDT { // forward, required for the traits template <class V, class S, class GV = typename S::GridViewType, class F = typename V::RealType> class VectorFunctionalDefault; namespace internal { template <class VectorImp, class SpaceImp, class GridViewImp, class FieldImp> class VectorFunctionalDefaultTraits { static_assert(Stuff::LA::is_vector<VectorImp>::value, "VectorType has to be derived from Stuff::LA::vectorInterface!"); static_assert(is_space<SpaceImp>::value, "SpaceType has to be derived from SpaceInterface!"); static_assert(std::is_same<typename SpaceImp::GridViewType::template Codim<0>::Entity, typename GridViewImp::template Codim<0>::Entity>::value, "SpaceType and GridViewType have to match!"); public: typedef VectorFunctionalDefault<VectorImp, SpaceImp, GridViewImp, FieldImp> derived_type; typedef FieldImp FieldType; }; } // namespace internal /** * \note Does a const_cast in apply(), not sure yet if this is fine. */ template <class VectorImp, class SpaceImp, class GridViewImp, class FieldImp> class VectorFunctionalDefault : public FunctionalInterface<internal::VectorFunctionalDefaultTraits<VectorImp, SpaceImp, GridViewImp, FieldImp>>, public SystemAssembler<SpaceImp, GridViewImp> { typedef FunctionalInterface<internal::VectorFunctionalDefaultTraits<VectorImp, SpaceImp, GridViewImp, FieldImp>> BaseFunctionalType; typedef SystemAssembler<SpaceImp, GridViewImp> BaseAssemblerType; typedef VectorFunctionalDefault<VectorImp, SpaceImp, GridViewImp, FieldImp> ThisType; public: typedef internal::VectorFunctionalDefaultTraits<VectorImp, SpaceImp, GridViewImp, FieldImp> Traits; typedef typename BaseAssemblerType::AnsatzSpaceType SpaceType; using typename BaseAssemblerType::GridViewType; typedef VectorImp VectorType; using typename BaseFunctionalType::FieldType; using typename BaseFunctionalType::derived_type; public: template <class... Args> explicit VectorFunctionalDefault(VectorType& vec, Args&&... args) : BaseAssemblerType(std::forward<Args>(args)...) , vector_(vec) { if (vector_.access().size() != this->space().mapper().size()) DUNE_THROW(Stuff::Exceptions::shapes_do_not_match, "vector.size(): " << vector_.access().size() << "\n" << "space().mapper().size(): " << this->space().mapper().size()); } // VectorFunctionalDefault(...) template <class... Args> explicit VectorFunctionalDefault(Args&&... args) : BaseAssemblerType(std::forward<Args>(args)...) , vector_(new VectorType(this->space().mapper().size(), 0.0)) { } VectorFunctionalDefault(ThisType&& source) = default; const VectorType& vector() const { return vector_.access(); } VectorType& vector() { return vector_.access(); } const SpaceType& space() const { return this->ansatz_space(); } using BaseAssemblerType::add; template <class F> void add(const LocalVolumeFunctionalInterface<F>& local_volume_functional, const DSG::ApplyOn::WhichEntity<GridViewType>* where = new DSG::ApplyOn::AllEntities<GridViewType>()) { typedef internal::LocalVolumeFunctionalWrapper<ThisType, typename LocalVolumeFunctionalInterface<F>::derived_type, VectorType> WrapperType; this->codim0_functors_.emplace_back( new WrapperType(this->test_space_, where, local_volume_functional.as_imp(), vector_.access())); } template <class F> void add(const LocalFaceFunctionalInterface<F>& local_face_functional, const DSG::ApplyOn::WhichIntersection<GridViewType>* where = new DSG::ApplyOn::AllIntersections<GridViewType>()) { typedef internal::LocalFaceFunctionalWrapper<ThisType, typename LocalFaceFunctionalInterface<F>::derived_type, VectorType> WrapperType; this->codim1_functors_.emplace_back( new WrapperType(this->test_space_, where, local_face_functional.as_imp(), vector_.access())); } template <class S> FieldType apply(const Stuff::LA::VectorInterface<S>& source) const { const_cast<ThisType&>(*this).assemble(); return vector().dot(source.as_imp()); } template <class S> void apply(const ConstDiscreteFunction<SpaceType, S>& source) const { return apply(source.vector()); } private: DSC::StorageProvider<VectorType> vector_; }; // class VectorFunctionalDefault } // namespace GDT } // namespace Dune #endif // DUNE_GDT_FUNCTIONALS_DEFAULT_HH
add `add()` for LocalFaceFunctionalInterface
[functionals.default] add `add()` for LocalFaceFunctionalInterface
C++
bsd-2-clause
pymor/dune-gdt
f6f56b2daaca4db44931ba46eadedcaa3a272ae3
src/mlpack/methods/naive_bayes/nbc_main.cpp
src/mlpack/methods/naive_bayes/nbc_main.cpp
/** * @author Parikshit Ram ([email protected]) * @file nbc_main.cpp * * This program runs the Simple Naive Bayes Classifier. * * This classifier does parametric naive bayes classification assuming that the * features are sampled from a Gaussian distribution. */ #include <mlpack/core.hpp> #include "naive_bayes_classifier.hpp" PROGRAM_INFO("Parametric Naive Bayes Classifier", "This program trains the Naive Bayes classifier on the given labeled " "training set and then uses the trained classifier to classify the points " "in the given test set." "\n\n" "Labels are expected to be the last row of the training set (--train_file)," " but labels can also be passed in separately as their own file " "(--labels_file)." "\n\n" "The '--incremental_variance' option can be used to force the training to " "use an incremental algorithm for calculating variance. This is slower, " "but can help avoid loss of precision in some cases."); PARAM_STRING_REQ("train_file", "A file containing the training set.", "t"); PARAM_STRING_REQ("test_file", "A file containing the test set.", "T"); PARAM_STRING("labels_file", "A file containing labels for the training set.", "l", ""); PARAM_STRING("output", "The file in which the predicted labels for the test set" " will be written.", "o", "output.csv"); PARAM_FLAG("incremental_variance", "The variance of each class will be " "calculated incrementally.", "I"); using namespace mlpack; using namespace mlpack::naive_bayes; using namespace std; using namespace arma; int main(int argc, char* argv[]) { CLI::ParseCommandLine(argc, argv); // Check input parameters. const string trainingDataFilename = CLI::GetParam<string>("train_file"); mat trainingData; data::Load(trainingDataFilename, trainingData, true); // Normalize labels. Col<size_t> labels; vec mappings; // Did the user pass in labels? const string labelsFilename = CLI::GetParam<string>("labels_file"); if (labelsFilename != "") { // Load labels. mat rawLabels; data::Load(labelsFilename, rawLabels, true, false); // Do the labels need to be transposed? if (rawLabels.n_rows == 1) rawLabels = rawLabels.t(); data::NormalizeLabels(rawLabels.unsafe_col(0), labels, mappings); } else { // Use the last row of the training data as the labels. Log::Info << "Using last dimension of training data as training labels." << std::endl; vec rawLabels = trans(trainingData.row(trainingData.n_rows - 1)); data::NormalizeLabels(rawLabels, labels, mappings); // Remove the label row. trainingData.shed_row(trainingData.n_rows - 1); } const string testingDataFilename = CLI::GetParam<std::string>("test_file"); mat testingData; data::Load(testingDataFilename, testingData, true); if (testingData.n_rows != trainingData.n_rows) Log::Fatal << "Test data dimensionality (" << testingData.n_rows << ") " << "must be the same as training data (" << trainingData.n_rows - 1 << ")!" << std::endl; const bool incrementalVariance = CLI::HasParam("incremental_variance"); // Create and train the classifier. Timer::Start("training"); NaiveBayesClassifier<> nbc(trainingData, labels, mappings.n_elem, incrementalVariance); Timer::Stop("training"); // Time the running of the Naive Bayes Classifier. Col<size_t> results; Timer::Start("testing"); nbc.Classify(testingData, results); Timer::Stop("testing"); // Un-normalize labels to prepare output. vec rawResults; data::RevertLabels(results, mappings, rawResults); // Output results. Don't transpose: one result per line. const string outputFilename = CLI::GetParam<string>("output"); data::Save(outputFilename, rawResults, true, false); }
/** * @author Parikshit Ram ([email protected]) * @file nbc_main.cpp * * This program runs the Simple Naive Bayes Classifier. * * This classifier does parametric naive bayes classification assuming that the * features are sampled from a Gaussian distribution. */ #include <mlpack/core.hpp> #include "naive_bayes_classifier.hpp" PROGRAM_INFO("Parametric Naive Bayes Classifier", "This program trains the Naive Bayes classifier on the given labeled " "training set and then uses the trained classifier to classify the points " "in the given test set." "\n\n" "Labels are expected to be the last row of the training set (--train_file)," " but labels can also be passed in separately as their own file " "(--labels_file)." "\n\n" "The '--incremental_variance' option can be used to force the training to " "use an incremental algorithm for calculating variance. This is slower, " "but can help avoid loss of precision in some cases."); PARAM_STRING_REQ("train_file", "A file containing the training set.", "t"); PARAM_STRING_REQ("test_file", "A file containing the test set.", "T"); PARAM_STRING("labels_file", "A file containing labels for the training set.", "l", ""); PARAM_STRING("output", "The file in which the predicted labels for the test set" " will be written.", "o", "output.csv"); PARAM_FLAG("incremental_variance", "The variance of each class will be " "calculated incrementally.", "I"); using namespace mlpack; using namespace mlpack::naive_bayes; using namespace std; using namespace arma; int main(int argc, char* argv[]) { CLI::ParseCommandLine(argc, argv); // Check input parameters. const string trainingDataFilename = CLI::GetParam<string>("train_file"); mat trainingData; data::Load(trainingDataFilename, trainingData, true); // Normalize labels. Col<size_t> labels; vec mappings; // Did the user pass in labels? const string labelsFilename = CLI::GetParam<string>("labels_file"); if (labelsFilename != "") { // Load labels. mat rawLabels; data::Load(labelsFilename, rawLabels, true, false); // Do the labels need to be transposed? if (rawLabels.n_rows == 1) rawLabels = rawLabels.t(); data::NormalizeLabels(rawLabels.unsafe_col(0), labels, mappings); } else { // Use the last row of the training data as the labels. Log::Info << "Using last dimension of training data as training labels." << std::endl; vec rawLabels = trans(trainingData.row(trainingData.n_rows - 1)); data::NormalizeLabels(rawLabels, labels, mappings); // Remove the label row. trainingData.shed_row(trainingData.n_rows - 1); } const string testingDataFilename = CLI::GetParam<std::string>("test_file"); mat testingData; data::Load(testingDataFilename, testingData, true); if (testingData.n_rows != (trainingData.n_rows - 1)) Log::Fatal << "Test data dimensionality (" << testingData.n_rows << ") " << "must be the same as training data (" << trainingData.n_rows - 1 << ")!" << std::endl; const bool incrementalVariance = CLI::HasParam("incremental_variance"); // Create and train the classifier. Timer::Start("training"); NaiveBayesClassifier<> nbc(trainingData, labels, mappings.n_elem, incrementalVariance); Timer::Stop("training"); // Time the running of the Naive Bayes Classifier. Col<size_t> results; Timer::Start("testing"); nbc.Classify(testingData, results); Timer::Stop("testing"); // Un-normalize labels to prepare output. vec rawResults; data::RevertLabels(results, mappings, rawResults); // Output results. Don't transpose: one result per line. const string outputFilename = CLI::GetParam<string>("output"); data::Save(outputFilename, rawResults, true, false); }
Fix incorrect check (how did this happen?).
Fix incorrect check (how did this happen?).
C++
bsd-3-clause
BookChan/mlpack,darcyliu/mlpack,ajjl/mlpack,theranger/mlpack,theranger/mlpack,ranjan1990/mlpack,thirdwing/mlpack,ersanliqiao/mlpack,chenmoshushi/mlpack,thirdwing/mlpack,ajjl/mlpack,erubboli/mlpack,Azizou/mlpack,minhpqn/mlpack,BookChan/mlpack,Azizou/mlpack,stereomatchingkiss/mlpack,chenmoshushi/mlpack,ranjan1990/mlpack,lezorich/mlpack,chenmoshushi/mlpack,palashahuja/mlpack,ersanliqiao/mlpack,erubboli/mlpack,stereomatchingkiss/mlpack,theranger/mlpack,darcyliu/mlpack,trungda/mlpack,minhpqn/mlpack,darcyliu/mlpack,ersanliqiao/mlpack,trungda/mlpack,datachand/mlpack,stereomatchingkiss/mlpack,thirdwing/mlpack,trungda/mlpack,ajjl/mlpack,erubboli/mlpack,palashahuja/mlpack,bmswgnp/mlpack,Azizou/mlpack,datachand/mlpack,lezorich/mlpack,bmswgnp/mlpack,datachand/mlpack,lezorich/mlpack,bmswgnp/mlpack,palashahuja/mlpack,BookChan/mlpack,minhpqn/mlpack,ranjan1990/mlpack
84c71b38d3fd182fd92f8376396b2198ed5002d1
src/main/cc/wfa/virtual_people/core/labeler/labeler.cc
src/main/cc/wfa/virtual_people/core/labeler/labeler.cc
// Copyright 2021 The Cross-Media Measurement Authors // // 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 "wfa/virtual_people/core/labeler/labeler.h" #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "common_cpp/macros/macros.h" #include "src/farmhash.h" #include "wfa/virtual_people/common/event.pb.h" #include "wfa/virtual_people/common/label.pb.h" #include "wfa/virtual_people/common/model.pb.h" #include "wfa/virtual_people/core/model/model_node.h" namespace wfa_virtual_people { absl::StatusOr<std::unique_ptr<Labeler>> Labeler::Build( const CompiledNode& root) { ASSIGN_OR_RETURN(std::unique_ptr<ModelNode> root_node, ModelNode::Build(root)); return absl::make_unique<Labeler>(std::move(root_node)); } absl::StatusOr<std::unique_ptr<Labeler>> Labeler::Build( const std::vector<CompiledNode>& nodes) { std::unique_ptr<ModelNode> root = nullptr; absl::flat_hash_map<uint32_t, std::unique_ptr<ModelNode>> node_refs; for (const CompiledNode& node_config : nodes) { if (root) { return absl::InvalidArgumentError( "No node is allowed after the root node."); } if (node_config.has_index()) { ASSIGN_OR_RETURN(std::unique_ptr<ModelNode> node, ModelNode::Build(node_config, node_refs)); if (!node_refs.insert({node_config.index(), std::move(node)}).second) { return absl::InvalidArgumentError( absl::StrCat("Duplicated indexes: ", node_config.index())); } } else { ASSIGN_OR_RETURN(root, ModelNode::Build(node_config, node_refs)); } } if (!root) { if (node_refs.empty()) { // This should never happen. return absl::InternalError("Cannot find root node."); } // We expect only 1 node in the node_refs map, which is the root node. root = std::move(node_refs.extract(node_refs.begin()).mapped()); } if (!root) { // This should never happen. return absl::InternalError("Root is NULL."); } if (!node_refs.empty()) { return absl::InvalidArgumentError("Some nodes are not in the model tree."); } return absl::make_unique<Labeler>(std::move(root)); } void SetUserInfoFingerprint(UserInfo& user_info) { if (user_info.has_user_id()) { user_info.set_user_id_fingerprint(util::Fingerprint64(user_info.user_id())); } } // Generates fingerprints for event_id and user_id. // The default value of acting_fingerprint is the fingerprint of event_id. void SetFingerprints(LabelerEvent& event) { LabelerInput* labeler_input = event.mutable_labeler_input(); if (labeler_input->has_event_id()) { uint64_t event_id_fingerprint = util::Fingerprint64(labeler_input->event_id().id()); labeler_input->mutable_event_id()->set_id_fingerprint(event_id_fingerprint); event.set_acting_fingerprint(event_id_fingerprint); } if (!labeler_input->has_profile_info()) { return; } ProfileInfo* profile_info = labeler_input->mutable_profile_info(); if (profile_info->has_email_user_info()) { SetUserInfoFingerprint(*profile_info->mutable_email_user_info()); } if (profile_info->has_phone_user_info()) { SetUserInfoFingerprint(*profile_info->mutable_phone_user_info()); } if (profile_info->has_proprietary_id_space_1_user_info()) { SetUserInfoFingerprint( *profile_info->mutable_proprietary_id_space_1_user_info()); } } absl::Status Labeler::Label(const LabelerInput& input, LabelerOutput& output) const { // Prepare labeler event. LabelerEvent event; *event.mutable_labeler_input() = input; SetFingerprints(event); // Apply model. RETURN_IF_ERROR(root_->Apply(event)); // Populate data to output. *output.mutable_people() = event.virtual_person_activities(); return absl::OkStatus(); } } // namespace wfa_virtual_people
// Copyright 2021 The Cross-Media Measurement Authors // // 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 "wfa/virtual_people/core/labeler/labeler.h" #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "common_cpp/macros/macros.h" #include "src/farmhash.h" #include "wfa/virtual_people/common/event.pb.h" #include "wfa/virtual_people/common/label.pb.h" #include "wfa/virtual_people/common/model.pb.h" #include "wfa/virtual_people/core/model/model_node.h" namespace wfa_virtual_people { absl::StatusOr<std::unique_ptr<Labeler>> Labeler::Build( const CompiledNode& root) { ASSIGN_OR_RETURN(std::unique_ptr<ModelNode> root_node, ModelNode::Build(root)); return absl::make_unique<Labeler>(std::move(root_node)); } absl::StatusOr<std::unique_ptr<Labeler>> Labeler::Build( const std::vector<CompiledNode>& nodes) { std::unique_ptr<ModelNode> root = nullptr; absl::flat_hash_map<uint32_t, std::unique_ptr<ModelNode>> node_refs; for (const CompiledNode& node_config : nodes) { if (root) { return absl::InvalidArgumentError( "No node is allowed after the root node."); } if (node_config.has_index()) { ASSIGN_OR_RETURN(std::unique_ptr<ModelNode> node, ModelNode::Build(node_config, node_refs)); if (!node_refs.insert({node_config.index(), std::move(node)}).second) { return absl::InvalidArgumentError( absl::StrCat("Duplicated indexes: ", node_config.index())); } } else { ASSIGN_OR_RETURN(root, ModelNode::Build(node_config, node_refs)); } } if (!root) { if (node_refs.empty()) { // This should never happen. return absl::InternalError("Cannot find root node."); } // We expect only 1 node in the node_refs map, which is the root node. root = std::move(node_refs.extract(node_refs.begin()).mapped()); } if (!root) { // This should never happen. return absl::InternalError("Root is NULL."); } if (!node_refs.empty()) { return absl::InvalidArgumentError("Some nodes are not in the model tree."); } return absl::make_unique<Labeler>(std::move(root)); } void SetUserInfoFingerprint(UserInfo& user_info) { if (user_info.has_user_id()) { user_info.set_user_id_fingerprint(util::Fingerprint64(user_info.user_id())); } } // Generates fingerprints for event_id and user_id. // The default value of acting_fingerprint is the fingerprint of event_id. void SetFingerprints(LabelerEvent& event) { LabelerInput* labeler_input = event.mutable_labeler_input(); if (labeler_input->has_event_id()) { uint64_t event_id_fingerprint = util::Fingerprint64(labeler_input->event_id().id()); labeler_input->mutable_event_id()->set_id_fingerprint(event_id_fingerprint); event.set_acting_fingerprint(event_id_fingerprint); } if (!labeler_input->has_profile_info()) { return; } ProfileInfo* profile_info = labeler_input->mutable_profile_info(); if (profile_info->has_email_user_info()) { SetUserInfoFingerprint(*profile_info->mutable_email_user_info()); } if (profile_info->has_phone_user_info()) { SetUserInfoFingerprint(*profile_info->mutable_phone_user_info()); } if (profile_info->has_proprietary_id_space_1_user_info()) { SetUserInfoFingerprint( *profile_info->mutable_proprietary_id_space_1_user_info()); } } absl::Status Labeler::Label(const LabelerInput& input, LabelerOutput& output) const { // Prepare labeler event. LabelerEvent event; *event.mutable_labeler_input() = input; SetFingerprints(event); // Apply model. RETURN_IF_ERROR(root_->Apply(event)); // Populate data to output. *output.mutable_people() = event.virtual_person_activities(); // TODO(@tcsnfkx): Update the content of debug trace. Currently only set the // debug trace to be the LabelerEvent. output.set_serialized_debug_trace(event.SerializeAsString()); return absl::OkStatus(); } } // namespace wfa_virtual_people
Set the debug trace to be LabelerEvent. (#26)
Set the debug trace to be LabelerEvent. (#26)
C++
apache-2.0
world-federation-of-advertisers/virtual-people-core-serving,world-federation-of-advertisers/virtual-people-core-serving
8d6aa35aa5149489841627aae79c23d3dce89f6a
bindings/python/src/session_settings.cpp
bindings/python/src/session_settings.cpp
// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; void bind_session_settings() { class_<session_settings>("session_settings") .def_readwrite("user_agent", &session_settings::user_agent) .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout) .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout) .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length) .def_readwrite("piece_timeout", &session_settings::piece_timeout) .def_readwrite("request_queue_time", &session_settings::request_queue_time) .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue) .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue) .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold) .def_readwrite("peer_timeout", &session_settings::peer_timeout) .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout) .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size) .def_readwrite("file_pool_size", &session_settings::file_pool_size) .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip) .def_readwrite("max_failcount", &session_settings::max_failcount) .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time) .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout) .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network) .def_readwrite("connection_speed", &session_settings::connection_speed) .def_readwrite("send_redundant_have", &session_settings::send_redundant_have) .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields) .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout) .def_readwrite("unchoke_interval", &session_settings::unchoke_interval) .def_readwrite("active_downloads", &session_settings::active_downloads) .def_readwrite("active_seeds", &session_settings::active_seeds) .def_readwrite("active_limit", &session_settings::active_limit) .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents) .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval) .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit) .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit) .def_readwrite("seed_time_limit", &session_settings::seed_time_limit) .def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval) #ifndef TORRENT_DISABLE_DHT .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback) #endif ; enum_<proxy_settings::proxy_type>("proxy_type") .value("none", proxy_settings::none) .value("socks4", proxy_settings::socks4) .value("socks5", proxy_settings::socks5) .value("socks5_pw", proxy_settings::socks5_pw) .value("http", proxy_settings::http) .value("http_pw", proxy_settings::http_pw) ; class_<proxy_settings>("proxy_settings") .def_readwrite("hostname", &proxy_settings::hostname) .def_readwrite("port", &proxy_settings::port) .def_readwrite("password", &proxy_settings::password) .def_readwrite("username", &proxy_settings::username) .def_readwrite("type", &proxy_settings::type) ; #ifndef TORRENT_DISABLE_ENCRYPTION enum_<pe_settings::enc_policy>("enc_policy") .value("forced", pe_settings::forced) .value("enabled", pe_settings::enabled) .value("disabled", pe_settings::disabled) ; enum_<pe_settings::enc_level>("enc_level") .value("rc4", pe_settings::rc4) .value("plaintext", pe_settings::plaintext) .value("both", pe_settings::both) ; class_<pe_settings>("pe_settings") .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy) .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy) .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level) .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4) ; #endif }
// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; void bind_session_settings() { class_<session_settings>("session_settings") .def_readwrite("user_agent", &session_settings::user_agent) .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout) .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout) .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length) .def_readwrite("piece_timeout", &session_settings::piece_timeout) .def_readwrite("request_queue_time", &session_settings::request_queue_time) .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue) .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue) .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold) .def_readwrite("peer_timeout", &session_settings::peer_timeout) .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout) .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size) .def_readwrite("file_pool_size", &session_settings::file_pool_size) .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip) .def_readwrite("max_failcount", &session_settings::max_failcount) .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time) .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout) .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network) .def_readwrite("connection_speed", &session_settings::connection_speed) .def_readwrite("send_redundant_have", &session_settings::send_redundant_have) .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields) .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout) .def_readwrite("unchoke_interval", &session_settings::unchoke_interval) .def_readwrite("active_downloads", &session_settings::active_downloads) .def_readwrite("active_seeds", &session_settings::active_seeds) .def_readwrite("active_limit", &session_settings::active_limit) .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents) .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval) .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit) .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit) .def_readwrite("seed_time_limit", &session_settings::seed_time_limit) .def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval) .def_readwrite("peer_tos", &session_settings::peer_tos) #ifndef TORRENT_DISABLE_DHT .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback) #endif ; enum_<proxy_settings::proxy_type>("proxy_type") .value("none", proxy_settings::none) .value("socks4", proxy_settings::socks4) .value("socks5", proxy_settings::socks5) .value("socks5_pw", proxy_settings::socks5_pw) .value("http", proxy_settings::http) .value("http_pw", proxy_settings::http_pw) ; class_<proxy_settings>("proxy_settings") .def_readwrite("hostname", &proxy_settings::hostname) .def_readwrite("port", &proxy_settings::port) .def_readwrite("password", &proxy_settings::password) .def_readwrite("username", &proxy_settings::username) .def_readwrite("type", &proxy_settings::type) ; #ifndef TORRENT_DISABLE_ENCRYPTION enum_<pe_settings::enc_policy>("enc_policy") .value("forced", pe_settings::forced) .value("enabled", pe_settings::enabled) .value("disabled", pe_settings::disabled) ; enum_<pe_settings::enc_level>("enc_level") .value("rc4", pe_settings::rc4) .value("plaintext", pe_settings::plaintext) .value("both", pe_settings::both) ; class_<pe_settings>("pe_settings") .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy) .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy) .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level) .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4) ; #endif }
Add session_settings::peer_tos to bindings
Add session_settings::peer_tos to bindings git-svn-id: c39a6fcb73c71bf990fd9353909696546eb40440@2581 a83610d8-ad2a-0410-a6ab-fc0612d85776
C++
bsd-3-clause
mirror/libtorrent,mirror/libtorrent,john-peterson/libtorrent-old,john-peterson/libtorrent-old,mirror/libtorrent,mirror/libtorrent,john-peterson/libtorrent-old,john-peterson/libtorrent-old,john-peterson/libtorrent-old,john-peterson/libtorrent-old,mirror/libtorrent,mirror/libtorrent
1e48244ff6f11060ac885a38e4ad0d29741e735e
src/common/tga_image.cpp
src/common/tga_image.cpp
// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstdint> #include <cstring> // for memset #include <fstream> #include <iostream> #include <ostream> #include <visionaray/swizzle.h> #include "tga_image.h" namespace visionaray { //------------------------------------------------------------------------------------------------- // TGA header // #pragma pack(push, 1) struct tga_header { uint8_t id_length; uint8_t color_map_type; uint8_t image_type; uint16_t color_map_first_entry; uint16_t color_map_num_entries; uint8_t color_map_entry_size; uint16_t x_origin; uint16_t y_origin; uint16_t width; uint16_t height; uint8_t bits_per_pixel; uint8_t image_desc; }; #pragma pack(pop) //------------------------------------------------------------------------------------------------- // Helper functions // pixel_format map_pixel_depth(uint8_t bits_per_pixel) { switch (bits_per_pixel) { case 24: return PF_RGB8; case 32: return PF_RGBA8; default: return PF_UNSPECIFIED; } } void load_true_color_uncompressed( uint8_t* dst, std::ifstream& file, int width, int height, int bytes_per_pixel, int y_origin ) { int pitch = width * bytes_per_pixel; if (y_origin == 0) { // Origin is bottom/left corner - same as visionaray image format file.read(reinterpret_cast<char*>(dst), pitch * height * sizeof(uint8_t)); } else if (y_origin == height) { // Origin is top/left corner - convert to bottom/left for (int y = 0; y < height; ++y) { auto ptr = dst + (height - 1) * pitch - y * pitch; file.read(reinterpret_cast<char*>(ptr), pitch * sizeof(uint8_t)); } } else { std::cerr << "Unsupported TGA image, y-origin (" << y_origin << ") is neither bottom nor top\n"; } } void load_true_color_rle( uint8_t* dst, std::ifstream& file, int width, int height, int bytes_per_pixel, int y_origin ) { if (y_origin != 0 && y_origin != height) { std::cerr << "Unsupported TGA image, y-origin (" << y_origin << ") is neither bottom nor top\n"; return; } int pixels = 0; while (pixels < width * height) { uint8_t chunk_header = 0; file.read((char*)&chunk_header, sizeof(chunk_header)); int current_pixel = pixels; // true if y-origin = 0 if (y_origin == height) { int x = pixels % width; int y = pixels / width; current_pixel = (height - 1) * width - y * width + x; } auto ptr = dst + current_pixel * bytes_per_pixel; if (chunk_header < 128) { ++chunk_header; file.read(reinterpret_cast<char*>(ptr), chunk_header * bytes_per_pixel); } else { chunk_header -= 127; char buffer[4]; file.read(buffer, bytes_per_pixel); for (uint8_t i = 0; i < chunk_header; ++i) { for (int b = 0; b < bytes_per_pixel; ++b) { *(ptr + i * bytes_per_pixel + b) = buffer[b]; } } } pixels += chunk_header; } } //------------------------------------------------------------------------------------------------- // tga_image // tga_image::tga_image(std::string const& filename) { std::ifstream file(filename, std::ios::in | std::ios::binary); // Read header tga_header header; memset(&header, 0, sizeof(header)); file.seekg (0, file.beg); file.read(reinterpret_cast<char*>(&header), sizeof(header)); width_ = static_cast<size_t>(header.width); height_ = static_cast<size_t>(header.height); format_ = map_pixel_depth(header.bits_per_pixel); auto pitch = header.width * (header.bits_per_pixel / 8); data_.resize(pitch * header.height); // Read image data file.seekg(sizeof(header) + header.id_length, file.beg); switch (header.image_type) { default: std::cerr << "Unsupported TGA image type (" << (int)header.image_type << ")\n"; // fall-through case 0: // no image data width_ = 0; height_ = 0; format_ = PF_UNSPECIFIED; data_.resize(0); break; case 2: load_true_color_uncompressed( data_.data(), file, header.width, header.height, header.bits_per_pixel / 8, header.y_origin ); break; case 10: load_true_color_rle( data_.data(), file, header.width, header.height, header.bits_per_pixel / 8, header.y_origin ); break; } // Swizzle from BGR(A) to RGB(A) if (format_ == PF_RGB8) { swizzle( reinterpret_cast<vector<3, unorm<8>>*>(data_.data()), PF_RGB8, PF_BGR8, data_.size() / 3 ); } else if (format_ == PF_RGBA8) { swizzle( reinterpret_cast<vector<4, unorm<8>>*>(data_.data()), PF_RGBA8, PF_BGRA8, data_.size() / 4 ); } } } // visionaray
// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstdint> #include <cstring> // for memset #include <fstream> #include <iostream> #include <ostream> #include <visionaray/swizzle.h> #include "tga_image.h" namespace visionaray { //------------------------------------------------------------------------------------------------- // TGA header // #pragma pack(push, 1) struct tga_header { uint8_t id_length; uint8_t color_map_type; uint8_t image_type; uint16_t color_map_first_entry; uint16_t color_map_num_entries; uint8_t color_map_entry_size; uint16_t x_origin; uint16_t y_origin; uint16_t width; uint16_t height; uint8_t bits_per_pixel; uint8_t image_desc; }; #pragma pack(pop) //------------------------------------------------------------------------------------------------- // Helper functions // pixel_format map_pixel_depth(uint8_t bits_per_pixel) { switch (bits_per_pixel) { case 24: return PF_RGB8; case 32: return PF_RGBA8; default: return PF_UNSPECIFIED; } } void load_true_color_uncompressed( uint8_t* dst, std::ifstream& file, int width, int height, int bytes_per_pixel, bool flip_y ) { int pitch = width * bytes_per_pixel; if (!flip_y) { // Origin is bottom/left corner - same as visionaray image format file.read(reinterpret_cast<char*>(dst), pitch * height * sizeof(uint8_t)); } else { // Origin is top/left corner - convert to bottom/left for (int y = 0; y < height; ++y) { auto ptr = dst + (height - 1) * pitch - y * pitch; file.read(reinterpret_cast<char*>(ptr), pitch * sizeof(uint8_t)); } } } void load_true_color_rle( uint8_t* dst, std::ifstream& file, int width, int height, int bytes_per_pixel, bool flip_y ) { assert(width > 0 && height > 0); int pixels = 0; int x = 0; int y = flip_y ? height - 1 : 0; int yinc = flip_y ? -1 : 1; while (pixels < width * height) { uint8_t hdr = 0; file.read((char*)&hdr, sizeof(hdr)); // Run-length packet or raw packet? bool rle = (hdr & 0x80) != 0; // Get number of pixels or repetition count int count = 1 + (hdr & 0x7f); pixels += count; char buffer[4]; if (rle) { // Read the RGB value for the next COUNT pixels file.read(buffer, bytes_per_pixel); } while (count-- > 0) { auto p = dst + (x + y * width) * bytes_per_pixel; if (rle) memcpy(p, buffer, bytes_per_pixel); else file.read((char*)p, bytes_per_pixel); // Adjust current pixel position ++x; if (x >= width) { x = 0; y += yinc; } } } } //------------------------------------------------------------------------------------------------- // tga_image // tga_image::tga_image(std::string const& filename) { std::ifstream file(filename, std::ios::in | std::ios::binary); // Read header tga_header header; memset(&header, 0, sizeof(header)); file.seekg (0, file.beg); // // XXX: // Values are always stored little-endian... // file.read(reinterpret_cast<char*>(&header), sizeof(header)); // Check header if (header.width <= 0 || header.height <= 0) { std::cerr << "Invalid image dimensions (" << header.width << " x " << header.height << ")\n"; return; } // Allocate storage width_ = static_cast<size_t>(header.width); height_ = static_cast<size_t>(header.height); format_ = map_pixel_depth(header.bits_per_pixel); auto pitch = header.width * (header.bits_per_pixel / 8); data_.resize(pitch * header.height); // Read image data file.seekg(sizeof(header) + header.id_length, file.beg); // Bit 5 specifies the screen origin: // 0 = Origin in lower left-hand corner. // 1 = Origin in upper left-hand corner. bool flip_y = (header.image_desc & (1 << 5)) != 0; switch (header.image_type) { default: std::cerr << "Unsupported TGA image type (" << (int)header.image_type << ")\n"; // fall-through case 0: // no image data width_ = 0; height_ = 0; format_ = PF_UNSPECIFIED; data_.resize(0); break; case 2: load_true_color_uncompressed( data_.data(), file, header.width, header.height, header.bits_per_pixel / 8, flip_y ); break; case 10: load_true_color_rle( data_.data(), file, header.width, header.height, header.bits_per_pixel / 8, flip_y ); break; } // Swizzle from BGR(A) to RGB(A) if (format_ == PF_RGB8) { swizzle( reinterpret_cast<vector<3, unorm<8>>*>(data_.data()), PF_RGB8, PF_BGR8, data_.size() / 3 ); } else if (format_ == PF_RGBA8) { swizzle( reinterpret_cast<vector<4, unorm<8>>*>(data_.data()), PF_RGBA8, PF_BGRA8, data_.size() / 4 ); } } } // visionaray
Fix TGA loader
Fix TGA loader * Bit 5 of the image descriptor specifies the image origin * Allow run-length or raw packets to cross scanlines
C++
mit
tu500/visionaray,ukoeln-vis/ctpperf,tu500/visionaray,ukoeln-vis/ctpperf,szellmann/visionaray,szellmann/visionaray
712b13f60771e7dff77514e220748f087cde43d3
src/plugins/resourceeditor/resourcenode.cpp
src/plugins/resourceeditor/resourcenode.cpp
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "resourcenode.h" #include "resourceeditorconstants.h" #include "qrceditor/resourcefile_p.h" #include <utils/fileutils.h> #include <coreplugin/documentmanager.h> #include <coreplugin/fileiconprovider.h> #include <coreplugin/mimedatabase.h> #include <qmljstools/qmljstoolsconstants.h> #include <QDir> #include <QDebug> using namespace ResourceEditor; using namespace ResourceEditor::Internal; static bool priority(const QStringList &files) { if (files.isEmpty()) return false; Core::MimeType mt = Core::MimeDatabase::findByFile(files.at(0)); QString type = mt.type(); if (type.startsWith(QLatin1String("image/")) || type == QLatin1String(QmlJSTools::Constants::QML_MIMETYPE) || type == QLatin1String(QmlJSTools::Constants::JS_MIMETYPE)) return true; return false; } static bool addFilesToResource(const QString &resourceFile, const QStringList &filePaths, QStringList *notAdded, const QString &prefix, const QString &lang) { if (notAdded) *notAdded = filePaths; ResourceFile file(resourceFile); if (!file.load()) return false; int index = file.indexOfPrefix(prefix, lang); if (index == -1) index = file.addPrefix(prefix, lang); if (notAdded) notAdded->clear(); foreach (const QString &path, filePaths) { if (file.contains(index, path)) *notAdded << path; else file.addFile(index, path); } Core::DocumentManager::expectFileChange(resourceFile); file.save(); Core::DocumentManager::unexpectFileChange(resourceFile); return true; } static bool sortByPrefixAndLang(ProjectExplorer::FolderNode *a, ProjectExplorer::FolderNode *b) { ResourceFolderNode *aa = static_cast<ResourceFolderNode *>(a); ResourceFolderNode *bb = static_cast<ResourceFolderNode *>(b); if (aa->prefix() < bb->prefix()) return true; if (bb->prefix() < aa->prefix()) return false; return aa->lang() < bb->lang(); } static bool sortNodesByPath(ProjectExplorer::Node *a, ProjectExplorer::Node *b) { return a->path() < b->path(); } ResourceTopLevelNode::ResourceTopLevelNode(const QString &filePath, FolderNode *parent) : ProjectExplorer::FolderNode(filePath) { setIcon(Core::FileIconProvider::icon(filePath)); m_document = new ResourceFileWatcher(this); Core::DocumentManager::addDocument(m_document); Utils::FileName base = Utils::FileName::fromString(parent->path()); Utils::FileName file = Utils::FileName::fromString(filePath); if (file.isChildOf(base)) setDisplayName(file.relativeChildPath(base).toString()); else setDisplayName(file.toString()); } ResourceTopLevelNode::~ResourceTopLevelNode() { Core::DocumentManager::removeDocument(m_document); } void ResourceTopLevelNode::update() { QList<ProjectExplorer::FolderNode *> newFolderList; QMap<QPair<QString, QString>, QList<ProjectExplorer::FileNode *> > filesToAdd; ResourceFile file(path()); if (file.load()) { QSet<QPair<QString, QString > > prefixes; int prfxcount = file.prefixCount(); for (int i = 0; i < prfxcount; ++i) { const QString &prefix = file.prefix(i); const QString &lang = file.lang(i); // ensure that we don't duplicate prefixes if (!prefixes.contains(qMakePair(prefix, lang))) { ProjectExplorer::FolderNode *fn = new ResourceFolderNode(file.prefix(i), file.lang(i), this); newFolderList << fn; prefixes.insert(qMakePair(prefix, lang)); } QSet<QString> fileNames; int filecount = file.fileCount(i); for (int j = 0; j < filecount; ++j) { const QString &fileName = file.file(i, j); if (fileNames.contains(fileName)) { // The file name is duplicated, skip it // Note: this is wrong, but the qrceditor doesn't allow it either // only aliases need to be unique } else { fileNames.insert(fileName); filesToAdd[qMakePair(prefix, lang)] << new ResourceFileNode(fileName, this); } } } } QList<ProjectExplorer::FolderNode *> oldFolderList = subFolderNodes(); QList<ProjectExplorer::FolderNode *> foldersToAdd; QList<ProjectExplorer::FolderNode *> foldersToRemove; std::sort(oldFolderList.begin(), oldFolderList.end(), sortByPrefixAndLang); std::sort(newFolderList.begin(), newFolderList.end(), sortByPrefixAndLang); ProjectExplorer::compareSortedLists(oldFolderList, newFolderList, foldersToRemove, foldersToAdd, sortByPrefixAndLang); removeFolderNodes(foldersToRemove); addFolderNodes(foldersToAdd); // delete nodes that weren't added qDeleteAll(ProjectExplorer::subtractSortedList(newFolderList, foldersToAdd, sortByPrefixAndLang)); foreach (FolderNode *fn, subFolderNodes()) { ResourceFolderNode *rn = static_cast<ResourceFolderNode *>(fn); rn->updateFiles(filesToAdd.value(qMakePair(rn->prefix(), rn->lang()))); } } QList<ProjectExplorer::ProjectAction> ResourceTopLevelNode::supportedActions(ProjectExplorer::Node *node) const { if (node != this) return QList<ProjectExplorer::ProjectAction>(); return QList<ProjectExplorer::ProjectAction>() << ProjectExplorer::AddNewFile << ProjectExplorer::AddExistingFile << ProjectExplorer::AddExistingDirectory << ProjectExplorer::HidePathActions << ProjectExplorer::Rename; } bool ResourceTopLevelNode::addFiles(const QStringList &filePaths, QStringList *notAdded) { return addFilesToResource(path(), filePaths, notAdded, QLatin1String("/"), QString()); } bool ResourceTopLevelNode::removeFiles(const QStringList &filePaths, QStringList *notRemoved) { return parentFolderNode()->removeFiles(filePaths, notRemoved); } bool ResourceTopLevelNode::addPrefix(const QString &prefix, const QString &lang) { ResourceFile file(path()); if (!file.load()) return false; int index = file.addPrefix(prefix, lang); if (index == -1) return false; Core::DocumentManager::expectFileChange(path()); file.save(); Core::DocumentManager::unexpectFileChange(path()); return true; } bool ResourceTopLevelNode::removePrefix(const QString &prefix, const QString &lang) { ResourceFile file(path()); if (!file.load()) return false; for (int i = 0; i < file.prefixCount(); ++i) { if (file.prefix(i) == prefix && file.lang(i) == lang) { file.removePrefix(i); Core::DocumentManager::expectFileChange(path()); file.save(); Core::DocumentManager::unexpectFileChange(path()); return true; } } return false; } ProjectExplorer::FolderNode::AddNewInformation ResourceTopLevelNode::addNewInformation(const QStringList &files, Node *context) const { QString name = tr("%1 Prefix: %2") .arg(QFileInfo(path()).fileName()) .arg(QLatin1String("/")); int p = 80; if (priority(files)) { if (context == 0 || context == this) p = 125; else if (projectNode() == context) p = 150; // steal from our project node // The ResourceFolderNode '/' defers to us, as otherwise // two nodes would be responsible for '/' // Thus also return a high priority for it if (ResourceFolderNode *rfn = qobject_cast<ResourceFolderNode *>(context)) if (rfn->prefix() == QLatin1String("/")) p = 150; } return AddNewInformation(name, p); } bool ResourceTopLevelNode::showInSimpleTree() const { return true; } ResourceFolderNode::ResourceFolderNode(const QString &prefix, const QString &lang, ResourceTopLevelNode *parent) : ProjectExplorer::FolderNode(parent->path() + QLatin1Char('/') + prefix), // TOOD Why add existing directory doesn't work m_topLevelNode(parent), m_prefix(prefix), m_lang(lang) { } ResourceFolderNode::~ResourceFolderNode() { } QList<ProjectExplorer::ProjectAction> ResourceFolderNode::supportedActions(ProjectExplorer::Node *node) const { Q_UNUSED(node) QList<ProjectExplorer::ProjectAction> actions; actions << ProjectExplorer::AddNewFile << ProjectExplorer::AddExistingFile << ProjectExplorer::AddExistingDirectory << ProjectExplorer::RemoveFile << ProjectExplorer::Rename // Note: only works for the filename, works akwardly for relative file paths << ProjectExplorer::HidePathActions; // hides open terminal etc. // if the prefix is '/' (without lang) hide this node in add new dialog, // as the ResouceTopLevelNode is always shown for the '/' prefix if (m_prefix == QLatin1String("/") && m_lang.isEmpty()) actions << ProjectExplorer::InheritedFromParent; return actions; } bool ResourceFolderNode::addFiles(const QStringList &filePaths, QStringList *notAdded) { return addFilesToResource(m_topLevelNode->path(), filePaths, notAdded, m_prefix, m_lang); } bool ResourceFolderNode::removeFiles(const QStringList &filePaths, QStringList *notRemoved) { if (notRemoved) *notRemoved = filePaths; ResourceFile file(m_topLevelNode->path()); if (!file.load()) return false; int index = file.indexOfPrefix(m_prefix, m_lang); if (index == -1) return false; for (int j = 0; j < file.fileCount(index); ++j) { QString fileName = file.file(index, j); if (!filePaths.contains(fileName)) continue; if (notRemoved) notRemoved->removeOne(fileName); file.removeFile(index, j); --j; } Core::DocumentManager::expectFileChange(m_topLevelNode->path()); file.save(); Core::DocumentManager::unexpectFileChange(m_topLevelNode->path()); return true; } bool ResourceFolderNode::renameFile(const QString &filePath, const QString &newFilePath) { ResourceFile file(m_topLevelNode->path()); if (!file.load()) return false; int index = file.indexOfPrefix(m_prefix, m_lang); if (index == -1) return false; for (int j = 0; j < file.fileCount(index); ++j) { if (file.file(index, j) == filePath) { file.replaceFile(index, j, newFilePath); Core::DocumentManager::expectFileChange(m_topLevelNode->path()); file.save(); Core::DocumentManager::unexpectFileChange(m_topLevelNode->path()); return true; } } return false; } bool ResourceFolderNode::renamePrefix(const QString &prefix, const QString &lang) { ResourceFile file(m_topLevelNode->path()); if (!file.load()) return false; int index = file.indexOfPrefix(m_prefix, m_lang); if (index == -1) return false; if (!file.replacePrefixAndLang(index, prefix, lang)) return false; Core::DocumentManager::expectFileChange(m_topLevelNode->path()); file.save(); Core::DocumentManager::unexpectFileChange(m_topLevelNode->path()); return true; } ProjectExplorer::FolderNode::AddNewInformation ResourceFolderNode::addNewInformation(const QStringList &files, Node *context) const { QString name = tr("%1 Prefix: %2") .arg(QFileInfo(m_topLevelNode->path()).fileName()) .arg(displayName()); int p = 80; if (priority(files)) { if (context == 0 || context == this) p = 120; } return AddNewInformation(name, p); } QString ResourceFolderNode::displayName() const { if (m_lang.isEmpty()) return m_prefix; return m_prefix + QLatin1String(" (") + m_lang + QLatin1Char(')'); } QString ResourceFolderNode::prefix() const { return m_prefix; } QString ResourceFolderNode::lang() const { return m_lang; } ResourceTopLevelNode *ResourceFolderNode::resourceNode() const { return m_topLevelNode; } void ResourceFolderNode::updateFiles(QList<ProjectExplorer::FileNode *> newList) { QList<ProjectExplorer::FileNode *> oldList = fileNodes(); QList<ProjectExplorer::FileNode *> filesToAdd; QList<ProjectExplorer::FileNode *> filesToRemove; std::sort(oldList.begin(), oldList.end(), sortNodesByPath); std::sort(newList.begin(), newList.end(), sortNodesByPath); ProjectExplorer::compareSortedLists(oldList, newList, filesToRemove, filesToAdd, sortNodesByPath); removeFileNodes(filesToRemove); addFileNodes(filesToAdd); qDeleteAll(ProjectExplorer::subtractSortedList(newList, filesToAdd, sortNodesByPath)); } ResourceFileWatcher::ResourceFileWatcher(ResourceTopLevelNode *node) : IDocument(node), m_node(node) { setFilePath(node->path()); } bool ResourceFileWatcher::save(QString *errorString, const QString &fileName, bool autoSave) { Q_UNUSED(errorString); Q_UNUSED(fileName); Q_UNUSED(autoSave); return false; } QString ResourceFileWatcher::defaultPath() const { return QString(); } QString ResourceFileWatcher::suggestedFileName() const { return QString(); } QString ResourceFileWatcher::mimeType() const { return QLatin1String(ResourceEditor::Constants::C_RESOURCE_MIMETYPE); } bool ResourceFileWatcher::isModified() const { return false; } bool ResourceFileWatcher::isSaveAsAllowed() const { return false; } Core::IDocument::ReloadBehavior ResourceFileWatcher::reloadBehavior(ChangeTrigger state, ChangeType type) const { Q_UNUSED(state) Q_UNUSED(type) return BehaviorSilent; } bool ResourceFileWatcher::reload(QString *errorString, ReloadFlag flag, ChangeType type) { Q_UNUSED(errorString) Q_UNUSED(flag) if (type == TypePermissions) return true; m_node->update(); return true; } ResourceFileNode::ResourceFileNode(const QString &filePath, ResourceTopLevelNode *topLevel) : ProjectExplorer::FileNode(filePath, ProjectExplorer::UnknownFileType, false), m_topLevel(topLevel) { QString baseDir = QFileInfo(topLevel->path()).absolutePath(); m_displayName = QDir(baseDir).relativeFilePath(filePath); } QString ResourceFileNode::displayName() const { return m_displayName; }
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "resourcenode.h" #include "resourceeditorconstants.h" #include "qrceditor/resourcefile_p.h" #include <utils/fileutils.h> #include <coreplugin/documentmanager.h> #include <coreplugin/fileiconprovider.h> #include <coreplugin/mimedatabase.h> #include <qmljstools/qmljstoolsconstants.h> #include <QDir> #include <QDebug> using namespace ResourceEditor; using namespace ResourceEditor::Internal; static bool priority(const QStringList &files) { if (files.isEmpty()) return false; Core::MimeType mt = Core::MimeDatabase::findByFile(files.at(0)); QString type = mt.type(); if (type.startsWith(QLatin1String("image/")) || type == QLatin1String(QmlJSTools::Constants::QML_MIMETYPE) || type == QLatin1String(QmlJSTools::Constants::JS_MIMETYPE)) return true; return false; } static bool addFilesToResource(const QString &resourceFile, const QStringList &filePaths, QStringList *notAdded, const QString &prefix, const QString &lang) { if (notAdded) *notAdded = filePaths; ResourceFile file(resourceFile); if (!file.load()) return false; int index = file.indexOfPrefix(prefix, lang); if (index == -1) index = file.addPrefix(prefix, lang); if (notAdded) notAdded->clear(); foreach (const QString &path, filePaths) { if (file.contains(index, path)) *notAdded << path; else file.addFile(index, path); } Core::DocumentManager::expectFileChange(resourceFile); file.save(); Core::DocumentManager::unexpectFileChange(resourceFile); return true; } static bool sortByPrefixAndLang(ProjectExplorer::FolderNode *a, ProjectExplorer::FolderNode *b) { ResourceFolderNode *aa = static_cast<ResourceFolderNode *>(a); ResourceFolderNode *bb = static_cast<ResourceFolderNode *>(b); if (aa->prefix() < bb->prefix()) return true; if (bb->prefix() < aa->prefix()) return false; return aa->lang() < bb->lang(); } static bool sortNodesByPath(ProjectExplorer::Node *a, ProjectExplorer::Node *b) { return a->path() < b->path(); } ResourceTopLevelNode::ResourceTopLevelNode(const QString &filePath, FolderNode *parent) : ProjectExplorer::FolderNode(filePath) { setIcon(Core::FileIconProvider::icon(filePath)); m_document = new ResourceFileWatcher(this); Core::DocumentManager::addDocument(m_document); Utils::FileName base = Utils::FileName::fromString(parent->path()); Utils::FileName file = Utils::FileName::fromString(filePath); if (file.isChildOf(base)) setDisplayName(file.relativeChildPath(base).toString()); else setDisplayName(file.toString()); } ResourceTopLevelNode::~ResourceTopLevelNode() { Core::DocumentManager::removeDocument(m_document); } void ResourceTopLevelNode::update() { QList<ProjectExplorer::FolderNode *> newFolderList; QMap<QPair<QString, QString>, QList<ProjectExplorer::FileNode *> > filesToAdd; ResourceFile file(path()); if (file.load()) { QSet<QPair<QString, QString > > prefixes; int prfxcount = file.prefixCount(); for (int i = 0; i < prfxcount; ++i) { const QString &prefix = file.prefix(i); const QString &lang = file.lang(i); // ensure that we don't duplicate prefixes if (!prefixes.contains(qMakePair(prefix, lang))) { ProjectExplorer::FolderNode *fn = new ResourceFolderNode(file.prefix(i), file.lang(i), this); newFolderList << fn; prefixes.insert(qMakePair(prefix, lang)); } QSet<QString> fileNames; int filecount = file.fileCount(i); for (int j = 0; j < filecount; ++j) { const QString &fileName = file.file(i, j); if (fileNames.contains(fileName)) { // The file name is duplicated, skip it // Note: this is wrong, but the qrceditor doesn't allow it either // only aliases need to be unique } else { fileNames.insert(fileName); filesToAdd[qMakePair(prefix, lang)] << new ResourceFileNode(fileName, this); } } } } QList<ProjectExplorer::FolderNode *> oldFolderList = subFolderNodes(); QList<ProjectExplorer::FolderNode *> foldersToAdd; QList<ProjectExplorer::FolderNode *> foldersToRemove; std::sort(oldFolderList.begin(), oldFolderList.end(), sortByPrefixAndLang); std::sort(newFolderList.begin(), newFolderList.end(), sortByPrefixAndLang); ProjectExplorer::compareSortedLists(oldFolderList, newFolderList, foldersToRemove, foldersToAdd, sortByPrefixAndLang); removeFolderNodes(foldersToRemove); addFolderNodes(foldersToAdd); // delete nodes that weren't added qDeleteAll(ProjectExplorer::subtractSortedList(newFolderList, foldersToAdd, sortByPrefixAndLang)); foreach (FolderNode *fn, subFolderNodes()) { ResourceFolderNode *rn = static_cast<ResourceFolderNode *>(fn); rn->updateFiles(filesToAdd.value(qMakePair(rn->prefix(), rn->lang()))); } } QList<ProjectExplorer::ProjectAction> ResourceTopLevelNode::supportedActions(ProjectExplorer::Node *node) const { if (node != this) return QList<ProjectExplorer::ProjectAction>(); return QList<ProjectExplorer::ProjectAction>() << ProjectExplorer::AddNewFile << ProjectExplorer::AddExistingFile << ProjectExplorer::AddExistingDirectory << ProjectExplorer::HidePathActions << ProjectExplorer::Rename; } bool ResourceTopLevelNode::addFiles(const QStringList &filePaths, QStringList *notAdded) { return addFilesToResource(path(), filePaths, notAdded, QLatin1String("/"), QString()); } bool ResourceTopLevelNode::removeFiles(const QStringList &filePaths, QStringList *notRemoved) { return parentFolderNode()->removeFiles(filePaths, notRemoved); } bool ResourceTopLevelNode::addPrefix(const QString &prefix, const QString &lang) { ResourceFile file(path()); if (!file.load()) return false; int index = file.addPrefix(prefix, lang); if (index == -1) return false; Core::DocumentManager::expectFileChange(path()); file.save(); Core::DocumentManager::unexpectFileChange(path()); return true; } bool ResourceTopLevelNode::removePrefix(const QString &prefix, const QString &lang) { ResourceFile file(path()); if (!file.load()) return false; for (int i = 0; i < file.prefixCount(); ++i) { if (file.prefix(i) == prefix && file.lang(i) == lang) { file.removePrefix(i); Core::DocumentManager::expectFileChange(path()); file.save(); Core::DocumentManager::unexpectFileChange(path()); return true; } } return false; } ProjectExplorer::FolderNode::AddNewInformation ResourceTopLevelNode::addNewInformation(const QStringList &files, Node *context) const { QString name = tr("%1 Prefix: %2") .arg(QFileInfo(path()).fileName()) .arg(QLatin1String("/")); int p = 80; if (priority(files)) { if (context == 0 || context == this) p = 125; else if (projectNode() == context) p = 150; // steal from our project node // The ResourceFolderNode '/' defers to us, as otherwise // two nodes would be responsible for '/' // Thus also return a high priority for it if (ResourceFolderNode *rfn = qobject_cast<ResourceFolderNode *>(context)) if (rfn->prefix() == QLatin1String("/") && rfn->parentFolderNode() == this) p = 150; } return AddNewInformation(name, p); } bool ResourceTopLevelNode::showInSimpleTree() const { return true; } ResourceFolderNode::ResourceFolderNode(const QString &prefix, const QString &lang, ResourceTopLevelNode *parent) : ProjectExplorer::FolderNode(parent->path() + QLatin1Char('/') + prefix), // TOOD Why add existing directory doesn't work m_topLevelNode(parent), m_prefix(prefix), m_lang(lang) { } ResourceFolderNode::~ResourceFolderNode() { } QList<ProjectExplorer::ProjectAction> ResourceFolderNode::supportedActions(ProjectExplorer::Node *node) const { Q_UNUSED(node) QList<ProjectExplorer::ProjectAction> actions; actions << ProjectExplorer::AddNewFile << ProjectExplorer::AddExistingFile << ProjectExplorer::AddExistingDirectory << ProjectExplorer::RemoveFile << ProjectExplorer::Rename // Note: only works for the filename, works akwardly for relative file paths << ProjectExplorer::HidePathActions; // hides open terminal etc. // if the prefix is '/' (without lang) hide this node in add new dialog, // as the ResouceTopLevelNode is always shown for the '/' prefix if (m_prefix == QLatin1String("/") && m_lang.isEmpty()) actions << ProjectExplorer::InheritedFromParent; return actions; } bool ResourceFolderNode::addFiles(const QStringList &filePaths, QStringList *notAdded) { return addFilesToResource(m_topLevelNode->path(), filePaths, notAdded, m_prefix, m_lang); } bool ResourceFolderNode::removeFiles(const QStringList &filePaths, QStringList *notRemoved) { if (notRemoved) *notRemoved = filePaths; ResourceFile file(m_topLevelNode->path()); if (!file.load()) return false; int index = file.indexOfPrefix(m_prefix, m_lang); if (index == -1) return false; for (int j = 0; j < file.fileCount(index); ++j) { QString fileName = file.file(index, j); if (!filePaths.contains(fileName)) continue; if (notRemoved) notRemoved->removeOne(fileName); file.removeFile(index, j); --j; } Core::DocumentManager::expectFileChange(m_topLevelNode->path()); file.save(); Core::DocumentManager::unexpectFileChange(m_topLevelNode->path()); return true; } bool ResourceFolderNode::renameFile(const QString &filePath, const QString &newFilePath) { ResourceFile file(m_topLevelNode->path()); if (!file.load()) return false; int index = file.indexOfPrefix(m_prefix, m_lang); if (index == -1) return false; for (int j = 0; j < file.fileCount(index); ++j) { if (file.file(index, j) == filePath) { file.replaceFile(index, j, newFilePath); Core::DocumentManager::expectFileChange(m_topLevelNode->path()); file.save(); Core::DocumentManager::unexpectFileChange(m_topLevelNode->path()); return true; } } return false; } bool ResourceFolderNode::renamePrefix(const QString &prefix, const QString &lang) { ResourceFile file(m_topLevelNode->path()); if (!file.load()) return false; int index = file.indexOfPrefix(m_prefix, m_lang); if (index == -1) return false; if (!file.replacePrefixAndLang(index, prefix, lang)) return false; Core::DocumentManager::expectFileChange(m_topLevelNode->path()); file.save(); Core::DocumentManager::unexpectFileChange(m_topLevelNode->path()); return true; } ProjectExplorer::FolderNode::AddNewInformation ResourceFolderNode::addNewInformation(const QStringList &files, Node *context) const { QString name = tr("%1 Prefix: %2") .arg(QFileInfo(m_topLevelNode->path()).fileName()) .arg(displayName()); int p = 80; if (priority(files)) { if (context == 0 || context == this) p = 120; } return AddNewInformation(name, p); } QString ResourceFolderNode::displayName() const { if (m_lang.isEmpty()) return m_prefix; return m_prefix + QLatin1String(" (") + m_lang + QLatin1Char(')'); } QString ResourceFolderNode::prefix() const { return m_prefix; } QString ResourceFolderNode::lang() const { return m_lang; } ResourceTopLevelNode *ResourceFolderNode::resourceNode() const { return m_topLevelNode; } void ResourceFolderNode::updateFiles(QList<ProjectExplorer::FileNode *> newList) { QList<ProjectExplorer::FileNode *> oldList = fileNodes(); QList<ProjectExplorer::FileNode *> filesToAdd; QList<ProjectExplorer::FileNode *> filesToRemove; std::sort(oldList.begin(), oldList.end(), sortNodesByPath); std::sort(newList.begin(), newList.end(), sortNodesByPath); ProjectExplorer::compareSortedLists(oldList, newList, filesToRemove, filesToAdd, sortNodesByPath); removeFileNodes(filesToRemove); addFileNodes(filesToAdd); qDeleteAll(ProjectExplorer::subtractSortedList(newList, filesToAdd, sortNodesByPath)); } ResourceFileWatcher::ResourceFileWatcher(ResourceTopLevelNode *node) : IDocument(node), m_node(node) { setFilePath(node->path()); } bool ResourceFileWatcher::save(QString *errorString, const QString &fileName, bool autoSave) { Q_UNUSED(errorString); Q_UNUSED(fileName); Q_UNUSED(autoSave); return false; } QString ResourceFileWatcher::defaultPath() const { return QString(); } QString ResourceFileWatcher::suggestedFileName() const { return QString(); } QString ResourceFileWatcher::mimeType() const { return QLatin1String(ResourceEditor::Constants::C_RESOURCE_MIMETYPE); } bool ResourceFileWatcher::isModified() const { return false; } bool ResourceFileWatcher::isSaveAsAllowed() const { return false; } Core::IDocument::ReloadBehavior ResourceFileWatcher::reloadBehavior(ChangeTrigger state, ChangeType type) const { Q_UNUSED(state) Q_UNUSED(type) return BehaviorSilent; } bool ResourceFileWatcher::reload(QString *errorString, ReloadFlag flag, ChangeType type) { Q_UNUSED(errorString) Q_UNUSED(flag) if (type == TypePermissions) return true; m_node->update(); return true; } ResourceFileNode::ResourceFileNode(const QString &filePath, ResourceTopLevelNode *topLevel) : ProjectExplorer::FileNode(filePath, ProjectExplorer::UnknownFileType, false), m_topLevel(topLevel) { QString baseDir = QFileInfo(topLevel->path()).absolutePath(); m_displayName = QDir(baseDir).relativeFilePath(filePath); } QString ResourceFileNode::displayName() const { return m_displayName; }
Fix matching on '/' node
ResourceNode: Fix matching on '/' node A ResourceTopLevelNode should only prioritize it's own child '/' node. Task-number: QTCREATORBUG-12297 Change-Id: Ia9834d7111622d4558e1a2c21b602b11ff5db139 Reviewed-by: Eike Ziller <[email protected]>
C++
lgpl-2.1
martyone/sailfish-qtcreator,danimo/qt-creator,danimo/qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,farseerri/git_code,martyone/sailfish-qtcreator,farseerri/git_code,danimo/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,AltarBeastiful/qt-creator,maui-packages/qt-creator,xianian/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,AltarBeastiful/qt-creator,AltarBeastiful/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,farseerri/git_code,farseerri/git_code,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,Distrotech/qtcreator,danimo/qt-creator,kuba1/qtcreator,Distrotech/qtcreator,danimo/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,amyvmiwei/qt-creator,xianian/qt-creator,kuba1/qtcreator,kuba1/qtcreator,martyone/sailfish-qtcreator,maui-packages/qt-creator,xianian/qt-creator,maui-packages/qt-creator,danimo/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,Distrotech/qtcreator,amyvmiwei/qt-creator,kuba1/qtcreator,farseerri/git_code,danimo/qt-creator,kuba1/qtcreator,xianian/qt-creator,amyvmiwei/qt-creator,amyvmiwei/qt-creator,farseerri/git_code,danimo/qt-creator,farseerri/git_code,AltarBeastiful/qt-creator,xianian/qt-creator,Distrotech/qtcreator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,maui-packages/qt-creator,xianian/qt-creator,xianian/qt-creator,kuba1/qtcreator,amyvmiwei/qt-creator,maui-packages/qt-creator
1757a3a542fd89bb87b02e4085b96fc5e2259c7c
src/booru/page.cc
src/booru/page.cc
#include <glibmm/i18n.h> #include <iostream> #include "page.h" using namespace AhoViewer::Booru; #include "curler.h" #include "image.h" #include "settings.h" Page::Page() : Gtk::ScrolledWindow(), m_ImageFetcher(new ImageFetcher()), m_IconView(Gtk::manage(new Gtk::IconView())), m_Tab(Gtk::manage(new Gtk::HBox())), m_TabIcon(Gtk::manage(new Gtk::Image(Gtk::Stock::NEW, Gtk::ICON_SIZE_MENU))), m_TabLabel(Gtk::manage(new Gtk::Label(_("New Tab")))), m_TabButton(Gtk::manage(new Gtk::Button())), m_ImageList(std::make_shared<ImageList>(this)), m_Page(0), m_NumPosts(0), m_LastPage(false), m_Saving(false), m_SaveCancel(Gio::Cancellable::create()), m_GetPostsThread(nullptr), m_SaveImagesThread(nullptr) { set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); set_shadow_type(Gtk::SHADOW_ETCHED_IN); // Create page tab {{{ GtkRcStyle *style = gtk_rc_style_new(); style->xthickness = style->ythickness = 0; gtk_widget_modify_style(reinterpret_cast<GtkWidget*>(m_TabButton->gobj()), style); g_object_unref(G_OBJECT(style)); m_TabButton->add(*(Gtk::manage(new Gtk::Image(Gtk::Stock::CLOSE, Gtk::ICON_SIZE_MENU)))); m_TabButton->property_relief() = Gtk::RELIEF_NONE; m_TabButton->set_focus_on_click(false); m_TabButton->set_tooltip_text(_("Close Tab")); m_TabButton->signal_clicked().connect([ this ]() { m_SignalClosed(); }); m_TabLabel->set_alignment(0.0, 0.5); m_TabLabel->set_ellipsize(Pango::ELLIPSIZE_END); m_Tab->pack_start(*m_TabIcon, false, false); m_Tab->pack_start(*m_TabLabel, true, true, 2); m_Tab->pack_start(*m_TabButton, false, false); m_Tab->show_all(); // }}} get_vadjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &Page::on_value_changed)); ModelColumns columns; m_ListStore = Gtk::ListStore::create(columns); m_IconView->set_model(m_ListStore); m_IconView->set_selection_mode(Gtk::SELECTION_BROWSE); m_IconView->signal_selection_changed().connect(sigc::mem_fun(*this, &Page::on_selection_changed)); // Workaround to have fully centered pixbufs Gtk::CellRendererPixbuf *cell = Gtk::manage(new Gtk::CellRendererPixbuf()); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(m_IconView->gobj()), reinterpret_cast<GtkCellRenderer*>(cell->gobj()), TRUE); gtk_cell_layout_add_attribute(GTK_CELL_LAYOUT(m_IconView->gobj()), reinterpret_cast<GtkCellRenderer*>(cell->gobj()), "pixbuf", 0); m_SignalPostsDownloaded.connect(sigc::mem_fun(*this, &Page::on_posts_downloaded)); m_SignalSaveProgressDisp.connect([ this ]() { m_SignalSaveProgress(m_SaveImagesCurrent, m_SaveImagesTotal); }); add(*m_IconView); show_all(); } Page::~Page() { m_Curler.cancel(); if (m_GetPostsThread) { m_GetPostsThread->join(); m_GetPostsThread = nullptr; } cancel_save(); m_ImageList->clear(); delete m_ImageFetcher; } void Page::set_selected(const size_t index) { get_window()->freeze_updates(); Gtk::TreePath path(std::to_string(index)); m_IconView->select_path(path); m_IconView->scroll_to_path(path, false, 0, 0); gtk_icon_view_set_cursor(m_IconView->gobj(), path.gobj(), NULL, FALSE); get_window()->thaw_updates(); } void Page::search(std::shared_ptr<Site> site, const std::string &tags) { if (!ask_cancel_save()) return; cancel_save(); m_ImageList->clear(); m_Site = site; m_Tags = tags; m_Page = 1; m_LastPage = false; m_TabLabel->set_text(site->get_name() + (!tags.empty() ? " - " + tags : "")); m_TabIcon->set(site->get_icon_pixbuf()); get_posts(); } void Page::save_images(const std::string &path) { m_SaveCancel->reset(); m_Saving = true; m_SaveImagesCurrent = 0; m_SaveImagesTotal = m_ImageList->get_size(); m_SaveImagesThread = Glib::Threads::Thread::create([ this, path ]() { // 2 if cachesize is 0, 8 if cachesize > 2 Glib::ThreadPool pool(std::max(std::min(Settings.get_int("CacheSize") * 4, 8), 2)); for (const std::shared_ptr<AhoViewer::Image> &img : m_ImageList->get_images()) { pool.push([ this, path, img ]() { if (m_SaveCancel->is_cancelled()) return; std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img); bimage->save(Glib::build_filename(path, Glib::path_get_basename(bimage->get_filename()))); ++m_SaveImagesCurrent; if (!m_SaveCancel->is_cancelled()) m_SignalSaveProgressDisp(); }); } pool.shutdown(m_SaveCancel->is_cancelled()); m_Saving = false; }); } /** * Returns true if we want to cancel or we're not saving **/ bool Page::ask_cancel_save() { if (!m_Saving) return true; Gtk::Window *window = static_cast<Gtk::Window*>(get_toplevel()); Gtk::MessageDialog dialog(*window, _("Are you sure that you want to stop saving images?"), false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO, true); dialog.set_secondary_text(_("Closing this tab will stop the save operation.")); return dialog.run() == Gtk::RESPONSE_YES; } void Page::cancel_save() { m_SaveCancel->cancel(); for (const std::shared_ptr<AhoViewer::Image> &img : m_ImageList->get_images()) { std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img); bimage->cancel_download(); } if (m_SaveImagesThread) { m_SaveImagesThread->join(); m_SaveImagesThread = nullptr; } } void Page::get_posts() { std::string tags(m_Tags); if (m_Tags.find("rating:") == std::string::npos) { if (Settings.get_booru_max_rating() == Site::Rating::SAFE) { tags += " rating:safe"; } else if (Settings.get_booru_max_rating() == Site::Rating::QUESTIONABLE) { tags += " -rating:explicit"; } } m_Curler.set_url(m_Site->get_posts_url(tags, m_Page)); if (m_GetPostsThread) m_GetPostsThread->join(); m_GetPostsThread = Glib::Threads::Thread::create([ this ]() { if (m_Curler.perform()) { pugi::xml_document doc; doc.load_buffer(m_Curler.get_data(), m_Curler.get_data_size()); m_Posts = doc.document_element(); m_NumPosts = std::distance(m_Posts.begin(), m_Posts.end()); } else { std::cerr << "Error while downloading posts on " << m_Curler.get_url() << std::endl << " " << m_Curler.get_error() << std::endl; } if (!m_Curler.is_cancelled()) m_SignalPostsDownloaded(); }); } bool Page::get_next_page() { if (m_LastPage || m_GetPostsThread) return false; if (!m_Saving) { ++m_Page; get_posts(); return false; } else if (!m_GetNextPageConn) { m_GetNextPageConn = Glib::signal_timeout().connect(sigc::mem_fun(*this, &Page::get_next_page), 1000); } return true; } /** * Adds the downloaded posts to the image list. **/ void Page::on_posts_downloaded() { if (m_NumPosts > 0) { reserve(m_NumPosts); m_ImageList->load(m_Posts, this); } else if (m_Page == 1) { m_SignalNoResults(); } if (m_NumPosts < static_cast<size_t>(Settings.get_int("BooruLimit"))) m_LastPage = true; m_GetPostsThread->join(); m_GetPostsThread = nullptr; } void Page::on_selection_changed() { std::vector<Gtk::TreePath> paths = static_cast<std::vector<Gtk::TreePath>>(m_IconView->get_selected_items()); if (!paths.empty()) { Gtk::TreePath path = paths[0]; if (path) { size_t index = path[0]; if (index + Settings.get_int("CacheSize") >= m_ImageList->get_size() - 1) get_next_page(); m_SignalSelectedChanged(index); } } } /** * Vertical scrollbar value changed **/ void Page::on_value_changed() { double value = get_vadjustment()->get_value(), limit = get_vadjustment()->get_upper() - get_vadjustment()->get_page_size() - get_vadjustment()->get_step_increment(); if (value >= limit) get_next_page(); }
#include <glibmm/i18n.h> #include <iostream> #include "page.h" using namespace AhoViewer::Booru; #include "curler.h" #include "image.h" #include "settings.h" Page::Page() : Gtk::ScrolledWindow(), m_ImageFetcher(new ImageFetcher()), m_IconView(Gtk::manage(new Gtk::IconView())), m_Tab(Gtk::manage(new Gtk::HBox())), m_TabIcon(Gtk::manage(new Gtk::Image(Gtk::Stock::NEW, Gtk::ICON_SIZE_MENU))), m_TabLabel(Gtk::manage(new Gtk::Label(_("New Tab")))), m_TabButton(Gtk::manage(new Gtk::Button())), m_ImageList(std::make_shared<ImageList>(this)), m_Page(0), m_NumPosts(0), m_LastPage(false), m_Saving(false), m_SaveCancel(Gio::Cancellable::create()), m_GetPostsThread(nullptr), m_SaveImagesThread(nullptr) { set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); set_shadow_type(Gtk::SHADOW_ETCHED_IN); // Create page tab {{{ GtkRcStyle *style = gtk_rc_style_new(); style->xthickness = style->ythickness = 0; gtk_widget_modify_style(reinterpret_cast<GtkWidget*>(m_TabButton->gobj()), style); g_object_unref(G_OBJECT(style)); m_TabButton->add(*(Gtk::manage(new Gtk::Image(Gtk::Stock::CLOSE, Gtk::ICON_SIZE_MENU)))); m_TabButton->property_relief() = Gtk::RELIEF_NONE; m_TabButton->set_focus_on_click(false); m_TabButton->set_tooltip_text(_("Close Tab")); m_TabButton->signal_clicked().connect([ this ]() { m_SignalClosed(); }); m_TabLabel->set_alignment(0.0, 0.5); m_TabLabel->set_ellipsize(Pango::ELLIPSIZE_END); m_Tab->pack_start(*m_TabIcon, false, false); m_Tab->pack_start(*m_TabLabel, true, true, 2); m_Tab->pack_start(*m_TabButton, false, false); m_Tab->show_all(); // }}} get_vadjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &Page::on_value_changed)); ModelColumns columns; m_ListStore = Gtk::ListStore::create(columns); m_IconView->set_model(m_ListStore); m_IconView->set_selection_mode(Gtk::SELECTION_BROWSE); m_IconView->signal_selection_changed().connect(sigc::mem_fun(*this, &Page::on_selection_changed)); // Workaround to have fully centered pixbufs Gtk::CellRendererPixbuf *cell = Gtk::manage(new Gtk::CellRendererPixbuf()); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(m_IconView->gobj()), reinterpret_cast<GtkCellRenderer*>(cell->gobj()), TRUE); gtk_cell_layout_add_attribute(GTK_CELL_LAYOUT(m_IconView->gobj()), reinterpret_cast<GtkCellRenderer*>(cell->gobj()), "pixbuf", 0); m_SignalPostsDownloaded.connect(sigc::mem_fun(*this, &Page::on_posts_downloaded)); m_SignalSaveProgressDisp.connect([ this ]() { m_SignalSaveProgress(m_SaveImagesCurrent, m_SaveImagesTotal); }); add(*m_IconView); show_all(); } Page::~Page() { m_Curler.cancel(); if (m_GetPostsThread) { m_GetPostsThread->join(); m_GetPostsThread = nullptr; } cancel_save(); m_ImageList->clear(); delete m_ImageFetcher; } void Page::set_selected(const size_t index) { get_window()->freeze_updates(); Gtk::TreePath path(std::to_string(index)); m_IconView->select_path(path); m_IconView->scroll_to_path(path, false, 0, 0); gtk_icon_view_set_cursor(m_IconView->gobj(), path.gobj(), NULL, FALSE); get_window()->thaw_updates(); } void Page::search(std::shared_ptr<Site> site, const std::string &tags) { if (!ask_cancel_save()) return; cancel_save(); m_ImageList->clear(); m_Site = site; m_Tags = tags; m_Page = 1; m_LastPage = false; m_TabLabel->set_text(site->get_name() + (!tags.empty() ? " - " + tags : "")); m_TabIcon->set(site->get_icon_pixbuf()); get_posts(); } void Page::save_images(const std::string &path) { m_SaveCancel->reset(); m_Saving = true; m_SaveImagesCurrent = 0; m_SaveImagesTotal = m_ImageList->get_size(); m_SaveImagesThread = Glib::Threads::Thread::create([ this, path ]() { // 2 if cachesize is 0, 8 if cachesize > 2 Glib::ThreadPool pool(std::max(std::min(Settings.get_int("CacheSize") * 4, 8), 2)); for (const std::shared_ptr<AhoViewer::Image> &img : m_ImageList->get_images()) { pool.push([ this, path, img ]() { if (m_SaveCancel->is_cancelled()) return; std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img); bimage->save(Glib::build_filename(path, Glib::path_get_basename(bimage->get_filename()))); ++m_SaveImagesCurrent; if (!m_SaveCancel->is_cancelled()) m_SignalSaveProgressDisp(); }); } pool.shutdown(m_SaveCancel->is_cancelled()); m_Saving = false; }); } /** * Returns true if we want to cancel or we're not saving **/ bool Page::ask_cancel_save() { if (!m_Saving) return true; Gtk::Window *window = static_cast<Gtk::Window*>(get_toplevel()); Gtk::MessageDialog dialog(*window, _("Are you sure that you want to stop saving images?"), false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO, true); dialog.set_secondary_text(_("Closing this tab will stop the save operation.")); return dialog.run() == Gtk::RESPONSE_YES; } void Page::cancel_save() { m_SaveCancel->cancel(); for (const std::shared_ptr<AhoViewer::Image> &img : m_ImageList->get_images()) { std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img); bimage->cancel_download(); } if (m_SaveImagesThread) { m_SaveImagesThread->join(); m_SaveImagesThread = nullptr; } } void Page::get_posts() { std::string tags(m_Tags); if (m_Tags.find("rating:") == std::string::npos) { if (Settings.get_booru_max_rating() == Site::Rating::SAFE) { tags += " rating:safe"; } else if (Settings.get_booru_max_rating() == Site::Rating::QUESTIONABLE) { tags += " -rating:explicit"; } } m_Curler.set_url(m_Site->get_posts_url(tags, m_Page)); if (m_GetPostsThread) m_GetPostsThread->join(); m_GetPostsThread = Glib::Threads::Thread::create([ this ]() { if (m_Curler.perform()) { pugi::xml_document doc; doc.load_buffer(m_Curler.get_data(), m_Curler.get_data_size()); m_Posts = doc.document_element(); m_NumPosts = std::distance(m_Posts.begin(), m_Posts.end()); } else { m_NumPosts = 0; std::cerr << "Error while downloading posts on " << m_Curler.get_url() << std::endl << " " << m_Curler.get_error() << std::endl; } if (!m_Curler.is_cancelled()) m_SignalPostsDownloaded(); }); } bool Page::get_next_page() { if (m_LastPage || m_GetPostsThread) return false; if (!m_Saving) { ++m_Page; get_posts(); return false; } else if (!m_GetNextPageConn) { m_GetNextPageConn = Glib::signal_timeout().connect(sigc::mem_fun(*this, &Page::get_next_page), 1000); } return true; } /** * Adds the downloaded posts to the image list. **/ void Page::on_posts_downloaded() { if (m_NumPosts > 0) { reserve(m_NumPosts); m_ImageList->load(m_Posts, this); } else if (m_Page == 1) { m_SignalNoResults(); } if (m_NumPosts < static_cast<size_t>(Settings.get_int("BooruLimit"))) m_LastPage = true; m_GetPostsThread->join(); m_GetPostsThread = nullptr; } void Page::on_selection_changed() { std::vector<Gtk::TreePath> paths = static_cast<std::vector<Gtk::TreePath>>(m_IconView->get_selected_items()); if (!paths.empty()) { Gtk::TreePath path = paths[0]; if (path) { size_t index = path[0]; if (index + Settings.get_int("CacheSize") >= m_ImageList->get_size() - 1) get_next_page(); m_SignalSelectedChanged(index); } } } /** * Vertical scrollbar value changed **/ void Page::on_value_changed() { double value = get_vadjustment()->get_value(), limit = get_vadjustment()->get_upper() - get_vadjustment()->get_page_size() - get_vadjustment()->get_step_increment(); if (value >= limit) get_next_page(); }
Fix possible issue when posts fail to load
booru/page: Fix possible issue when posts fail to load
C++
mit
ahodesuka/ahoviewer,ahodesuka/ahoviewer,ahodesuka/ahoviewer
eb9dbe68a71d096bd6e78b36f55683f3f68504c6
src/textures/ptex.cpp
src/textures/ptex.cpp
/* pbrt source code is Copyright(c) 1998-2016 Matt Pharr, Greg Humphreys, and Wenzel Jakob. This file is part of pbrt. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // textures/ptex.cpp* #include "textures/ptex.h" #include "error.h" #include "interaction.h" #include "paramset.h" #include "stats.h" #include <Ptexture.h> namespace pbrt { namespace { // Reference count for the cache. Note: we assume that PtexTextures aren't // being created/destroyed concurrently by multiple threads. int nActiveTextures; Ptex::PtexCache *cache; STAT_COUNTER("Texture/Ptex lookups", nLookups); STAT_COUNTER("Texture/Ptex files accessed", nFilesAccessed); STAT_COUNTER("Texture/Ptex block reads", nBlockReads); STAT_MEMORY_COUNTER("Memory/Ptex peak memory used", peakMemoryUsed); struct : public PtexErrorHandler { void reportError(const char *error) override { Error("%s", error); } } errorHandler; } // anonymous namespace // PtexTexture Method Definitions template <typename T> PtexTexture<T>::PtexTexture(const std::string &filename, Float gamma) : filename(filename), gamma(gamma) { if (!cache) { CHECK_EQ(nActiveTextures, 0); int maxFiles = 100; size_t maxMem = 1ull << 32; // 4GB bool premultiply = true; cache = Ptex::PtexCache::create(maxFiles, maxMem, premultiply, nullptr, &errorHandler); // TODO? cache->setSearchPath(...); } ++nActiveTextures; // Issue an error if the texture doesn't exist or has an unsupported // number of channels. valid = false; Ptex::String error; Ptex::PtexTexture *texture = cache->get(filename.c_str(), error); if (!texture) Error("%s", error.c_str()); else { if (texture->numChannels() != 1 && texture->numChannels() != 3) Error("%s: only one and three channel ptex textures are supported", filename.c_str()); else { valid = true; LOG(INFO) << filename << ": added ptex texture"; } texture->release(); } } template <typename T> PtexTexture<T>::~PtexTexture() { if (--nActiveTextures == 0) { LOG(INFO) << "Releasing ptex cache"; Ptex::PtexCache::Stats stats; cache->getStats(stats); nFilesAccessed += stats.filesAccessed; nBlockReads += stats.blockReads; peakMemoryUsed = stats.peakMemUsed; cache->release(); cache = nullptr; } } template <typename T> inline T fromResult(int nc, float *result) { return T::unimplemented; } template <> inline Float fromResult<Float>(int nc, float *result) { if (nc == 1) return result[0]; else return (result[0] + result[1] + result[2]) / 3; } template <> inline Spectrum fromResult<Spectrum>(int nc, float *result) { if (nc == 1) return Spectrum(result[0]); else { Float rgb[3] = { result[0], result[1], result[2] }; return Spectrum::FromRGB(rgb); } } template <typename T> T PtexTexture<T>::Evaluate(const SurfaceInteraction &si) const { ProfilePhase _(Prof::TexFiltPtex); if (!valid) return T{}; ++nLookups; Ptex::String error; Ptex::PtexTexture *texture = cache->get(filename.c_str(), error); CHECK_NOTNULL(texture); // TODO: make the filter an option? Ptex::PtexFilter::Options opts(Ptex::PtexFilter::FilterType::f_bspline); Ptex::PtexFilter *filter = Ptex::PtexFilter::getFilter(texture, opts); int nc = texture->numChannels(); float result[3]; int firstChan = 0; filter->eval(result, firstChan, nc, si.faceIndex, si.uv[0], si.uv[1], si.dudx, si.dvdx, si.dudy, si.dvdy); filter->release(); texture->release(); if (gamma != 1) for (int i = 0; i < 3; ++i) if (result[i] >= 0 && result[i] <= 1) // FIXME: should use something more efficient here result[i] = std::pow(result[i], gamma); return fromResult<T>(nc, result); } PtexTexture<Float> *CreatePtexFloatTexture(const Transform &tex2world, const TextureParams &tp) { std::string filename = tp.FindFilename("filename"); Float gamma = tp.FindFloat("gamma", 2.2); return new PtexTexture<Float>(filename, gamma); } PtexTexture<Spectrum> *CreatePtexSpectrumTexture(const Transform &tex2world, const TextureParams &tp) { std::string filename = tp.FindFilename("filename"); Float gamma = tp.FindFloat("gamma", 2.2); return new PtexTexture<Spectrum>(filename, gamma); } } // namespace pbrt
/* pbrt source code is Copyright(c) 1998-2016 Matt Pharr, Greg Humphreys, and Wenzel Jakob. This file is part of pbrt. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // textures/ptex.cpp* #include "textures/ptex.h" #include "error.h" #include "interaction.h" #include "paramset.h" #include "stats.h" #include <Ptexture.h> namespace pbrt { namespace { // Reference count for the cache. Note: we assume that PtexTextures aren't // being created/destroyed concurrently by multiple threads. int nActiveTextures; Ptex::PtexCache *cache; STAT_COUNTER("Texture/Ptex lookups", nLookups); STAT_COUNTER("Texture/Ptex files accessed", nFilesAccessed); STAT_COUNTER("Texture/Ptex block reads", nBlockReads); STAT_MEMORY_COUNTER("Memory/Ptex peak memory used", peakMemoryUsed); struct : public PtexErrorHandler { void reportError(const char *error) override { Error("%s", error); } } errorHandler; } // anonymous namespace // PtexTexture Method Definitions template <typename T> PtexTexture<T>::PtexTexture(const std::string &filename, Float gamma) : filename(filename), gamma(gamma) { if (!cache) { CHECK_EQ(nActiveTextures, 0); int maxFiles = 100; size_t maxMem = 1ull << 32; // 4GB bool premultiply = true; cache = Ptex::PtexCache::create(maxFiles, maxMem, premultiply, nullptr, &errorHandler); // TODO? cache->setSearchPath(...); } ++nActiveTextures; // Issue an error if the texture doesn't exist or has an unsupported // number of channels. valid = false; Ptex::String error; Ptex::PtexTexture *texture = cache->get(filename.c_str(), error); if (!texture) Error("%s", error.c_str()); else { if (texture->numChannels() != 1 && texture->numChannels() != 3) Error("%s: only one and three channel ptex textures are supported", filename.c_str()); else { valid = true; LOG(INFO) << filename << ": added ptex texture"; } texture->release(); } } template <typename T> PtexTexture<T>::~PtexTexture() { if (--nActiveTextures == 0) { LOG(INFO) << "Releasing ptex cache"; Ptex::PtexCache::Stats stats; cache->getStats(stats); nFilesAccessed += stats.filesAccessed; nBlockReads += stats.blockReads; peakMemoryUsed = stats.peakMemUsed; cache->release(); cache = nullptr; } } template <typename T> inline T fromResult(int nc, float *result) { return T::unimplemented; } template <> inline Float fromResult<Float>(int nc, float *result) { if (nc == 1) return result[0]; else return (result[0] + result[1] + result[2]) / 3; } template <> inline Spectrum fromResult<Spectrum>(int nc, float *result) { if (nc == 1) return Spectrum(result[0]); else { Float rgb[3] = { result[0], result[1], result[2] }; return Spectrum::FromRGB(rgb); } } template <typename T> T PtexTexture<T>::Evaluate(const SurfaceInteraction &si) const { ProfilePhase _(Prof::TexFiltPtex); if (!valid) return T{}; ++nLookups; Ptex::String error; Ptex::PtexTexture *texture = cache->get(filename.c_str(), error); CHECK_NOTNULL(texture); // TODO: make the filter an option? Ptex::PtexFilter::Options opts(Ptex::PtexFilter::FilterType::f_bspline); Ptex::PtexFilter *filter = Ptex::PtexFilter::getFilter(texture, opts); int nc = texture->numChannels(); float result[3]; int firstChan = 0; filter->eval(result, firstChan, nc, si.faceIndex, si.uv[0], si.uv[1], si.dudx, si.dvdx, si.dudy, si.dvdy); filter->release(); texture->release(); if (gamma != 1) for (int i = 0; i < nc; ++i) if (result[i] >= 0 && result[i] <= 1) // FIXME: should use something more efficient here result[i] = std::pow(result[i], gamma); return fromResult<T>(nc, result); } PtexTexture<Float> *CreatePtexFloatTexture(const Transform &tex2world, const TextureParams &tp) { std::string filename = tp.FindFilename("filename"); Float gamma = tp.FindFloat("gamma", 2.2); return new PtexTexture<Float>(filename, gamma); } PtexTexture<Spectrum> *CreatePtexSpectrumTexture(const Transform &tex2world, const TextureParams &tp) { std::string filename = tp.FindFilename("filename"); Float gamma = tp.FindFloat("gamma", 2.2); return new PtexTexture<Spectrum>(filename, gamma); } } // namespace pbrt
Fix bug in ptex gamma correction
Fix bug in ptex gamma correction
C++
bsd-2-clause
nyue/pbrt-v3,nyue/pbrt-v3,nyue/pbrt-v3,mmp/pbrt-v3,mmp/pbrt-v3,mmp/pbrt-v3,mmp/pbrt-v3,nyue/pbrt-v3
63a3cced5b4d29f9a2a43396ddde1b4d52339185
Graphics/vtkContourGrid.cxx
Graphics/vtkContourGrid.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkContourGrid.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 <math.h> #include "vtkContourGrid.h" #include "vtkCell.h" #include "vtkMergePoints.h" #include "vtkContourValues.h" #include "vtkScalarTree.h" #include "vtkObjectFactory.h" #include "vtkUnstructuredGrid.h" #include "vtkFloatArray.h" //--------------------------------------------------------------------------- vtkContourGrid* vtkContourGrid::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkContourGrid"); if(ret) { return (vtkContourGrid*)ret; } // If the factory was unable to create the object, then create it here. return new vtkContourGrid; } // Construct object with initial range (0,1) and single contour value // of 0.0. vtkContourGrid::vtkContourGrid() { this->ContourValues = vtkContourValues::New(); this->ComputeNormals = 1; this->ComputeGradients = 0; this->ComputeScalars = 1; this->Locator = NULL; this->UseScalarTree = 0; this->ScalarTree = NULL; this->InputScalarsSelection = NULL; } vtkContourGrid::~vtkContourGrid() { this->ContourValues->Delete(); if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } this->SetInputScalarsSelection(NULL); } // Overload standard modified time function. If contour values are modified, // then this object is modified as well. unsigned long vtkContourGrid::GetMTime() { unsigned long mTime=this->vtkUnstructuredGridToPolyDataFilter::GetMTime(); unsigned long time; if (this->ContourValues) { time = this->ContourValues->GetMTime(); mTime = ( time > mTime ? time : mTime ); } if (this->Locator) { time = this->Locator->GetMTime(); mTime = ( time > mTime ? time : mTime ); } return mTime; } template <class T> static void vtkContourGridExecute(vtkContourGrid *self, vtkDataSet *input, vtkDataArray *inScalars, T *scalarArrayPtr, int numContours, float *values, vtkPointLocator *locator, int computeScalars, int useScalarTree,vtkScalarTree *&scalarTree) { vtkIdType cellId, i; int abortExecute=0; vtkPolyData *output=self->GetOutput(); vtkIdList *cellPts; vtkCell *cell; float range[2]; vtkCellArray *newVerts, *newLines, *newPolys; vtkPoints *newPts; vtkIdType numCells, estimatedSize; vtkPointData *inPd=input->GetPointData(), *outPd=output->GetPointData(); vtkCellData *inCd=input->GetCellData(), *outCd=output->GetCellData(); vtkDataArray *cellScalars; vtkUnstructuredGrid *grid = (vtkUnstructuredGrid *)input; //In this case, we know that the input is an unstructured grid. vtkIdType numPoints, cellArrayIt = 0; int needCell = 0; vtkIdType *cellArrayPtr; T tempScalar; numCells = input->GetNumberOfCells(); // // Create objects to hold output of contour operation. First estimate // allocation size. // estimatedSize = (vtkIdType) pow ((double) numCells, .75); estimatedSize *= numContours; estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024 if (estimatedSize < 1024) { estimatedSize = 1024; } newPts = vtkPoints::New(); newPts->Allocate(estimatedSize,estimatedSize); newVerts = vtkCellArray::New(); newVerts->Allocate(estimatedSize,estimatedSize); newLines = vtkCellArray::New(); newLines->Allocate(estimatedSize,estimatedSize); newPolys = vtkCellArray::New(); newPolys->Allocate(estimatedSize,estimatedSize); cellScalars = inScalars->MakeObject(); cellScalars->Allocate(VTK_CELL_SIZE*inScalars->GetNumberOfComponents()); // locator used to merge potentially duplicate points locator->InitPointInsertion (newPts, input->GetBounds(),estimatedSize); // interpolate data along edge // if we did not ask for scalars to be computed, don't copy them if (!computeScalars) { outPd->CopyScalarsOff(); } outPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize); outCd->CopyAllocate(inCd,estimatedSize,estimatedSize); // If enabled, build a scalar tree to accelerate search // if ( !useScalarTree ) { cellArrayPtr = grid->GetCells()->GetPointer(); for (cellId=0; cellId < numCells && !abortExecute; cellId++) { numPoints = cellArrayPtr[cellArrayIt]; cellArrayIt++; //find min and max values in scalar data range[0] = scalarArrayPtr[cellArrayPtr[cellArrayIt]]; range[1] = scalarArrayPtr[cellArrayPtr[cellArrayIt]]; cellArrayIt++; for (i = 1; i < numPoints; i++) { tempScalar = scalarArrayPtr[cellArrayPtr[cellArrayIt]]; cellArrayIt++; if (tempScalar <= range[0]) { range[0] = tempScalar; } //if tempScalar <= min range value if (tempScalar >= range[1]) { range[1] = tempScalar; } //if tempScalar >= max range value } // for all points in this cell if ( ! (cellId % 5000) ) { self->UpdateProgress ((float)cellId/numCells); if (self->GetAbortExecute()) { abortExecute = 1; break; } } for (i = 0; i < numContours; i++) { if ((values[i] >= range[0]) && (values[i] <= range[1])) { needCell = 1; } // if contour value in range for this cell } // end for numContours if (needCell) { cell = input->GetCell(cellId); cellPts = cell->GetPointIds(); inScalars->GetTuples(cellPts,cellScalars); for (i=0; i < numContours; i++) { if ((values[i] >= range[0]) && (values[i] <= range[1])) { cell->Contour(values[i], cellScalars, locator, newVerts, newLines, newPolys, inPd, outPd, inCd, cellId, outCd); } // if contour value in range of values for this cell } // for all contour values } // if contour goes through this cell needCell = 0; } // for all cells } //if using scalar tree else { if ( scalarTree == NULL ) { scalarTree = vtkScalarTree::New(); } scalarTree->SetDataSet(input); // // Loop over all contour values. Then for each contour value, // loop over all cells. // for (i=0; i < numContours; i++) { for ( scalarTree->InitTraversal(values[i]); (cell=scalarTree->GetNextCell(cellId,cellPts,cellScalars)) != NULL; ) { cell->Contour(values[i], cellScalars, locator, newVerts, newLines, newPolys, inPd, outPd, inCd, cellId, outCd); //don't want to call Contour any more than necessary } //for all cells } //for all contour values } //using scalar tree // // Update ourselves. Because we don't know up front how many verts, lines, // polys we've created, take care to reclaim memory. // output->SetPoints(newPts); newPts->Delete(); cellScalars->Delete(); if (newVerts->GetNumberOfCells()) { output->SetVerts(newVerts); } newVerts->Delete(); if (newLines->GetNumberOfCells()) { output->SetLines(newLines); } newLines->Delete(); if (newPolys->GetNumberOfCells()) { output->SetPolys(newPolys); } newPolys->Delete(); locator->Initialize();//releases leftover memory output->Squeeze(); } // // Contouring filter for unstructured grids. // void vtkContourGrid::Execute() { vtkDataArray *inScalars; vtkDataSet *input=this->GetInput(); void *scalarArrayPtr; vtkIdType numCells; int numContours = this->ContourValues->GetNumberOfContours(); float *values = this->ContourValues->GetValues(); int computeScalars = this->ComputeScalars; int useScalarTree = this->UseScalarTree; vtkScalarTree *&scalarTree = this->ScalarTree; vtkDebugMacro(<< "Executing contour filter"); if ( this->Locator == NULL ) { this->CreateDefaultLocator(); } numCells = input->GetNumberOfCells(); inScalars = input->GetPointData()->GetScalars(this->InputScalarsSelection); if ( ! inScalars || numCells < 1 ) { vtkErrorMacro(<<"No data to contour"); return; } scalarArrayPtr = inScalars->GetVoidPointer(0); switch (inScalars->GetDataType()) { vtkTemplateMacro10(vtkContourGridExecute, this, input, inScalars, (VTK_TT *)(scalarArrayPtr), numContours, values, this->Locator, computeScalars, useScalarTree, scalarTree); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } // Specify a spatial locator for merging points. By default, // an instance of vtkMergePoints is used. void vtkContourGrid::SetLocator(vtkPointLocator *locator) { if ( this->Locator == locator ) { return; } if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } if ( locator ) { locator->Register(this); } this->Locator = locator; this->Modified(); } void vtkContourGrid::CreateDefaultLocator() { if ( this->Locator == NULL ) { this->Locator = vtkMergePoints::New(); } } void vtkContourGrid::PrintSelf(ostream& os, vtkIndent indent) { vtkUnstructuredGridToPolyDataFilter::PrintSelf(os,indent); os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n"); os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n"); os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n"); os << indent << "Use Scalar Tree: " << (this->UseScalarTree ? "On\n" : "Off\n"); this->ContourValues->PrintSelf(os,indent); if ( this->Locator ) { os << indent << "Locator: " << this->Locator << "\n"; } else { os << indent << "Locator: (none)\n"; } }
/*========================================================================= Program: Visualization Toolkit Module: vtkContourGrid.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 <math.h> #include "vtkContourGrid.h" #include "vtkCell.h" #include "vtkMergePoints.h" #include "vtkContourValues.h" #include "vtkScalarTree.h" #include "vtkObjectFactory.h" #include "vtkUnstructuredGrid.h" #include "vtkFloatArray.h" //--------------------------------------------------------------------------- vtkContourGrid* vtkContourGrid::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkContourGrid"); if(ret) { return (vtkContourGrid*)ret; } // If the factory was unable to create the object, then create it here. return new vtkContourGrid; } // Construct object with initial range (0,1) and single contour value // of 0.0. vtkContourGrid::vtkContourGrid() { this->ContourValues = vtkContourValues::New(); this->ComputeNormals = 1; this->ComputeGradients = 0; this->ComputeScalars = 1; this->Locator = NULL; this->UseScalarTree = 0; this->ScalarTree = NULL; this->InputScalarsSelection = NULL; } vtkContourGrid::~vtkContourGrid() { this->ContourValues->Delete(); if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } this->SetInputScalarsSelection(NULL); } // Overload standard modified time function. If contour values are modified, // then this object is modified as well. unsigned long vtkContourGrid::GetMTime() { unsigned long mTime=this->vtkUnstructuredGridToPolyDataFilter::GetMTime(); unsigned long time; if (this->ContourValues) { time = this->ContourValues->GetMTime(); mTime = ( time > mTime ? time : mTime ); } if (this->Locator) { time = this->Locator->GetMTime(); mTime = ( time > mTime ? time : mTime ); } return mTime; } template <class T> static void vtkContourGridExecute(vtkContourGrid *self, vtkDataSet *input, vtkDataArray *inScalars, T *scalarArrayPtr, int numContours, float *values, vtkPointLocator *locator, int computeScalars, int useScalarTree,vtkScalarTree *&scalarTree) { vtkIdType cellId, i; int abortExecute=0; vtkPolyData *output=self->GetOutput(); vtkIdList *cellPts; vtkCell *cell; float range[2]; vtkCellArray *newVerts, *newLines, *newPolys; vtkPoints *newPts; vtkIdType numCells, estimatedSize; vtkPointData *inPd=input->GetPointData(), *outPd=output->GetPointData(); vtkCellData *inCd=input->GetCellData(), *outCd=output->GetCellData(); vtkDataArray *cellScalars; vtkUnstructuredGrid *grid = (vtkUnstructuredGrid *)input; //In this case, we know that the input is an unstructured grid. vtkIdType numPoints, cellArrayIt = 0; int needCell = 0; vtkIdType *cellArrayPtr; T tempScalar; numCells = input->GetNumberOfCells(); // // Create objects to hold output of contour operation. First estimate // allocation size. // estimatedSize = (vtkIdType) pow ((double) numCells, .75); estimatedSize *= numContours; estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024 if (estimatedSize < 1024) { estimatedSize = 1024; } newPts = vtkPoints::New(); newPts->Allocate(estimatedSize,estimatedSize); newVerts = vtkCellArray::New(); newVerts->Allocate(estimatedSize,estimatedSize); newLines = vtkCellArray::New(); newLines->Allocate(estimatedSize,estimatedSize); newPolys = vtkCellArray::New(); newPolys->Allocate(estimatedSize,estimatedSize); cellScalars = inScalars->MakeObject(); cellScalars->Allocate(VTK_CELL_SIZE*inScalars->GetNumberOfComponents()); // locator used to merge potentially duplicate points locator->InitPointInsertion (newPts, input->GetBounds(),estimatedSize); // interpolate data along edge // if we did not ask for scalars to be computed, don't copy them if (!computeScalars) { outPd->CopyScalarsOff(); } outPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize); outCd->CopyAllocate(inCd,estimatedSize,estimatedSize); // If enabled, build a scalar tree to accelerate search // if ( !useScalarTree ) { cellArrayPtr = grid->GetCells()->GetPointer(); for (cellId=0; cellId < numCells && !abortExecute; cellId++) { numPoints = cellArrayPtr[cellArrayIt]; cellArrayIt++; //find min and max values in scalar data range[0] = scalarArrayPtr[cellArrayPtr[cellArrayIt]]; range[1] = scalarArrayPtr[cellArrayPtr[cellArrayIt]]; cellArrayIt++; for (i = 1; i < numPoints; i++) { tempScalar = scalarArrayPtr[cellArrayPtr[cellArrayIt]]; cellArrayIt++; if (tempScalar <= range[0]) { range[0] = tempScalar; } //if tempScalar <= min range value if (tempScalar >= range[1]) { range[1] = tempScalar; } //if tempScalar >= max range value } // for all points in this cell if ( ! (cellId % 5000) ) { self->UpdateProgress ((float)cellId/numCells); if (self->GetAbortExecute()) { abortExecute = 1; break; } } for (i = 0; i < numContours; i++) { if ((values[i] >= range[0]) && (values[i] <= range[1])) { needCell = 1; } // if contour value in range for this cell } // end for numContours if (needCell) { cell = input->GetCell(cellId); cellPts = cell->GetPointIds(); inScalars->GetTuples(cellPts,cellScalars); for (i=0; i < numContours; i++) { if ((values[i] >= range[0]) && (values[i] <= range[1])) { cell->Contour(values[i], cellScalars, locator, newVerts, newLines, newPolys, inPd, outPd, inCd, cellId, outCd); } // if contour value in range of values for this cell } // for all contour values } // if contour goes through this cell needCell = 0; } // for all cells } //if using scalar tree else { if ( scalarTree == NULL ) { scalarTree = vtkScalarTree::New(); } scalarTree->SetDataSet(input); // // Loop over all contour values. Then for each contour value, // loop over all cells. // for (i=0; i < numContours; i++) { for ( scalarTree->InitTraversal(values[i]); (cell=scalarTree->GetNextCell(cellId,cellPts,cellScalars)) != NULL; ) { cell->Contour(values[i], cellScalars, locator, newVerts, newLines, newPolys, inPd, outPd, inCd, cellId, outCd); //don't want to call Contour any more than necessary } //for all cells } //for all contour values } //using scalar tree // // Update ourselves. Because we don't know up front how many verts, lines, // polys we've created, take care to reclaim memory. // output->SetPoints(newPts); newPts->Delete(); cellScalars->Delete(); if (newVerts->GetNumberOfCells()) { output->SetVerts(newVerts); } newVerts->Delete(); if (newLines->GetNumberOfCells()) { output->SetLines(newLines); } newLines->Delete(); if (newPolys->GetNumberOfCells()) { output->SetPolys(newPolys); } newPolys->Delete(); locator->Initialize();//releases leftover memory output->Squeeze(); } // // Contouring filter for unstructured grids. // void vtkContourGrid::Execute() { vtkDataArray *inScalars; vtkDataSet *input=this->GetInput(); void *scalarArrayPtr; vtkIdType numCells; int numContours = this->ContourValues->GetNumberOfContours(); float *values = this->ContourValues->GetValues(); int computeScalars = this->ComputeScalars; int useScalarTree = this->UseScalarTree; vtkScalarTree *&scalarTree = this->ScalarTree; vtkDebugMacro(<< "Executing contour filter"); if ( this->Locator == NULL ) { this->CreateDefaultLocator(); } numCells = input->GetNumberOfCells(); inScalars = input->GetPointData()->GetScalars(this->InputScalarsSelection); if ( ! inScalars || numCells < 1 ) { vtkErrorMacro(<<"No data to contour"); return; } scalarArrayPtr = inScalars->GetVoidPointer(0); switch (inScalars->GetDataType()) { vtkTemplateMacro10(vtkContourGridExecute, this, input, inScalars, (VTK_TT *)(scalarArrayPtr), numContours, values, this->Locator, computeScalars, useScalarTree, scalarTree); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } // Specify a spatial locator for merging points. By default, // an instance of vtkMergePoints is used. void vtkContourGrid::SetLocator(vtkPointLocator *locator) { if ( this->Locator == locator ) { return; } if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } if ( locator ) { locator->Register(this); } this->Locator = locator; this->Modified(); } void vtkContourGrid::CreateDefaultLocator() { if ( this->Locator == NULL ) { this->Locator = vtkMergePoints::New(); } } void vtkContourGrid::PrintSelf(ostream& os, vtkIndent indent) { vtkUnstructuredGridToPolyDataFilter::PrintSelf(os,indent); os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n"); os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n"); os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n"); os << indent << "Use Scalar Tree: " << (this->UseScalarTree ? "On\n" : "Off\n"); this->ContourValues->PrintSelf(os,indent); if ( this->Locator ) { os << indent << "Locator: " << this->Locator << "\n"; } else { os << indent << "Locator: (none)\n"; } os << indent << "InputScalarsSelection: " << (this->InputScalarsSelection ? this->InputScalarsSelection : "(none)") << "\n"; }
print self
print self
C++
bsd-3-clause
hendradarwin/VTK,sumedhasingla/VTK,jmerkow/VTK,ashray/VTK-EVM,ashray/VTK-EVM,sumedhasingla/VTK,sankhesh/VTK,sgh/vtk,gram526/VTK,biddisco/VTK,Wuteyan/VTK,johnkit/vtk-dev,jmerkow/VTK,demarle/VTK,cjh1/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,spthaolt/VTK,arnaudgelas/VTK,berendkleinhaneveld/VTK,mspark93/VTK,keithroe/vtkoptix,gram526/VTK,hendradarwin/VTK,demarle/VTK,johnkit/vtk-dev,Wuteyan/VTK,berendkleinhaneveld/VTK,sgh/vtk,jeffbaumes/jeffbaumes-vtk,cjh1/VTK,arnaudgelas/VTK,sankhesh/VTK,keithroe/vtkoptix,jeffbaumes/jeffbaumes-vtk,hendradarwin/VTK,demarle/VTK,biddisco/VTK,SimVascular/VTK,SimVascular/VTK,SimVascular/VTK,cjh1/VTK,sankhesh/VTK,demarle/VTK,candy7393/VTK,sumedhasingla/VTK,arnaudgelas/VTK,johnkit/vtk-dev,collects/VTK,msmolens/VTK,msmolens/VTK,SimVascular/VTK,spthaolt/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,daviddoria/PointGraphsPhase1,ashray/VTK-EVM,msmolens/VTK,gram526/VTK,sankhesh/VTK,jmerkow/VTK,mspark93/VTK,candy7393/VTK,demarle/VTK,collects/VTK,keithroe/vtkoptix,aashish24/VTK-old,demarle/VTK,keithroe/vtkoptix,candy7393/VTK,candy7393/VTK,naucoin/VTKSlicerWidgets,johnkit/vtk-dev,mspark93/VTK,keithroe/vtkoptix,jmerkow/VTK,Wuteyan/VTK,arnaudgelas/VTK,berendkleinhaneveld/VTK,arnaudgelas/VTK,Wuteyan/VTK,Wuteyan/VTK,berendkleinhaneveld/VTK,hendradarwin/VTK,daviddoria/PointGraphsPhase1,hendradarwin/VTK,keithroe/vtkoptix,jmerkow/VTK,aashish24/VTK-old,hendradarwin/VTK,sankhesh/VTK,mspark93/VTK,biddisco/VTK,spthaolt/VTK,sumedhasingla/VTK,mspark93/VTK,sgh/vtk,gram526/VTK,berendkleinhaneveld/VTK,sgh/vtk,jeffbaumes/jeffbaumes-vtk,sgh/vtk,cjh1/VTK,sankhesh/VTK,jmerkow/VTK,jeffbaumes/jeffbaumes-vtk,sankhesh/VTK,demarle/VTK,msmolens/VTK,gram526/VTK,Wuteyan/VTK,spthaolt/VTK,sankhesh/VTK,aashish24/VTK-old,mspark93/VTK,SimVascular/VTK,Wuteyan/VTK,sgh/vtk,jmerkow/VTK,msmolens/VTK,collects/VTK,sumedhasingla/VTK,aashish24/VTK-old,daviddoria/PointGraphsPhase1,demarle/VTK,msmolens/VTK,candy7393/VTK,hendradarwin/VTK,aashish24/VTK-old,SimVascular/VTK,cjh1/VTK,daviddoria/PointGraphsPhase1,mspark93/VTK,naucoin/VTKSlicerWidgets,gram526/VTK,naucoin/VTKSlicerWidgets,mspark93/VTK,collects/VTK,naucoin/VTKSlicerWidgets,biddisco/VTK,biddisco/VTK,jmerkow/VTK,collects/VTK,candy7393/VTK,ashray/VTK-EVM,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,sumedhasingla/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,biddisco/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,sumedhasingla/VTK,keithroe/vtkoptix,aashish24/VTK-old,naucoin/VTKSlicerWidgets,SimVascular/VTK,cjh1/VTK,ashray/VTK-EVM,arnaudgelas/VTK,naucoin/VTKSlicerWidgets,collects/VTK,keithroe/vtkoptix,spthaolt/VTK,johnkit/vtk-dev,ashray/VTK-EVM,candy7393/VTK,spthaolt/VTK,gram526/VTK,daviddoria/PointGraphsPhase1,candy7393/VTK,gram526/VTK,ashray/VTK-EVM,SimVascular/VTK,sumedhasingla/VTK,spthaolt/VTK
6ce768e68ab3cbd154024981c707f8b3ac46853d
src/Data.cpp
src/Data.cpp
#include "Data.hh" Data::Data() : _pteam((uint64_t) (workRAM + PTEAM_PTR)), _eteam((uint64_t) (workRAM + ETEAM_PTR)) { _loadNames(); } Data::~Data() { } void Data::update() { _player.update(); _pteam.update(); _eteam.update(); } void Data::_loadNames() { uint8_t *ptr; _names = new char*[153](); for (int id = 0; id <= 151; id++) { _names[id] = new char[11](); ptr = rom + NAMES_PTR + id * 11; for (int i = 0; i < 11; i++) _names[id][i] = (i < 10 && ptr[i] != 0xFF) * pokeCharsetToAscii(ptr[i]); } _names[152] = NULL; }
#include "Data.hh" Data::Data() : _pteam((uint64_t) (workRAM + PTEAM_PTR)), _eteam((uint64_t) (workRAM + ETEAM_PTR)) { _loadNames(); } Data::~Data() { } void Data::update() { _player.update(); _pteam.update(); _eteam.update(); } void Data::_loadNames() { uint8_t *ptr; _names = new char*[440](); for (int id = 0; id <= 438; id++) { _names[id] = new char[11](); ptr = rom + NAMES_PTR + id * 11; for (int i = 0; i < 11; i++) _names[id][i] = (i < 10 && ptr[i] != 0xFF) * pokeCharsetToAscii(ptr[i]); } _names[152] = NULL; }
extend range to generatio III pokemons
add: extend range to generatio III pokemons
C++
mit
Ensiss/pokebot,Ensiss/pokebot,Ensiss/pokebot