text
stringlengths
54
60.6k
<commit_before>#include <QtGui> #include <QtNetwork> #include "account-mgr.h" #include "seafile-applet.h" #include "api/requests.h" #include "login-dialog.h" namespace { const QString kDefaultServerAddr1 = "https://seacloud.cc"; const QString kDefaultServerAddr2 = "https://cloud.seafile.com"; } // namespace LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("Add an account")); setWindowIcon(QIcon(":/images/seafile.png")); request_ = NULL; mStatusText->setText(""); mLogo->setPixmap(QPixmap(":/images/seafile-32.png")); mServerAddr->addItem(kDefaultServerAddr1); mServerAddr->addItem(kDefaultServerAddr2); mServerAddr->clearEditText(); connect(mSubmitBtn, SIGNAL(clicked()), this, SLOT(doLogin())); const QRect screen = QApplication::desktop()->screenGeometry(); move(screen.center() - this->rect().center()); } void LoginDialog::doLogin() { if (!validateInputs()) { return; } mStatusText->setText(tr("Logging in...")); mServerAddr->setEnabled(false); mUsername->setEnabled(false); mPassword->setEnabled(false); mSubmitBtn->setEnabled(false); if (request_) { delete request_; } request_ = new LoginRequest(url_, username_, password_); request_->setIgnoreSslErrors(false); connect(request_, SIGNAL(success(const QString&)), this, SLOT(loginSuccess(const QString&))); connect(request_, SIGNAL(failed(int)), this, SLOT(loginFailed(int))); connect(request_, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)), this, SLOT(onSslErrors(QNetworkReply*, const QList<QSslError>&))); request_->send(); } void LoginDialog::onSslErrors(QNetworkReply* reply, const QList<QSslError>& errors) { QString question = tr("<b>Warning:</b> The ssl certificate of this server is not trusted, proceed anyway?"); if (QMessageBox::question(this, tr(SEAFILE_CLIENT_BRAND), question, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { reply->ignoreSslErrors(); } } bool LoginDialog::validateInputs() { QString serverAddr = mServerAddr->itemText(mServerAddr->currentIndex()); QString protocol; QUrl url; if (serverAddr.size() == 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Please enter the server address"), QMessageBox::Ok); return false; } else { if (!serverAddr.startsWith("http://") && !serverAddr.startsWith("https://")) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("%1 is not a valid server address") .arg(serverAddr), QMessageBox::Ok); return false; } url = QUrl(serverAddr, QUrl::StrictMode); // qDebug("url is %s\n", url.toString().toUtf8().data()); if (!url.isValid()) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("%1 is not a valid server address") .arg(serverAddr), QMessageBox::Ok); return false; } } QString email = mUsername->text(); if (email.size() == 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Please enter the username"), QMessageBox::Ok); return false; } else if (!email.contains("@")) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("%1 is not a valid email") .arg(email), QMessageBox::Ok); return false; } if (mPassword->text().size() == 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Please enter the password"), QMessageBox::Ok); return false; } url_ = url; username_ = mUsername->text(); password_ = mPassword->text(); return true; } void LoginDialog::loginSuccess(const QString& token) { Account account(url_, username_, token); if (seafApplet->accountManager()->saveAccount(account) < 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Internal Error"), QMessageBox::Ok); } else { done(QDialog::Accepted); } } void LoginDialog::loginFailed(int code) { QString err_msg, reason; if (code == 400) { reason = tr("Incorrect email or password"); } else if (code != 0) { reason = tr("error code %1").arg(code); } if (reason.length() > 0) { err_msg = tr("Failed to login: %1").arg(reason); } else { err_msg = tr("Failed to login"); } QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), err_msg, QMessageBox::Ok); mSubmitBtn->setEnabled(true); mServerAddr->setEnabled(true); mUsername->setEnabled(true); mPassword->setEnabled(true); mStatusText->setText(""); } <commit_msg>fixed a bug in login dialog<commit_after>#include <QtGui> #include <QtNetwork> #include "account-mgr.h" #include "seafile-applet.h" #include "api/requests.h" #include "login-dialog.h" namespace { const QString kDefaultServerAddr1 = "https://seacloud.cc"; const QString kDefaultServerAddr2 = "https://cloud.seafile.com"; } // namespace LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("Add an account")); setWindowIcon(QIcon(":/images/seafile.png")); request_ = NULL; mStatusText->setText(""); mLogo->setPixmap(QPixmap(":/images/seafile-32.png")); mServerAddr->addItem(kDefaultServerAddr1); mServerAddr->addItem(kDefaultServerAddr2); mServerAddr->clearEditText(); connect(mSubmitBtn, SIGNAL(clicked()), this, SLOT(doLogin())); const QRect screen = QApplication::desktop()->screenGeometry(); move(screen.center() - this->rect().center()); } void LoginDialog::doLogin() { if (!validateInputs()) { return; } mStatusText->setText(tr("Logging in...")); mServerAddr->setEnabled(false); mUsername->setEnabled(false); mPassword->setEnabled(false); mSubmitBtn->setEnabled(false); if (request_) { delete request_; } request_ = new LoginRequest(url_, username_, password_); request_->setIgnoreSslErrors(false); connect(request_, SIGNAL(success(const QString&)), this, SLOT(loginSuccess(const QString&))); connect(request_, SIGNAL(failed(int)), this, SLOT(loginFailed(int))); connect(request_, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)), this, SLOT(onSslErrors(QNetworkReply*, const QList<QSslError>&))); request_->send(); } void LoginDialog::onSslErrors(QNetworkReply* reply, const QList<QSslError>& errors) { QString question = tr("<b>Warning:</b> The ssl certificate of this server is not trusted, proceed anyway?"); if (QMessageBox::question(this, tr(SEAFILE_CLIENT_BRAND), question, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { reply->ignoreSslErrors(); } } bool LoginDialog::validateInputs() { QString serverAddr = mServerAddr->currentText(); QString protocol; QUrl url; if (serverAddr.size() == 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Please enter the server address"), QMessageBox::Ok); return false; } else { if (!serverAddr.startsWith("http://") && !serverAddr.startsWith("https://")) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("%1 is not a valid server address") .arg(serverAddr), QMessageBox::Ok); return false; } url = QUrl(serverAddr, QUrl::StrictMode); // qDebug("url is %s\n", url.toString().toUtf8().data()); if (!url.isValid()) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("%1 is not a valid server address") .arg(serverAddr), QMessageBox::Ok); return false; } } QString email = mUsername->text(); if (email.size() == 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Please enter the username"), QMessageBox::Ok); return false; } else if (!email.contains("@")) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("%1 is not a valid email") .arg(email), QMessageBox::Ok); return false; } if (mPassword->text().size() == 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Please enter the password"), QMessageBox::Ok); return false; } url_ = url; username_ = mUsername->text(); password_ = mPassword->text(); return true; } void LoginDialog::loginSuccess(const QString& token) { Account account(url_, username_, token); if (seafApplet->accountManager()->saveAccount(account) < 0) { QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), tr("Internal Error"), QMessageBox::Ok); } else { done(QDialog::Accepted); } } void LoginDialog::loginFailed(int code) { QString err_msg, reason; if (code == 400) { reason = tr("Incorrect email or password"); } else if (code != 0) { reason = tr("error code %1").arg(code); } if (reason.length() > 0) { err_msg = tr("Failed to login: %1").arg(reason); } else { err_msg = tr("Failed to login"); } QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND), err_msg, QMessageBox::Ok); mSubmitBtn->setEnabled(true); mServerAddr->setEnabled(true); mUsername->setEnabled(true); mPassword->setEnabled(true); mStatusText->setText(""); } <|endoftext|>
<commit_before>#include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif #include <QtNetwork> #include <QInputDialog> #include <QStringList> #include <QSettings> #include "settings-mgr.h" #include "account-mgr.h" #include "seafile-applet.h" #include "api/api-error.h" #include "api/requests.h" #include "login-dialog.h" #include "utils/utils.h" #ifdef HAVE_SHIBBOLETH_SUPPORT #include "shib/shib-login-dialog.h" #endif // HAVE_SHIBBOLETH_SUPPORT namespace { const char *kDefaultServerAddr1 = "https://seacloud.cc"; const char *kDefaultServerAddr2 = "https://cloud.seafile.de"; const char *kUsedServerAddresses = "UsedServerAddresses"; const char *const kPreconfigureServerAddr = "PreconfigureServerAddr"; const char *const kPreconfigureServerAddrOnly = "PreconfigureServerAddrOnly"; QStringList getUsedServerAddresses() { QSettings settings; settings.beginGroup(kUsedServerAddresses); QStringList retval = settings.value("main").toStringList(); settings.endGroup(); QString preconfigure_addr = seafApplet->readPreconfigureExpandedString(kPreconfigureServerAddr); if (!preconfigure_addr.isEmpty() && !retval.contains(preconfigure_addr)) { retval.push_back(preconfigure_addr); } if (!retval.contains(kDefaultServerAddr1)) { retval.push_back(kDefaultServerAddr1); } if (!retval.contains(kDefaultServerAddr2)) { retval.push_back(kDefaultServerAddr2); } return retval; } void saveUsedServerAddresses(const QString &new_address) { QSettings settings; settings.beginGroup(kUsedServerAddresses); QStringList list = settings.value("main").toStringList(); // put the last used address to the front list.removeAll(new_address); list.insert(0, new_address); settings.setValue("main", list); settings.endGroup(); } } // namespace LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("Add an account")); setWindowIcon(QIcon(":/images/seafile.png")); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); request_ = NULL; mStatusText->setText(""); mLogo->setPixmap(QPixmap(":/images/seafile-32.png")); QString preconfigure_addr = seafApplet->readPreconfigureExpandedString(kPreconfigureServerAddr); if (seafApplet->readPreconfigureEntry(kPreconfigureServerAddrOnly).toBool() && !preconfigure_addr.isEmpty()) { mServerAddr->setMaxCount(1); mServerAddr->insertItem(0, preconfigure_addr); mServerAddr->setCurrentIndex(0); mServerAddr->setEditable(false); } else { mServerAddr->addItems(getUsedServerAddresses()); mServerAddr->clearEditText(); } mServerAddr->setAutoCompletion(false); QString computerName = seafApplet->settingsManager()->getComputerName(); mComputerName->setText(computerName); connect(mSubmitBtn, SIGNAL(clicked()), this, SLOT(doLogin())); const QRect screen = QApplication::desktop()->screenGeometry(); move(screen.center() - this->rect().center()); #ifdef HAVE_SHIBBOLETH_SUPPORT setupShibLoginLink(); #else mShibLoginLink->hide(); #endif } #ifdef HAVE_SHIBBOLETH_SUPPORT void LoginDialog::setupShibLoginLink() { QString txt = QString("<a style=\"color:#777\" href=\"#\">%1</a>").arg(tr("Shibboleth Login")); mShibLoginLink->setText(txt); connect(mShibLoginLink, SIGNAL(linkActivated(const QString&)), this, SLOT(loginWithShib())); } #endif // HAVE_SHIBBOLETH_SUPPORT void LoginDialog::initFromAccount(const Account& account) { setWindowTitle(tr("Re-login")); mTitle->setText(tr("Re-login")); mServerAddr->setMaxCount(1); mServerAddr->insertItem(0, account.serverUrl.toString()); mServerAddr->setCurrentIndex(0); mServerAddr->setEditable(false); mUsername->setText(account.username); mPassword->setFocus(Qt::OtherFocusReason); } void LoginDialog::doLogin() { if (!validateInputs()) { return; } mStatusText->setText(tr("Logging in...")); disableInputs(); if (request_) { delete request_; } request_ = new LoginRequest(url_, username_, password_, computer_name_); request_->setIgnoreSslErrors(false); connect(request_, SIGNAL(success(const QString&)), this, SLOT(loginSuccess(const QString&))); connect(request_, SIGNAL(failed(const ApiError&)), this, SLOT(loginFailed(const ApiError&))); request_->send(); } void LoginDialog::disableInputs() { mServerAddr->setEnabled(false); mUsername->setEnabled(false); mPassword->setEnabled(false); mSubmitBtn->setEnabled(false); mComputerName->setEnabled(false); } void LoginDialog::enableInputs() { mServerAddr->setEnabled(true); mUsername->setEnabled(true); mPassword->setEnabled(true); mSubmitBtn->setEnabled(true); mComputerName->setEnabled(true); } void LoginDialog::onNetworkError(const QNetworkReply::NetworkError& error, const QString& error_string) { showWarning(tr("Network Error:\n %1").arg(error_string)); enableInputs(); mStatusText->setText(""); } void LoginDialog::onSslErrors(QNetworkReply* reply, const QList<QSslError>& errors) { const QSslCertificate &cert = reply->sslConfiguration().peerCertificate(); qDebug() << "\n= SslErrors =\n" << dumpSslErrors(errors); qDebug() << "\n= Certificate =\n" << dumpCertificate(cert); if (seafApplet->detailedYesOrNoBox(tr("<b>Warning:</b> The ssl certificate of this server is not trusted, proceed anyway?"), dumpSslErrors(errors) + dumpCertificate(cert), this, false)) reply->ignoreSslErrors(); } bool LoginDialog::validateInputs() { QString serverAddr = mServerAddr->currentText(); QString protocol; QUrl url; if (serverAddr.size() == 0) { showWarning(tr("Please enter the server address")); return false; } else { if (!serverAddr.startsWith("http://") && !serverAddr.startsWith("https://")) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return false; } url = QUrl(serverAddr, QUrl::StrictMode); if (!url.isValid()) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return false; } } QString email = mUsername->text(); if (email.size() == 0) { showWarning(tr("Please enter the username")); return false; } if (mPassword->text().size() == 0) { showWarning(tr("Please enter the password")); return false; } QString computer_name = mComputerName->text().trimmed(); if (computer_name.size() == 0) { showWarning(tr("Please enter the computer name")); } url_ = url; username_ = mUsername->text(); password_ = mPassword->text(); computer_name_ = mComputerName->text(); seafApplet->settingsManager()->setComputerName(computer_name_); return true; } void LoginDialog::loginSuccess(const QString& token) { Account account(url_, username_, token); saveUsedServerAddresses(url_.toString()); if (seafApplet->accountManager()->saveAccount(account) < 0) { showWarning(tr("Failed to save current account")); } else { done(QDialog::Accepted); } } void LoginDialog::loginFailed(const ApiError& error) { switch (error.type()) { case ApiError::SSL_ERROR: onSslErrors(error.sslReply(), error.sslErrors()); break; case ApiError::NETWORK_ERROR: onNetworkError(error.networkError(), error.networkErrorString()); break; case ApiError::HTTP_ERROR: onHttpError(error.httpErrorCode()); default: // impossible break; } } void LoginDialog::onHttpError(int code) { QString err_msg, reason; if (code == 400) { reason = tr("Incorrect email or password"); } else if (code == 429) { reason = tr("Logging in too frequently, please wait a minute"); } else if (code == 500) { reason = tr("Internal Server Error"); } if (reason.length() > 0) { err_msg = tr("Failed to login: %1").arg(reason); } else { err_msg = tr("Failed to login"); } showWarning(err_msg); enableInputs(); mStatusText->setText(""); } void LoginDialog::showWarning(const QString& msg) { seafApplet->warningBox(msg, this); } #ifdef HAVE_SHIBBOLETH_SUPPORT void LoginDialog::loginWithShib() { QString serverAddr = seafApplet->settingsManager()->getLastShibUrl(); serverAddr = QInputDialog::getText(this, tr("Shibboleth Login"), tr("Seafile Server Address"), QLineEdit::Normal, serverAddr); serverAddr = serverAddr.trimmed(); if (serverAddr.isEmpty()) { return; } if (!serverAddr.startsWith("http://") && !serverAddr.startsWith("https://")) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return; } QUrl url = QUrl(serverAddr, QUrl::StrictMode); if (!url.isValid()) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return; } seafApplet->settingsManager()->setLastShibUrl(serverAddr); ShibLoginDialog shib_dialog(url, mComputerName->text(), this); if (shib_dialog.exec() == QDialog::Accepted) { accept(); } } #endif // HAVE_SHIBBOLETH_SUPPORT <commit_msg>update builtin servers lists<commit_after>#include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif #include <QtNetwork> #include <QInputDialog> #include <QStringList> #include <QSettings> #include "settings-mgr.h" #include "account-mgr.h" #include "seafile-applet.h" #include "api/api-error.h" #include "api/requests.h" #include "login-dialog.h" #include "utils/utils.h" #ifdef HAVE_SHIBBOLETH_SUPPORT #include "shib/shib-login-dialog.h" #endif // HAVE_SHIBBOLETH_SUPPORT namespace { const char *kDefaultServerAddr1 = "https://seacloud.cc"; const char *kDefaultServerAddr2 = "https://app.seafile.de"; const char *kUsedServerAddresses = "UsedServerAddresses"; const char *const kPreconfigureServerAddr = "PreconfigureServerAddr"; const char *const kPreconfigureServerAddrOnly = "PreconfigureServerAddrOnly"; QStringList getUsedServerAddresses() { QSettings settings; settings.beginGroup(kUsedServerAddresses); QStringList retval = settings.value("main").toStringList(); settings.endGroup(); QString preconfigure_addr = seafApplet->readPreconfigureExpandedString(kPreconfigureServerAddr); if (!preconfigure_addr.isEmpty() && !retval.contains(preconfigure_addr)) { retval.push_back(preconfigure_addr); } if (!retval.contains(kDefaultServerAddr1)) { retval.push_back(kDefaultServerAddr1); } if (!retval.contains(kDefaultServerAddr2)) { retval.push_back(kDefaultServerAddr2); } return retval; } void saveUsedServerAddresses(const QString &new_address) { QSettings settings; settings.beginGroup(kUsedServerAddresses); QStringList list = settings.value("main").toStringList(); // put the last used address to the front list.removeAll(new_address); list.insert(0, new_address); settings.setValue("main", list); settings.endGroup(); } } // namespace LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("Add an account")); setWindowIcon(QIcon(":/images/seafile.png")); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); request_ = NULL; mStatusText->setText(""); mLogo->setPixmap(QPixmap(":/images/seafile-32.png")); QString preconfigure_addr = seafApplet->readPreconfigureExpandedString(kPreconfigureServerAddr); if (seafApplet->readPreconfigureEntry(kPreconfigureServerAddrOnly).toBool() && !preconfigure_addr.isEmpty()) { mServerAddr->setMaxCount(1); mServerAddr->insertItem(0, preconfigure_addr); mServerAddr->setCurrentIndex(0); mServerAddr->setEditable(false); } else { mServerAddr->addItems(getUsedServerAddresses()); mServerAddr->clearEditText(); } mServerAddr->setAutoCompletion(false); QString computerName = seafApplet->settingsManager()->getComputerName(); mComputerName->setText(computerName); connect(mSubmitBtn, SIGNAL(clicked()), this, SLOT(doLogin())); const QRect screen = QApplication::desktop()->screenGeometry(); move(screen.center() - this->rect().center()); #ifdef HAVE_SHIBBOLETH_SUPPORT setupShibLoginLink(); #else mShibLoginLink->hide(); #endif } #ifdef HAVE_SHIBBOLETH_SUPPORT void LoginDialog::setupShibLoginLink() { QString txt = QString("<a style=\"color:#777\" href=\"#\">%1</a>").arg(tr("Shibboleth Login")); mShibLoginLink->setText(txt); connect(mShibLoginLink, SIGNAL(linkActivated(const QString&)), this, SLOT(loginWithShib())); } #endif // HAVE_SHIBBOLETH_SUPPORT void LoginDialog::initFromAccount(const Account& account) { setWindowTitle(tr("Re-login")); mTitle->setText(tr("Re-login")); mServerAddr->setMaxCount(1); mServerAddr->insertItem(0, account.serverUrl.toString()); mServerAddr->setCurrentIndex(0); mServerAddr->setEditable(false); mUsername->setText(account.username); mPassword->setFocus(Qt::OtherFocusReason); } void LoginDialog::doLogin() { if (!validateInputs()) { return; } mStatusText->setText(tr("Logging in...")); disableInputs(); if (request_) { delete request_; } request_ = new LoginRequest(url_, username_, password_, computer_name_); request_->setIgnoreSslErrors(false); connect(request_, SIGNAL(success(const QString&)), this, SLOT(loginSuccess(const QString&))); connect(request_, SIGNAL(failed(const ApiError&)), this, SLOT(loginFailed(const ApiError&))); request_->send(); } void LoginDialog::disableInputs() { mServerAddr->setEnabled(false); mUsername->setEnabled(false); mPassword->setEnabled(false); mSubmitBtn->setEnabled(false); mComputerName->setEnabled(false); } void LoginDialog::enableInputs() { mServerAddr->setEnabled(true); mUsername->setEnabled(true); mPassword->setEnabled(true); mSubmitBtn->setEnabled(true); mComputerName->setEnabled(true); } void LoginDialog::onNetworkError(const QNetworkReply::NetworkError& error, const QString& error_string) { showWarning(tr("Network Error:\n %1").arg(error_string)); enableInputs(); mStatusText->setText(""); } void LoginDialog::onSslErrors(QNetworkReply* reply, const QList<QSslError>& errors) { const QSslCertificate &cert = reply->sslConfiguration().peerCertificate(); qDebug() << "\n= SslErrors =\n" << dumpSslErrors(errors); qDebug() << "\n= Certificate =\n" << dumpCertificate(cert); if (seafApplet->detailedYesOrNoBox(tr("<b>Warning:</b> The ssl certificate of this server is not trusted, proceed anyway?"), dumpSslErrors(errors) + dumpCertificate(cert), this, false)) reply->ignoreSslErrors(); } bool LoginDialog::validateInputs() { QString serverAddr = mServerAddr->currentText(); QString protocol; QUrl url; if (serverAddr.size() == 0) { showWarning(tr("Please enter the server address")); return false; } else { if (!serverAddr.startsWith("http://") && !serverAddr.startsWith("https://")) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return false; } url = QUrl(serverAddr, QUrl::StrictMode); if (!url.isValid()) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return false; } } QString email = mUsername->text(); if (email.size() == 0) { showWarning(tr("Please enter the username")); return false; } if (mPassword->text().size() == 0) { showWarning(tr("Please enter the password")); return false; } QString computer_name = mComputerName->text().trimmed(); if (computer_name.size() == 0) { showWarning(tr("Please enter the computer name")); } url_ = url; username_ = mUsername->text(); password_ = mPassword->text(); computer_name_ = mComputerName->text(); seafApplet->settingsManager()->setComputerName(computer_name_); return true; } void LoginDialog::loginSuccess(const QString& token) { Account account(url_, username_, token); saveUsedServerAddresses(url_.toString()); if (seafApplet->accountManager()->saveAccount(account) < 0) { showWarning(tr("Failed to save current account")); } else { done(QDialog::Accepted); } } void LoginDialog::loginFailed(const ApiError& error) { switch (error.type()) { case ApiError::SSL_ERROR: onSslErrors(error.sslReply(), error.sslErrors()); break; case ApiError::NETWORK_ERROR: onNetworkError(error.networkError(), error.networkErrorString()); break; case ApiError::HTTP_ERROR: onHttpError(error.httpErrorCode()); default: // impossible break; } } void LoginDialog::onHttpError(int code) { QString err_msg, reason; if (code == 400) { reason = tr("Incorrect email or password"); } else if (code == 429) { reason = tr("Logging in too frequently, please wait a minute"); } else if (code == 500) { reason = tr("Internal Server Error"); } if (reason.length() > 0) { err_msg = tr("Failed to login: %1").arg(reason); } else { err_msg = tr("Failed to login"); } showWarning(err_msg); enableInputs(); mStatusText->setText(""); } void LoginDialog::showWarning(const QString& msg) { seafApplet->warningBox(msg, this); } #ifdef HAVE_SHIBBOLETH_SUPPORT void LoginDialog::loginWithShib() { QString serverAddr = seafApplet->settingsManager()->getLastShibUrl(); serverAddr = QInputDialog::getText(this, tr("Shibboleth Login"), tr("Seafile Server Address"), QLineEdit::Normal, serverAddr); serverAddr = serverAddr.trimmed(); if (serverAddr.isEmpty()) { return; } if (!serverAddr.startsWith("http://") && !serverAddr.startsWith("https://")) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return; } QUrl url = QUrl(serverAddr, QUrl::StrictMode); if (!url.isValid()) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return; } seafApplet->settingsManager()->setLastShibUrl(serverAddr); ShibLoginDialog shib_dialog(url, mComputerName->text(), this); if (shib_dialog.exec() == QDialog::Accepted) { accept(); } } #endif // HAVE_SHIBBOLETH_SUPPORT <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2017 Ryo Suzuki // Copyright (C) 2016-2017 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Platform.hpp> # if defined(SIV3D_TARGET_MACOS) # include "CWindow_macOS.hpp" namespace s3d { CWindow_macOS::CWindow_macOS() { } CWindow_macOS::~CWindow_macOS() { glfwTerminate(); } bool CWindow_macOS::init() { if (!glfwInit()) { return false; } m_glfwWindow = glfwCreateWindow(Window::DefaultClientSize.x, Window::DefaultClientSize.y, m_currentTitle.narrow().c_str(), nullptr, nullptr); if (!m_glfwWindow) { glfwTerminate(); return false; } glfwMakeContextCurrent(m_glfwWindow); return true; } bool CWindow_macOS::update() { glClearColor(11/255.0f, 22/255.0f, 33/255.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(m_glfwWindow); glfwPollEvents(); if(glfwGetKey(m_glfwWindow, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(m_glfwWindow, GL_TRUE); } if(glfwWindowShouldClose(m_glfwWindow)) { return false; } return true; } WindowHandle CWindow_macOS::getHandle() const { return m_glfwWindow; } void CWindow_macOS::setTitle(const String& title) { if (title == m_currentTitle) { return; } m_currentTitle = title; glfwSetWindowTitle(m_glfwWindow, m_currentTitle.narrow().c_str()); } } # endif <commit_msg>window size fixed<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2017 Ryo Suzuki // Copyright (C) 2016-2017 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Platform.hpp> # if defined(SIV3D_TARGET_MACOS) # include "CWindow_macOS.hpp" namespace s3d { CWindow_macOS::CWindow_macOS() { } CWindow_macOS::~CWindow_macOS() { glfwTerminate(); } bool CWindow_macOS::init() { if (!glfwInit()) { return false; } glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); m_glfwWindow = glfwCreateWindow(Window::DefaultClientSize.x, Window::DefaultClientSize.y, m_currentTitle.narrow().c_str(), nullptr, nullptr); if (!m_glfwWindow) { glfwTerminate(); return false; } glfwMakeContextCurrent(m_glfwWindow); return true; } bool CWindow_macOS::update() { glClearColor(11/255.0f, 22/255.0f, 33/255.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(m_glfwWindow); glfwPollEvents(); if(glfwGetKey(m_glfwWindow, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(m_glfwWindow, GL_TRUE); } if(glfwWindowShouldClose(m_glfwWindow)) { return false; } return true; } WindowHandle CWindow_macOS::getHandle() const { return m_glfwWindow; } void CWindow_macOS::setTitle(const String& title) { if (title == m_currentTitle) { return; } m_currentTitle = title; glfwSetWindowTitle(m_glfwWindow, m_currentTitle.narrow().c_str()); } } # endif <|endoftext|>
<commit_before>/* * DeliverMissionObjectiveImplementation.cpp * * Created on: 20/08/2010 * Author: dannuic */ #include "DeliverMissionObjective.h" #include "server/zone/objects/area/MissionSpawnActiveArea.h" #include "server/zone/objects/waypoint/WaypointObject.h" #include "server/zone/objects/creature/AiAgent.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/region/Region.h" #include "server/zone/Zone.h" #include "server/zone/ZoneServer.h" #include "server/zone/managers/object/ObjectManager.h" #include "server/zone/managers/creature/CreatureManager.h" #include "server/zone/managers/mission/MissionManager.h" #include "server/zone/managers/terrain/TerrainManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/packets/object/NpcConversationMessage.h" #include "server/zone/packets/object/StartNpcConversation.h" #include "server/zone/packets/object/StopNpcConversation.h" #include "MissionObject.h" #include "MissionObserver.h" void DeliverMissionObjectiveImplementation::activate() { MissionObjectiveImplementation::activate(); if (!activateWithResult()) { //Send error message to player. CreatureObject* owner = getPlayerOwner(); if (owner == NULL) { return; } int randomNumber = System::random(4) + 1; StringIdChatParameter message("@mission/mission_generic:mission_incomplete_0" + String::valueOf(randomNumber)); owner->sendSystemMessage(message); removeMissionFromPlayer(); } } bool DeliverMissionObjectiveImplementation::activateWithResult() { CreatureObject* owner = getPlayerOwner(); if (owner == NULL) { return false; } Zone* zone = owner->getZone(); if (zone == NULL) { return false; } CreatureManager* creatureManager = zone->getCreatureManager(); PlanetManager* planetManager = zone->getPlanetManager(); if (planetManager == NULL) { return false; } TerrainManager* terrainManager = planetManager->getTerrainManager(); if (terrainManager == NULL) { return false; } ZoneServer* zoneServer = owner->getZoneServer(); if (zoneServer == NULL) { return false; } MissionManager* missionManager = zoneServer->getMissionManager(); if (missionManager == NULL) { return false; } //Select spawn type. int spawnType = NpcSpawnPoint::NEUTRALSPAWN; switch (mission->getFaction()) { case MissionObject::FACTIONIMPERIAL: spawnType = NpcSpawnPoint::IMPERIALSPAWN; break; case MissionObject::FACTIONREBEL: spawnType = NpcSpawnPoint::REBELSPAWN; break; default: spawnType = NpcSpawnPoint::NEUTRALSPAWN; break; } //Spawn target and destination NPC's. //Target NPC //Find a free spawn point. targetSpawnPoint = missionManager->getRandomFreeNpcSpawnPoint(mission->getStartPlanetCRC(), mission->getStartPositionX(), mission->getStartPositionY(), spawnType); if (targetSpawnPoint == NULL) { return false; } Vector3* targetPosition = targetSpawnPoint->getPosition(); if (targetPosition == NULL) { return false; } String deliverNpc = "deliver_npc"; //Get the terrain height at the spawn point. float z = terrainManager->getHeight(targetPosition->getX(), targetPosition->getY()); //Spawn the NPC. target = cast<AiAgent*>(creatureManager->spawnCreature(deliverNpc.hashCode(), 0, targetPosition->getX(), z, targetPosition->getY(), 0)); //Update the heading direction of the NPC. Quaternion* direction = targetSpawnPoint->getDirection(); target->updateDirection(direction->getW(), direction->getX(), direction->getY(), direction->getZ()); //Set the name of the NPC. target->setCustomObjectName(mission->getCreatorName(), true); //Destination NPC. //Find a free spawn point. destinationSpawnPoint = missionManager->getRandomFreeNpcSpawnPoint(mission->getEndPlanet().hashCode(), mission->getEndPositionX(), mission->getEndPositionY(), spawnType); if (destinationSpawnPoint == NULL) { return false; } Vector3* destinationPosition = destinationSpawnPoint->getPosition(); if (destinationPosition == NULL) { return false; } //Get the terrain height at the spawn point. z = terrainManager->getHeight(destinationPosition->getX(), destinationPosition->getY()); //Spawn the NPC. destination = cast<AiAgent*>(creatureManager->spawnCreature(deliverNpc.hashCode(), 0, destinationPosition->getX(), z, destinationPosition->getY(), 0)); //Update the heading direction of the NPC. direction = destinationSpawnPoint->getDirection(); destination->updateDirection(direction->getW(), direction->getX(), direction->getY(), direction->getZ()); //Set the name of the NPC. destination->setCustomObjectName(mission->getTargetName(), true); //Create waypoint and activate it. if (objectiveStatus == 0) { WaypointObject* waypoint = mission->getWaypointToMission(); if (waypoint == NULL) { waypoint = mission->createWaypoint(); } waypoint->setPlanetCRC(mission->getStartPlanetCRC()); waypoint->setPosition(targetPosition->getX(), 0, targetPosition->getY()); waypoint->setActive(true); mission->updateMissionLocation(); } else { updateMissionTarget(getPlayerOwner()); } return true; } void DeliverMissionObjectiveImplementation::abort() { MissionObjectiveImplementation::abort(); despawnNpcs(); } void DeliverMissionObjectiveImplementation::complete() { despawnNpcs(); MissionObjectiveImplementation::complete(); } void DeliverMissionObjectiveImplementation::despawnNpcs() { ZoneServer* zoneServer = getPlayerOwner()->getZoneServer(); MissionManager* missionManager = zoneServer->getMissionManager(); if (despawnMissionNpcsTask == NULL) { despawnMissionNpcsTask = new DespawnMissionNpcsTask(target, destination, targetSpawnPoint, destinationSpawnPoint, missionManager); } if (despawnMissionNpcsTask->isScheduled()) { return; } else { //Despawn after 1 minute. despawnMissionNpcsTask->schedule(60 * 1000); } } void DeliverMissionObjectiveImplementation::updateMissionStatus(CreatureObject* player) { StringBuffer itemEntry; itemEntry << "m" << mission->getMissionNumber(); ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); StringId itemName; Locker lock(player); switch (objectiveStatus) { case 0: itemEntry << "l"; item = NULL; //TODO: create correct item. item = cast<TangibleObject*>( player->getZoneServer()->createObject(String("object/tangible/mission/mission_datadisk.iff").hashCode(), 2)); if (item == NULL) { return; } itemName.setStringId("mission/mission_deliver_neutral_easy", itemEntry.toString()); item->setObjectName(itemName); item->sendTo(player, true); //Give player the item to deliver inventory->transferObject(item, -1, true); updateMissionTarget(player); objectiveStatus = PICKEDUPSTATUS; break; case 1: // check for item, then remove item if (item == NULL || !inventory->hasObjectInContainer(item->getObjectID())) { return; } item->destroyObjectFromWorld(true); complete(); objectiveStatus = DELIVEREDSTATUS; break; default: break; } } bool DeliverMissionObjectiveImplementation::updateMissionTarget(CreatureObject* player) { //Now update the waypoint to the new target WaypointObject* waypoint = mission->getWaypointToMission(); if (waypoint == NULL) { waypoint = mission->createWaypoint(); } waypoint->setPlanetCRC(mission->getEndPlanet().hashCode()); waypoint->setPosition(destinationSpawnPoint->getPosition()->getX(), 0, destinationSpawnPoint->getPosition()->getY()); waypoint->setActive(true); mission->updateMissionLocation(); return true; } <commit_msg>[fixed] stability issue<commit_after>/* * DeliverMissionObjectiveImplementation.cpp * * Created on: 20/08/2010 * Author: dannuic */ #include "DeliverMissionObjective.h" #include "server/zone/objects/area/MissionSpawnActiveArea.h" #include "server/ServerCore.h" #include "server/zone/objects/waypoint/WaypointObject.h" #include "server/zone/objects/creature/AiAgent.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/region/Region.h" #include "server/zone/Zone.h" #include "server/zone/ZoneServer.h" #include "server/zone/managers/object/ObjectManager.h" #include "server/zone/managers/creature/CreatureManager.h" #include "server/zone/managers/mission/MissionManager.h" #include "server/zone/managers/terrain/TerrainManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/packets/object/NpcConversationMessage.h" #include "server/zone/packets/object/StartNpcConversation.h" #include "server/zone/packets/object/StopNpcConversation.h" #include "MissionObject.h" #include "MissionObserver.h" void DeliverMissionObjectiveImplementation::activate() { MissionObjectiveImplementation::activate(); if (!activateWithResult()) { //Send error message to player. CreatureObject* owner = getPlayerOwner(); if (owner == NULL) { return; } int randomNumber = System::random(4) + 1; StringIdChatParameter message("@mission/mission_generic:mission_incomplete_0" + String::valueOf(randomNumber)); owner->sendSystemMessage(message); removeMissionFromPlayer(); } } bool DeliverMissionObjectiveImplementation::activateWithResult() { CreatureObject* owner = getPlayerOwner(); if (owner == NULL) { return false; } Zone* zone = owner->getZone(); if (zone == NULL) { return false; } CreatureManager* creatureManager = zone->getCreatureManager(); PlanetManager* planetManager = zone->getPlanetManager(); if (planetManager == NULL) { return false; } TerrainManager* terrainManager = planetManager->getTerrainManager(); if (terrainManager == NULL) { return false; } ZoneServer* zoneServer = owner->getZoneServer(); if (zoneServer == NULL) { return false; } MissionManager* missionManager = zoneServer->getMissionManager(); if (missionManager == NULL) { return false; } //Select spawn type. int spawnType = NpcSpawnPoint::NEUTRALSPAWN; switch (mission->getFaction()) { case MissionObject::FACTIONIMPERIAL: spawnType = NpcSpawnPoint::IMPERIALSPAWN; break; case MissionObject::FACTIONREBEL: spawnType = NpcSpawnPoint::REBELSPAWN; break; default: spawnType = NpcSpawnPoint::NEUTRALSPAWN; break; } //Spawn target and destination NPC's. //Target NPC //Find a free spawn point. targetSpawnPoint = missionManager->getRandomFreeNpcSpawnPoint(mission->getStartPlanetCRC(), mission->getStartPositionX(), mission->getStartPositionY(), spawnType); if (targetSpawnPoint == NULL) { return false; } Vector3* targetPosition = targetSpawnPoint->getPosition(); if (targetPosition == NULL) { return false; } String deliverNpc = "deliver_npc"; //Get the terrain height at the spawn point. float z = terrainManager->getHeight(targetPosition->getX(), targetPosition->getY()); //Spawn the NPC. target = cast<AiAgent*>(creatureManager->spawnCreature(deliverNpc.hashCode(), 0, targetPosition->getX(), z, targetPosition->getY(), 0)); //Update the heading direction of the NPC. Quaternion* direction = targetSpawnPoint->getDirection(); target->updateDirection(direction->getW(), direction->getX(), direction->getY(), direction->getZ()); //Set the name of the NPC. target->setCustomObjectName(mission->getCreatorName(), true); //Destination NPC. //Find a free spawn point. destinationSpawnPoint = missionManager->getRandomFreeNpcSpawnPoint(mission->getEndPlanet().hashCode(), mission->getEndPositionX(), mission->getEndPositionY(), spawnType); if (destinationSpawnPoint == NULL) { return false; } Vector3* destinationPosition = destinationSpawnPoint->getPosition(); if (destinationPosition == NULL) { return false; } //Get the terrain height at the spawn point. z = terrainManager->getHeight(destinationPosition->getX(), destinationPosition->getY()); //Spawn the NPC. destination = cast<AiAgent*>(creatureManager->spawnCreature(deliverNpc.hashCode(), 0, destinationPosition->getX(), z, destinationPosition->getY(), 0)); //Update the heading direction of the NPC. direction = destinationSpawnPoint->getDirection(); destination->updateDirection(direction->getW(), direction->getX(), direction->getY(), direction->getZ()); //Set the name of the NPC. destination->setCustomObjectName(mission->getTargetName(), true); //Create waypoint and activate it. if (objectiveStatus == 0) { WaypointObject* waypoint = mission->getWaypointToMission(); if (waypoint == NULL) { waypoint = mission->createWaypoint(); } waypoint->setPlanetCRC(mission->getStartPlanetCRC()); waypoint->setPosition(targetPosition->getX(), 0, targetPosition->getY()); waypoint->setActive(true); mission->updateMissionLocation(); } else { updateMissionTarget(getPlayerOwner()); } return true; } void DeliverMissionObjectiveImplementation::abort() { MissionObjectiveImplementation::abort(); despawnNpcs(); } void DeliverMissionObjectiveImplementation::complete() { despawnNpcs(); MissionObjectiveImplementation::complete(); } void DeliverMissionObjectiveImplementation::despawnNpcs() { ZoneServer* zoneServer = ServerCore::getZoneServer(); MissionManager* missionManager = zoneServer->getMissionManager(); if (despawnMissionNpcsTask == NULL) { despawnMissionNpcsTask = new DespawnMissionNpcsTask(target, destination, targetSpawnPoint, destinationSpawnPoint, missionManager); } if (despawnMissionNpcsTask->isScheduled()) { return; } else { //Despawn after 1 minute. despawnMissionNpcsTask->schedule(60 * 1000); } } void DeliverMissionObjectiveImplementation::updateMissionStatus(CreatureObject* player) { StringBuffer itemEntry; itemEntry << "m" << mission->getMissionNumber(); ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); StringId itemName; Locker lock(player); switch (objectiveStatus) { case 0: itemEntry << "l"; item = NULL; //TODO: create correct item. item = cast<TangibleObject*>( player->getZoneServer()->createObject(String("object/tangible/mission/mission_datadisk.iff").hashCode(), 2)); if (item == NULL) { return; } itemName.setStringId("mission/mission_deliver_neutral_easy", itemEntry.toString()); item->setObjectName(itemName); item->sendTo(player, true); //Give player the item to deliver inventory->transferObject(item, -1, true); updateMissionTarget(player); objectiveStatus = PICKEDUPSTATUS; break; case 1: // check for item, then remove item if (item == NULL || !inventory->hasObjectInContainer(item->getObjectID())) { return; } item->destroyObjectFromWorld(true); complete(); objectiveStatus = DELIVEREDSTATUS; break; default: break; } } bool DeliverMissionObjectiveImplementation::updateMissionTarget(CreatureObject* player) { //Now update the waypoint to the new target WaypointObject* waypoint = mission->getWaypointToMission(); if (waypoint == NULL) { waypoint = mission->createWaypoint(); } waypoint->setPlanetCRC(mission->getEndPlanet().hashCode()); waypoint->setPosition(destinationSpawnPoint->getPosition()->getX(), 0, destinationSpawnPoint->getPosition()->getY()); waypoint->setActive(true); mission->updateMissionLocation(); return true; } <|endoftext|>
<commit_before>// // Created by marc on 15-11-16. // #include <iostream> #include "PartitionSafe.h" int main() { std::cout << "PartitionSafe :: Test script" << std::endl; try { // // Create vault // // Vault metadata const char *vaultPath = "/tmp/marc.vault"; const char *keyStorePath = "/tmp/marc.vault"; char label[40] = "Marc"; // Create the partition safe instance PartitionSafe *ps = new PartitionSafe(); // Create the vault ps->create(vaultPath, keyStorePath, label, 1024); std::cout << "Partition created" << std::endl; // // Open vault // // Init the vault ps->init(vaultPath, keyStorePath)->open(); std::cout << "Partition opened" << std::endl; // // Write file // // File content const std::string filename = "sample.txt"; const char line[] = "Hello world\nHai"; // Write content ps->writeFile(filename, line, sizeof(line)); std::cout << "File written" << std::endl; // // Open file // // File metadata FILINFO fileInfo; // Get file info ps->fileInfo(filename, &fileInfo); // The file buffer char readLines[fileInfo.fsize]; // Read content ps->readFile(filename, readLines, sizeof(readLines)); std::cout << "Read from file: " << std::endl << readLines; } catch(const char* exception) { // Hey, exception std::cout << "Thrown exception: " << exception << std::endl; } return 0; } <commit_msg>Fixed test script bug<commit_after>// // Created by marc on 15-11-16. // #include <iostream> #include "PartitionSafe.h" int main() { std::cout << "PartitionSafe :: Test script" << std::endl << std::endl; try { // // Create vault // // Vault metadata const char *vaultPath = "/tmp/marc.vault"; const char *keyStorePath = "/tmp/marc.keystore"; char label[40] = "Marc"; // Create the partition safe instance PartitionSafe *ps = new PartitionSafe(); // Create the vault ps->create(vaultPath, keyStorePath, label, 1024); std::cout << "-- Partition created" << std::endl; // // Open vault // // Init the vault ps->init(vaultPath, keyStorePath)->open(); std::cout << "-- Partition opened" << std::endl; // // Write file // // File content const std::string filename = "sample.txt"; const char line[] = "Hello world\nHai"; // Write content ps->writeFile(filename, line, sizeof(line)); std::cout << "-- File written" << std::endl; // // Open file // // File metadata FILINFO fileInfo; // Get file info ps->fileInfo(filename, &fileInfo); // The file buffer char readLines[fileInfo.fsize]; // Read content ps->readFile(filename, readLines, sizeof(readLines)); std::cout << "-- Read from file: " << std::endl << readLines << std::endl; } catch(const char* exception) { // Hey, exception std::cout << "Thrown exception: " << exception << std::endl; } return 0; } <|endoftext|>
<commit_before><commit_msg>Working on bug fix<commit_after><|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * 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. */ #pragma once #include "util/Cancellable.hxx" #include <boost/intrusive/list.hpp> /** * A job running in the background, which shall be aborted when * beng-proxy is shut down. The job holds a reference to an * #Cancellable object, which may be used to stop it. */ struct BackgroundJob { static constexpr auto link_mode = boost::intrusive::normal_link; typedef boost::intrusive::link_mode<link_mode> LinkMode; typedef boost::intrusive::list_member_hook<LinkMode> SiblingsListHook; SiblingsListHook siblings; CancellablePointer cancel_ptr; }; /** * A container for background jobs. */ class BackgroundManager { boost::intrusive::list<BackgroundJob, boost::intrusive::member_hook<BackgroundJob, BackgroundJob::SiblingsListHook, &BackgroundJob::siblings>, boost::intrusive::constant_time_size<false>> jobs; public: /** * Register a job to the manager. */ void Add(BackgroundJob &job) { jobs.push_front(job); } /** * Add a background job to the manager, and return its * #CancellablePointer. This is a convenience function. */ CancellablePointer &Add2(BackgroundJob &job) { Add(job); return job.cancel_ptr; } /** * Leave the job registered in the manager, and reuse its * #CancellablePointer for another job iteration. */ CancellablePointer &Reuse(BackgroundJob &job) { return job.cancel_ptr; } /** * Unregister a job from the manager. */ void Remove(BackgroundJob &job) { jobs.erase(jobs.iterator_to(job)); } /** * Abort all background jobs in the manager. This is called on * shutdown. */ void AbortAll() { jobs.clear_and_dispose([](BackgroundJob *job){ job->cancel_ptr.Cancel(); }); } }; class LinkedBackgroundJob : public BackgroundJob { BackgroundManager &manager; public: LinkedBackgroundJob(BackgroundManager &_manager):manager(_manager) {} void Remove() { manager.Remove(*this); } }; <commit_msg>util/Background: add `noexcept`<commit_after>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * 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. */ #pragma once #include "util/Cancellable.hxx" #include <boost/intrusive/list.hpp> /** * A job running in the background, which shall be aborted when * beng-proxy is shut down. The job holds a reference to an * #Cancellable object, which may be used to stop it. */ struct BackgroundJob { static constexpr auto link_mode = boost::intrusive::normal_link; typedef boost::intrusive::link_mode<link_mode> LinkMode; typedef boost::intrusive::list_member_hook<LinkMode> SiblingsListHook; SiblingsListHook siblings; CancellablePointer cancel_ptr; }; /** * A container for background jobs. */ class BackgroundManager { boost::intrusive::list<BackgroundJob, boost::intrusive::member_hook<BackgroundJob, BackgroundJob::SiblingsListHook, &BackgroundJob::siblings>, boost::intrusive::constant_time_size<false>> jobs; public: /** * Register a job to the manager. */ void Add(BackgroundJob &job) noexcept { jobs.push_front(job); } /** * Add a background job to the manager, and return its * #CancellablePointer. This is a convenience function. */ CancellablePointer &Add2(BackgroundJob &job) noexcept { Add(job); return job.cancel_ptr; } /** * Leave the job registered in the manager, and reuse its * #CancellablePointer for another job iteration. */ CancellablePointer &Reuse(BackgroundJob &job) noexcept { return job.cancel_ptr; } /** * Unregister a job from the manager. */ void Remove(BackgroundJob &job) noexcept { jobs.erase(jobs.iterator_to(job)); } /** * Abort all background jobs in the manager. This is called on * shutdown. */ void AbortAll() noexcept { jobs.clear_and_dispose([](BackgroundJob *job){ job->cancel_ptr.Cancel(); }); } }; class LinkedBackgroundJob : public BackgroundJob { BackgroundManager &manager; public: LinkedBackgroundJob(BackgroundManager &_manager) noexcept :manager(_manager) {} void Remove() noexcept { manager.Remove(*this); } }; <|endoftext|>
<commit_before>// Copyright 2019 The MediaPipe 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 <algorithm> #include <memory> #include "mediapipe/examples/desktop/autoflip/autoflip_messages.pb.h" #include "mediapipe/examples/desktop/autoflip/calculators/active_speaker_to_region_calculator.pb.h" #include "mediapipe/examples/desktop/autoflip/quality/visual_scorer.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h" #include "mediapipe/framework/formats/rect.pb.h" #include "mediapipe/framework/formats/image_frame.h" #include "mediapipe/framework/formats/image_frame_opencv.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/port/opencv_core_inc.h" #include "mediapipe/framework/port/opencv_imgproc_inc.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/framework/port/status_builder.h" namespace mediapipe { namespace autoflip { constexpr char kInputVideo[] = "VIDEO"; constexpr char kInputRois[] = "DETECTIONS_SPEAKERS"; constexpr char kOutputRegion[] = "REGIONS"; // This calculator converts detected active speaker to SalientRegion protos that can be // used for downstream processing. Each SalientRegion is scored using image // cues. Scoring can be controlled through // ActiveSpeakerToRegionCalculator::scorer_options. // Example: // calculator: "ActiveSpeakerToRegionCalculator" // input_stream: "VIDEO:frames" // input_stream: "DETECTIONS_SPEAKERS:active_speakers_detections" // output_stream: "REGIONS:regions" // options:{ // [mediapipe.autoflip.ActiveSpeakerToRegionCalculatorOptions.ext]:{ // use_visual_scorer: true // } // } // class ActiveSpeakerToRegionCalculator : public CalculatorBase { public: ActiveSpeakerToRegionCalculator(); ~ActiveSpeakerToRegionCalculator() override {} ActiveSpeakerToRegionCalculator(const ActiveSpeakerToRegionCalculator&) = delete; ActiveSpeakerToRegionCalculator& operator=(const ActiveSpeakerToRegionCalculator&) = delete; static ::mediapipe::Status GetContract(mediapipe::CalculatorContract* cc); ::mediapipe::Status Open(mediapipe::CalculatorContext* cc) override; ::mediapipe::Status Process(mediapipe::CalculatorContext* cc) override; private: // Calculator options. ActiveSpeakerToRegionCalculatorOptions options_; // A scorer used to assign weights to active speakers. std::unique_ptr<VisualScorer> scorer_; // Dimensions of video frame int frame_width_; int frame_height_; }; // end with inheritance REGISTER_CALCULATOR(ActiveSpeakerToRegionCalculator); ActiveSpeakerToRegionCalculator::ActiveSpeakerToRegionCalculator() {} ::mediapipe::Status ActiveSpeakerToRegionCalculator::GetContract( mediapipe::CalculatorContract* cc) { if (cc->Inputs().HasTag(kInputVideo)) { cc->Inputs().Tag(kInputVideo).Set<ImageFrame>(); } cc->Inputs().Tag(kInputRois).Set<std::vector<Detection>>(); cc->Outputs().Tag(kOutputRegion).Set<DetectionSet>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status ActiveSpeakerToRegionCalculator::Open( mediapipe::CalculatorContext* cc) { options_ = cc->Options<ActiveSpeakerToRegionCalculatorOptions>(); if (!cc->Inputs().HasTag(kInputVideo)) { RET_CHECK(!options_.use_visual_scorer()) << "VIDEO input must be provided when using visual_scorer."; } scorer_ = absl::make_unique<VisualScorer>(options_.scorer_options()); frame_width_ = -1; frame_height_ = -1; return ::mediapipe::OkStatus(); } ::mediapipe::Status ActiveSpeakerToRegionCalculator::Process( mediapipe::CalculatorContext* cc) { if (cc->Inputs().HasTag(kInputVideo) && cc->Inputs().Tag(kInputVideo).Value().IsEmpty()) { return ::mediapipe::UnknownErrorBuilder(MEDIAPIPE_LOC) << "No VIDEO input at time " << cc->InputTimestamp().Seconds(); } cv::Mat frame; if (cc->Inputs().HasTag(kInputVideo)) { frame = mediapipe::formats::MatView( &cc->Inputs().Tag(kInputVideo).Get<ImageFrame>()); frame_width_ = frame.cols; frame_height_ = frame.rows; } auto region_set = ::absl::make_unique<DetectionSet>(); if (!cc->Inputs().Tag(kInputRois).Value().IsEmpty()) { const auto& input_rois = cc->Inputs().Tag(kInputRois).Get<std::vector<Detection>>(); for (const auto& input_roi : input_rois) { RET_CHECK(input_roi.location_data().format() == mediapipe::LocationData::RELATIVE_BOUNDING_BOX) << "Speaker detection input is lacking required relative_bounding_box()"; const auto& location = input_roi.location_data().relative_bounding_box(); float x = std::max(0.0f, location.xmin()); float y = std::max(0.0f, location.ymin()); float width = std::min(location.width() - x + location.xmin(), 1 - x); float height = std::min(location.height() - y + location.ymin(), 1 - y); // Convert the text bounding box to a region. SalientRegion* region = region_set->add_detections(); region->mutable_location_normalized()->set_x(x); region->mutable_location_normalized()->set_y(y); region->mutable_location_normalized()->set_width(width); region->mutable_location_normalized()->set_height(height); region->mutable_signal_type()->set_standard(SignalType::FACE_FULL); // Score the scores based on image cues. float visual_score = 1.0f; if (options_.use_visual_scorer()) { MP_RETURN_IF_ERROR( scorer_->CalculateScore(frame, *region, &visual_score)); } region->set_score(visual_score); } } cc->Outputs().Tag(kOutputRegion).Add(region_set.release(), cc->InputTimestamp()); return ::mediapipe::OkStatus(); } } // namespace autoflip } // namespace mediapipe <commit_msg>Add SPEAKER signal type<commit_after>// Copyright 2019 The MediaPipe 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 <algorithm> #include <memory> #include "mediapipe/examples/desktop/autoflip/autoflip_messages.pb.h" #include "mediapipe/examples/desktop/autoflip/calculators/active_speaker_to_region_calculator.pb.h" #include "mediapipe/examples/desktop/autoflip/quality/visual_scorer.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h" #include "mediapipe/framework/formats/rect.pb.h" #include "mediapipe/framework/formats/image_frame.h" #include "mediapipe/framework/formats/image_frame_opencv.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/port/opencv_core_inc.h" #include "mediapipe/framework/port/opencv_imgproc_inc.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/framework/port/status_builder.h" namespace mediapipe { namespace autoflip { constexpr char kInputVideo[] = "VIDEO"; constexpr char kInputRois[] = "DETECTIONS_SPEAKERS"; constexpr char kOutputRegion[] = "REGIONS"; // This calculator converts detected active speaker to SalientRegion protos that can be // used for downstream processing. Each SalientRegion is scored using image // cues. Scoring can be controlled through // ActiveSpeakerToRegionCalculator::scorer_options. // Example: // calculator: "ActiveSpeakerToRegionCalculator" // input_stream: "VIDEO:frames" // input_stream: "DETECTIONS_SPEAKERS:active_speakers_detections" // output_stream: "REGIONS:regions" // options:{ // [mediapipe.autoflip.ActiveSpeakerToRegionCalculatorOptions.ext]:{ // use_visual_scorer: true // } // } // class ActiveSpeakerToRegionCalculator : public CalculatorBase { public: ActiveSpeakerToRegionCalculator(); ~ActiveSpeakerToRegionCalculator() override {} ActiveSpeakerToRegionCalculator(const ActiveSpeakerToRegionCalculator&) = delete; ActiveSpeakerToRegionCalculator& operator=(const ActiveSpeakerToRegionCalculator&) = delete; static ::mediapipe::Status GetContract(mediapipe::CalculatorContract* cc); ::mediapipe::Status Open(mediapipe::CalculatorContext* cc) override; ::mediapipe::Status Process(mediapipe::CalculatorContext* cc) override; private: // Calculator options. ActiveSpeakerToRegionCalculatorOptions options_; // A scorer used to assign weights to active speakers. std::unique_ptr<VisualScorer> scorer_; // Dimensions of video frame int frame_width_; int frame_height_; }; // end with inheritance REGISTER_CALCULATOR(ActiveSpeakerToRegionCalculator); ActiveSpeakerToRegionCalculator::ActiveSpeakerToRegionCalculator() {} ::mediapipe::Status ActiveSpeakerToRegionCalculator::GetContract( mediapipe::CalculatorContract* cc) { if (cc->Inputs().HasTag(kInputVideo)) { cc->Inputs().Tag(kInputVideo).Set<ImageFrame>(); } cc->Inputs().Tag(kInputRois).Set<std::vector<Detection>>(); cc->Outputs().Tag(kOutputRegion).Set<DetectionSet>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status ActiveSpeakerToRegionCalculator::Open( mediapipe::CalculatorContext* cc) { options_ = cc->Options<ActiveSpeakerToRegionCalculatorOptions>(); if (!cc->Inputs().HasTag(kInputVideo)) { RET_CHECK(!options_.use_visual_scorer()) << "VIDEO input must be provided when using visual_scorer."; } scorer_ = absl::make_unique<VisualScorer>(options_.scorer_options()); frame_width_ = -1; frame_height_ = -1; return ::mediapipe::OkStatus(); } ::mediapipe::Status ActiveSpeakerToRegionCalculator::Process( mediapipe::CalculatorContext* cc) { if (cc->Inputs().HasTag(kInputVideo) && cc->Inputs().Tag(kInputVideo).Value().IsEmpty()) { return ::mediapipe::UnknownErrorBuilder(MEDIAPIPE_LOC) << "No VIDEO input at time " << cc->InputTimestamp().Seconds(); } cv::Mat frame; if (cc->Inputs().HasTag(kInputVideo)) { frame = mediapipe::formats::MatView( &cc->Inputs().Tag(kInputVideo).Get<ImageFrame>()); frame_width_ = frame.cols; frame_height_ = frame.rows; } auto region_set = ::absl::make_unique<DetectionSet>(); if (!cc->Inputs().Tag(kInputRois).Value().IsEmpty()) { const auto& input_rois = cc->Inputs().Tag(kInputRois).Get<std::vector<Detection>>(); for (const auto& input_roi : input_rois) { RET_CHECK(input_roi.location_data().format() == mediapipe::LocationData::RELATIVE_BOUNDING_BOX) << "Speaker detection input is lacking required relative_bounding_box()"; const auto& location = input_roi.location_data().relative_bounding_box(); float x = std::max(0.0f, location.xmin()); float y = std::max(0.0f, location.ymin()); float width = std::min(location.width() - x + location.xmin(), 1 - x); float height = std::min(location.height() - y + location.ymin(), 1 - y); // Convert the text bounding box to a region. SalientRegion* region = region_set->add_detections(); region->mutable_location_normalized()->set_x(x); region->mutable_location_normalized()->set_y(y); region->mutable_location_normalized()->set_width(width); region->mutable_location_normalized()->set_height(height); region->mutable_signal_type()->set_standard(SignalType::SPEAKER); // Score the scores based on image cues. float visual_score = 1.0f; if (options_.use_visual_scorer()) { MP_RETURN_IF_ERROR( scorer_->CalculateScore(frame, *region, &visual_score)); } region->set_score(visual_score); } } cc->Outputs().Tag(kOutputRegion).Add(region_set.release(), cc->InputTimestamp()); return ::mediapipe::OkStatus(); } } // namespace autoflip } // namespace mediapipe <|endoftext|>
<commit_before>/* * Copyright (C) 2006, 2008, 2009, 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * 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 "core/html/HTMLViewSourceDocument.h" #include "HTMLNames.h" #include "core/dom/Attribute.h" #include "core/dom/DOMImplementation.h" #include "core/dom/DocumentStyleSheetCollection.h" #include "core/dom/Text.h" #include "core/html/HTMLAnchorElement.h" #include "core/html/HTMLBRElement.h" #include "core/html/HTMLBaseElement.h" #include "core/html/HTMLBodyElement.h" #include "core/html/HTMLDivElement.h" #include "core/html/HTMLHtmlElement.h" #include "core/html/HTMLTableCellElement.h" #include "core/html/HTMLTableElement.h" #include "core/html/HTMLTableRowElement.h" #include "core/html/HTMLTableSectionElement.h" #include "core/html/parser/HTMLToken.h" #include "core/html/parser/HTMLViewSourceParser.h" #include "core/html/parser/TextViewSourceParser.h" #include "core/platform/text/SegmentedString.h" namespace WebCore { using namespace HTMLNames; HTMLViewSourceDocument::HTMLViewSourceDocument(Frame* frame, const KURL& url, const String& mimeType) : HTMLDocument(frame, url) , m_type(mimeType) { styleSheetCollection()->setUsesBeforeAfterRulesOverride(true); setIsViewSource(true); setCompatibilityMode(QuirksMode); lockCompatibilityMode(); } PassRefPtr<DocumentParser> HTMLViewSourceDocument::createParser() { if (m_type == "text/html" || m_type == "application/xhtml+xml" || m_type == "image/svg+xml" || DOMImplementation::isXMLMIMEType(m_type)) return HTMLViewSourceParser::create(this); return TextViewSourceParser::create(this); } void HTMLViewSourceDocument::createContainingTable() { RefPtr<HTMLHtmlElement> html = HTMLHtmlElement::create(this); parserAppendChild(html); html->attach(); RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(this); html->parserAppendChild(body); body->attach(); // Create a line gutter div that can be used to make sure the gutter extends down the height of the whole // document. RefPtr<HTMLDivElement> div = HTMLDivElement::create(this); div->setAttribute(classAttr, "webkit-line-gutter-backdrop"); body->parserAppendChild(div); div->attach(); RefPtr<HTMLTableElement> table = HTMLTableElement::create(this); body->parserAppendChild(table); table->attach(); m_tbody = HTMLTableSectionElement::create(tbodyTag, this); table->parserAppendChild(m_tbody); m_tbody->attach(); m_current = m_tbody; } void HTMLViewSourceDocument::addSource(const String& source, HTMLToken& token) { if (!m_current) createContainingTable(); switch (token.type()) { case HTMLToken::Uninitialized: ASSERT_NOT_REACHED(); break; case HTMLToken::DOCTYPE: processDoctypeToken(source, token); break; case HTMLToken::EndOfFile: if (!m_tbody->hasChildNodes()) addLine(String()); break; case HTMLToken::StartTag: case HTMLToken::EndTag: processTagToken(source, token); break; case HTMLToken::Comment: processCommentToken(source, token); break; case HTMLToken::Character: processCharacterToken(source, token); break; } } void HTMLViewSourceDocument::processDoctypeToken(const String& source, HTMLToken&) { if (!m_current) createContainingTable(); m_current = addSpanWithClassName("webkit-html-doctype"); addText(source, "webkit-html-doctype"); m_current = m_td; } void HTMLViewSourceDocument::processTagToken(const String& source, HTMLToken& token) { m_current = addSpanWithClassName("webkit-html-tag"); AtomicString tagName(token.name()); unsigned index = 0; HTMLToken::AttributeList::const_iterator iter = token.attributes().begin(); while (index < source.length()) { if (iter == token.attributes().end()) { // We want to show the remaining characters in the token. index = addRange(source, index, source.length(), ""); ASSERT(index == source.length()); break; } AtomicString name(iter->name); String value = StringImpl::create8BitIfPossible(iter->value); index = addRange(source, index, iter->nameRange.start - token.startIndex(), ""); index = addRange(source, index, iter->nameRange.end - token.startIndex(), "webkit-html-attribute-name"); if (tagName == baseTag && name == hrefAttr) m_current = addBase(value); index = addRange(source, index, iter->valueRange.start - token.startIndex(), ""); bool isLink = name == srcAttr || name == hrefAttr; index = addRange(source, index, iter->valueRange.end - token.startIndex(), "webkit-html-attribute-value", isLink, tagName == aTag, value); ++iter; } m_current = m_td; } void HTMLViewSourceDocument::processCommentToken(const String& source, HTMLToken&) { m_current = addSpanWithClassName("webkit-html-comment"); addText(source, "webkit-html-comment"); m_current = m_td; } void HTMLViewSourceDocument::processCharacterToken(const String& source, HTMLToken&) { addText(source, ""); } PassRefPtr<Element> HTMLViewSourceDocument::addSpanWithClassName(const AtomicString& className) { if (m_current == m_tbody) { addLine(className); return m_current; } RefPtr<HTMLElement> span = HTMLElement::create(spanTag, this); span->setAttribute(classAttr, className); m_current->parserAppendChild(span); span->attach(); return span.release(); } void HTMLViewSourceDocument::addLine(const AtomicString& className) { // Create a table row. RefPtr<HTMLTableRowElement> trow = HTMLTableRowElement::create(this); m_tbody->parserAppendChild(trow); trow->attach(); // Create a cell that will hold the line number (it is generated in the stylesheet using counters). RefPtr<HTMLTableCellElement> td = HTMLTableCellElement::create(tdTag, this); td->setAttribute(classAttr, "webkit-line-number"); trow->parserAppendChild(td); td->attach(); // Create a second cell for the line contents td = HTMLTableCellElement::create(tdTag, this); td->setAttribute(classAttr, "webkit-line-content"); trow->parserAppendChild(td); td->attach(); m_current = m_td = td; #ifdef DEBUG_LINE_NUMBERS RefPtr<Text> lineNumberText = Text::create(this, String::number(parser()->lineNumber() + 1) + " "); td->addChild(lineNumberText); lineNumberText->attach(); #endif // Open up the needed spans. if (!className.isEmpty()) { if (className == "webkit-html-attribute-name" || className == "webkit-html-attribute-value") m_current = addSpanWithClassName("webkit-html-tag"); m_current = addSpanWithClassName(className); } } void HTMLViewSourceDocument::finishLine() { if (!m_current->hasChildNodes()) { RefPtr<HTMLBRElement> br = HTMLBRElement::create(this); m_current->parserAppendChild(br); br->attach(); } m_current = m_tbody; } void HTMLViewSourceDocument::addText(const String& text, const AtomicString& className) { if (text.isEmpty()) return; // Add in the content, splitting on newlines. Vector<String> lines; text.split('\n', true, lines); unsigned size = lines.size(); for (unsigned i = 0; i < size; i++) { String substring = lines[i]; if (m_current == m_tbody) addLine(className); if (substring.isEmpty()) { if (i == size - 1) break; finishLine(); continue; } RefPtr<Text> t = Text::create(this, substring); m_current->parserAppendChild(t); t->attach(); if (i < size - 1) finishLine(); } } int HTMLViewSourceDocument::addRange(const String& source, int start, int end, const String& className, bool isLink, bool isAnchor, const String& link) { ASSERT(start <= end); if (start == end) return start; String text = source.substring(start, end - start); if (!className.isEmpty()) { if (isLink) m_current = addLink(link, isAnchor); else m_current = addSpanWithClassName(className); } addText(text, className); if (!className.isEmpty() && m_current != m_tbody) m_current = toElement(m_current->parentNode()); return end; } PassRefPtr<Element> HTMLViewSourceDocument::addBase(const AtomicString& href) { RefPtr<HTMLBaseElement> base = HTMLBaseElement::create(baseTag, this); base->setAttribute(hrefAttr, href); m_current->parserAppendChild(base); base->attach(); return base.release(); } PassRefPtr<Element> HTMLViewSourceDocument::addLink(const AtomicString& url, bool isAnchor) { if (m_current == m_tbody) addLine("webkit-html-tag"); // Now create a link for the attribute value instead of a span. RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(this); const char* classValue; if (isAnchor) classValue = "webkit-html-attribute-value webkit-html-external-link"; else classValue = "webkit-html-attribute-value webkit-html-resource-link"; anchor->setAttribute(classAttr, classValue); anchor->setAttribute(targetAttr, "_blank"); anchor->setAttribute(hrefAttr, url); m_current->parserAppendChild(anchor); anchor->attach(); return anchor.release(); } } <commit_msg>HTMLViewSourceDocument should lazyAttach<commit_after>/* * Copyright (C) 2006, 2008, 2009, 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * 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 "core/html/HTMLViewSourceDocument.h" #include "HTMLNames.h" #include "core/dom/Attribute.h" #include "core/dom/DOMImplementation.h" #include "core/dom/DocumentStyleSheetCollection.h" #include "core/dom/Text.h" #include "core/html/HTMLAnchorElement.h" #include "core/html/HTMLBRElement.h" #include "core/html/HTMLBaseElement.h" #include "core/html/HTMLBodyElement.h" #include "core/html/HTMLDivElement.h" #include "core/html/HTMLHtmlElement.h" #include "core/html/HTMLTableCellElement.h" #include "core/html/HTMLTableElement.h" #include "core/html/HTMLTableRowElement.h" #include "core/html/HTMLTableSectionElement.h" #include "core/html/parser/HTMLToken.h" #include "core/html/parser/HTMLViewSourceParser.h" #include "core/html/parser/TextViewSourceParser.h" #include "core/platform/text/SegmentedString.h" namespace WebCore { using namespace HTMLNames; HTMLViewSourceDocument::HTMLViewSourceDocument(Frame* frame, const KURL& url, const String& mimeType) : HTMLDocument(frame, url) , m_type(mimeType) { styleSheetCollection()->setUsesBeforeAfterRulesOverride(true); setIsViewSource(true); setCompatibilityMode(QuirksMode); lockCompatibilityMode(); } PassRefPtr<DocumentParser> HTMLViewSourceDocument::createParser() { if (m_type == "text/html" || m_type == "application/xhtml+xml" || m_type == "image/svg+xml" || DOMImplementation::isXMLMIMEType(m_type)) return HTMLViewSourceParser::create(this); return TextViewSourceParser::create(this); } void HTMLViewSourceDocument::createContainingTable() { RefPtr<HTMLHtmlElement> html = HTMLHtmlElement::create(this); parserAppendChild(html); html->lazyAttach(); RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(this); html->parserAppendChild(body); body->lazyAttach(); // Create a line gutter div that can be used to make sure the gutter extends down the height of the whole // document. RefPtr<HTMLDivElement> div = HTMLDivElement::create(this); div->setAttribute(classAttr, "webkit-line-gutter-backdrop"); body->parserAppendChild(div); div->lazyAttach(); RefPtr<HTMLTableElement> table = HTMLTableElement::create(this); body->parserAppendChild(table); table->lazyAttach(); m_tbody = HTMLTableSectionElement::create(tbodyTag, this); table->parserAppendChild(m_tbody); m_tbody->lazyAttach(); m_current = m_tbody; } void HTMLViewSourceDocument::addSource(const String& source, HTMLToken& token) { if (!m_current) createContainingTable(); switch (token.type()) { case HTMLToken::Uninitialized: ASSERT_NOT_REACHED(); break; case HTMLToken::DOCTYPE: processDoctypeToken(source, token); break; case HTMLToken::EndOfFile: if (!m_tbody->hasChildNodes()) addLine(String()); break; case HTMLToken::StartTag: case HTMLToken::EndTag: processTagToken(source, token); break; case HTMLToken::Comment: processCommentToken(source, token); break; case HTMLToken::Character: processCharacterToken(source, token); break; } } void HTMLViewSourceDocument::processDoctypeToken(const String& source, HTMLToken&) { m_current = addSpanWithClassName("webkit-html-doctype"); addText(source, "webkit-html-doctype"); m_current = m_td; } void HTMLViewSourceDocument::processTagToken(const String& source, HTMLToken& token) { m_current = addSpanWithClassName("webkit-html-tag"); AtomicString tagName(token.name()); unsigned index = 0; HTMLToken::AttributeList::const_iterator iter = token.attributes().begin(); while (index < source.length()) { if (iter == token.attributes().end()) { // We want to show the remaining characters in the token. index = addRange(source, index, source.length(), ""); ASSERT(index == source.length()); break; } AtomicString name(iter->name); String value = StringImpl::create8BitIfPossible(iter->value); index = addRange(source, index, iter->nameRange.start - token.startIndex(), ""); index = addRange(source, index, iter->nameRange.end - token.startIndex(), "webkit-html-attribute-name"); if (tagName == baseTag && name == hrefAttr) m_current = addBase(value); index = addRange(source, index, iter->valueRange.start - token.startIndex(), ""); bool isLink = name == srcAttr || name == hrefAttr; index = addRange(source, index, iter->valueRange.end - token.startIndex(), "webkit-html-attribute-value", isLink, tagName == aTag, value); ++iter; } m_current = m_td; } void HTMLViewSourceDocument::processCommentToken(const String& source, HTMLToken&) { m_current = addSpanWithClassName("webkit-html-comment"); addText(source, "webkit-html-comment"); m_current = m_td; } void HTMLViewSourceDocument::processCharacterToken(const String& source, HTMLToken&) { addText(source, ""); } PassRefPtr<Element> HTMLViewSourceDocument::addSpanWithClassName(const AtomicString& className) { if (m_current == m_tbody) { addLine(className); return m_current; } RefPtr<HTMLElement> span = HTMLElement::create(spanTag, this); span->setAttribute(classAttr, className); m_current->parserAppendChild(span); span->lazyAttach(); return span.release(); } void HTMLViewSourceDocument::addLine(const AtomicString& className) { // Create a table row. RefPtr<HTMLTableRowElement> trow = HTMLTableRowElement::create(this); m_tbody->parserAppendChild(trow); trow->lazyAttach(); // Create a cell that will hold the line number (it is generated in the stylesheet using counters). RefPtr<HTMLTableCellElement> td = HTMLTableCellElement::create(tdTag, this); td->setAttribute(classAttr, "webkit-line-number"); trow->parserAppendChild(td); td->lazyAttach(); // Create a second cell for the line contents td = HTMLTableCellElement::create(tdTag, this); td->setAttribute(classAttr, "webkit-line-content"); trow->parserAppendChild(td); td->lazyAttach(); m_current = m_td = td; #ifdef DEBUG_LINE_NUMBERS RefPtr<Text> lineNumberText = Text::create(this, String::number(parser()->lineNumber() + 1) + " "); td->addChild(lineNumberText); lineNumberText->lazyAttach(); #endif // Open up the needed spans. if (!className.isEmpty()) { if (className == "webkit-html-attribute-name" || className == "webkit-html-attribute-value") m_current = addSpanWithClassName("webkit-html-tag"); m_current = addSpanWithClassName(className); } } void HTMLViewSourceDocument::finishLine() { if (!m_current->hasChildNodes()) { RefPtr<HTMLBRElement> br = HTMLBRElement::create(this); m_current->parserAppendChild(br); br->lazyAttach(); } m_current = m_tbody; } void HTMLViewSourceDocument::addText(const String& text, const AtomicString& className) { if (text.isEmpty()) return; // Add in the content, splitting on newlines. Vector<String> lines; text.split('\n', true, lines); unsigned size = lines.size(); for (unsigned i = 0; i < size; i++) { String substring = lines[i]; if (m_current == m_tbody) addLine(className); if (substring.isEmpty()) { if (i == size - 1) break; finishLine(); continue; } RefPtr<Text> t = Text::create(this, substring); m_current->parserAppendChild(t); t->lazyAttach(); if (i < size - 1) finishLine(); } } int HTMLViewSourceDocument::addRange(const String& source, int start, int end, const String& className, bool isLink, bool isAnchor, const String& link) { ASSERT(start <= end); if (start == end) return start; String text = source.substring(start, end - start); if (!className.isEmpty()) { if (isLink) m_current = addLink(link, isAnchor); else m_current = addSpanWithClassName(className); } addText(text, className); if (!className.isEmpty() && m_current != m_tbody) m_current = toElement(m_current->parentNode()); return end; } PassRefPtr<Element> HTMLViewSourceDocument::addBase(const AtomicString& href) { RefPtr<HTMLBaseElement> base = HTMLBaseElement::create(baseTag, this); base->setAttribute(hrefAttr, href); m_current->parserAppendChild(base); base->lazyAttach(); return base.release(); } PassRefPtr<Element> HTMLViewSourceDocument::addLink(const AtomicString& url, bool isAnchor) { if (m_current == m_tbody) addLine("webkit-html-tag"); // Now create a link for the attribute value instead of a span. RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(this); const char* classValue; if (isAnchor) classValue = "webkit-html-attribute-value webkit-html-external-link"; else classValue = "webkit-html-attribute-value webkit-html-resource-link"; anchor->setAttribute(classAttr, classValue); anchor->setAttribute(targetAttr, "_blank"); anchor->setAttribute(hrefAttr, url); m_current->parserAppendChild(anchor); anchor->lazyAttach(); return anchor.release(); } } <|endoftext|>
<commit_before>#include<iostream> #include<hc.hpp> #include<eap_resources.hpp> #include<lua_cmds.hpp> #include<boost/format.hpp> #include<boost/filesystem.hpp> namespace { const std::string c_iterations = "iterations"; const std::string c_convergence_factor = "convergence_factor"; } hc::hc(std::string lua_file) : algorithm(lua_file) { m_convergence_factor = 0.0f; m_best_fitness = 0.0f; m_converged_iterations = 0.0f; } /** * @desc Loads parameters for the hill climber algorithm */ void hc::setup_algo_params() { try { algorithm::setup_algo_params(); m_iterations = eap::get_fvalue(c_iterations); m_convergence_factor = eap::get_fvalue(c_convergence_factor); m_converged_iterations = m_iterations * m_convergence_factor; std::cout<<"***completed HC parameter setup"<<std::endl; } catch (const eap::InvalidStateException &e) { std::cerr<<e.what()<<"\n"; } } /** * @desc Implements logic for HC runs */ void hc::run(unsigned int run_id) { std::ofstream outfile; try { std::vector<position_ptr> placements; outfile.open(eap::results_directory + boost::filesystem::basename(m_lua_file) + "_r" + std::to_string(run_id) + "iters.csv"); boost::format nec_input(eap::run_directory + "iter%09d"); int q = 0; // successive state with best solution for (ant_config_ptr i_ant : m_ant_configs) { int pos; do { pos = eap::rand(0, i_ant->m_positions.size() - 1); } while(overlap(placements, i_ant->m_positions[pos])); placements.push_back(i_ant->m_positions[pos]); } m_p_parent = create_individual(str(nec_input % 0) + "a%02d.nec", placements); evaluate(0, m_p_parent); m_best_fitness = m_p_parent->m_fitness; outfile << 0 << "," << m_p_parent->m_fitness << "," << m_p_parent->m_gain_fitness << "," << m_p_parent->m_coupling_fitness << ","; for (position_ptr p_pos : m_p_parent->m_positions) outfile << p_pos->m_x << "," << p_pos->m_y << "," << p_pos->m_z <<","; outfile << "\n"; for (unsigned int i=1; i<m_iterations; ++i) { std::vector<position_ptr> placements = mutate_pos_once(m_p_parent->m_positions); individual_ptr p_child = create_individual(str(nec_input % i) + "a%02d.nec", placements); evaluate(i, p_child); if (p_child->m_fitness < m_p_parent->m_fitness) { m_best_fitness = p_child->m_fitness; swap(m_p_parent, p_child); outfile << i << "," << m_p_parent->m_fitness << "," << m_p_parent->m_gain_fitness << "," << m_p_parent->m_coupling_fitness << ","; for (position_ptr p_pos : m_p_parent->m_positions) outfile << p_pos->m_x << "," << p_pos->m_y << "," << p_pos->m_z <<","; outfile << "\n"; std::cout<<"***iter="<<i<<", best ind "<<m_p_parent->m_fitness<<"\n"; } if (m_p_parent->m_fitness >= m_best_fitness) q++; else q=0; if (q > m_converged_iterations) { //change mutation probability m_mutation *= 1.1; std::cout<<"***mutatation_prob changed to "<<m_mutation<<"\n"; q = 0; } // remove all after an iteration boost::filesystem::path path_to_remove(eap::run_directory); for (boost::filesystem::directory_iterator end_dir_it, it(path_to_remove); it!=end_dir_it; ++it) remove_all(it->path()); if (abs(m_p_parent->m_fitness - 0.496877) > 0.0000001) //exit condition for tc2 break; } outfile.close(); } catch (...) { outfile.close(); throw; } } void hc::evaluate(unsigned int id, individual_ptr &p_ind) { try { run_simulation(id); boost::format nec_output(eap::run_directory + "iter%09da%02d.out"); for (unsigned int i_ant=0; i_ant<m_ant_configs.size(); ++i_ant) { evaluation_ptr p_eval(new evaluation); p_ind->m_evals.push_back(p_eval); unsigned int read = read_radiation(str(nec_output % id % i_ant), p_eval); if (read != (num_polar() * m_step_freq)) throw eap::InvalidStateException("HC:Problem with output in " + str(nec_output % id % i_ant)); p_ind->m_one_ant_on_fitness.push_back(compare(m_free_inds[i_ant]->m_evals[0], p_ind->m_evals[i_ant])); p_ind->m_gain_fitness += p_ind->m_one_ant_on_fitness[i_ant]; } p_ind->m_gain_fitness /= m_max_gain; p_ind->m_coupling_fitness = read_coupling(str(nec_output % id % m_ant_configs.size()), m_ant_configs.size()); //normalizing fitness p_ind->m_coupling_fitness += std::abs(m_min_coup); p_ind->m_coupling_fitness /= m_max_coup; p_ind->m_fitness = cal_fitness(p_ind); } catch (...) { throw; } } void hc::run_simulation(unsigned int id) { try { boost::format formatter("ls " + eap::run_directory + "iter%09da*.nec | parallel -j+0 nec2++ -i {}"); system(str(formatter % id).c_str()); std::cout<<"***completed simulation for iteration "<<id<<"\n"; } catch (...) { throw; } } hc::~hc(void) { } <commit_msg>hc converged iterations<commit_after>#include<iostream> #include<hc.hpp> #include<eap_resources.hpp> #include<lua_cmds.hpp> #include<boost/format.hpp> #include<boost/filesystem.hpp> namespace { const std::string c_iterations = "iterations"; const std::string c_convergence_factor = "convergence_factor"; } hc::hc(std::string lua_file) : algorithm(lua_file) { m_convergence_factor = 0.0f; m_best_fitness = 0.0f; m_converged_iterations = 0.0f; } /** * @desc Loads parameters for the hill climber algorithm */ void hc::setup_algo_params() { try { algorithm::setup_algo_params(); m_iterations = eap::get_fvalue(c_iterations); m_convergence_factor = eap::get_fvalue(c_convergence_factor); m_converged_iterations = m_iterations * m_convergence_factor; std::cout<<"***completed HC parameter setup"<<std::endl; } catch (const eap::InvalidStateException &e) { std::cerr<<e.what()<<"\n"; } } /** * @desc Implements logic for HC runs */ void hc::run(unsigned int run_id) { std::ofstream outfile; try { std::vector<position_ptr> placements; outfile.open(eap::results_directory + boost::filesystem::basename(m_lua_file) + "_r" + std::to_string(run_id) + "iters.csv"); boost::format nec_input(eap::run_directory + "iter%09d"); int q = 0; // successive state with best solution for (ant_config_ptr i_ant : m_ant_configs) { int pos; do { pos = eap::rand(0, i_ant->m_positions.size() - 1); } while(overlap(placements, i_ant->m_positions[pos])); placements.push_back(i_ant->m_positions[pos]); } m_p_parent = create_individual(str(nec_input % 0) + "a%02d.nec", placements); evaluate(0, m_p_parent); m_best_fitness = m_p_parent->m_fitness; outfile << 0 << "," << m_p_parent->m_fitness << "," << m_p_parent->m_gain_fitness << "," << m_p_parent->m_coupling_fitness << ","; for (position_ptr p_pos : m_p_parent->m_positions) outfile << p_pos->m_x << "," << p_pos->m_y << "," << p_pos->m_z <<","; outfile << "\n"; for (unsigned int i=1; i<m_iterations; ++i) { std::vector<position_ptr> placements = mutate_pos_once(m_p_parent->m_positions); individual_ptr p_child = create_individual(str(nec_input % i) + "a%02d.nec", placements); evaluate(i, p_child); if (p_child->m_fitness < m_p_parent->m_fitness) { m_best_fitness = p_child->m_fitness; swap(m_p_parent, p_child); outfile << i << "," << m_p_parent->m_fitness << "," << m_p_parent->m_gain_fitness << "," << m_p_parent->m_coupling_fitness << ","; for (position_ptr p_pos : m_p_parent->m_positions) outfile << p_pos->m_x << "," << p_pos->m_y << "," << p_pos->m_z <<","; outfile << "\n"; std::cout<<"***iter="<<i<<", best ind "<<m_p_parent->m_fitness<<"\n"; } if (m_p_parent->m_fitness >= m_best_fitness) q++; else q=0; if (q > m_converged_iterations) { break; } // remove all after an iteration boost::filesystem::path path_to_remove(eap::run_directory); for (boost::filesystem::directory_iterator end_dir_it, it(path_to_remove); it!=end_dir_it; ++it) remove_all(it->path()); } outfile.close(); } catch (...) { outfile.close(); throw; } } void hc::evaluate(unsigned int id, individual_ptr &p_ind) { try { run_simulation(id); boost::format nec_output(eap::run_directory + "iter%09da%02d.out"); for (unsigned int i_ant=0; i_ant<m_ant_configs.size(); ++i_ant) { evaluation_ptr p_eval(new evaluation); p_ind->m_evals.push_back(p_eval); unsigned int read = read_radiation(str(nec_output % id % i_ant), p_eval); if (read != (num_polar() * m_step_freq)) throw eap::InvalidStateException("HC:Problem with output in " + str(nec_output % id % i_ant)); p_ind->m_one_ant_on_fitness.push_back(compare(m_free_inds[i_ant]->m_evals[0], p_ind->m_evals[i_ant])); p_ind->m_gain_fitness += p_ind->m_one_ant_on_fitness[i_ant]; } p_ind->m_gain_fitness /= m_max_gain; p_ind->m_coupling_fitness = read_coupling(str(nec_output % id % m_ant_configs.size()), m_ant_configs.size()); //normalizing fitness p_ind->m_coupling_fitness += std::abs(m_min_coup); p_ind->m_coupling_fitness /= m_max_coup; p_ind->m_fitness = cal_fitness(p_ind); } catch (...) { throw; } } void hc::run_simulation(unsigned int id) { try { boost::format formatter("ls " + eap::run_directory + "iter%09da*.nec | parallel -j+0 nec2++ -i {}"); system(str(formatter % id).c_str()); std::cout<<"***completed simulation for iteration "<<id<<"\n"; } catch (...) { throw; } } hc::~hc(void) { } <|endoftext|>
<commit_before>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "SimpleInline.h" #include "InlineHelper.h" #include "Deleter.h" #include "DexClass.h" #include "DexInstruction.h" #include "DexUtil.h" #include "Resolver.h" #include "Transform.h" #include "Walkers.h" #include "ReachableClasses.h" #include "VirtualScope.h" #include <algorithm> #include <string> #include <vector> #include <map> #include <set> namespace { // the max number of callers we care to track explicitly, after that we // group all callees/callers count in the same bucket const int MAX_COUNT = 10; DEBUG_ONLY bool method_breakup( std::vector<std::vector<DexMethod*>>& calls_group) { size_t size = calls_group.size(); for (size_t i = 0; i < size; ++i) { size_t inst = 0; size_t stat = 0; auto group = calls_group[i]; for (auto callee : group) { is_static(callee) ? stat++ : inst++; } TRACE(SINL, 5, "%ld callers %ld: instance %ld, static %ld\n", i, group.size(), inst, stat); } return true; } std::unordered_set<DexType*> no_inline_annos( const std::vector<std::string>& annos, ConfigFiles& cfg ) { std::unordered_set<DexType*> no_inline; for (const auto& anno : cfg.get_no_optimizations_annos()) { no_inline.insert(anno); } for (auto const& no_inline_anno : annos) { auto type = DexType::get_type( DexString::get_string(no_inline_anno.c_str())); if (type != nullptr) { no_inline.insert(type); } } return no_inline; } std::unordered_set<DexType*> force_inline_annos( const std::vector<std::string>& annos) { std::unordered_set<DexType*> force_inline; for (auto const& force_inline_anno : annos) { auto type = DexType::get_type(force_inline_anno.c_str()); if (type != nullptr) { force_inline.insert(type); } } return force_inline; } template<typename DexMember> bool has_anno(DexMember* m, const std::unordered_set<DexType*>& no_inline) { if (no_inline.size() == 0) return false; if (m != nullptr && m->get_anno_set() != nullptr) { for (const auto& anno : m->get_anno_set()->get_annotations()) { if (no_inline.count(anno->type()) > 0) { return true; } } } return false; } } void SimpleInlinePass::run_pass(DexStoresVector& stores, ConfigFiles& cfg, PassManager& mgr) { if (mgr.no_proguard_rules()) { TRACE(SINL, 1, "SimpleInlinePass not run because no ProGuard configuration was provided."); return; } const auto no_inline = no_inline_annos(m_no_inline_annos, cfg); const auto force_inline = force_inline_annos(m_force_inline_annos); auto scope = build_class_scope(stores); // gather all inlinable candidates auto methods = gather_non_virtual_methods(scope, no_inline, force_inline); select_single_called(scope, methods); auto resolver = [&](DexMethod* method, MethodSearch search) { return resolve_method(method, search, resolved_refs); }; // inline candidates MultiMethodInliner inliner( scope, stores[0].get_dexen()[0], inlinable, resolver, m_inliner_config); inliner.inline_methods(); MethodTransform::sync_all(scope); MethodTransform::balloon_all(scope); // delete all methods that can be deleted auto inlined = inliner.get_inlined(); size_t inlined_count = inlined.size(); size_t deleted = delete_methods(scope, inlined, resolver); TRACE(SINL, 3, "recursive %ld\n", inliner.get_info().recursive); TRACE(SINL, 3, "blacklisted meths %ld\n", inliner.get_info().blacklisted); TRACE(SINL, 3, "more than 16 regs %ld\n", inliner.get_info().more_than_16regs); TRACE(SINL, 3, "try/catch in callee %ld\n", inliner.get_info().try_catch_block); TRACE(SINL, 3, "try/catch in caller %ld\n", inliner.get_info().caller_tries); TRACE(SINL, 3, "virtualizing methods %ld\n", inliner.get_info().need_vmethod); TRACE(SINL, 3, "invoke super %ld\n", inliner.get_info().invoke_super); TRACE(SINL, 3, "override inputs %ld\n", inliner.get_info().write_over_ins); TRACE(SINL, 3, "escaped virtual %ld\n", inliner.get_info().escaped_virtual); TRACE(SINL, 3, "known non public virtual %ld\n", inliner.get_info().non_pub_virtual); TRACE(SINL, 3, "non public ctor %ld\n", inliner.get_info().non_pub_ctor); TRACE(SINL, 3, "unknown field %ld\n", inliner.get_info().escaped_field); TRACE(SINL, 3, "non public field %ld\n", inliner.get_info().non_pub_field); TRACE(SINL, 3, "throws %ld\n", inliner.get_info().throws); TRACE(SINL, 3, "multiple returns %ld\n", inliner.get_info().multi_ret); TRACE(SINL, 3, "reference outside of primary %ld\n", inliner.get_info().not_in_primary); TRACE(SINL, 3, "not found %ld\n", inliner.get_info().not_found); TRACE(SINL, 3, "caller too large %ld\n", inliner.get_info().caller_too_large); TRACE(SINL, 1, "%ld inlined calls over %ld methods and %ld methods removed\n", inliner.get_info().calls_inlined, inlined_count, deleted); mgr.incr_metric("calls_inlined", inliner.get_info().calls_inlined); mgr.incr_metric("methods_removed", deleted); } /** * Collect all non virtual methods and make all small methods candidates * for inlining. */ std::unordered_set<DexMethod*> SimpleInlinePass::gather_non_virtual_methods( Scope& scope, const std::unordered_set<DexType*>& no_inline, const std::unordered_set<DexType*>& force_inline) { // trace counter size_t all_methods = 0; size_t direct_methods = 0; size_t direct_no_code = 0; size_t non_virtual_no_code = 0; size_t clinit = 0; size_t init = 0; size_t static_methods = 0; size_t private_methods = 0; size_t dont_strip = 0; size_t no_inline_anno_count = 0; size_t non_virt_dont_strip = 0; size_t non_virt_methods = 0; // collect all non virtual methods (dmethods and vmethods) std::unordered_set<DexMethod*> methods; const auto can_inline_method = [&](DexMethod* meth, const DexCode& code) { DexClass* cls = type_class(meth->get_class()); if (has_anno(cls, no_inline) || has_anno(meth, no_inline)) { no_inline_anno_count++; return; } if (code.get_entries()->count_opcodes() < SMALL_CODE_SIZE) { // always inline small methods even if they are not deletable inlinable.insert(meth); } else { if (!can_delete(meth)) { // never inline methods that cannot be deleted TRACE(SINL, 4, "cannot_delete: %s\n", SHOW(meth)); dont_strip++; } else { methods.insert(meth); } } if (has_anno(meth, force_inline)) { inlinable.insert(meth); } }; walk_methods(scope, [&](DexMethod* method) { all_methods++; if (method->is_virtual()) return; auto& code = method->get_code(); bool dont_inline = code == nullptr; direct_methods++; if (code == nullptr) direct_no_code++; if (is_constructor(method)) { (is_static(method)) ? clinit++ : init++; dont_inline = true; } else { (is_static(method)) ? static_methods++ : private_methods++; } if (dont_inline) return; can_inline_method(method, *code); }); if (m_virtual_inline) { auto non_virtual = devirtualize(scope); non_virt_methods = non_virtual.size(); for (const auto& vmeth : non_virtual) { auto& code = vmeth->get_code(); if (code == nullptr) { non_virtual_no_code++; continue; } can_inline_method(vmeth, *code); } } TRACE(SINL, 2, "All methods count: %ld\n", all_methods); TRACE(SINL, 2, "Direct methods count: %ld\n", direct_methods); TRACE(SINL, 2, "Virtual methods count: %ld\n", all_methods - direct_methods); TRACE(SINL, 2, "Direct methods no code: %ld\n", direct_no_code); TRACE(SINL, 2, "Direct methods with code: %ld\n", direct_methods - direct_no_code); TRACE(SINL, 2, "Constructors with or without code: %ld\n", init); TRACE(SINL, 2, "Static constructors: %ld\n", clinit); TRACE(SINL, 2, "Static methods: %ld\n", static_methods); TRACE(SINL, 2, "Private methods: %ld\n", private_methods); TRACE(SINL, 2, "Virtual methods non virtual count: %ld\n", non_virt_methods); TRACE(SINL, 2, "Non virtual no code count: %ld\n", non_virtual_no_code); TRACE(SINL, 2, "Non virtual no strip count: %ld\n", non_virt_dont_strip); TRACE(SINL, 2, "Small methods: %ld\n", inlinable.size()); TRACE(SINL, 2, "Don't strip inlinable methods count: %ld\n", dont_strip); TRACE(SINL, 2, "Don't inline annotation count: %ld\n", no_inline_anno_count); return methods; } /** * Add to the list the single called. */ void SimpleInlinePass::select_single_called( Scope& scope, std::unordered_set<DexMethod*>& methods) { std::unordered_map<DexMethod*, int> calls; for (const auto& method : methods) { calls[method] = 0; } // count call sites for each method walk_opcodes(scope, [](DexMethod* meth) { return true; }, [&](DexMethod* meth, DexInstruction* insn) { if (is_invoke(insn->opcode())) { auto mop = static_cast<DexOpcodeMethod*>(insn); auto callee = resolve_method( mop->get_method(), opcode_to_search(insn), resolved_refs); if (callee != nullptr && callee->is_concrete() && methods.count(callee) > 0) { calls[callee]++; } } }); // pick methods with a single call site and add to candidates. // This vector usage is only because of logging we should remove it // once the optimization is "closed" std::vector<std::vector<DexMethod*>> calls_group(MAX_COUNT); for (auto call_it : calls) { if (call_it.second >= MAX_COUNT) { calls_group[MAX_COUNT - 1].push_back(call_it.first); continue; } calls_group[call_it.second].push_back(call_it.first); } assert(method_breakup(calls_group)); for (auto callee : calls_group[1]) { inlinable.insert(callee); } } static SimpleInlinePass s_pass; <commit_msg>Don't call sync_all after SimpleInline<commit_after>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "SimpleInline.h" #include "InlineHelper.h" #include "Deleter.h" #include "DexClass.h" #include "DexInstruction.h" #include "DexUtil.h" #include "Resolver.h" #include "Transform.h" #include "Walkers.h" #include "ReachableClasses.h" #include "VirtualScope.h" #include <algorithm> #include <string> #include <vector> #include <map> #include <set> namespace { // the max number of callers we care to track explicitly, after that we // group all callees/callers count in the same bucket const int MAX_COUNT = 10; DEBUG_ONLY bool method_breakup( std::vector<std::vector<DexMethod*>>& calls_group) { size_t size = calls_group.size(); for (size_t i = 0; i < size; ++i) { size_t inst = 0; size_t stat = 0; auto group = calls_group[i]; for (auto callee : group) { is_static(callee) ? stat++ : inst++; } TRACE(SINL, 5, "%ld callers %ld: instance %ld, static %ld\n", i, group.size(), inst, stat); } return true; } std::unordered_set<DexType*> no_inline_annos( const std::vector<std::string>& annos, ConfigFiles& cfg ) { std::unordered_set<DexType*> no_inline; for (const auto& anno : cfg.get_no_optimizations_annos()) { no_inline.insert(anno); } for (auto const& no_inline_anno : annos) { auto type = DexType::get_type( DexString::get_string(no_inline_anno.c_str())); if (type != nullptr) { no_inline.insert(type); } } return no_inline; } std::unordered_set<DexType*> force_inline_annos( const std::vector<std::string>& annos) { std::unordered_set<DexType*> force_inline; for (auto const& force_inline_anno : annos) { auto type = DexType::get_type(force_inline_anno.c_str()); if (type != nullptr) { force_inline.insert(type); } } return force_inline; } template<typename DexMember> bool has_anno(DexMember* m, const std::unordered_set<DexType*>& no_inline) { if (no_inline.size() == 0) return false; if (m != nullptr && m->get_anno_set() != nullptr) { for (const auto& anno : m->get_anno_set()->get_annotations()) { if (no_inline.count(anno->type()) > 0) { return true; } } } return false; } } void SimpleInlinePass::run_pass(DexStoresVector& stores, ConfigFiles& cfg, PassManager& mgr) { if (mgr.no_proguard_rules()) { TRACE(SINL, 1, "SimpleInlinePass not run because no ProGuard configuration was provided."); return; } const auto no_inline = no_inline_annos(m_no_inline_annos, cfg); const auto force_inline = force_inline_annos(m_force_inline_annos); auto scope = build_class_scope(stores); // gather all inlinable candidates auto methods = gather_non_virtual_methods(scope, no_inline, force_inline); select_single_called(scope, methods); auto resolver = [&](DexMethod* method, MethodSearch search) { return resolve_method(method, search, resolved_refs); }; // inline candidates MultiMethodInliner inliner( scope, stores[0].get_dexen()[0], inlinable, resolver, m_inliner_config); inliner.inline_methods(); // delete all methods that can be deleted auto inlined = inliner.get_inlined(); size_t inlined_count = inlined.size(); size_t deleted = delete_methods(scope, inlined, resolver); TRACE(SINL, 3, "recursive %ld\n", inliner.get_info().recursive); TRACE(SINL, 3, "blacklisted meths %ld\n", inliner.get_info().blacklisted); TRACE(SINL, 3, "more than 16 regs %ld\n", inliner.get_info().more_than_16regs); TRACE(SINL, 3, "try/catch in callee %ld\n", inliner.get_info().try_catch_block); TRACE(SINL, 3, "try/catch in caller %ld\n", inliner.get_info().caller_tries); TRACE(SINL, 3, "virtualizing methods %ld\n", inliner.get_info().need_vmethod); TRACE(SINL, 3, "invoke super %ld\n", inliner.get_info().invoke_super); TRACE(SINL, 3, "override inputs %ld\n", inliner.get_info().write_over_ins); TRACE(SINL, 3, "escaped virtual %ld\n", inliner.get_info().escaped_virtual); TRACE(SINL, 3, "known non public virtual %ld\n", inliner.get_info().non_pub_virtual); TRACE(SINL, 3, "non public ctor %ld\n", inliner.get_info().non_pub_ctor); TRACE(SINL, 3, "unknown field %ld\n", inliner.get_info().escaped_field); TRACE(SINL, 3, "non public field %ld\n", inliner.get_info().non_pub_field); TRACE(SINL, 3, "throws %ld\n", inliner.get_info().throws); TRACE(SINL, 3, "multiple returns %ld\n", inliner.get_info().multi_ret); TRACE(SINL, 3, "reference outside of primary %ld\n", inliner.get_info().not_in_primary); TRACE(SINL, 3, "not found %ld\n", inliner.get_info().not_found); TRACE(SINL, 3, "caller too large %ld\n", inliner.get_info().caller_too_large); TRACE(SINL, 1, "%ld inlined calls over %ld methods and %ld methods removed\n", inliner.get_info().calls_inlined, inlined_count, deleted); mgr.incr_metric("calls_inlined", inliner.get_info().calls_inlined); mgr.incr_metric("methods_removed", deleted); } /** * Collect all non virtual methods and make all small methods candidates * for inlining. */ std::unordered_set<DexMethod*> SimpleInlinePass::gather_non_virtual_methods( Scope& scope, const std::unordered_set<DexType*>& no_inline, const std::unordered_set<DexType*>& force_inline) { // trace counter size_t all_methods = 0; size_t direct_methods = 0; size_t direct_no_code = 0; size_t non_virtual_no_code = 0; size_t clinit = 0; size_t init = 0; size_t static_methods = 0; size_t private_methods = 0; size_t dont_strip = 0; size_t no_inline_anno_count = 0; size_t non_virt_dont_strip = 0; size_t non_virt_methods = 0; // collect all non virtual methods (dmethods and vmethods) std::unordered_set<DexMethod*> methods; const auto can_inline_method = [&](DexMethod* meth, const DexCode& code) { DexClass* cls = type_class(meth->get_class()); if (has_anno(cls, no_inline) || has_anno(meth, no_inline)) { no_inline_anno_count++; return; } if (code.get_entries()->count_opcodes() < SMALL_CODE_SIZE) { // always inline small methods even if they are not deletable inlinable.insert(meth); } else { if (!can_delete(meth)) { // never inline methods that cannot be deleted TRACE(SINL, 4, "cannot_delete: %s\n", SHOW(meth)); dont_strip++; } else { methods.insert(meth); } } if (has_anno(meth, force_inline)) { inlinable.insert(meth); } }; walk_methods(scope, [&](DexMethod* method) { all_methods++; if (method->is_virtual()) return; auto& code = method->get_code(); bool dont_inline = code == nullptr; direct_methods++; if (code == nullptr) direct_no_code++; if (is_constructor(method)) { (is_static(method)) ? clinit++ : init++; dont_inline = true; } else { (is_static(method)) ? static_methods++ : private_methods++; } if (dont_inline) return; can_inline_method(method, *code); }); if (m_virtual_inline) { auto non_virtual = devirtualize(scope); non_virt_methods = non_virtual.size(); for (const auto& vmeth : non_virtual) { auto& code = vmeth->get_code(); if (code == nullptr) { non_virtual_no_code++; continue; } can_inline_method(vmeth, *code); } } TRACE(SINL, 2, "All methods count: %ld\n", all_methods); TRACE(SINL, 2, "Direct methods count: %ld\n", direct_methods); TRACE(SINL, 2, "Virtual methods count: %ld\n", all_methods - direct_methods); TRACE(SINL, 2, "Direct methods no code: %ld\n", direct_no_code); TRACE(SINL, 2, "Direct methods with code: %ld\n", direct_methods - direct_no_code); TRACE(SINL, 2, "Constructors with or without code: %ld\n", init); TRACE(SINL, 2, "Static constructors: %ld\n", clinit); TRACE(SINL, 2, "Static methods: %ld\n", static_methods); TRACE(SINL, 2, "Private methods: %ld\n", private_methods); TRACE(SINL, 2, "Virtual methods non virtual count: %ld\n", non_virt_methods); TRACE(SINL, 2, "Non virtual no code count: %ld\n", non_virtual_no_code); TRACE(SINL, 2, "Non virtual no strip count: %ld\n", non_virt_dont_strip); TRACE(SINL, 2, "Small methods: %ld\n", inlinable.size()); TRACE(SINL, 2, "Don't strip inlinable methods count: %ld\n", dont_strip); TRACE(SINL, 2, "Don't inline annotation count: %ld\n", no_inline_anno_count); return methods; } /** * Add to the list the single called. */ void SimpleInlinePass::select_single_called( Scope& scope, std::unordered_set<DexMethod*>& methods) { std::unordered_map<DexMethod*, int> calls; for (const auto& method : methods) { calls[method] = 0; } // count call sites for each method walk_opcodes(scope, [](DexMethod* meth) { return true; }, [&](DexMethod* meth, DexInstruction* insn) { if (is_invoke(insn->opcode())) { auto mop = static_cast<DexOpcodeMethod*>(insn); auto callee = resolve_method( mop->get_method(), opcode_to_search(insn), resolved_refs); if (callee != nullptr && callee->is_concrete() && methods.count(callee) > 0) { calls[callee]++; } } }); // pick methods with a single call site and add to candidates. // This vector usage is only because of logging we should remove it // once the optimization is "closed" std::vector<std::vector<DexMethod*>> calls_group(MAX_COUNT); for (auto call_it : calls) { if (call_it.second >= MAX_COUNT) { calls_group[MAX_COUNT - 1].push_back(call_it.first); continue; } calls_group[call_it.second].push_back(call_it.first); } assert(method_breakup(calls_group)); for (auto callee : calls_group[1]) { inlinable.insert(callee); } } static SimpleInlinePass s_pass; <|endoftext|>
<commit_before>#include "objmaterial.h" #include "objmaterial_ispc.h" #include "../../common/data.h" namespace ospray { namespace obj { //extern "C" void ispc_OBJMaterial_create(void *cppE); // extern "C" void ispc_OBJMaterial_set( //! \brief commit the material's parameters void OBJMaterial::commit() { if (ispcEquivalent == NULL) ispcEquivalent = ispc::OBJMaterial_create(this); Ref<Data> textureData = getParamData("textures.list",NULL); int32 num_textures = getParam1i("textures.count",0); if(textureData && num_textures > 0) { Texture2D **textures = (ospray::Texture2D**)textureData->data; int map_d_idx = getParam1i("map_d", num_textures+1); int map_Kd_idx = getParam1i("map_Kd", getParam1i("map_kd",num_textures+1)); int map_Ks_idx = getParam1i("map_Ks", getParam1i("map_ks",num_textures+1)); int map_Ns_idx = getParam1i("map_Ns", getParam1i("map_ns",num_textures+1)); int map_Bump_idx = getParam1i("map_Bump", getParam1i("map_bump",num_textures+1)); map_d = map_d_idx < num_textures ? textures[map_d_idx] : NULL; map_Kd = map_Kd_idx < num_textures ? textures[map_Kd_idx] : NULL; map_Ks = map_Ks_idx < num_textures ? textures[map_Ks_idx] : NULL; map_Ns = map_Ns_idx < num_textures ? textures[map_Ns_idx] : NULL; map_Bump = map_Bump_idx < num_textures ? textures[map_Bump_idx] : NULL; } else { map_d = map_Kd = map_Ks = map_Ns = map_Bump = NULL; } d = getParam1f("d", 1.f); Kd = getParam3f("kd",vec3f(.8f)); Ks = getParam3f("ks",vec3f(0.f)); Ns = getParam1f("ns",0.f); ispc::OBJMaterial_set(getIE(), map_d ? map_d->getIE() : NULL, d, map_Kd ? map_Kd->getIE() : NULL, (ispc::vec3f&)Kd, map_Ks ? map_Ks->getIE() : NULL, (ispc::vec3f&)Ks, map_Ns ? map_Ns->getIE() : NULL, Ns, map_Bump != NULL ? map_Bump->getIE() : NULL ); } OBJMaterial::~OBJMaterial() { if (getIE() != NULL) ispc::OBJMaterial_destroy(getIE()); } OSP_REGISTER_MATERIAL(OBJMaterial,OBJMaterial); } } <commit_msg>Fixed parameter handling for obj materials<commit_after>#include "objmaterial.h" #include "objmaterial_ispc.h" #include "../../common/data.h" namespace ospray { namespace obj { //extern "C" void ispc_OBJMaterial_create(void *cppE); // extern "C" void ispc_OBJMaterial_set( //! \brief commit the material's parameters void OBJMaterial::commit() { if (ispcEquivalent == NULL) ispcEquivalent = ispc::OBJMaterial_create(this); Ref<Data> textureData = getParamData("textures.list",NULL); int32 num_textures = getParam1i("textures.count",0); if(textureData && num_textures > 0) { Texture2D **textures = (ospray::Texture2D**)textureData->data; int map_d_idx = getParam1i("map_d", num_textures+1); int map_Kd_idx = getParam1i("map_Kd", getParam1i("map_kd",num_textures+1)); int map_Ks_idx = getParam1i("map_Ks", getParam1i("map_ks",num_textures+1)); int map_Ns_idx = getParam1i("map_Ns", getParam1i("map_ns",num_textures+1)); int map_Bump_idx = getParam1i("map_Bump", getParam1i("map_bump",num_textures+1)); map_d = map_d_idx < num_textures ? textures[map_d_idx] : NULL; map_Kd = map_Kd_idx < num_textures ? textures[map_Kd_idx] : NULL; map_Ks = map_Ks_idx < num_textures ? textures[map_Ks_idx] : NULL; map_Ns = map_Ns_idx < num_textures ? textures[map_Ns_idx] : NULL; map_Bump = map_Bump_idx < num_textures ? textures[map_Bump_idx] : NULL; } else { map_d = map_Kd = map_Ks = map_Ns = map_Bump = NULL; } d = getParam1f("d", 1.f); Kd = getParam3f("kd", getParam3f("Kd", vec3f(.8f))); Ks = getParam3f("ks", getParam3f("Ks", vec3f(0.f))); Ns = getParam1f("ns", getParam1f("Ns", 0.f)); ispc::OBJMaterial_set(getIE(), map_d ? map_d->getIE() : NULL, d, map_Kd ? map_Kd->getIE() : NULL, (ispc::vec3f&)Kd, map_Ks ? map_Ks->getIE() : NULL, (ispc::vec3f&)Ks, map_Ns ? map_Ns->getIE() : NULL, Ns, map_Bump != NULL ? map_Bump->getIE() : NULL ); } OBJMaterial::~OBJMaterial() { if (getIE() != NULL) ispc::OBJMaterial_destroy(getIE()); } OSP_REGISTER_MATERIAL(OBJMaterial,OBJMaterial); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ZipFile.cxx,v $ * * $Revision: 1.21 $ * * last change: $Author: mtg $ $Date: 2001-04-30 18:19:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _ZIP_FILE_HXX #include <ZipFile.hxx> #endif #ifndef _ENTRY_INPUT_STREAM_HXX #include <EntryInputStream.hxx> #endif #ifndef _ZIP_ENUMERATION_HXX #include <ZipEnumeration.hxx> #endif #ifndef _VOS_DIAGNOSE_H_ #include <vos/diagnose.hxx> #endif #ifndef _COM_SUN_STAR_PACKAGES_ZIPCONSTANTS_HPP_ #include <com/sun/star/packages/ZipConstants.hpp> #endif #include <vector> using namespace rtl; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::packages; using namespace com::sun::star::packages::ZipConstants; /** This class is used to read entries from a zip file */ ZipFile::ZipFile( Reference < io::XInputStream > &xInput, sal_Bool bInitialise) throw(io::IOException, ZipException, RuntimeException) : xStream(xInput) , aGrabber(xInput) , aInflater (sal_True) { if (bInitialise) readCEN(); } void ZipFile::setInputStream ( Reference < io::XInputStream > xNewStream ) { xStream = xNewStream; aGrabber.setInputStream ( xStream ); } /* void ZipFile::updateFromManList(std::vector < ManifestEntry * > &rManList) { sal_Int32 i=0, nSize = rManList.size(); aEntries.clear(); // This is a bitwise copy, = is not an overloaded operator // I'm not sure how evil this is in this case... for (;i < nSize ; i++) { ZipEntry * pEntry = &rManList[i]->aEntry; aEntries[pEntry->sName] = *pEntry; } } */ ZipFile::~ZipFile() { aEntries.clear(); } void SAL_CALL ZipFile::close( ) throw(io::IOException, RuntimeException) { } ZipEnumeration * SAL_CALL ZipFile::entries( ) { return new ZipEnumeration ( aEntries ); } ::rtl::OUString SAL_CALL ZipFile::getName( ) throw(RuntimeException) { return sName; } sal_Int32 SAL_CALL ZipFile::getSize( ) throw(RuntimeException) { return aEntries.size(); } Type SAL_CALL ZipFile::getElementType( ) throw(RuntimeException) { return ::getCppuType((ZipEntry *) 0); } sal_Bool SAL_CALL ZipFile::hasElements( ) throw(RuntimeException) { return (aEntries.size()>0); } Any SAL_CALL ZipFile::getByName( const ::rtl::OUString& aName ) throw(container::NoSuchElementException, lang::WrappedTargetException, RuntimeException) { Any aAny; EntryHash::const_iterator aCI = aEntries.find(sName); if (aCI == aEntries.end()) throw container::NoSuchElementException(); aAny <<= (*aCI).second; return aAny; } Sequence< ::rtl::OUString > SAL_CALL ZipFile::getElementNames( ) throw(RuntimeException) { sal_uInt32 i=0, nSize = aEntries.size(); OUString *pNames = new OUString[aEntries.size()]; for (EntryHash::const_iterator aIterator = aEntries.begin(); aIterator != aEntries.end(); aIterator++,i++) pNames[i] = (*aIterator).first; return Sequence<OUString> (pNames, nSize); } sal_Bool SAL_CALL ZipFile::hasByName( const ::rtl::OUString& aName ) throw(RuntimeException) { return aEntries.find(aName) != aEntries.end(); } Reference< io::XInputStream > SAL_CALL ZipFile::getInputStream( ZipEntry& rEntry, const vos::ORef < EncryptionData > &rData) throw(io::IOException, ZipException, RuntimeException) { if (rEntry.nOffset <= 0) readLOC(rEntry); Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_False ); return xStreamRef; } Reference< io::XInputStream > SAL_CALL ZipFile::getRawStream( ZipEntry& rEntry, const vos::ORef < EncryptionData > &rData) throw(io::IOException, ZipException, RuntimeException) { if (rEntry.nOffset <= 0) readLOC(rEntry); Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_True ); return xStreamRef; } sal_Bool ZipFile::readLOC( ZipEntry &rEntry ) throw(io::IOException, ZipException, RuntimeException) { sal_uInt32 nTestSig, nTime, nCRC, nSize, nCompressedSize; sal_uInt16 nVersion, nFlag, nHow, nNameLen, nExtraLen; sal_Int32 nPos = -rEntry.nOffset; aGrabber.seek(nPos); aGrabber >> nTestSig; if (nTestSig != LOCSIG) throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid LOC header (bad signature") ), Reference < XInterface > () ); aGrabber >> nVersion; aGrabber >> nFlag; aGrabber >> nHow; aGrabber >> nTime; aGrabber >> nCRC; aGrabber >> nCompressedSize; aGrabber >> nSize; aGrabber >> nNameLen; aGrabber >> nExtraLen; rEntry.nOffset = static_cast < sal_Int32 > (aGrabber.getPosition()) + nNameLen + nExtraLen; return sal_True; } sal_Int32 ZipFile::findEND( ) throw(io::IOException, ZipException, RuntimeException) { sal_Int32 nLength=0, nPos=0; Sequence < sal_Int8 > aByteSeq; nLength = nPos = static_cast <sal_Int32 > (aGrabber.getLength()); if (nLength == 0) return -1; //throw (ZipException( OUString::createFromAscii("Trying to find Zip END signature in a zero length file!"), Reference < XInterface> () )); aGrabber.seek( nLength ); while (nLength - nPos < 0xFFFF) { sal_uInt32 nCount = 0xFFFF - ( nLength - nPos); if (nCount > ENDHDR) nCount = ENDHDR; nPos -= nCount; for (sal_uInt16 i=0; i <nCount;i++) { sal_uInt32 nTest=0, nFoo=ENDSIG; aGrabber.seek (nPos+i); aGrabber >> nTest; if (nTest == ENDSIG) { sal_uInt16 nCommentLength; sal_Int32 nEndPos = nPos + i; aGrabber.seek(nEndPos+ENDCOM); aGrabber >> nCommentLength; if (nEndPos + ENDHDR + nCommentLength == nLength) { if (nCommentLength>0) { aByteSeq.realloc(nCommentLength+1); aGrabber.readBytes(Sequence< sal_Int8>(aByteSeq.getArray(), nCommentLength), nCommentLength); aByteSeq[nCommentLength]='\0'; sComment = OUString((sal_Char*)aByteSeq.getConstArray(), nCommentLength+1, RTL_TEXTENCODING_ASCII_US); } return nPos + i; } } } } throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), Reference < XInterface> () ); } sal_Int32 ZipFile::readCEN() throw(io::IOException, ZipException, RuntimeException) { sal_Int32 nEndPos, nLocPos; sal_Int16 nCount, nTotal; sal_Int32 nCenLen, nCenPos, nCenOff; nEndPos = findEND(); if (nEndPos == -1) return -1; aGrabber.seek(nEndPos + ENDTOT); aGrabber >> nTotal; aGrabber >> nCenLen; aGrabber >> nCenOff; if (nTotal<0 || nTotal * CENHDR > nCenLen) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "invalid END header (bad entry count)") ), Reference < XInterface > ()); if (nTotal > ZIP_MAXENTRIES) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "too many entries in ZIP File") ), Reference < XInterface > ()); if (nCenLen < 0 || nCenLen > nEndPos) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), Reference < XInterface > ()); nCenPos = nEndPos - nCenLen; if (nCenOff < 0 || nCenOff > nCenPos) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), Reference < XInterface > ()); nLocPos = nCenPos - nCenOff; aGrabber.seek(nCenPos); ZipEntry *pEntry = new ZipEntry; for (nCount = 0 ; nCount < nTotal; nCount++) { sal_Int32 nTestSig, nCRC, nCompressedSize, nTime, nSize, nExtAttr, nOffset; sal_Int16 nVerMade, nVersion, nFlag, nHow, nNameLen, nExtraLen, nCommentLen; sal_Int16 nDisk, nIntAttr; if (aGrabber.getPosition() - nCenPos + CENHDR > nCenLen) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad header size check 1)") ), Reference < XInterface > ()); aGrabber >> nTestSig; if (nTestSig != CENSIG) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad signature)") ), Reference < XInterface > ()); aGrabber >> nVerMade; aGrabber >> nVersion; if ((nVersion & 1) == 1) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (encrypted entry)") ), Reference < XInterface > ()); aGrabber >> nFlag; aGrabber >> nHow; if (nHow != STORED && nHow != DEFLATED) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad compression method)") ), Reference < XInterface > ()); aGrabber >> nTime; aGrabber >> nCRC; aGrabber >> nCompressedSize; aGrabber >> nSize; aGrabber >> nNameLen; aGrabber >> nExtraLen; aGrabber >> nCommentLen; aGrabber >> nDisk; aGrabber >> nIntAttr; aGrabber >> nExtAttr; aGrabber >> nOffset; if (aGrabber.getPosition() - nCenPos + nNameLen + nExtraLen + nCommentLen > nCenLen) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad header size check 2)") ), Reference < XInterface > ()); if (nNameLen > ZIP_MAXNAMELEN) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "name length exceeds 512 bytes" ) ), Reference < XInterface > ()); if (nExtraLen > ZIP_MAXEXTRA) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "extra header info exceeds 256 bytes") ), Reference < XInterface > ()); pEntry->nTime = nTime; pEntry->nCrc = nCRC; pEntry->nSize = nSize; pEntry->nCompressedSize = nCompressedSize; pEntry->nMethod = nHow; pEntry->nFlag = nFlag; pEntry->nVersion= nVersion; pEntry->nOffset = nOffset + nLocPos; pEntry->nOffset *= -1; /* if (nHow == STORED) pEntry->nCompressedSize = 0; */ Sequence < sal_Int8> aSequence (nNameLen); aGrabber.readBytes(aSequence, nNameLen); pEntry->sName = OUString((sal_Char*)aSequence.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US); aGrabber.seek(aGrabber.getPosition() + nExtraLen); if (nCommentLen>0) { Sequence < sal_Int8 > aCommentSeq( nCommentLen ); aGrabber.readBytes(aCommentSeq, nCommentLen); pEntry->sComment = OUString((sal_Char*)aCommentSeq.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US); } aEntries[pEntry->sName] = *pEntry; } delete pEntry; if (nCount != nTotal) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Count != Total") ), Reference < XInterface > ()); return nCenPos; } <commit_msg>#87099# Remove unused method<commit_after>/************************************************************************* * * $RCSfile: ZipFile.cxx,v $ * * $Revision: 1.22 $ * * last change: $Author: mtg $ $Date: 2001-05-31 09:48:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _ZIP_FILE_HXX #include <ZipFile.hxx> #endif #ifndef _ENTRY_INPUT_STREAM_HXX #include <EntryInputStream.hxx> #endif #ifndef _ZIP_ENUMERATION_HXX #include <ZipEnumeration.hxx> #endif #ifndef _VOS_DIAGNOSE_H_ #include <vos/diagnose.hxx> #endif #ifndef _COM_SUN_STAR_PACKAGES_ZIPCONSTANTS_HPP_ #include <com/sun/star/packages/ZipConstants.hpp> #endif #include <vector> using namespace rtl; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::packages; using namespace com::sun::star::packages::ZipConstants; /** This class is used to read entries from a zip file */ ZipFile::ZipFile( Reference < io::XInputStream > &xInput, sal_Bool bInitialise) throw(io::IOException, ZipException, RuntimeException) : xStream(xInput) , aGrabber(xInput) , aInflater (sal_True) { if (bInitialise) readCEN(); } void ZipFile::setInputStream ( Reference < io::XInputStream > xNewStream ) { xStream = xNewStream; aGrabber.setInputStream ( xStream ); } ZipFile::~ZipFile() { aEntries.clear(); } void SAL_CALL ZipFile::close( ) throw(io::IOException, RuntimeException) { } ZipEnumeration * SAL_CALL ZipFile::entries( ) { return new ZipEnumeration ( aEntries ); } ::rtl::OUString SAL_CALL ZipFile::getName( ) throw(RuntimeException) { return sName; } sal_Int32 SAL_CALL ZipFile::getSize( ) throw(RuntimeException) { return aEntries.size(); } Type SAL_CALL ZipFile::getElementType( ) throw(RuntimeException) { return ::getCppuType((ZipEntry *) 0); } sal_Bool SAL_CALL ZipFile::hasElements( ) throw(RuntimeException) { return (aEntries.size()>0); } Any SAL_CALL ZipFile::getByName( const ::rtl::OUString& aName ) throw(container::NoSuchElementException, lang::WrappedTargetException, RuntimeException) { Any aAny; EntryHash::const_iterator aCI = aEntries.find(sName); if (aCI == aEntries.end()) throw container::NoSuchElementException(); aAny <<= (*aCI).second; return aAny; } Sequence< ::rtl::OUString > SAL_CALL ZipFile::getElementNames( ) throw(RuntimeException) { sal_uInt32 i=0, nSize = aEntries.size(); OUString *pNames = new OUString[aEntries.size()]; for (EntryHash::const_iterator aIterator = aEntries.begin(); aIterator != aEntries.end(); aIterator++,i++) pNames[i] = (*aIterator).first; return Sequence<OUString> (pNames, nSize); } sal_Bool SAL_CALL ZipFile::hasByName( const ::rtl::OUString& aName ) throw(RuntimeException) { return aEntries.find(aName) != aEntries.end(); } Reference< io::XInputStream > SAL_CALL ZipFile::getInputStream( ZipEntry& rEntry, const vos::ORef < EncryptionData > &rData) throw(io::IOException, ZipException, RuntimeException) { if (rEntry.nOffset <= 0) readLOC(rEntry); Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_False ); return xStreamRef; } Reference< io::XInputStream > SAL_CALL ZipFile::getRawStream( ZipEntry& rEntry, const vos::ORef < EncryptionData > &rData) throw(io::IOException, ZipException, RuntimeException) { if (rEntry.nOffset <= 0) readLOC(rEntry); Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_True ); return xStreamRef; } sal_Bool ZipFile::readLOC( ZipEntry &rEntry ) throw(io::IOException, ZipException, RuntimeException) { sal_uInt32 nTestSig, nTime, nCRC, nSize, nCompressedSize; sal_uInt16 nVersion, nFlag, nHow, nNameLen, nExtraLen; sal_Int32 nPos = -rEntry.nOffset; aGrabber.seek(nPos); aGrabber >> nTestSig; if (nTestSig != LOCSIG) throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid LOC header (bad signature") ), Reference < XInterface > () ); aGrabber >> nVersion; aGrabber >> nFlag; aGrabber >> nHow; aGrabber >> nTime; aGrabber >> nCRC; aGrabber >> nCompressedSize; aGrabber >> nSize; aGrabber >> nNameLen; aGrabber >> nExtraLen; rEntry.nOffset = static_cast < sal_Int32 > (aGrabber.getPosition()) + nNameLen + nExtraLen; return sal_True; } sal_Int32 ZipFile::findEND( ) throw(io::IOException, ZipException, RuntimeException) { sal_Int32 nLength=0, nPos=0; Sequence < sal_Int8 > aByteSeq; nLength = nPos = static_cast <sal_Int32 > (aGrabber.getLength()); if (nLength == 0) return -1; //throw (ZipException( OUString::createFromAscii("Trying to find Zip END signature in a zero length file!"), Reference < XInterface> () )); aGrabber.seek( nLength ); while (nLength - nPos < 0xFFFF) { sal_uInt32 nCount = 0xFFFF - ( nLength - nPos); if (nCount > ENDHDR) nCount = ENDHDR; nPos -= nCount; for (sal_uInt16 i=0; i <nCount;i++) { sal_uInt32 nTest=0, nFoo=ENDSIG; aGrabber.seek (nPos+i); aGrabber >> nTest; if (nTest == ENDSIG) { sal_uInt16 nCommentLength; sal_Int32 nEndPos = nPos + i; aGrabber.seek(nEndPos+ENDCOM); aGrabber >> nCommentLength; if (nEndPos + ENDHDR + nCommentLength == nLength) { if (nCommentLength>0) { aByteSeq.realloc(nCommentLength+1); aGrabber.readBytes(Sequence< sal_Int8>(aByteSeq.getArray(), nCommentLength), nCommentLength); aByteSeq[nCommentLength]='\0'; sComment = OUString((sal_Char*)aByteSeq.getConstArray(), nCommentLength+1, RTL_TEXTENCODING_ASCII_US); } return nPos + i; } } } } throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), Reference < XInterface> () ); } sal_Int32 ZipFile::readCEN() throw(io::IOException, ZipException, RuntimeException) { sal_Int32 nEndPos, nLocPos; sal_Int16 nCount, nTotal; sal_Int32 nCenLen, nCenPos, nCenOff; nEndPos = findEND(); if (nEndPos == -1) return -1; aGrabber.seek(nEndPos + ENDTOT); aGrabber >> nTotal; aGrabber >> nCenLen; aGrabber >> nCenOff; if (nTotal<0 || nTotal * CENHDR > nCenLen) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "invalid END header (bad entry count)") ), Reference < XInterface > ()); if (nTotal > ZIP_MAXENTRIES) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "too many entries in ZIP File") ), Reference < XInterface > ()); if (nCenLen < 0 || nCenLen > nEndPos) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), Reference < XInterface > ()); nCenPos = nEndPos - nCenLen; if (nCenOff < 0 || nCenOff > nCenPos) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), Reference < XInterface > ()); nLocPos = nCenPos - nCenOff; aGrabber.seek(nCenPos); ZipEntry *pEntry = new ZipEntry; for (nCount = 0 ; nCount < nTotal; nCount++) { sal_Int32 nTestSig, nCRC, nCompressedSize, nTime, nSize, nExtAttr, nOffset; sal_Int16 nVerMade, nVersion, nFlag, nHow, nNameLen, nExtraLen, nCommentLen; sal_Int16 nDisk, nIntAttr; if (aGrabber.getPosition() - nCenPos + CENHDR > nCenLen) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad header size check 1)") ), Reference < XInterface > ()); aGrabber >> nTestSig; if (nTestSig != CENSIG) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad signature)") ), Reference < XInterface > ()); aGrabber >> nVerMade; aGrabber >> nVersion; if ((nVersion & 1) == 1) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (encrypted entry)") ), Reference < XInterface > ()); aGrabber >> nFlag; aGrabber >> nHow; if (nHow != STORED && nHow != DEFLATED) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad compression method)") ), Reference < XInterface > ()); aGrabber >> nTime; aGrabber >> nCRC; aGrabber >> nCompressedSize; aGrabber >> nSize; aGrabber >> nNameLen; aGrabber >> nExtraLen; aGrabber >> nCommentLen; aGrabber >> nDisk; aGrabber >> nIntAttr; aGrabber >> nExtAttr; aGrabber >> nOffset; if (aGrabber.getPosition() - nCenPos + nNameLen + nExtraLen + nCommentLen > nCenLen) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad header size check 2)") ), Reference < XInterface > ()); if (nNameLen > ZIP_MAXNAMELEN) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "name length exceeds 512 bytes" ) ), Reference < XInterface > ()); if (nExtraLen > ZIP_MAXEXTRA) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "extra header info exceeds 256 bytes") ), Reference < XInterface > ()); pEntry->nTime = nTime; pEntry->nCrc = nCRC; pEntry->nSize = nSize; pEntry->nCompressedSize = nCompressedSize; pEntry->nMethod = nHow; pEntry->nFlag = nFlag; pEntry->nVersion= nVersion; pEntry->nOffset = nOffset + nLocPos; pEntry->nOffset *= -1; /* if (nHow == STORED) pEntry->nCompressedSize = 0; */ Sequence < sal_Int8> aSequence (nNameLen); aGrabber.readBytes(aSequence, nNameLen); pEntry->sName = OUString((sal_Char*)aSequence.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US); aGrabber.seek(aGrabber.getPosition() + nExtraLen); if (nCommentLen>0) { Sequence < sal_Int8 > aCommentSeq( nCommentLen ); aGrabber.readBytes(aCommentSeq, nCommentLen); pEntry->sComment = OUString((sal_Char*)aCommentSeq.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US); } aEntries[pEntry->sName] = *pEntry; } delete pEntry; if (nCount != nTotal) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Count != Total") ), Reference < XInterface > ()); return nCenPos; } <|endoftext|>
<commit_before>#include "gb-include.h" #include "ip.h" long atoip ( char *s , long slen ) { // point to it char *p = s; if ( s[slen] ) { // copy into buffer and NULL terminate char buf[1024]; if ( slen >= 1024 ) slen = 1023; memcpy ( buf , s , slen ); buf [ slen ] = '\0'; // point to that p = buf; } // convert to int struct in_addr in; in.s_addr = 0; inet_aton ( p , &in ); // ensure this really is a long before returning ip if ( sizeof(in_addr) == 4 ) return in.s_addr; // otherwise bitch and return 0 log("ip:bad inet_aton"); return 0; } long atoip ( char *s ) { // convert to int struct in_addr in; in.s_addr = 0; inet_aton ( s , &in ); // ensure this really is a long before returning ip if ( sizeof(in_addr) == 4 ) return in.s_addr; // otherwise bitch and return 0 log("ip:bad inet_aton"); return 0; } char *iptoa ( long ip ) { static char s_buf [ 32 ]; sprintf ( s_buf , "%hhu.%hhu.%hhu.%hhu", (unsigned char)(ip >> 0)&0xff, (unsigned char)(ip >> 8)&0xff, (unsigned char)(ip >> 16)&0xff, (unsigned char)(ip >> 24)&0xff); return s_buf; //struct in_addr in; //in.s_addr = ip; //return inet_ntoa ( in ); } // . get domain of ip address // . first byte is the host (little endian) long ipdom ( long ip ) { return ip & 0x00ffffff; }; // most significant 2 bytes of ip long iptop ( long ip ) { return ip & 0x0000ffff; }; // . is least significant byte a zero? // . if it is then this ip is probably representing a whole ip domain bool isIpDom ( long ip ) { return ( (ip & 0xff000000) == 0 ); }; // are last 2 bytes 0's? long isIpTop ( long ip ) { return ( (ip & 0xffff0000) == 0 ); }; // returns number of top bytes in comon long ipCmp ( long ip1 , long ip2 ) { char *a = (char *)ip1; char *b = (char *)ip2; // little endian compare if ( a[3] != b[3] ) return 0; if ( a[2] != b[2] ) return 1; if ( a[1] != b[1] ) return 2; if ( a[0] != b[0] ) return 3; return 4; // exact match } <commit_msg>fix old bug.<commit_after>#include "gb-include.h" #include "ip.h" long atoip ( char *s , long slen ) { // point to it char *p = s; if ( s[slen] ) { // copy into buffer and NULL terminate char buf[1024]; if ( slen >= 1024 ) slen = 1023; memcpy ( buf , s , slen ); buf [ slen ] = '\0'; // point to that p = buf; } // convert to int struct in_addr in; in.s_addr = 0; inet_aton ( p , &in ); // ensure this really is a long before returning ip if ( sizeof(in_addr) == 4 ) return in.s_addr; // otherwise bitch and return 0 log("ip:bad inet_aton"); return 0; } long atoip ( char *s ) { // convert to int struct in_addr in; in.s_addr = 0; inet_aton ( s , &in ); // ensure this really is a long before returning ip if ( sizeof(in_addr) == 4 ) return in.s_addr; // otherwise bitch and return 0 log("ip:bad inet_aton"); return 0; } char *iptoa ( long ip ) { static char s_buf [ 32 ]; sprintf ( s_buf , "%hhu.%hhu.%hhu.%hhu", (unsigned char)(ip >> 0)&0xff, (unsigned char)(ip >> 8)&0xff, (unsigned char)(ip >> 16)&0xff, (unsigned char)(ip >> 24)&0xff); return s_buf; //struct in_addr in; //in.s_addr = ip; //return inet_ntoa ( in ); } // . get domain of ip address // . first byte is the host (little endian) long ipdom ( long ip ) { return ip & 0x00ffffff; }; // most significant 2 bytes of ip long iptop ( long ip ) { return ip & 0x0000ffff; }; // . is least significant byte a zero? // . if it is then this ip is probably representing a whole ip domain bool isIpDom ( long ip ) { return ( (ip & 0xff000000) == 0 ); }; // are last 2 bytes 0's? long isIpTop ( long ip ) { return ( (ip & 0xffff0000) == 0 ); }; // returns number of top bytes in comon long ipCmp ( long ip1 , long ip2 ) { char *a = (char *)&ip1; char *b = (char *)&ip2; // little endian compare if ( a[3] != b[3] ) return 0; if ( a[2] != b[2] ) return 1; if ( a[1] != b[1] ) return 2; if ( a[0] != b[0] ) return 3; return 4; // exact match } <|endoftext|>
<commit_before>#include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImage.h" int main( int argc, char ** argv ) { if( argc < 3 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile " << std::endl; return EXIT_FAILURE; } typedef float PixelType; const unsigned int Dimension = 3; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); const char * inputFilename = argv[1]; const char * outputFilename = argv[2]; reader->SetFileName( inputFilename ); writer->SetFileName( outputFilename ); writer->SetInput( reader->GetOutput() ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Usage spelling.<commit_after>#include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImage.h" int main( int argc, char ** argv ) { if( argc < 3 ) { std::cerr << "Usage:" << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile" << std::endl; return EXIT_FAILURE; } typedef float PixelType; const unsigned int Dimension = 3; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); const char * inputFilename = argv[1]; const char * outputFilename = argv[2]; reader->SetFileName( inputFilename ); writer->SetFileName( outputFilename ); writer->SetInput( reader->GetOutput() ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "net/http_client.h" #ifndef _WIN32 #include <arpa/inet.h> #include <sys/socket.h> #include <unistd.h> #define closesocket close #else #include <winsock2.h> #include <ws2tcpip.h> #include <io.h> #endif #include <stdio.h> #include <stdlib.h> #include "base/logging.h" #include "base/buffer.h" #include "base/stringutil.h" #include "data/compression.h" #include "net/resolve.h" #include "net/url.h" // #include "strings/strutil.h" namespace net { Connection::Connection() : port_(-1), sock_(-1), resolved_(NULL) { } Connection::~Connection() { Disconnect(); if (resolved_ != NULL) DNSResolveFree(resolved_); } // For whatever crazy reason, htons isn't available on android x86 on the build server. so here we go. // TODO: Fix for big-endian inline unsigned short myhtons(unsigned short x) { return (x >> 8) | (x << 8); } bool Connection::Resolve(const char *host, int port) { if ((intptr_t)sock_ != -1) { ELOG("Resolve: Already have a socket"); return false; } host_ = host; port_ = port; char port_str[10]; snprintf(port_str, sizeof(port_str), "%d", port); std::string err; if (!net::DNSResolve(host, port_str, &resolved_, err)) { ELOG("Failed to resolve host %s: %s", host, err.c_str()); // So that future calls fail. port_ = 0; return false; } return true; } bool Connection::Connect() { if (port_ <= 0) { ELOG("Bad port"); return false; } sock_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if ((intptr_t)sock_ == -1) { ELOG("Bad socket"); return false; } for (int tries = 100; tries > 0; --tries) { for (addrinfo *possible = resolved_; possible != NULL; possible = possible->ai_next) { // TODO: Could support ipv6 without huge difficulty... if (possible->ai_family != AF_INET) continue; int retval = connect(sock_, possible->ai_addr, (int)possible->ai_addrlen); if (retval >= 0) return true; } #ifdef _WIN32 Sleep(1); #else sleep(1); #endif } // Let's not leak this socket. closesocket(sock_); sock_ = -1; return false; } void Connection::Disconnect() { if ((intptr_t)sock_ != -1) { closesocket(sock_); sock_ = -1; } } } // net namespace http { Client::Client() { } Client::~Client() { Disconnect(); } // TODO: do something sane here #define USERAGENT "NATIVEAPP 1.0" void DeChunk(Buffer *inbuffer, Buffer *outbuffer) { while (true) { std::string line; inbuffer->TakeLineCRLF(&line); if (!line.size()) return; int chunkSize; sscanf(line.c_str(), "%x", &chunkSize); if (chunkSize) { std::string data; inbuffer->Take(chunkSize, &data); outbuffer->Append(data); } else { // a zero size chunk should mean the end. inbuffer->clear(); return; } inbuffer->Skip(2); } } int Client::GET(const char *resource, Buffer *output) { Buffer buffer; const char *tpl = "GET %s HTTP/1.1\r\n" "Host: %s\r\n" "User-Agent: " USERAGENT "\r\n" "Accept: */*\r\n" "Accept-Encoding: gzip\r\n" "Connection: close\r\n" "\r\n"; buffer.Printf(tpl, resource, host_.c_str()); bool flushed = buffer.FlushSocket(sock()); if (!flushed) { return -1; // TODO error code. } Buffer readbuf; // Snarf all the data we can into RAM. A little unsafe but hey. if (!readbuf.ReadAll(sock())) return -1; // Grab the first header line that contains the http code. // Skip the header. TODO: read HTTP code and file size so we can make progress bars. std::string line; readbuf.TakeLineCRLF(&line); int code = atoi(&line[line.find(" ") + 1]); bool gzip = false; int contentLength = 0; while (true) { int sz = readbuf.TakeLineCRLF(&line); if (!sz) break; if (startsWith(line, "Content-Length:")) { contentLength = atoi(&line[16]); } else if (startsWith(line, "Content-Encoding:")) { if (line.find("gzip") != std::string::npos) { gzip = true; } } } // output now contains the rest of the reply. Dechunk it. DeChunk(&readbuf, output); // If it's gzipped, we decompress it and put it back in the buffer. if (gzip) { std::string compressed; output->TakeAll(&compressed); // What is this garbage? //if (compressed[0] == 0x8e) // compressed = compressed.substr(4); std::string decompressed; bool result = decompress_string(compressed, &decompressed); if (!result) { ELOG("Error decompressing using zlib"); return -1; } output->Append(decompressed); } return code; } int Client::POST(const char *resource, const std::string &data, const std::string &mime, Buffer *output) { Buffer buffer; const char *tpl = "POST %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: " USERAGENT "\r\nContent-Length: %d\r\n"; buffer.Printf(tpl, resource, host_.c_str(), (int)data.size()); if (!mime.empty()) { buffer.Printf("Content-Type: %s\r\n", mime.c_str()); } buffer.Append("\r\n"); buffer.Append(data); if (!buffer.FlushSocket(sock())) { ELOG("Failed posting"); } // I guess we could add a deadline here. output->ReadAll(sock()); if (output->size() == 0) { // The connection was closed. ELOG("POST failed."); return -1; } std::string debug_data; output->PeekAll(&debug_data); //VLOG(1) << "Reply size (before stripping headers): " << debug_data.size(); std::string debug_str; StringToHexString(debug_data, &debug_str); // Tear off the http headers, leaving the actual response data. std::string firstline; CHECK_GT(output->TakeLineCRLF(&firstline), 0); int code = atoi(&firstline[9]); //VLOG(1) << "HTTP result code: " << code; while (true) { int skipped = output->SkipLineCRLF(); if (skipped == 0) break; } output->PeekAll(&debug_data); return code; } int Client::POST(const char *resource, const std::string &data, Buffer *output) { return POST(resource, data, "", output); } Download::Download(const std::string &url, const std::string &outfile) : url_(url), outfile_(outfile), progress_(0.0f), failed_(false), resultCode_(0) { std::thread th(std::bind(&Download::Do, this)); th.detach(); } Download::~Download() { } void Download::Do() { resultCode_ = 0; Url fileUrl(url_); if (!fileUrl.Valid()) { failed_ = true; progress_ = 1.0f; return; } net::Init(); http::Client client; if (!client.Resolve(fileUrl.Host().c_str(), 80)) { ELOG("Failed resolving %s", url_.c_str()); failed_ = true; progress_ = 1.0f; net::Shutdown(); return; } if (!client.Connect()) { ELOG("Failed connecting to server."); resultCode_ = -1; net::Shutdown(); progress_ = 1.0f; return; } int resultCode = client.GET(fileUrl.Resource().c_str(), &buffer_); if (resultCode == 200) { ILOG("Completed downloading %s to %s", url_.c_str(), outfile_.c_str()); if (!outfile_.empty() && !buffer_.FlushToFile(outfile_.c_str())) { ELOG("Failed writing download to %s", outfile_.c_str()); } } else { ELOG("Error downloading %s to %s: %i", url_.c_str(), outfile_.c_str(), resultCode); } resultCode_ = resultCode; net::Shutdown(); progress_ = 1.0f; } std::shared_ptr<Download> Downloader::StartDownload(const std::string &url, const std::string &outfile) { std::shared_ptr<Download> dl(new Download(url, outfile)); downloads_.push_back(dl); return dl; } void Downloader::Update() { restart: for (size_t i = 0; i < downloads_.size(); i++) { if (downloads_[i]->Progress() == 1.0f || downloads_[i]->Failed()) { downloads_.erase(downloads_.begin() + i); goto restart; } } } } // http <commit_msg>Support non-chunked HTTP responses.<commit_after>#include "net/http_client.h" #ifndef _WIN32 #include <arpa/inet.h> #include <sys/socket.h> #include <unistd.h> #define closesocket close #else #include <winsock2.h> #include <ws2tcpip.h> #include <io.h> #endif #include <stdio.h> #include <stdlib.h> #include "base/logging.h" #include "base/buffer.h" #include "base/stringutil.h" #include "data/compression.h" #include "net/resolve.h" #include "net/url.h" // #include "strings/strutil.h" namespace net { Connection::Connection() : port_(-1), sock_(-1), resolved_(NULL) { } Connection::~Connection() { Disconnect(); if (resolved_ != NULL) DNSResolveFree(resolved_); } // For whatever crazy reason, htons isn't available on android x86 on the build server. so here we go. // TODO: Fix for big-endian inline unsigned short myhtons(unsigned short x) { return (x >> 8) | (x << 8); } bool Connection::Resolve(const char *host, int port) { if ((intptr_t)sock_ != -1) { ELOG("Resolve: Already have a socket"); return false; } host_ = host; port_ = port; char port_str[10]; snprintf(port_str, sizeof(port_str), "%d", port); std::string err; if (!net::DNSResolve(host, port_str, &resolved_, err)) { ELOG("Failed to resolve host %s: %s", host, err.c_str()); // So that future calls fail. port_ = 0; return false; } return true; } bool Connection::Connect() { if (port_ <= 0) { ELOG("Bad port"); return false; } sock_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if ((intptr_t)sock_ == -1) { ELOG("Bad socket"); return false; } for (int tries = 100; tries > 0; --tries) { for (addrinfo *possible = resolved_; possible != NULL; possible = possible->ai_next) { // TODO: Could support ipv6 without huge difficulty... if (possible->ai_family != AF_INET) continue; int retval = connect(sock_, possible->ai_addr, (int)possible->ai_addrlen); if (retval >= 0) return true; } #ifdef _WIN32 Sleep(1); #else sleep(1); #endif } // Let's not leak this socket. closesocket(sock_); sock_ = -1; return false; } void Connection::Disconnect() { if ((intptr_t)sock_ != -1) { closesocket(sock_); sock_ = -1; } } } // net namespace http { Client::Client() { } Client::~Client() { Disconnect(); } // TODO: do something sane here #define USERAGENT "NATIVEAPP 1.0" void DeChunk(Buffer *inbuffer, Buffer *outbuffer) { while (true) { std::string line; inbuffer->TakeLineCRLF(&line); if (!line.size()) return; int chunkSize; sscanf(line.c_str(), "%x", &chunkSize); if (chunkSize) { std::string data; inbuffer->Take(chunkSize, &data); outbuffer->Append(data); } else { // a zero size chunk should mean the end. inbuffer->clear(); return; } inbuffer->Skip(2); } } int Client::GET(const char *resource, Buffer *output) { Buffer buffer; const char *tpl = "GET %s HTTP/1.1\r\n" "Host: %s\r\n" "User-Agent: " USERAGENT "\r\n" "Accept: */*\r\n" "Accept-Encoding: gzip\r\n" "Connection: close\r\n" "\r\n"; buffer.Printf(tpl, resource, host_.c_str()); bool flushed = buffer.FlushSocket(sock()); if (!flushed) { return -1; // TODO error code. } Buffer readbuf; // Snarf all the data we can into RAM. A little unsafe but hey. if (!readbuf.ReadAll(sock())) return -1; // Grab the first header line that contains the http code. // Skip the header. TODO: read HTTP code and file size so we can make progress bars. std::string line; readbuf.TakeLineCRLF(&line); int code; size_t code_pos = line.find(' '); if (code_pos != line.npos) { code_pos = line.find_first_not_of(' ', code_pos); } if (code_pos != line.npos) { code = atoi(&line[code_pos]); } else { return -1; } bool gzip = false; bool chunked = false; int contentLength = 0; while (true) { int sz = readbuf.TakeLineCRLF(&line); if (!sz) break; // TODO: Case folding. if (startsWith(line, "Content-Length:")) { size_t size_pos = line.find_first_of(' '); if (size_pos != line.npos) { size_pos = line.find_first_not_of(' ', size_pos); } if (size_pos != line.npos) { contentLength = atoi(&line[size_pos]); chunked = false; } } else if (startsWith(line, "Content-Encoding:")) { if (line.find("gzip") != std::string::npos) { gzip = true; } } else if (startsWith(line, "Transfer-Encoding:")) { if (line.find("chunked") != std::string::npos) { chunked = true; } } } // output now contains the rest of the reply. Dechunk it. if (chunked) { DeChunk(&readbuf, output); } else { output->Append(readbuf); } // If it's gzipped, we decompress it and put it back in the buffer. if (gzip) { std::string compressed; output->TakeAll(&compressed); // What is this garbage? //if (compressed[0] == 0x8e) // compressed = compressed.substr(4); std::string decompressed; bool result = decompress_string(compressed, &decompressed); if (!result) { ELOG("Error decompressing using zlib"); return -1; } output->Append(decompressed); } return code; } int Client::POST(const char *resource, const std::string &data, const std::string &mime, Buffer *output) { Buffer buffer; const char *tpl = "POST %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: " USERAGENT "\r\nContent-Length: %d\r\n"; buffer.Printf(tpl, resource, host_.c_str(), (int)data.size()); if (!mime.empty()) { buffer.Printf("Content-Type: %s\r\n", mime.c_str()); } buffer.Append("\r\n"); buffer.Append(data); if (!buffer.FlushSocket(sock())) { ELOG("Failed posting"); } // I guess we could add a deadline here. output->ReadAll(sock()); if (output->size() == 0) { // The connection was closed. ELOG("POST failed."); return -1; } std::string debug_data; output->PeekAll(&debug_data); //VLOG(1) << "Reply size (before stripping headers): " << debug_data.size(); std::string debug_str; StringToHexString(debug_data, &debug_str); // Tear off the http headers, leaving the actual response data. std::string firstline; CHECK_GT(output->TakeLineCRLF(&firstline), 0); int code = atoi(&firstline[9]); //VLOG(1) << "HTTP result code: " << code; while (true) { int skipped = output->SkipLineCRLF(); if (skipped == 0) break; } output->PeekAll(&debug_data); return code; } int Client::POST(const char *resource, const std::string &data, Buffer *output) { return POST(resource, data, "", output); } Download::Download(const std::string &url, const std::string &outfile) : url_(url), outfile_(outfile), progress_(0.0f), failed_(false), resultCode_(0) { std::thread th(std::bind(&Download::Do, this)); th.detach(); } Download::~Download() { } void Download::Do() { resultCode_ = 0; Url fileUrl(url_); if (!fileUrl.Valid()) { failed_ = true; progress_ = 1.0f; return; } net::Init(); http::Client client; if (!client.Resolve(fileUrl.Host().c_str(), 80)) { ELOG("Failed resolving %s", url_.c_str()); failed_ = true; progress_ = 1.0f; net::Shutdown(); return; } if (!client.Connect()) { ELOG("Failed connecting to server."); resultCode_ = -1; net::Shutdown(); progress_ = 1.0f; return; } int resultCode = client.GET(fileUrl.Resource().c_str(), &buffer_); if (resultCode == 200) { ILOG("Completed downloading %s to %s", url_.c_str(), outfile_.c_str()); if (!outfile_.empty() && !buffer_.FlushToFile(outfile_.c_str())) { ELOG("Failed writing download to %s", outfile_.c_str()); } } else { ELOG("Error downloading %s to %s: %i", url_.c_str(), outfile_.c_str(), resultCode); } resultCode_ = resultCode; net::Shutdown(); progress_ = 1.0f; } std::shared_ptr<Download> Downloader::StartDownload(const std::string &url, const std::string &outfile) { std::shared_ptr<Download> dl(new Download(url, outfile)); downloads_.push_back(dl); return dl; } void Downloader::Update() { restart: for (size_t i = 0; i < downloads_.size(); i++) { if (downloads_[i]->Progress() == 1.0f || downloads_[i]->Failed()) { downloads_.erase(downloads_.begin() + i); goto restart; } } } } // http <|endoftext|>
<commit_before>#include "core/wordwrap.h" namespace euphoria::core { std::vector<std::string> word_wrap ( const std::string& str, std::function<bool (const std::string&)> measure ) { using I = std::string::size_type; if(measure(str)) { return {str}; } auto ret = std::vector<std::string>{}; I start = 0; I last = 0; auto get_string = [&str, &start](I end) { if(end == std::string::npos) { return str.substr(start); } else { return str.substr(start, end - (start+1)); } }; for(int bulldog=0; bulldog<50; bulldog+=1) { if(last == std::string::npos) { return ret; } const auto first = str.find(' ', last); const auto s = get_string(first); const auto fit = measure(s); if(fit) { // fit.. continue last = (first != std::string::npos) ? first+1 : first; } if(!fit || last == std::string::npos) { // new doesn't fit, use last const auto p = last == start ? first : last; const auto pp = last == start && p != std::string::npos ? p+1 : p; ret.emplace_back(get_string(pp)); if(p == std::string::npos) { return ret; } if(last == start) { start = p+1; last = p; } else { start = p; } } } return ret; } } <commit_msg>watchdog, not bulldog...<commit_after>#include "core/wordwrap.h" namespace euphoria::core { std::vector<std::string> word_wrap ( const std::string& str, std::function<bool (const std::string&)> measure ) { using I = std::string::size_type; if(measure(str)) { return {str}; } auto ret = std::vector<std::string>{}; I start = 0; I last = 0; auto get_string = [&str, &start](I end) { if(end == std::string::npos) { return str.substr(start); } else { return str.substr(start, end - (start+1)); } }; for(int watchdog=0; watchdog<50; watchdog+=1) { if(last == std::string::npos) { return ret; } const auto first = str.find(' ', last); const auto s = get_string(first); const auto fit = measure(s); if(fit) { // fit.. continue last = (first != std::string::npos) ? first+1 : first; } if(!fit || last == std::string::npos) { // new doesn't fit, use last const auto p = last == start ? first : last; const auto pp = last == start && p != std::string::npos ? p+1 : p; ret.emplace_back(get_string(pp)); if(p == std::string::npos) { return ret; } if(last == start) { start = p+1; last = p; } else { start = p; } } } return ret; } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <set> #include "otbImage.h" #include "itkImageRegionIterator.h" #include "itkImageRegionReverseIterator.h" #include "itkImageRandomIteratorWithIndex.h" #include "itkImageScanlineIterator.h" #include "itkImageRandomNonRepeatingIteratorWithIndex.h" #include "otbSubsampledImageRegionIterator.h" #include "otbMaskedIteratorDecorator.h" // Generate a test image of specified size and value template <typename ImageType> typename ImageType::Pointer GetTestImage(itk::SizeValueType fillSize, const typename ImageType::PixelType& value) { typename ImageType::Pointer image = ImageType::New(); typename ImageType::SizeType size; size.Fill(fillSize); typename ImageType::RegionType region; region.SetSize(size); image->SetRegions(region); image->Allocate(); image->FillBuffer(value); return image; } // Fill half of the pixels with a value // Used for generating a test mask template <typename ImageType> void FillHalf(typename ImageType::Pointer image, const typename ImageType::RegionType& region, const typename ImageType::PixelType& value) { itk::ImageRegionIterator<ImageType> it(image, region); unsigned int count = 0; for(it.GoToBegin(); !it.IsAtEnd(); ++it, ++count) { if (count % 2 == 0) { it.Set(value); } } } // Test template instanciation int otbMaskedIteratorDecoratorNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) { typedef otb::Image<double, 2> ImageType; ImageType::Pointer image = GetTestImage<ImageType>(10, 10); ImageType::Pointer mask = GetTestImage<ImageType>(10, 0); ImageType::RegionType region(image->GetLargestPossibleRegion()); otb::MaskedIteratorDecorator<itk::ImageRegionIterator<ImageType> > it(mask, image, region); return EXIT_SUCCESS; } // Function to test the forward iteration interface template <typename IteratorType> int ForwardTest(typename IteratorType::ImageType::Pointer mask, typename IteratorType::ImageType::Pointer image, typename IteratorType::ImageType::RegionType region) { otb::MaskedIteratorDecorator<IteratorType> it(mask, image, region); it.GoToBegin(); if (!it.IsAtBegin()) {return EXIT_FAILURE;} unsigned int loopCount = 0; for(; !it.IsAtEnd(); ++it) { if (loopCount != 0 && it.IsAtBegin()) {return EXIT_FAILURE;} if (it.IsAtEnd()) {return EXIT_FAILURE;} //it.Set(it.Value() * 0.42); loopCount += 1; } if(!it.IsAtEnd()) {return EXIT_FAILURE;} return EXIT_SUCCESS; } // Test reverse iteration interface template <typename IteratorType> int ReverseTest(typename IteratorType::ImageType::Pointer mask, typename IteratorType::ImageType::Pointer image, typename IteratorType::ImageType::RegionType region) { otb::MaskedIteratorDecorator<IteratorType> it(mask, image, region); it.GoToEnd(); if (!it.IsAtEnd()) {return EXIT_FAILURE;} bool beginReached = false; do { --it; if (it.IsAtEnd()) {return EXIT_FAILURE;} if (it.IsAtBegin()) { if (beginReached) { return EXIT_FAILURE; } else { beginReached = true; } } //it.Set(it.Value() * 0.42); } while (!it.IsAtBegin()); if(!it.IsAtBegin()) {return EXIT_FAILURE;} return EXIT_SUCCESS; } // Check bijection between iterated and non masked // i.e all locations where mask value != 0 are in the iteration (injection) // and mask value != 0 at all iteration locations (surjection) // Templated to test decoration of different iterator types template <typename IteratorType> int BijectiveTest(typename IteratorType::ImageType::Pointer mask, typename IteratorType::ImageType::Pointer image, typename IteratorType::ImageType::RegionType region) { otb::MaskedIteratorDecorator<IteratorType> itDecorated(mask, image, region); IteratorType it(image, region); it.GoToBegin(); itDecorated.GoToBegin(); // Find the non maked begin for the image iterator while (mask->GetPixel(it.GetIndex()) == 0 && !it.IsAtEnd()) { ++it; } // Begins are the same if (!(it.GetIndex() == itDecorated.GetIndex() && it.GetIndex() == itDecorated.GetImageIterator().GetIndex() && it.GetIndex() == itDecorated.GetMaskIterator().GetIndex())) { return EXIT_FAILURE; } // Advance both and check while (!it.IsAtEnd() && !itDecorated.IsAtEnd()) { // Iteration locations are the same if (!(it.GetIndex() == itDecorated.GetIndex() && it.GetIndex() == itDecorated.GetImageIterator().GetIndex() && it.GetIndex() == itDecorated.GetMaskIterator().GetIndex())) { return EXIT_FAILURE; } ++itDecorated; do { ++it; } while (mask->GetPixel(it.GetIndex()) == 0 && !it.IsAtEnd()); } // Check IsAtEnd if (!(it.IsAtEnd() && itDecorated.IsAtEnd())) { return EXIT_FAILURE; } return EXIT_SUCCESS; } // Multiplex to forward, reverse and bijection test template <typename IteratorType> int TripleTest(typename IteratorType::ImageType::Pointer mask, typename IteratorType::ImageType::Pointer image, typename IteratorType::ImageType::RegionType region) { int ret; int retGlobal = EXIT_SUCCESS; ret = ForwardTest<IteratorType>(mask, image, region); if (ret == EXIT_FAILURE) { std::cout << "Forward(FAILED) "; retGlobal = EXIT_FAILURE; } ret = ReverseTest<IteratorType>(mask, image, region); if (ret == EXIT_FAILURE) { std::cout << "Reverse(FAILED) "; retGlobal = EXIT_FAILURE; } ret = BijectiveTest<IteratorType>(mask, image, region); if (ret == EXIT_FAILURE) { std::cout << "Bijective(FAILED) "; retGlobal = EXIT_FAILURE; } if (retGlobal == EXIT_SUCCESS) { std::cout << "PASSED"; } return retGlobal; } // Nominal case int otbMaskedIteratorDecoratorNominal(int itkNotUsed(argc), char * itkNotUsed(argv) []) { typedef otb::Image<double, 2> ImageType; ImageType::Pointer image = GetTestImage<ImageType>(10, 10); ImageType::Pointer mask = GetTestImage<ImageType>(10, 0); ImageType::RegionType region(image->GetLargestPossibleRegion()); FillHalf<ImageType>(mask, region, 1); int ret; int retGlobal = EXIT_SUCCESS; std::cout << std::endl << "itk::ImageRegionIterator : "; ret = TripleTest<itk::ImageRegionIterator<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); std::cout << std::endl << "itk::ImageRegionConstIterator : "; ret = TripleTest< itk::ImageRegionConstIterator<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); std::cout << std::endl << "itk::ImageRandomConstIteratorWithIndex : "; ret = TripleTest< itk::ImageRandomConstIteratorWithIndex<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); std::cout << std::endl << "otb::SubsampledImageRegionIterator : "; ret = TripleTest< otb::SubsampledImageRegionIterator<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); std::cout << std::endl << "itk::ImageRandomIteratorWithIndex : "; ret = TripleTest< itk::ImageRandomIteratorWithIndex<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); std::cout << std::endl << "itk::ImageScanlineIterator : "; ret = TripleTest< itk::ImageScanlineIterator<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); std::cout << std::endl << "itk::ImageScanlineConstIterator : "; ret = TripleTest< itk::ImageScanlineConstIterator<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); std::cout << std::endl << "itk::ImageRandomNonRepeatingConstIteratorWithIndex : "; ret = TripleTest< itk::ImageRandomNonRepeatingConstIteratorWithIndex<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); std::cout << std::endl << "itk::ImageRandomNonRepeatingIteratorWithIndex : "; ret = TripleTest< itk::ImageRandomNonRepeatingIteratorWithIndex<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); return retGlobal; } // Degenerate cases int otbMaskedIteratorDecoratorDegenerate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { // Fully masked (0 everywhere) and image is smaller than mask typedef otb::Image<double, 2> ImageType; ImageType::Pointer image = GetTestImage<ImageType>(9, 10); ImageType::Pointer mask = GetTestImage<ImageType>(100, 0); ImageType::RegionType region(image->GetLargestPossibleRegion()); return TripleTest<itk::ImageRegionIterator<ImageType> >(image, mask, region); } /* Other iterators potentially compatible: Different constructor arguments than (image, region) itk::PathIterator itk::LineIterator itk::SliceIterator itk::NeighborhoodIterator GoToEnd is not implemented itk::ImageLinearIteratorWithIndex itk::ReflectiveImageRegionIterator itk::ImageRegionExclusionConstIteratorWithIndex itk::ImageRegionIteratorWithIndex Other problem: itk::ImageRegionReverseIterator>() // IsAtEnd not a const method otb::PolyLineImageIterator>() // header not found itk::ImageRandomConstIteratorWithOnlyIndex>() // no Value method */ <commit_msg>ENH: Update working iterators comments in MaskedIteratorDecorator<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <set> #include "otbImage.h" #include "itkImageRegionIterator.h" #include "itkImageRegionReverseIterator.h" #include "itkImageRandomIteratorWithIndex.h" #include "itkImageScanlineIterator.h" #include "itkImageRandomNonRepeatingIteratorWithIndex.h" #include "otbSubsampledImageRegionIterator.h" #include "otbMaskedIteratorDecorator.h" // Generate a test image of specified size and value template <typename ImageType> typename ImageType::Pointer GetTestImage(itk::SizeValueType fillSize, const typename ImageType::PixelType& value) { typename ImageType::Pointer image = ImageType::New(); typename ImageType::SizeType size; size.Fill(fillSize); typename ImageType::RegionType region; region.SetSize(size); image->SetRegions(region); image->Allocate(); image->FillBuffer(value); return image; } // Fill half of the pixels with a value // Used for generating a test mask template <typename ImageType> void FillHalf(typename ImageType::Pointer image, const typename ImageType::RegionType& region, const typename ImageType::PixelType& value) { itk::ImageRegionIterator<ImageType> it(image, region); unsigned int count = 0; for(it.GoToBegin(); !it.IsAtEnd(); ++it, ++count) { if (count % 2 == 0) { it.Set(value); } } } // Test template instanciation int otbMaskedIteratorDecoratorNew(int itkNotUsed(argc), char * itkNotUsed(argv) []) { typedef otb::Image<double, 2> ImageType; ImageType::Pointer image = GetTestImage<ImageType>(10, 10); ImageType::Pointer mask = GetTestImage<ImageType>(10, 0); ImageType::RegionType region(image->GetLargestPossibleRegion()); otb::MaskedIteratorDecorator<itk::ImageRegionIterator<ImageType> > it(mask, image, region); return EXIT_SUCCESS; } // Function to test the forward iteration interface template <typename IteratorType> int ForwardTest(typename IteratorType::ImageType::Pointer mask, typename IteratorType::ImageType::Pointer image, typename IteratorType::ImageType::RegionType region) { otb::MaskedIteratorDecorator<IteratorType> it(mask, image, region); it.GoToBegin(); if (!it.IsAtBegin()) {return EXIT_FAILURE;} unsigned int loopCount = 0; for(; !it.IsAtEnd(); ++it) { if (loopCount != 0 && it.IsAtBegin()) {return EXIT_FAILURE;} if (it.IsAtEnd()) {return EXIT_FAILURE;} //it.Set(it.Value() * 0.42); loopCount += 1; } if(!it.IsAtEnd()) {return EXIT_FAILURE;} return EXIT_SUCCESS; } // Test reverse iteration interface template <typename IteratorType> int ReverseTest(typename IteratorType::ImageType::Pointer mask, typename IteratorType::ImageType::Pointer image, typename IteratorType::ImageType::RegionType region) { otb::MaskedIteratorDecorator<IteratorType> it(mask, image, region); it.GoToEnd(); if (!it.IsAtEnd()) {return EXIT_FAILURE;} bool beginReached = false; do { --it; if (it.IsAtEnd()) {return EXIT_FAILURE;} if (it.IsAtBegin()) { if (beginReached) { return EXIT_FAILURE; } else { beginReached = true; } } //it.Set(it.Value() * 0.42); } while (!it.IsAtBegin()); if(!it.IsAtBegin()) {return EXIT_FAILURE;} return EXIT_SUCCESS; } // Check bijection between iterated and non masked // i.e all locations where mask value != 0 are in the iteration (injection) // and mask value != 0 at all iteration locations (surjection) // Templated to test decoration of different iterator types template <typename IteratorType> int BijectiveTest(typename IteratorType::ImageType::Pointer mask, typename IteratorType::ImageType::Pointer image, typename IteratorType::ImageType::RegionType region) { otb::MaskedIteratorDecorator<IteratorType> itDecorated(mask, image, region); IteratorType it(image, region); it.GoToBegin(); itDecorated.GoToBegin(); // Find the non maked begin for the image iterator while (mask->GetPixel(it.GetIndex()) == 0 && !it.IsAtEnd()) { ++it; } // Begins are the same if (!(it.GetIndex() == itDecorated.GetIndex() && it.GetIndex() == itDecorated.GetImageIterator().GetIndex() && it.GetIndex() == itDecorated.GetMaskIterator().GetIndex())) { return EXIT_FAILURE; } // Advance both and check while (!it.IsAtEnd() && !itDecorated.IsAtEnd()) { // Iteration locations are the same if (!(it.GetIndex() == itDecorated.GetIndex() && it.GetIndex() == itDecorated.GetImageIterator().GetIndex() && it.GetIndex() == itDecorated.GetMaskIterator().GetIndex())) { return EXIT_FAILURE; } ++itDecorated; do { ++it; } while (mask->GetPixel(it.GetIndex()) == 0 && !it.IsAtEnd()); } // Check IsAtEnd if (!(it.IsAtEnd() && itDecorated.IsAtEnd())) { return EXIT_FAILURE; } return EXIT_SUCCESS; } // Multiplex to forward, reverse and bijection test template <typename IteratorType> int TripleTest(typename IteratorType::ImageType::Pointer mask, typename IteratorType::ImageType::Pointer image, typename IteratorType::ImageType::RegionType region) { int ret; int retGlobal = EXIT_SUCCESS; ret = ForwardTest<IteratorType>(mask, image, region); if (ret == EXIT_FAILURE) { std::cout << "Forward(FAILED) "; retGlobal = EXIT_FAILURE; } ret = ReverseTest<IteratorType>(mask, image, region); if (ret == EXIT_FAILURE) { std::cout << "Reverse(FAILED) "; retGlobal = EXIT_FAILURE; } ret = BijectiveTest<IteratorType>(mask, image, region); if (ret == EXIT_FAILURE) { std::cout << "Bijective(FAILED) "; retGlobal = EXIT_FAILURE; } if (retGlobal == EXIT_SUCCESS) { std::cout << "PASSED"; } return retGlobal; } // Nominal case int otbMaskedIteratorDecoratorNominal(int itkNotUsed(argc), char * itkNotUsed(argv) []) { typedef otb::Image<double, 2> ImageType; ImageType::Pointer image = GetTestImage<ImageType>(10, 10); ImageType::Pointer mask = GetTestImage<ImageType>(10, 0); ImageType::RegionType region(image->GetLargestPossibleRegion()); FillHalf<ImageType>(mask, region, 1); int ret; int retGlobal = EXIT_SUCCESS; std::cout << std::endl << "itk::ImageRegionIterator : "; ret = TripleTest<itk::ImageRegionIterator<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); std::cout << std::endl << "itk::ImageRegionConstIterator : "; ret = TripleTest< itk::ImageRegionConstIterator<ImageType> >(image, mask, region); retGlobal = (ret == EXIT_FAILURE ? EXIT_FAILURE : retGlobal); return retGlobal; } // Degenerate cases int otbMaskedIteratorDecoratorDegenerate(int itkNotUsed(argc), char * itkNotUsed(argv) []) { // Fully masked (0 everywhere) and image is smaller than mask typedef otb::Image<double, 2> ImageType; ImageType::Pointer image = GetTestImage<ImageType>(9, 10); ImageType::Pointer mask = GetTestImage<ImageType>(100, 0); ImageType::RegionType region(image->GetLargestPossibleRegion()); return TripleTest<itk::ImageRegionIterator<ImageType> >(image, mask, region); } /* Other iterators potentially compatible: Different constructor arguments than (image, region) itk::PathIterator itk::LineIterator itk::SliceIterator itk::NeighborhoodIterator Needs initialization code: itk::ImageRandomConstIteratorWithIndex otb::SubsampledImageRegionIterator itk::ImageRandomIteratorWithIndex itk::ImageRandomNonRepeatingConstIteratorWithIndex itk::ImageRandomNonRepeatingIteratorWithIndex Different iteration interface than normal iterators: itk::ImageScanlineIterator itk::ImageScanlineConstIterator GoToEnd is not implemented itk::ImageLinearIteratorWithIndex itk::ReflectiveImageRegionIterator itk::ImageRegionExclusionConstIteratorWithIndex itk::ImageRegionIteratorWithIndex Other problem: itk::ImageRegionReverseIterator>() // IsAtEnd not a const method otb::PolyLineImageIterator>() // header not found itk::ImageRandomConstIteratorWithOnlyIndex>() // no Value method */ <|endoftext|>
<commit_before>/** * @file Simulation.cpp * @author <a href="mailto:schlottb@informatik.hu-berlin.de">Benjamin Schlotter</a> * Implementation of class Simulation */ #include "Simulation.h" using namespace naoth; using namespace std; Simulation::Simulation() { DEBUG_REQUEST_REGISTER("Simulation:draw_one_action_point:global","draw_one_action_point:global", false); DEBUG_REQUEST_REGISTER("Simulation:draw_ball","draw_ball", false); DEBUG_REQUEST_REGISTER("Simulation:ActionTarget","ActionTarget", false); DEBUG_REQUEST_REGISTER("Simulation:draw_best_action","best action",false); //DEBUG_REQUEST_REGISTER("Simulation:draw_pessimistic_best_action","best pessimistic action",false); DEBUG_REQUEST_REGISTER("Simulation:GoalLinePreview","GoalLinePreview",false); DEBUG_REQUEST_REGISTER("Simulation:draw_potential_field","Draw Potential Field",false); DEBUG_REQUEST_REGISTER("Simulation:use_Parameters","use_Parameters",false); getDebugParameterList().add(&theParameters); //calculate the actions action_local.reserve(KickActionModel::numOfActions); action_local.push_back(Action(KickActionModel::none, Vector2d())); action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left } Simulation::~Simulation(){} void Simulation::execute() { DEBUG_REQUEST("Simulation:use_Parameters", action_local.clear(); action_local.reserve(KickActionModel::numOfActions); action_local.push_back(Action(KickActionModel::none, Vector2d())); action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left ); if(!getBallModel().valid || getFrameInfo().getTimeInSeconds() >= getBallModel().frameInfoWhenBallWasSeen.getTimeInSeconds()+1) { return; } else { int best_action = 0; for(size_t i=0; i<action_local.size(); i++) { // physics simulator std::vector<Vector2d> ballPositionResults; // this size needs to be exposed for(size_t j=0; j<30; j++) { const Vector2d& ballRelativePreview = getBallModel().positionPreview; Vector2d ballPositionResult = action_local[i].predict(ballRelativePreview, theParameters.distance_variance, theParameters.angle_variance); DEBUG_REQUEST("Simulation:ActionTarget", FIELD_DRAWING_CONTEXT; PEN("0000FF", 1); Vector2d ball = getRobotPose() * ballPositionResult; CIRCLE( ball.x, ball.y, 50); ); ballPositionResults.push_back(ballPositionResult); } // categorize positions std::vector<CategorizedBallPosition> categorizedBallPositionResults; categorizePosition(ballPositionResults, categorizedBallPositionResults); } getKickActionModel().myAction = action_local[best_action].id(); DEBUG_REQUEST("Simulation:draw_best_action", { FIELD_DRAWING_CONTEXT; PEN("FF69B4", 7); Vector2d actionGlobal = action_local[best_action].target; FILLOVAL(actionGlobal.x, actionGlobal.y, 50,50); }); // DEBUG_REQUEST("Simulation:draw_potential_field", // draw_potential_field(); // ); } }//end execute void Simulation::categorizePosition( const std::vector<Vector2d>& ballPositions, std::vector<CategorizedBallPosition>& categorizedBallPositions ) const { // HINT: categorizedBallPositions is not necessarily empty here! Maybe we should clear it // calculate the opponent goal line GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo()); Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.leftPost; Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.rightPost; Vector2d oppGoalDir = (oppGoalPostRightPreview - oppGoalPostLeftPreview).normalize(); Vector2d oppLeftEndpoint = oppGoalPostLeftPreview + oppGoalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius); Vector2d oppRightEndpoint = oppGoalPostRightPreview - oppGoalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius); Math::LineSegment oppGoalLinePreview(oppLeftEndpoint, oppRightEndpoint); // calculate the own goal line GoalModel::Goal ownGoalModel = getSelfLocGoalModel().getOwnGoal(getCompassDirection(), getFieldInfo()); Vector2d ownGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / ownGoalModel.leftPost; Vector2d ownGoalPostRightPreview = getMotionStatus().plannedMotion.hip / ownGoalModel.rightPost; Vector2d ownGoalDir = (ownGoalPostRightPreview - ownGoalPostLeftPreview).normalize(); Vector2d ownLeftEndpoint = ownGoalPostLeftPreview + ownGoalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius); Vector2d ownRightEndpoint = ownGoalPostRightPreview - ownGoalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius); Math::LineSegment ownGoalLinePreview(ownLeftEndpoint, ownRightEndpoint); // now loop through all positions for(std::vector<Vector2d>::const_iterator ballPosition = ballPositions.begin(); ballPosition != ballPositions.end(); ballPosition++) { //Schusslinie Math::LineSegment shootLine(getBallModel().positionPreview, *ballPosition); BallPositionCategory category = INFIELD; // inside field if(getFieldInfo().fieldRect.inside(*ballPosition)) { category = INFIELD; } // goal!! else if(shootLine.intersect(oppGoalLinePreview) && oppGoalLinePreview.intersect(shootLine)) { category = OPPGOAL; } // own goal else if(shootLine.intersect(ownGoalLinePreview) && ownGoalLinePreview.intersect(shootLine)) { category = OWNGOAL; } //Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht else if(ballPosition->x > getFieldInfo().xPosOpponentGroundline) { category = OPPOUT; } //Own Groundline out - an der seite wo raus geht else if(ballPosition->x < getFieldInfo().xPosOwnGroundline) { category = OWNOUT; } //an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(ballPosition->y > getFieldInfo().yPosLeftSideline ) { category = LEFTOUT; } //an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(ballPosition->y < getFieldInfo().yPosRightSideline) { category = RIGHTOUT; } CategorizedBallPosition categorizedBallPosition = CategorizedBallPosition(*ballPosition, category); categorizedBallPositions.push_back(categorizedBallPosition); } } //correction of distance in percentage, angle in degrees Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const { double random_length = 2.0*Math::random()-1.0; double random_angle = 2.0*Math::random()-1.0; Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length); noisyAction.rotate(angle_variance*random_angle); return ball + noisyAction; } //calcualte according to the rules, without the roboter position, the ball position //if it goes outside the field Vector2d Simulation::outsideField(const Vector2d& globalPoint) const { Vector2d point = globalPoint; //Schusslinie Math::LineSegment shootLine(getBallModel().positionPreview, globalPoint); if(getFieldInfo().fieldRect.inside(point)){ return point; } else //Nach Prioritten geordnet - zuerst die Regeln mit dem mglichst schlimmsten Resultat { //Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht if(point.x > getFieldInfo().xPosOpponentGroundline) { Vector2d OppOutPoint = getFieldInfo().oppLineSegment.point(getFieldInfo().oppLineSegment.intersection(shootLine)); if(OppOutPoint.y < 0) { return Vector2d(0, getFieldInfo().yThrowInLineRight);//range check } else { return Vector2d(0, getFieldInfo().yThrowInLineLeft); } } //Own Groundline out - an der seite wo raus geht else if(point.x < getFieldInfo().xPosOwnGroundline) { Vector2d OwnOutPoint = getFieldInfo().ownLineSegment.point(getFieldInfo().ownLineSegment.intersection(shootLine)); if(OwnOutPoint.y < 0) { return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);//range check } else { return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft); } } //an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(point.y > getFieldInfo().yPosLeftSideline ) { Vector2d leftOutPoint = getFieldInfo().leftLineSegment.point(getFieldInfo().leftLineSegment.intersection(shootLine)); point.x = min(leftOutPoint.x,getRobotPose().translation.x); if(point.x-1000 < getFieldInfo().xThrowInLineOwn) { point.x = getFieldInfo().xThrowInLineOwn; } else { point.x -= 1000; } return Vector2d(point.x, getFieldInfo().yThrowInLineLeft); //range check } //an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else //(point.y < getFieldInfo().yPosRightSideline) { Vector2d rightOutPoint = getFieldInfo().rightLineSegment.point(getFieldInfo().rightLineSegment.intersection(shootLine)); point.x = min(rightOutPoint.x,getRobotPose().translation.x); if(point.x-1000 < getFieldInfo().xThrowInLineOwn) { point.x = getFieldInfo().xThrowInLineOwn; } else { point.x -= 1000; } return Vector2d(point.x, getFieldInfo().yThrowInLineRight);//range check } } } double Simulation::evaluateAction(const Vector2d& a) const{ Vector2d oppGoal(getFieldInfo().xPosOpponentGoal+200, 0.0); Vector2d oppDiff = oppGoal - a; double oppValueX = 0.1; double oppValueY = 1; MODIFY("Simulation:oppValueX", oppValueX); MODIFY("Simulation:oppValueY", oppValueY); double value_opp = oppValueX*oppDiff.x*oppDiff.x + oppValueY*oppDiff.y*oppDiff.y; //Vector2d ownGoal(getFieldInfo().xPosOwnGoal, 0.0); //Vector2d ownDiff = ownGoal - a; //double ownValueX = 0.01; //double ownValueY = 0.1; //MODIFY("Simulation:ownValueX", ownValueX); //MODIFY("Simulation:ownValueY", ownValueY); //double value_own = ownValueX*ownDiff.x*ownDiff.x + ownValueY*ownDiff.y*ownDiff.y; //return value_opp - value_own; return value_opp; } void Simulation::draw_potential_field() const { static const int ySize = 20; static const int xSize = 30; double yWidth = 0.5*getFieldInfo().yFieldLength/(double)ySize; double xWidth = 0.5*getFieldInfo().xFieldLength/(double)xSize; FIELD_DRAWING_CONTEXT; Color white(0.0,0.0,1.0,0.5); // transparent Color black(1.0,0.0,0.0,0.5); // create new sample set std::vector<double> potential(xSize*ySize); int idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1)); potential[idx] = evaluateAction(point); idx++; } } double maxValue = 0; idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { maxValue = max(maxValue, potential[idx++]); } } if(maxValue == 0) return; idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1)); double t = potential[idx++] / maxValue; Color color = black*t + white*(1-t); PEN(color, 20); FILLBOX(point.x - xWidth, point.y - yWidth, point.x+xWidth, point.y+yWidth); } } }//end draw_closest_points <commit_msg>Cleanup DebugRequest<commit_after>/** * @file Simulation.cpp * @author <a href="mailto:schlottb@informatik.hu-berlin.de">Benjamin Schlotter</a> * Implementation of class Simulation */ #include "Simulation.h" using namespace naoth; using namespace std; Simulation::Simulation() { DEBUG_REQUEST_REGISTER("Simulation:draw_ball","draw_ball", false); DEBUG_REQUEST_REGISTER("Simulation:ActionTarget","ActionTarget", false); DEBUG_REQUEST_REGISTER("Simulation:draw_best_action","best action",false); DEBUG_REQUEST_REGISTER("Simulation:draw_potential_field","Draw Potential Field",false); DEBUG_REQUEST_REGISTER("Simulation:use_Parameters","use_Parameters",false); getDebugParameterList().add(&theParameters); //calculate the actions action_local.reserve(KickActionModel::numOfActions); action_local.push_back(Action(KickActionModel::none, Vector2d())); action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left } Simulation::~Simulation(){} void Simulation::execute() { DEBUG_REQUEST("Simulation:use_Parameters", action_local.clear(); action_local.reserve(KickActionModel::numOfActions); action_local.push_back(Action(KickActionModel::none, Vector2d())); action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left ); if(!getBallModel().valid || getFrameInfo().getTimeInSeconds() >= getBallModel().frameInfoWhenBallWasSeen.getTimeInSeconds()+1) { return; } else { int best_action = 0; for(size_t i=0; i<action_local.size(); i++) { // physics simulator std::vector<Vector2d> ballPositionResults; // this size needs to be exposed for(size_t j=0; j<30; j++) { const Vector2d& ballRelativePreview = getBallModel().positionPreview; Vector2d ballPositionResult = action_local[i].predict(ballRelativePreview, theParameters.distance_variance, theParameters.angle_variance); DEBUG_REQUEST("Simulation:ActionTarget", FIELD_DRAWING_CONTEXT; PEN("0000FF", 1); Vector2d ball = getRobotPose() * ballPositionResult; CIRCLE( ball.x, ball.y, 50); ); ballPositionResults.push_back(ballPositionResult); } // categorize positions std::vector<CategorizedBallPosition> categorizedBallPositionResults; categorizePosition(ballPositionResults, categorizedBallPositionResults); } getKickActionModel().myAction = action_local[best_action].id(); DEBUG_REQUEST("Simulation:draw_best_action", { FIELD_DRAWING_CONTEXT; PEN("FF69B4", 7); Vector2d actionGlobal = action_local[best_action].target; FILLOVAL(actionGlobal.x, actionGlobal.y, 50,50); }); DEBUG_REQUEST("Simulation:draw_potential_field", draw_potential_field(); ); } }//end execute void Simulation::categorizePosition( const std::vector<Vector2d>& ballPositions, std::vector<CategorizedBallPosition>& categorizedBallPositions ) const { // HINT: categorizedBallPositions is not necessarily empty here! Maybe we should clear it // calculate the opponent goal line GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo()); Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.leftPost; Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.rightPost; Vector2d oppGoalDir = (oppGoalPostRightPreview - oppGoalPostLeftPreview).normalize(); Vector2d oppLeftEndpoint = oppGoalPostLeftPreview + oppGoalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius); Vector2d oppRightEndpoint = oppGoalPostRightPreview - oppGoalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius); Math::LineSegment oppGoalLinePreview(oppLeftEndpoint, oppRightEndpoint); // calculate the own goal line GoalModel::Goal ownGoalModel = getSelfLocGoalModel().getOwnGoal(getCompassDirection(), getFieldInfo()); Vector2d ownGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / ownGoalModel.leftPost; Vector2d ownGoalPostRightPreview = getMotionStatus().plannedMotion.hip / ownGoalModel.rightPost; Vector2d ownGoalDir = (ownGoalPostRightPreview - ownGoalPostLeftPreview).normalize(); Vector2d ownLeftEndpoint = ownGoalPostLeftPreview + ownGoalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius); Vector2d ownRightEndpoint = ownGoalPostRightPreview - ownGoalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius); Math::LineSegment ownGoalLinePreview(ownLeftEndpoint, ownRightEndpoint); // now loop through all positions for(std::vector<Vector2d>::const_iterator ballPosition = ballPositions.begin(); ballPosition != ballPositions.end(); ballPosition++) { //Schusslinie Math::LineSegment shootLine(getBallModel().positionPreview, *ballPosition); BallPositionCategory category = INFIELD; // inside field if(getFieldInfo().fieldRect.inside(*ballPosition)) { category = INFIELD; } // goal!! else if(shootLine.intersect(oppGoalLinePreview) && oppGoalLinePreview.intersect(shootLine)) { category = OPPGOAL; } // own goal else if(shootLine.intersect(ownGoalLinePreview) && ownGoalLinePreview.intersect(shootLine)) { category = OWNGOAL; } //Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht else if(ballPosition->x > getFieldInfo().xPosOpponentGroundline) { category = OPPOUT; } //Own Groundline out - an der seite wo raus geht else if(ballPosition->x < getFieldInfo().xPosOwnGroundline) { category = OWNOUT; } //an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(ballPosition->y > getFieldInfo().yPosLeftSideline ) { category = LEFTOUT; } //an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(ballPosition->y < getFieldInfo().yPosRightSideline) { category = RIGHTOUT; } CategorizedBallPosition categorizedBallPosition = CategorizedBallPosition(*ballPosition, category); categorizedBallPositions.push_back(categorizedBallPosition); } } //correction of distance in percentage, angle in degrees Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const { double random_length = 2.0*Math::random()-1.0; double random_angle = 2.0*Math::random()-1.0; Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length); noisyAction.rotate(angle_variance*random_angle); return ball + noisyAction; } //calcualte according to the rules, without the roboter position, the ball position //if it goes outside the field Vector2d Simulation::outsideField(const Vector2d& globalPoint) const { Vector2d point = globalPoint; //Schusslinie Math::LineSegment shootLine(getBallModel().positionPreview, globalPoint); if(getFieldInfo().fieldRect.inside(point)){ return point; } else //Nach Prioritten geordnet - zuerst die Regeln mit dem mglichst schlimmsten Resultat { //Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht if(point.x > getFieldInfo().xPosOpponentGroundline) { Vector2d OppOutPoint = getFieldInfo().oppLineSegment.point(getFieldInfo().oppLineSegment.intersection(shootLine)); if(OppOutPoint.y < 0) { return Vector2d(0, getFieldInfo().yThrowInLineRight);//range check } else { return Vector2d(0, getFieldInfo().yThrowInLineLeft); } } //Own Groundline out - an der seite wo raus geht else if(point.x < getFieldInfo().xPosOwnGroundline) { Vector2d OwnOutPoint = getFieldInfo().ownLineSegment.point(getFieldInfo().ownLineSegment.intersection(shootLine)); if(OwnOutPoint.y < 0) { return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);//range check } else { return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft); } } //an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(point.y > getFieldInfo().yPosLeftSideline ) { Vector2d leftOutPoint = getFieldInfo().leftLineSegment.point(getFieldInfo().leftLineSegment.intersection(shootLine)); point.x = min(leftOutPoint.x,getRobotPose().translation.x); if(point.x-1000 < getFieldInfo().xThrowInLineOwn) { point.x = getFieldInfo().xThrowInLineOwn; } else { point.x -= 1000; } return Vector2d(point.x, getFieldInfo().yThrowInLineLeft); //range check } //an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else //(point.y < getFieldInfo().yPosRightSideline) { Vector2d rightOutPoint = getFieldInfo().rightLineSegment.point(getFieldInfo().rightLineSegment.intersection(shootLine)); point.x = min(rightOutPoint.x,getRobotPose().translation.x); if(point.x-1000 < getFieldInfo().xThrowInLineOwn) { point.x = getFieldInfo().xThrowInLineOwn; } else { point.x -= 1000; } return Vector2d(point.x, getFieldInfo().yThrowInLineRight);//range check } } } double Simulation::evaluateAction(const Vector2d& a) const{ Vector2d oppGoal(getFieldInfo().xPosOpponentGoal+200, 0.0); Vector2d oppDiff = oppGoal - a; double oppValueX = 0.1; double oppValueY = 1; MODIFY("Simulation:oppValueX", oppValueX); MODIFY("Simulation:oppValueY", oppValueY); double value_opp = oppValueX*oppDiff.x*oppDiff.x + oppValueY*oppDiff.y*oppDiff.y; //Vector2d ownGoal(getFieldInfo().xPosOwnGoal, 0.0); //Vector2d ownDiff = ownGoal - a; //double ownValueX = 0.01; //double ownValueY = 0.1; //MODIFY("Simulation:ownValueX", ownValueX); //MODIFY("Simulation:ownValueY", ownValueY); //double value_own = ownValueX*ownDiff.x*ownDiff.x + ownValueY*ownDiff.y*ownDiff.y; //return value_opp - value_own; return value_opp; } void Simulation::draw_potential_field() const { static const int ySize = 20; static const int xSize = 30; double yWidth = 0.5*getFieldInfo().yFieldLength/(double)ySize; double xWidth = 0.5*getFieldInfo().xFieldLength/(double)xSize; FIELD_DRAWING_CONTEXT; Color white(0.0,0.0,1.0,0.5); // transparent Color black(1.0,0.0,0.0,0.5); // create new sample set std::vector<double> potential(xSize*ySize); int idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1)); potential[idx] = evaluateAction(point); idx++; } } double maxValue = 0; idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { maxValue = max(maxValue, potential[idx++]); } } if(maxValue == 0) return; idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1)); double t = potential[idx++] / maxValue; Color color = black*t + white*(1-t); PEN(color, 20); FILLBOX(point.x - xWidth, point.y - yWidth, point.x+xWidth, point.y+yWidth); } } }//end draw_closest_points <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkSimpleExampleFunctionality.h" #include "QmitkSimpleExampleControls.h" #include <qaction.h> #include "slicer.xpm" // for slice-navigation #include <mitkEventMapper.h> #include <mitkGlobalInteraction.h> #include <mitkBaseRenderer.h> #include "QmitkRenderWindow.h" #include "QmitkSelectableGLWidget.h" #include "QmitkStdMultiWidget.h" #include <QmitkStepperAdapter.h> #include "qpushbutton.h" // for stereo setting #include <mitkOpenGLRenderer.h> #include <mitkVtkRenderWindow.h> #include <vtkRenderWindow.h> // for zoom/pan #include <mitkDisplayCoordinateOperation.h> #include <mitkDisplayVectorInteractor.h> #include <mitkDisplayInteractor.h> #include <mitkInteractionConst.h> QmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it) , controls(NULL), multiWidget(mitkStdMultiWidget), m_NavigatorsInitialized(false) { setAvailability(true); } QmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality() { // delete moveNzoom; } QWidget * QmitkSimpleExampleFunctionality::createMainWidget(QWidget *parent) { QWidget *result = NULL; if (multiWidget == NULL) { multiWidget = new QmitkStdMultiWidget(parent); result = multiWidget; } else { result = NULL; } mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine()); if(globalInteraction!=NULL) { globalInteraction->AddListener(multiWidget->GetMoveAndZoomInteractor() );//sends DisplayCoordinateOperation } return result; } QWidget * QmitkSimpleExampleFunctionality::createControlWidget(QWidget *parent) { if (controls == NULL) { controls = new QmitkSimpleExampleControls(parent); new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), multiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(), "sliceNavigatorTransversalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), multiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), multiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorTime(), multiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample"); new QmitkStepperAdapter(controls->getMovieNavigatorTime(), multiWidget->GetTimeNavigationController()->GetTime(), "movieNavigatorTimeFromSimpleExample"); mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine()); if(globalInteraction!=NULL) { globalInteraction->AddListener(multiWidget->GetMultiplexUpdateController()); } } return controls; } void QmitkSimpleExampleFunctionality::createConnections() { if ( controls ) { connect(controls->getStereoSelect(), SIGNAL(activated(int)), this, SLOT(stereoSelectionChanged(int)) ); connect(controls->getReInitializeNavigatorsButton(), SIGNAL(clicked()), this, SLOT(initNavigators()) ); } } QAction * QmitkSimpleExampleFunctionality::createAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "Left" ), QPixmap((const char**)slicer_xpm), tr( "&Left" ), CTRL + Key_L, parent, "simple example" ); return action; } void QmitkSimpleExampleFunctionality::initNavigators() { m_NavigatorsInitialized = multiWidget->InitializeStandardViews(m_DataTreeIterator.GetPointer()); } void QmitkSimpleExampleFunctionality::treeChanged() { if(m_NavigatorsInitialized==false) initNavigators(); } void QmitkSimpleExampleFunctionality::activated() { QmitkFunctionality::activated(); assert( multiWidget != NULL ); // init widget 4 as a 3D widget multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2); if(m_NavigatorsInitialized) { multiWidget->ReInitializeStandardViews(); } } void QmitkSimpleExampleFunctionality::stereoSelectionChanged( int id ) { vtkRenderWindow * vtkrenderwindow = ((mitk::OpenGLRenderer*)(multiWidget->mitkWidget4->GetRenderer()))->GetVtkRenderWindow(); switch(id) { case 0: vtkrenderwindow->StereoRenderOff(); break; case 1: vtkrenderwindow->SetStereoTypeToRedBlue(); vtkrenderwindow->StereoRenderOn(); break; case 2: vtkrenderwindow->SetStereoTypeToDresden(); vtkrenderwindow->StereoRenderOn(); break; } multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2); multiWidget->mitkWidget4->GetRenderer()->GetRenderWindow()->Repaint(); } <commit_msg>ENH: better tooltip text<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkSimpleExampleFunctionality.h" #include "QmitkSimpleExampleControls.h" #include <qaction.h> #include "slicer.xpm" // for slice-navigation #include <mitkEventMapper.h> #include <mitkGlobalInteraction.h> #include <mitkBaseRenderer.h> #include "QmitkRenderWindow.h" #include "QmitkSelectableGLWidget.h" #include "QmitkStdMultiWidget.h" #include <QmitkStepperAdapter.h> #include "qpushbutton.h" // for stereo setting #include <mitkOpenGLRenderer.h> #include <mitkVtkRenderWindow.h> #include <vtkRenderWindow.h> // for zoom/pan #include <mitkDisplayCoordinateOperation.h> #include <mitkDisplayVectorInteractor.h> #include <mitkDisplayInteractor.h> #include <mitkInteractionConst.h> QmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it) , controls(NULL), multiWidget(mitkStdMultiWidget), m_NavigatorsInitialized(false) { setAvailability(true); } QmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality() { // delete moveNzoom; } QWidget * QmitkSimpleExampleFunctionality::createMainWidget(QWidget *parent) { QWidget *result = NULL; if (multiWidget == NULL) { multiWidget = new QmitkStdMultiWidget(parent); result = multiWidget; } else { result = NULL; } mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine()); if(globalInteraction!=NULL) { globalInteraction->AddListener(multiWidget->GetMoveAndZoomInteractor() );//sends DisplayCoordinateOperation } return result; } QWidget * QmitkSimpleExampleFunctionality::createControlWidget(QWidget *parent) { if (controls == NULL) { controls = new QmitkSimpleExampleControls(parent); new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), multiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(), "sliceNavigatorTransversalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), multiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), multiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorTime(), multiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample"); new QmitkStepperAdapter(controls->getMovieNavigatorTime(), multiWidget->GetTimeNavigationController()->GetTime(), "movieNavigatorTimeFromSimpleExample"); mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine()); if(globalInteraction!=NULL) { globalInteraction->AddListener(multiWidget->GetMultiplexUpdateController()); } } return controls; } void QmitkSimpleExampleFunctionality::createConnections() { if ( controls ) { connect(controls->getStereoSelect(), SIGNAL(activated(int)), this, SLOT(stereoSelectionChanged(int)) ); connect(controls->getReInitializeNavigatorsButton(), SIGNAL(clicked()), this, SLOT(initNavigators()) ); } } QAction * QmitkSimpleExampleFunctionality::createAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "Simple Example" ), QPixmap((const char**)slicer_xpm), tr( "&Simple Example" ), CTRL + Key_L, parent, "simple example" ); return action; } void QmitkSimpleExampleFunctionality::initNavigators() { m_NavigatorsInitialized = multiWidget->InitializeStandardViews(m_DataTreeIterator.GetPointer()); } void QmitkSimpleExampleFunctionality::treeChanged() { if(m_NavigatorsInitialized==false) initNavigators(); } void QmitkSimpleExampleFunctionality::activated() { QmitkFunctionality::activated(); assert( multiWidget != NULL ); // init widget 4 as a 3D widget multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2); if(m_NavigatorsInitialized) { multiWidget->ReInitializeStandardViews(); } } void QmitkSimpleExampleFunctionality::stereoSelectionChanged( int id ) { vtkRenderWindow * vtkrenderwindow = ((mitk::OpenGLRenderer*)(multiWidget->mitkWidget4->GetRenderer()))->GetVtkRenderWindow(); switch(id) { case 0: vtkrenderwindow->StereoRenderOff(); break; case 1: vtkrenderwindow->SetStereoTypeToRedBlue(); vtkrenderwindow->StereoRenderOn(); break; case 2: vtkrenderwindow->SetStereoTypeToDresden(); vtkrenderwindow->StereoRenderOn(); break; } multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2); multiWidget->mitkWidget4->GetRenderer()->GetRenderWindow()->Repaint(); } <|endoftext|>
<commit_before>#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insertElement(7); bool n=bst.isFound(7); REQUIRE(n=1); REQUIRE(bst.count() == 1); } <commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.isInserted(7); bool n=bst.isFound(7); REQUIRE(n=1); REQUIRE(bst.count() == 1); } <|endoftext|>
<commit_before>#pragma once namespace snap { #include <scomplex/simplicial_complex.h> #include <Eigen/Sparse> #include <scomplex/graph_utils.hpp> #include <scomplex/nn_utils.hpp> #include <scomplex/types.hpp> typedef Eigen::SparseVector<double> vector_t; class path_snapper { private: struct impl; std::shared_ptr<impl> p_impl; public: path_snapper(std::vector<point_t>& pts, std::vector<cell_t>& cells); path_snapper(simplicial::simplicial_complex&); ~path_snapper(); path_snapper(path_snapper& other); path_snapper& operator=(path_snapper& other); std::vector<size_t> snap_path(std::vector<point_t> path); vector_t get_chain_vector(std::vector<point_t> path); }; }; <commit_msg>more cleanup<commit_after><|endoftext|>
<commit_before>#include <cstdlib> #include <iostream> #include <boost/lambda/lambda.hpp> #include <boost/mem_fn.hpp> #include <libport/compiler.hh> // For ECHO #include <libport/containers.hh> #include <libport/foreach.hh> #include <scheduler/job.hh> namespace scheduler { extern unsigned int Job::alive_jobs_; StopException::StopException(unsigned depth, boost::any payload) : depth_(depth) , payload_(payload) { } void Job::run() { assert(state_ == to_start); ECHO("In Job::run for " << this); // We may get interrupted during our first run, in which case // we better not be in the to_start state while we are executing // or we would get removed abruptly from the scheduler pending_ // list. state_ = running; try { if (pending_exception_ && dynamic_cast<SchedulerException*>(pending_exception_.get())) check_for_pending_exception(); work(); } catch (TerminateException&) { // Normal termination requested } catch (StopException&) { // Termination through "stop" or "block" on a top-level tag, // that is a tag inherited at the job creation time. } catch (const kernel::exception& e) { // Signal the exception to each linked job in turn. foreach (const rJob& job, links_) { job->links_.remove(this); job->async_throw(e); } } catch (...) { // Exception is lost and cannot be propagated properly std::cerr << "Exception caught in job " << this << ", loosing it\n"; } terminate_cleanup(); // We should never go there as the scheduler will have terminated us. abort(); } void Job::terminate_now() { if (!terminated()) async_throw(TerminateException()); } void Job::terminate_cleanup() { // Remove pending links. foreach (const rJob& job, links_) job->links_.remove(this); links_.clear(); // Wake-up waiting jobs. foreach (const rJob& job, to_wake_up_) if (!job->terminated()) job->state_set(running); to_wake_up_.clear(); state_ = zombie; scheduler_.resume_scheduler(this); } void Job::yield_until_terminated(Job& other) { if (non_interruptible_ && this != &other) throw object::SchedulingError ("dependency on other task in non-interruptible code"); if (!other.terminated()) { // We allow enqueuing on ourselves, but without doing it for real. if (&other != this) other.to_wake_up_.push_back(this); state_ = joining; try { scheduler_.resume_scheduler(this); } catch (...) { // We have been awoken by an exception; in this case, // dequeue ourselves from the other thread queue if // we are still enqueued there. libport::erase_if(other.to_wake_up_, boost::lambda::_1 == this); throw; } } } void Job::yield_until_terminated(const jobs_type& jobs) { foreach (const rJob& job, jobs) yield_until_terminated(*job); } void Job::yield_until_things_changed() { if (non_interruptible_ && !frozen()) throw object::SchedulingError ("attempt to wait for condition changes in non-interruptible code"); state_ = waiting; scheduler_.resume_scheduler(this); } bool Job::frozen() const { return libport::has_if(tags_, boost::mem_fn(&scheduler::Tag::frozen)); } void Job::async_throw(const kernel::exception& e) { pending_exception_ = e.clone(); // A job which has received an exception is no longer side effect // free or non-interruptible. side_effect_free_ = false; non_interruptible_ = false; // If this is the current job we are talking about, the exception // is synchronous. if (scheduler_.is_current_job(*this)) check_for_pending_exception(); // Now that we acquired an exception to raise, we are active again, // even if we were previously sleeping or waiting for something. if (state_ != to_start && state_ != zombie) state_ = running; } void Job::register_stopped_tag(const Tag& tag, const boost::any& payload) { size_t max_tag_check = tags_.size(); if (pending_exception_) { // If we are going to terminate, do nothing if (dynamic_cast<TerminateException*>(pending_exception_.get())) return; // If we already have a StopException stored, do not go any // further. StopException* exc = dynamic_cast<StopException*>(pending_exception_.get()); if (exc) max_tag_check = exc->depth_get(); } // Check if we are affected by this tag, up-to max_tag_check from // the beginning of the tag list. for (unsigned int i = 0; i < max_tag_check; i++) if (tags_[i]->derives_from(tag)) { async_throw(StopException(i, payload)); return; } } void Job::check_for_pending_exception() { // If an exception has been stored for further rethrow, now is // a good time to do so. if (pending_exception_) { current_exception_ = pending_exception_; pending_exception_ = 0; kernel::rethrow(current_exception_); } } void Job::recompute_prio() { if (tags_.empty()) { prio_ = UPRIO_DEFAULT; return; } prio_ = UPRIO_MIN; foreach(const rTag& tag, tags_) prio_ = std::max(prio_, tag->prio_get()); } void Job::recompute_prio(const Tag& tag) { if (tag.prio_get() >= prio_ || tags_.empty()) recompute_prio(); } unsigned int Job::alive_jobs() { return alive_jobs_; } } <commit_msg>Do not use "extern" to declare static members.<commit_after>#include <cstdlib> #include <iostream> #include <boost/lambda/lambda.hpp> #include <boost/mem_fn.hpp> #include <libport/compiler.hh> // For ECHO #include <libport/containers.hh> #include <libport/foreach.hh> #include <scheduler/job.hh> namespace scheduler { unsigned int Job::alive_jobs_; StopException::StopException(unsigned depth, boost::any payload) : depth_(depth) , payload_(payload) { } void Job::run() { assert(state_ == to_start); ECHO("In Job::run for " << this); // We may get interrupted during our first run, in which case // we better not be in the to_start state while we are executing // or we would get removed abruptly from the scheduler pending_ // list. state_ = running; try { if (pending_exception_ && dynamic_cast<SchedulerException*>(pending_exception_.get())) check_for_pending_exception(); work(); } catch (TerminateException&) { // Normal termination requested } catch (StopException&) { // Termination through "stop" or "block" on a top-level tag, // that is a tag inherited at the job creation time. } catch (const kernel::exception& e) { // Signal the exception to each linked job in turn. foreach (const rJob& job, links_) { job->links_.remove(this); job->async_throw(e); } } catch (...) { // Exception is lost and cannot be propagated properly std::cerr << "Exception caught in job " << this << ", loosing it\n"; } terminate_cleanup(); // We should never go there as the scheduler will have terminated us. abort(); } void Job::terminate_now() { if (!terminated()) async_throw(TerminateException()); } void Job::terminate_cleanup() { // Remove pending links. foreach (const rJob& job, links_) job->links_.remove(this); links_.clear(); // Wake-up waiting jobs. foreach (const rJob& job, to_wake_up_) if (!job->terminated()) job->state_set(running); to_wake_up_.clear(); state_ = zombie; scheduler_.resume_scheduler(this); } void Job::yield_until_terminated(Job& other) { if (non_interruptible_ && this != &other) throw object::SchedulingError ("dependency on other task in non-interruptible code"); if (!other.terminated()) { // We allow enqueuing on ourselves, but without doing it for real. if (&other != this) other.to_wake_up_.push_back(this); state_ = joining; try { scheduler_.resume_scheduler(this); } catch (...) { // We have been awoken by an exception; in this case, // dequeue ourselves from the other thread queue if // we are still enqueued there. libport::erase_if(other.to_wake_up_, boost::lambda::_1 == this); throw; } } } void Job::yield_until_terminated(const jobs_type& jobs) { foreach (const rJob& job, jobs) yield_until_terminated(*job); } void Job::yield_until_things_changed() { if (non_interruptible_ && !frozen()) throw object::SchedulingError ("attempt to wait for condition changes in non-interruptible code"); state_ = waiting; scheduler_.resume_scheduler(this); } bool Job::frozen() const { return libport::has_if(tags_, boost::mem_fn(&scheduler::Tag::frozen)); } void Job::async_throw(const kernel::exception& e) { pending_exception_ = e.clone(); // A job which has received an exception is no longer side effect // free or non-interruptible. side_effect_free_ = false; non_interruptible_ = false; // If this is the current job we are talking about, the exception // is synchronous. if (scheduler_.is_current_job(*this)) check_for_pending_exception(); // Now that we acquired an exception to raise, we are active again, // even if we were previously sleeping or waiting for something. if (state_ != to_start && state_ != zombie) state_ = running; } void Job::register_stopped_tag(const Tag& tag, const boost::any& payload) { size_t max_tag_check = tags_.size(); if (pending_exception_) { // If we are going to terminate, do nothing if (dynamic_cast<TerminateException*>(pending_exception_.get())) return; // If we already have a StopException stored, do not go any // further. StopException* exc = dynamic_cast<StopException*>(pending_exception_.get()); if (exc) max_tag_check = exc->depth_get(); } // Check if we are affected by this tag, up-to max_tag_check from // the beginning of the tag list. for (unsigned int i = 0; i < max_tag_check; i++) if (tags_[i]->derives_from(tag)) { async_throw(StopException(i, payload)); return; } } void Job::check_for_pending_exception() { // If an exception has been stored for further rethrow, now is // a good time to do so. if (pending_exception_) { current_exception_ = pending_exception_; pending_exception_ = 0; kernel::rethrow(current_exception_); } } void Job::recompute_prio() { if (tags_.empty()) { prio_ = UPRIO_DEFAULT; return; } prio_ = UPRIO_MIN; foreach(const rTag& tag, tags_) prio_ = std::max(prio_, tag->prio_get()); } void Job::recompute_prio(const Tag& tag) { if (tag.prio_get() >= prio_ || tags_.empty()) recompute_prio(); } unsigned int Job::alive_jobs() { return alive_jobs_; } } <|endoftext|>
<commit_before>/* Copyright (c) 2010-2019, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <pluginlib/class_list_macros.h> #include <nodelet/nodelet.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/io/pcd_io.h> #include <pcl/filters/voxel_grid.h> #include <pcl_ros/transforms.h> #include <tf/transform_listener.h> #include <nav_msgs/Odometry.h> #include <sensor_msgs/PointCloud2.h> #include <message_filters/subscriber.h> #include <message_filters/sync_policies/exact_time.h> #include <rtabmap_ros/MsgConversion.h> #include <rtabmap_ros/OdomInfo.h> #include <rtabmap/core/util3d.h> #include <rtabmap/core/util3d_filtering.h> namespace rtabmap_ros { /** * This nodelet can assemble a number of clouds (max_clouds) coming * from the same sensor, taking into account the displacement of the robot based on * fixed_frame_id, then publish the resulting cloud. * If fixed_frame_id is set to "" (empty), the nodelet will subscribe to * an odom topic that should have the exact same stamp than to input cloud. * The output cloud has the same stamp and frame than the last assembled cloud. */ class PointCloudAssembler : public nodelet::Nodelet { public: PointCloudAssembler() : warningThread_(0), callbackCalled_(false), exactSync_(0), exactInfoSync_(0), maxClouds_(0), assemblingTime_(0), skipClouds_(0), cloudsSkipped_(0), circularBuffer_(false), waitForTransformDuration_(0.1), rangeMin_(0), rangeMax_(0), voxelSize_(0), fixedFrameId_("odom") {} virtual ~PointCloudAssembler() { delete exactSync_; delete exactInfoSync_; if(warningThread_) { callbackCalled_=true; warningThread_->join(); delete warningThread_; } } private: virtual void onInit() { ros::NodeHandle & nh = getNodeHandle(); ros::NodeHandle & pnh = getPrivateNodeHandle(); int queueSize = 5; bool subscribeOdomInfo = false; pnh.param("queue_size", queueSize, queueSize); pnh.param("fixed_frame_id", fixedFrameId_, fixedFrameId_); pnh.param("max_clouds", maxClouds_, maxClouds_); pnh.param("assembling_time", assemblingTime_, assemblingTime_); pnh.param("skip_clouds", skipClouds_, skipClouds_); pnh.param("circular_buffer", circularBuffer_, circularBuffer_); pnh.param("wait_for_transform_duration", waitForTransformDuration_, waitForTransformDuration_); pnh.param("range_min", rangeMin_, rangeMin_); pnh.param("range_max", rangeMax_, rangeMax_); pnh.param("voxel_size", voxelSize_, voxelSize_); pnh.param("subscribe_odom_info", subscribeOdomInfo, subscribeOdomInfo); ROS_ASSERT(maxClouds_>0 || assemblingTime_ >0.0); ROS_INFO("%s: queue_size=%d", getName().c_str(), queueSize); ROS_INFO("%s: fixed_frame_id=%s", getName().c_str(), fixedFrameId_.c_str()); ROS_INFO("%s: max_clouds=%d", getName().c_str(), maxClouds_); ROS_INFO("%s: assembling_time=%fs", getName().c_str(), assemblingTime_); ROS_INFO("%s: skip_clouds=%d", getName().c_str(), skipClouds_); ROS_INFO("%s: circular_buffer=%s", getName().c_str(), circularBuffer_?"true":"false"); ROS_INFO("%s: wait_for_transform_duration=%f", getName().c_str(), waitForTransformDuration_); ROS_INFO("%s: range_min=%f", getName().c_str(), rangeMin_); ROS_INFO("%s: range_max=%f", getName().c_str(), rangeMax_); ROS_INFO("%s: voxel_size=%fm", getName().c_str(), voxelSize_); cloudsSkipped_ = skipClouds_; std::string subscribedTopicsMsg; if(!fixedFrameId_.empty()) { cloudSub_ = nh.subscribe("cloud", 1, &PointCloudAssembler::callbackCloud, this); subscribedTopicsMsg = uFormat("\n%s subscribed to %s", getName().c_str(), cloudSub_.getTopic().c_str()); } else if(subscribeOdomInfo) { syncCloudSub_.subscribe(nh, "cloud", 1); syncOdomSub_.subscribe(nh, "odom", 1); syncOdomInfoSub_.subscribe(nh, "odom_info", 1); exactInfoSync_ = new message_filters::Synchronizer<syncInfoPolicy>(syncInfoPolicy(queueSize), syncCloudSub_, syncOdomSub_, syncOdomInfoSub_); exactInfoSync_->registerCallback(boost::bind(&rtabmap_ros::PointCloudAssembler::callbackCloudOdomInfo, this, _1, _2, _3)); subscribedTopicsMsg = uFormat("\n%s subscribed to (exact sync):\n %s,\n %s", getName().c_str(), syncCloudSub_.getTopic().c_str(), syncOdomSub_.getTopic().c_str(), syncOdomInfoSub_.getTopic().c_str()); warningThread_ = new boost::thread(boost::bind(&PointCloudAssembler::warningLoop, this, subscribedTopicsMsg)); } else { syncCloudSub_.subscribe(nh, "cloud", 1); syncOdomSub_.subscribe(nh, "odom", 1); exactSync_ = new message_filters::Synchronizer<syncPolicy>(syncPolicy(queueSize), syncCloudSub_, syncOdomSub_); exactSync_->registerCallback(boost::bind(&rtabmap_ros::PointCloudAssembler::callbackCloudOdom, this, _1, _2)); subscribedTopicsMsg = uFormat("\n%s subscribed to (exact sync):\n %s,\n %s", getName().c_str(), syncCloudSub_.getTopic().c_str(), syncOdomSub_.getTopic().c_str()); warningThread_ = new boost::thread(boost::bind(&PointCloudAssembler::warningLoop, this, subscribedTopicsMsg)); } cloudPub_ = nh.advertise<sensor_msgs::PointCloud2>("assembled_cloud", 1); NODELET_INFO("%s", subscribedTopicsMsg.c_str()); } void callbackCloudOdom( const sensor_msgs::PointCloud2ConstPtr & cloudMsg, const nav_msgs::OdometryConstPtr & odomMsg) { callbackCalled_ = true; rtabmap::Transform odom = rtabmap_ros::transformFromPoseMsg(odomMsg->pose.pose); if(!odom.isNull()) { fixedFrameId_ = odomMsg->header.frame_id; callbackCloud(cloudMsg); } else { NODELET_WARN("Reseting point cloud assembler as null odometry has been received."); clouds_.clear(); } } void callbackCloudOdomInfo( const sensor_msgs::PointCloud2ConstPtr & cloudMsg, const nav_msgs::OdometryConstPtr & odomMsg, const rtabmap_ros::OdomInfoConstPtr & odomInfoMsg) { callbackCalled_ = true; rtabmap::Transform odom = rtabmap_ros::transformFromPoseMsg(odomMsg->pose.pose); if(!odom.isNull()) { if(odomInfoMsg->keyFrameAdded) { fixedFrameId_ = odomMsg->header.frame_id; callbackCloud(cloudMsg); } else { NODELET_INFO("Skipping non keyframe..."); } } else { NODELET_WARN("Reseting point cloud assembler as null odometry has been received."); clouds_.clear(); } } void callbackCloud(const sensor_msgs::PointCloud2ConstPtr & cloudMsg) { if(cloudPub_.getNumSubscribers()) { if(skipClouds_<=0 || cloudsSkipped_ >= skipClouds_) { cloudsSkipped_ = 0; rtabmap::Transform t = rtabmap_ros::getTransform( fixedFrameId_, //fromFrame cloudMsg->header.frame_id, //toFrame cloudMsg->header.stamp, tfListener_, waitForTransformDuration_); if(t.isNull()) { ROS_ERROR("Cloud not transform all clouds! Resetting..."); clouds_.clear(); return; } pcl::PCLPointCloud2::Ptr newCloud(new pcl::PCLPointCloud2); if(rangeMin_ > 0.0 || rangeMax_ > 0.0 || voxelSize_ > 0.0f) { pcl_conversions::toPCL(*cloudMsg, *newCloud); rtabmap::LaserScan scan = rtabmap::util3d::laserScanFromPointCloud(*newCloud); scan = rtabmap::util3d::commonFiltering(scan, 1, rangeMin_, rangeMax_, voxelSize_); pcl::uint64_t stamp = newCloud->header.stamp; newCloud = rtabmap::util3d::laserScanToPointCloud2(scan, t); newCloud->header.stamp = stamp; } else { sensor_msgs::PointCloud2 output; pcl_ros::transformPointCloud(t.toEigen4f(), *cloudMsg, output); pcl_conversions::toPCL(output, *newCloud); } clouds_.push_back(newCloud); bool reachedMaxSize = ((int)clouds_.size() >= maxClouds_ && maxClouds_ > 0) || ((*newCloud).header.stamp >= clouds_.front()->header.stamp + static_cast<pcl::uint64_t>(assemblingTime_*1000000.0) && assemblingTime_ > 0.0); if( circularBuffer_ || reachedMaxSize ) { pcl::PCLPointCloud2Ptr assembled(new pcl::PCLPointCloud2); for(std::list<pcl::PCLPointCloud2::Ptr>::iterator iter=clouds_.begin(); iter!=clouds_.end(); ++iter) { if(assembled->data.empty()) { *assembled = *(*iter); } else { pcl::PCLPointCloud2Ptr assembledTmp(new pcl::PCLPointCloud2); pcl::concatenatePointCloud(*assembled, *(*iter), *assembledTmp); assembled = assembledTmp; } } sensor_msgs::PointCloud2 rosCloud; if(voxelSize_>0.0) { pcl::VoxelGrid<pcl::PCLPointCloud2> filter; filter.setLeafSize(voxelSize_, voxelSize_, voxelSize_); filter.setInputCloud(assembled); pcl::PCLPointCloud2Ptr output(new pcl::PCLPointCloud2); filter.filter(*output); assembled = output; } pcl_conversions::moveFromPCL(*assembled, rosCloud); pcl_ros::transformPointCloud(t.toEigen4f().inverse(), rosCloud, rosCloud); rosCloud.header = cloudMsg->header; cloudPub_.publish(rosCloud); if(circularBuffer_) { if(reachedMaxSize) { clouds_.pop_front(); } } else { clouds_.clear(); } } } else { ++cloudsSkipped_; } } } void warningLoop(const std::string & subscribedTopicsMsg) { ros::Duration r(5.0); while(!callbackCalled_) { r.sleep(); if(!callbackCalled_) { ROS_WARN("%s: Did not receive data since 5 seconds! Make sure the input topics are " "published (\"$ rostopic hz my_topic\") and the timestamps in their " "header are set. %s", getName().c_str(), subscribedTopicsMsg.c_str()); } } } private: boost::thread * warningThread_; bool callbackCalled_; ros::Subscriber cloudSub_; ros::Publisher cloudPub_; typedef message_filters::sync_policies::ExactTime<sensor_msgs::PointCloud2, nav_msgs::Odometry> syncPolicy; typedef message_filters::sync_policies::ExactTime<sensor_msgs::PointCloud2, nav_msgs::Odometry, rtabmap_ros::OdomInfo> syncInfoPolicy; message_filters::Synchronizer<syncPolicy>* exactSync_; message_filters::Synchronizer<syncInfoPolicy>* exactInfoSync_; message_filters::Subscriber<sensor_msgs::PointCloud2> syncCloudSub_; message_filters::Subscriber<nav_msgs::Odometry> syncOdomSub_; message_filters::Subscriber<rtabmap_ros::OdomInfo> syncOdomInfoSub_; int maxClouds_; int skipClouds_; int cloudsSkipped_; bool circularBuffer_; double assemblingTime_; double waitForTransformDuration_; double rangeMin_; double rangeMax_; double voxelSize_; std::string fixedFrameId_; tf::TransformListener tfListener_; std::list<pcl::PCLPointCloud2::Ptr> clouds_; }; PLUGINLIB_EXPORT_CLASS(rtabmap_ros::PointCloudAssembler, nodelet::Nodelet); } <commit_msg>Fixed PCL 1.10 deprecated warnings<commit_after>/* Copyright (c) 2010-2019, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <pluginlib/class_list_macros.h> #include <nodelet/nodelet.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/io/pcd_io.h> #include <pcl/filters/voxel_grid.h> #include <pcl_ros/transforms.h> #include <tf/transform_listener.h> #include <nav_msgs/Odometry.h> #include <sensor_msgs/PointCloud2.h> #include <message_filters/subscriber.h> #include <message_filters/sync_policies/exact_time.h> #include <rtabmap_ros/MsgConversion.h> #include <rtabmap_ros/OdomInfo.h> #include <rtabmap/core/util3d.h> #include <rtabmap/core/util3d_filtering.h> namespace rtabmap_ros { /** * This nodelet can assemble a number of clouds (max_clouds) coming * from the same sensor, taking into account the displacement of the robot based on * fixed_frame_id, then publish the resulting cloud. * If fixed_frame_id is set to "" (empty), the nodelet will subscribe to * an odom topic that should have the exact same stamp than to input cloud. * The output cloud has the same stamp and frame than the last assembled cloud. */ class PointCloudAssembler : public nodelet::Nodelet { public: PointCloudAssembler() : warningThread_(0), callbackCalled_(false), exactSync_(0), exactInfoSync_(0), maxClouds_(0), assemblingTime_(0), skipClouds_(0), cloudsSkipped_(0), circularBuffer_(false), waitForTransformDuration_(0.1), rangeMin_(0), rangeMax_(0), voxelSize_(0), fixedFrameId_("odom") {} virtual ~PointCloudAssembler() { delete exactSync_; delete exactInfoSync_; if(warningThread_) { callbackCalled_=true; warningThread_->join(); delete warningThread_; } } private: virtual void onInit() { ros::NodeHandle & nh = getNodeHandle(); ros::NodeHandle & pnh = getPrivateNodeHandle(); int queueSize = 5; bool subscribeOdomInfo = false; pnh.param("queue_size", queueSize, queueSize); pnh.param("fixed_frame_id", fixedFrameId_, fixedFrameId_); pnh.param("max_clouds", maxClouds_, maxClouds_); pnh.param("assembling_time", assemblingTime_, assemblingTime_); pnh.param("skip_clouds", skipClouds_, skipClouds_); pnh.param("circular_buffer", circularBuffer_, circularBuffer_); pnh.param("wait_for_transform_duration", waitForTransformDuration_, waitForTransformDuration_); pnh.param("range_min", rangeMin_, rangeMin_); pnh.param("range_max", rangeMax_, rangeMax_); pnh.param("voxel_size", voxelSize_, voxelSize_); pnh.param("subscribe_odom_info", subscribeOdomInfo, subscribeOdomInfo); ROS_ASSERT(maxClouds_>0 || assemblingTime_ >0.0); ROS_INFO("%s: queue_size=%d", getName().c_str(), queueSize); ROS_INFO("%s: fixed_frame_id=%s", getName().c_str(), fixedFrameId_.c_str()); ROS_INFO("%s: max_clouds=%d", getName().c_str(), maxClouds_); ROS_INFO("%s: assembling_time=%fs", getName().c_str(), assemblingTime_); ROS_INFO("%s: skip_clouds=%d", getName().c_str(), skipClouds_); ROS_INFO("%s: circular_buffer=%s", getName().c_str(), circularBuffer_?"true":"false"); ROS_INFO("%s: wait_for_transform_duration=%f", getName().c_str(), waitForTransformDuration_); ROS_INFO("%s: range_min=%f", getName().c_str(), rangeMin_); ROS_INFO("%s: range_max=%f", getName().c_str(), rangeMax_); ROS_INFO("%s: voxel_size=%fm", getName().c_str(), voxelSize_); cloudsSkipped_ = skipClouds_; std::string subscribedTopicsMsg; if(!fixedFrameId_.empty()) { cloudSub_ = nh.subscribe("cloud", 1, &PointCloudAssembler::callbackCloud, this); subscribedTopicsMsg = uFormat("\n%s subscribed to %s", getName().c_str(), cloudSub_.getTopic().c_str()); } else if(subscribeOdomInfo) { syncCloudSub_.subscribe(nh, "cloud", 1); syncOdomSub_.subscribe(nh, "odom", 1); syncOdomInfoSub_.subscribe(nh, "odom_info", 1); exactInfoSync_ = new message_filters::Synchronizer<syncInfoPolicy>(syncInfoPolicy(queueSize), syncCloudSub_, syncOdomSub_, syncOdomInfoSub_); exactInfoSync_->registerCallback(boost::bind(&rtabmap_ros::PointCloudAssembler::callbackCloudOdomInfo, this, _1, _2, _3)); subscribedTopicsMsg = uFormat("\n%s subscribed to (exact sync):\n %s,\n %s", getName().c_str(), syncCloudSub_.getTopic().c_str(), syncOdomSub_.getTopic().c_str(), syncOdomInfoSub_.getTopic().c_str()); warningThread_ = new boost::thread(boost::bind(&PointCloudAssembler::warningLoop, this, subscribedTopicsMsg)); } else { syncCloudSub_.subscribe(nh, "cloud", 1); syncOdomSub_.subscribe(nh, "odom", 1); exactSync_ = new message_filters::Synchronizer<syncPolicy>(syncPolicy(queueSize), syncCloudSub_, syncOdomSub_); exactSync_->registerCallback(boost::bind(&rtabmap_ros::PointCloudAssembler::callbackCloudOdom, this, _1, _2)); subscribedTopicsMsg = uFormat("\n%s subscribed to (exact sync):\n %s,\n %s", getName().c_str(), syncCloudSub_.getTopic().c_str(), syncOdomSub_.getTopic().c_str()); warningThread_ = new boost::thread(boost::bind(&PointCloudAssembler::warningLoop, this, subscribedTopicsMsg)); } cloudPub_ = nh.advertise<sensor_msgs::PointCloud2>("assembled_cloud", 1); NODELET_INFO("%s", subscribedTopicsMsg.c_str()); } void callbackCloudOdom( const sensor_msgs::PointCloud2ConstPtr & cloudMsg, const nav_msgs::OdometryConstPtr & odomMsg) { callbackCalled_ = true; rtabmap::Transform odom = rtabmap_ros::transformFromPoseMsg(odomMsg->pose.pose); if(!odom.isNull()) { fixedFrameId_ = odomMsg->header.frame_id; callbackCloud(cloudMsg); } else { NODELET_WARN("Reseting point cloud assembler as null odometry has been received."); clouds_.clear(); } } void callbackCloudOdomInfo( const sensor_msgs::PointCloud2ConstPtr & cloudMsg, const nav_msgs::OdometryConstPtr & odomMsg, const rtabmap_ros::OdomInfoConstPtr & odomInfoMsg) { callbackCalled_ = true; rtabmap::Transform odom = rtabmap_ros::transformFromPoseMsg(odomMsg->pose.pose); if(!odom.isNull()) { if(odomInfoMsg->keyFrameAdded) { fixedFrameId_ = odomMsg->header.frame_id; callbackCloud(cloudMsg); } else { NODELET_INFO("Skipping non keyframe..."); } } else { NODELET_WARN("Reseting point cloud assembler as null odometry has been received."); clouds_.clear(); } } void callbackCloud(const sensor_msgs::PointCloud2ConstPtr & cloudMsg) { if(cloudPub_.getNumSubscribers()) { if(skipClouds_<=0 || cloudsSkipped_ >= skipClouds_) { cloudsSkipped_ = 0; rtabmap::Transform t = rtabmap_ros::getTransform( fixedFrameId_, //fromFrame cloudMsg->header.frame_id, //toFrame cloudMsg->header.stamp, tfListener_, waitForTransformDuration_); if(t.isNull()) { ROS_ERROR("Cloud not transform all clouds! Resetting..."); clouds_.clear(); return; } pcl::PCLPointCloud2::Ptr newCloud(new pcl::PCLPointCloud2); if(rangeMin_ > 0.0 || rangeMax_ > 0.0 || voxelSize_ > 0.0f) { pcl_conversions::toPCL(*cloudMsg, *newCloud); rtabmap::LaserScan scan = rtabmap::util3d::laserScanFromPointCloud(*newCloud); scan = rtabmap::util3d::commonFiltering(scan, 1, rangeMin_, rangeMax_, voxelSize_); #if PCL_VERSION_COMPARE(>=, 1, 10, 0) std::uint64_t stamp = newCloud->header.stamp; #else pcl::uint64_t stamp = newCloud->header.stamp; #endif newCloud = rtabmap::util3d::laserScanToPointCloud2(scan, t); newCloud->header.stamp = stamp; } else { sensor_msgs::PointCloud2 output; pcl_ros::transformPointCloud(t.toEigen4f(), *cloudMsg, output); pcl_conversions::toPCL(output, *newCloud); } clouds_.push_back(newCloud); #if PCL_VERSION_COMPARE(>=, 1, 10, 0) bool reachedMaxSize = ((int)clouds_.size() >= maxClouds_ && maxClouds_ > 0) || ((*newCloud).header.stamp >= clouds_.front()->header.stamp + static_cast<std::uint64_t>(assemblingTime_*1000000.0) && assemblingTime_ > 0.0); #else bool reachedMaxSize = ((int)clouds_.size() >= maxClouds_ && maxClouds_ > 0) || ((*newCloud).header.stamp >= clouds_.front()->header.stamp + static_cast<pcl::uint64_t>(assemblingTime_*1000000.0) && assemblingTime_ > 0.0); #endif if( circularBuffer_ || reachedMaxSize ) { pcl::PCLPointCloud2Ptr assembled(new pcl::PCLPointCloud2); for(std::list<pcl::PCLPointCloud2::Ptr>::iterator iter=clouds_.begin(); iter!=clouds_.end(); ++iter) { if(assembled->data.empty()) { *assembled = *(*iter); } else { pcl::PCLPointCloud2Ptr assembledTmp(new pcl::PCLPointCloud2); #if PCL_VERSION_COMPARE(>=, 1, 10, 0) pcl::concatenate(*assembled, *(*iter), *assembledTmp); #else pcl::concatenatePointCloud(*assembled, *(*iter), *assembledTmp); #endif assembled = assembledTmp; } } sensor_msgs::PointCloud2 rosCloud; if(voxelSize_>0.0) { pcl::VoxelGrid<pcl::PCLPointCloud2> filter; filter.setLeafSize(voxelSize_, voxelSize_, voxelSize_); filter.setInputCloud(assembled); pcl::PCLPointCloud2Ptr output(new pcl::PCLPointCloud2); filter.filter(*output); assembled = output; } pcl_conversions::moveFromPCL(*assembled, rosCloud); pcl_ros::transformPointCloud(t.toEigen4f().inverse(), rosCloud, rosCloud); rosCloud.header = cloudMsg->header; cloudPub_.publish(rosCloud); if(circularBuffer_) { if(reachedMaxSize) { clouds_.pop_front(); } } else { clouds_.clear(); } } } else { ++cloudsSkipped_; } } } void warningLoop(const std::string & subscribedTopicsMsg) { ros::Duration r(5.0); while(!callbackCalled_) { r.sleep(); if(!callbackCalled_) { ROS_WARN("%s: Did not receive data since 5 seconds! Make sure the input topics are " "published (\"$ rostopic hz my_topic\") and the timestamps in their " "header are set. %s", getName().c_str(), subscribedTopicsMsg.c_str()); } } } private: boost::thread * warningThread_; bool callbackCalled_; ros::Subscriber cloudSub_; ros::Publisher cloudPub_; typedef message_filters::sync_policies::ExactTime<sensor_msgs::PointCloud2, nav_msgs::Odometry> syncPolicy; typedef message_filters::sync_policies::ExactTime<sensor_msgs::PointCloud2, nav_msgs::Odometry, rtabmap_ros::OdomInfo> syncInfoPolicy; message_filters::Synchronizer<syncPolicy>* exactSync_; message_filters::Synchronizer<syncInfoPolicy>* exactInfoSync_; message_filters::Subscriber<sensor_msgs::PointCloud2> syncCloudSub_; message_filters::Subscriber<nav_msgs::Odometry> syncOdomSub_; message_filters::Subscriber<rtabmap_ros::OdomInfo> syncOdomInfoSub_; int maxClouds_; int skipClouds_; int cloudsSkipped_; bool circularBuffer_; double assemblingTime_; double waitForTransformDuration_; double rangeMin_; double rangeMax_; double voxelSize_; std::string fixedFrameId_; tf::TransformListener tfListener_; std::list<pcl::PCLPointCloud2::Ptr> clouds_; }; PLUGINLIB_EXPORT_CLASS(rtabmap_ros::PointCloudAssembler, nodelet::Nodelet); } <|endoftext|>
<commit_before>/* Copyright (c) 2016, Dennis Wölfing * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* kernel/src/keyboard.cpp * Keyboard. */ #include <stddef.h> #include <dennix/kernel/keyboard.h> // German keyboard layout. static const char KBLAYOUT_DE[] = { 0, 0, 0, 0, 0, 0, 0, 0, // Escape '1', '!', 0, 0, '2', '"', 0/*'²'*/, 0, '3', 0/*'§'*/, 0/*'³'*/, 0, '4', '$', 0, 0, '5', '%', 0, 0, '6', '&', 0, 0, '7', '/', '{', 0, '8', '(', '[', 0, '9', ')', ']', 0, '0', '=', '}', 0, 0/*'ß'*/, '?', '\\', 0, 0/*'´'*/, '`', 0, 0, '\b', '\b', '\b', '\b', '\t', '\t', '\t', '\t', 'q', 'Q', '@', 0, 'w', 'W', 0, 0, 'e', 'E', 0/*'€'*/, 0, 'r', 'R', 0, 0, 't', 'T', 0, 0, 'z', 'Z', 0, 0, 'u', 'U', 0, 0, 'i', 'I', 0, 0, 'o', 'O', 0, 0, 'p', 'P', 0, 0, 0/*'ü'*/, 0/*'Ü'*/, 0, 0, '+', '*', '~', 0, '\n', '\n', '\n', '\n', 0, 0, 0, 0, // left Control 'a', 'A', 0, 0, 's', 'S', 0, 0, 'd', 'D', 0, 0, 'f', 'F', 0, 0, 'g', 'G', 0, 0, 'h', 'H', 0, 0, 'j', 'J', 0, 0, 'k', 'K', 0, 0, 'l', 'L', 0, 0, 0/*'ö'*/, 0/*'Ö'*/, 0, 0, 0/*'ä'*/, 0/*'Ä'*/, 0, 0, '^', 0/*'°'*/, 0, 0, 0, 0, 0, 0, // left Shift '#', '\'', 0, 0, 'y', 'Y', 0, 0, 'x', 'X', 0, 0, 'c', 'C', 0, 0, 'v', 'V', 0, 0, 'b', 'B', 0, 0, 'n', 'N', 0, 0, 'm', 'M', 0/*'µ'*/, 0, ',', ';', 0, 0, '.', ':', 0, 0, '-', '_', 0, 0, 0, 0, 0, 0, // right Shift '*', '*', '*', '*', 0, 0, 0, 0, // left Alt ' ', ' ', ' ', ' ', 0, 0, 0, 0, // Caps Lock 0, 0, 0, 0, // F1 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F10 0, 0, 0, 0, // Num Lock 0, 0, 0, 0, // Scroll Lock '7', 0, '7', 0, '8', 0, '8', 0, '9', 0, '9', 0, '-', '-', '-', '-', '4', 0, '4', 0, '5', 0, '5', 0, '6', 0, '6', 0, '+', '+', '+', '+', '1', 0, '1', 0, '2', 0, '2', 0, '3', 0, '3', 0, '0', 0, '0', 0, ',', 0, ',', 0, 0, 0, 0, 0, 0, 0, 0, 0, '<', '>', '|', 0, 0, 0, 0, 0, // F11 0, 0, 0, 0, // F12 // Most things below are not printable }; char Keyboard::getCharFromKey(int key) { static bool leftShift = false; static bool rightShift = false; static bool capsLock = false; static bool altGr = false; if (key == 0x2A) { leftShift = true; } else if (key == 0x36) { rightShift = true; } else if (key == 0x3A) { capsLock = !capsLock; } else if (key == 0xB8) { altGr = true; } else if (key == -0x2A) { leftShift = false; } else if (key == -0x36) { rightShift = false; } else if (key == -0xB8) { altGr = false; } if (key < 0) return '\0'; size_t index = key << 2 | altGr << 1 | ((leftShift || rightShift) ^ capsLock); if (index < sizeof(KBLAYOUT_DE)) { return KBLAYOUT_DE[index]; } if (key == 0x9C) { return '\n'; } else if (key == 0xB5) { return '/'; } return '\0'; } <commit_msg>Switch to US keyboard layout.<commit_after>/* Copyright (c) 2016, Dennis Wölfing * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* kernel/src/keyboard.cpp * Keyboard. */ #include <stddef.h> #include <dennix/kernel/keyboard.h> // US keyboard layout. static const char KBLAYOUT_US[] = { // No modifiers, Shift, Caps, Shift + Caps, 0, 0, 0, 0, 0, 0, 0, 0, // Escape '1', '!', '1', '!', '2', '@', '2', '@', '3', '#', '3', '#', '4', '$', '4', '$', '5', '%', '5', '%', '6', '^', '6', '^', '7', '&', '7', '&', '8', '*', '8', '*', '9', '(', '9', '(', '0', ')', '0', ')', '-', '_', '-', '_', '=', '+', '=', '+', '\b', '\b', '\b', '\b', '\t', '\t', '\t', '\t', 'q', 'Q', 'Q', 'q', 'w', 'W', 'W', 'w', 'e', 'E', 'E', 'e', 'r', 'R', 'R', 'r', 't', 'T', 'T', 't', 'y', 'Y', 'Y', 'y', 'u', 'U', 'U', 'u', 'i', 'I', 'I', 'i', 'o', 'O', 'O', 'o', 'p', 'P', 'P', 'p', '[', '{', '[', '{', ']', '}', ']', '}', '\n', '\n', '\n', '\n', 0, 0, 0, 0, // left Control 'a', 'A', 'A', 'a', 's', 'S', 'S', 's', 'd', 'D', 'D', 'd', 'f', 'F', 'F', 'f', 'g', 'G', 'G', 'g', 'h', 'H', 'H', 'h', 'j', 'J', 'J', 'j', 'k', 'K', 'K', 'k', 'l', 'L', 'L', 'l', ';', ':', ';', ':', '\'', '"', '\'', '"', '`', '~', '`', '~', 0, 0, 0, 0, // left Shift '\\', '|', '\\', '|', 'z', 'Z', 'Z', 'z', 'x', 'X', 'X', 'x', 'c', 'C', 'C', 'c', 'v', 'V', 'V', 'v', 'b', 'B', 'B', 'b', 'n', 'N', 'N', 'n', 'm', 'M', 'M', 'm', ',', '<', ',', '<', '.', '>', '.', '>', '/', '?', '/', '?', 0, 0, 0, 0, // right Shift '*', '*', '*', '*', 0, 0, 0, 0, // left Alt ' ', ' ', ' ', ' ', 0, 0, 0, 0, // Caps Lock 0, 0, 0, 0, // F1 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F10 0, 0, 0, 0, // Num Lock 0, 0, 0, 0, // Scroll Lock '7', 0, '7', 0, '8', 0, '8', 0, '9', 0, '9', 0, '-', '-', '-', '-', '4', 0, '4', 0, '5', 0, '5', 0, '6', 0, '6', 0, '+', '+', '+', '+', '1', 0, '1', 0, '2', 0, '2', 0, '3', 0, '3', 0, '0', 0, '0', 0, '.', 0, '.', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F11 0, 0, 0, 0, // F12 // Most things below are not printable }; char Keyboard::getCharFromKey(int key) { static bool leftShift = false; static bool rightShift = false; static bool capsLock = false; if (key == 0x2A) { leftShift = true; } else if (key == 0x36) { rightShift = true; } else if (key == 0x3A) { capsLock = !capsLock; } else if (key == -0x2A) { leftShift = false; } else if (key == -0x36) { rightShift = false; } if (key < 0) return '\0'; size_t index = key << 2 | (capsLock << 1) | (leftShift || rightShift); if (index < sizeof(KBLAYOUT_US)) { return KBLAYOUT_US[index]; } if (key == 0x9C) { return '\n'; } else if (key == 0xB5) { return '/'; } return '\0'; } <|endoftext|>
<commit_before>#include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <vector> #include <string> struct LLVMCodeGen { using IRBuilder = llvm::IRBuilder<>; llvm::LLVMContext &Context; llvm::Module &M; IRBuilder &Builder; LLVMCodeGen(llvm::LLVMContext &context, llvm::Module &m, llvm::IRBuilder<> &builder) : Context(context), M(m), Builder(builder) {} void dump() const { M.dump(); } // ----------------------- Value ------------------------------------------- struct Value { LLVMCodeGen &CG; llvm::Value &V; Value(LLVMCodeGen &cg, llvm::Value &value) : CG(cg), V(value) {} operator llvm::Value *() { return &V; } Value operator*(Value R) const { return Value{CG, *CG.Builder.CreateMul(&V, R, "mul")}; } }; //----------------------- Type --------------------------------------------- struct Type { enum Kind { int32, float32, float64 }; LLVMCodeGen const &CG; Kind TypeKind; Type(LLVMCodeGen const &cg, Kind type_kind) : CG(cg), TypeKind(type_kind) {} operator llvm::Type *() const { switch (TypeKind) { case int32: return CG.Builder.getInt32Ty(); case float32: return CG.Builder.getFloatTy(); case float64: return CG.Builder.getDoubleTy(); default: assert(0 && "Must not happen"); } } size_t size() const { switch (TypeKind) { case int32: case float32: return 4; case float64: return 8; default: assert(0 && "Must not happen"); } return 0; } }; // --------------------- Global Variable ----------------------------------- struct GlobalVar { LLVMCodeGen &CG; llvm::GlobalVariable &Var; GlobalVar(LLVMCodeGen &cg, llvm::GlobalVariable &var) : CG(cg), Var(var) {} }; GlobalVar mkGlobalVar(std::string name, Type type) { M.getOrInsertGlobal(name, type); llvm::GlobalVariable *gvar = M.getNamedGlobal(name); gvar->setLinkage(llvm::GlobalValue::CommonLinkage); gvar->setAlignment(type.size()); return GlobalVar{*this, *gvar}; } //---------------------- Function ------------------------------------------- struct Function { LLVMCodeGen &CG; llvm::Function &F; std::vector<llvm::Value*> Args; Function(LLVMCodeGen &cg, llvm::Function &f) : CG(cg), F(f) { Args.reserve(16); for (auto &arg : F.args()) { Args.push_back(&arg); } } void verify() const { llvm::verifyFunction(F); } operator llvm::Function *() { return &F; } Value arg(size_t num) const { assert(num < Args.size()); return Value{CG, *Args[num]}; } }; Function mkFunction(std::string name, Type ret_type, std::vector<std::pair<Type, std::string>> args = {}) { std::vector<llvm::Type*> args_type; args_type.reserve(args.size()); for (auto arg : args) { args_type.push_back(arg.first); } llvm::FunctionType *funcType = llvm::FunctionType::get(ret_type, args_type, false); llvm::Function *func = llvm::Function::Create( funcType, llvm::Function::ExternalLinkage, name, &M); int count = 0; for (auto &arg : func->args()) { arg.setName(args[count++].second); } return Function{*this, *func}; } //------------------- Basic Block ------------------------------------------- struct BasicBlock { LLVMCodeGen &CG; llvm::BasicBlock &BB; BasicBlock(LLVMCodeGen &cg, llvm::BasicBlock &bb) : CG(cg), BB(bb) {} operator llvm::BasicBlock *() { return &BB; } void set() { CG.Builder.SetInsertPoint(&BB); } }; BasicBlock mkBasicBlock(Function &func, std::string name) { llvm::BasicBlock *bb = llvm::BasicBlock::Create(Context, name, func); return BasicBlock{*this, *bb}; } // ------------- type & vals Type mkInt() { return Type(*this, Type::int32); } Value mkInt(int val) { return {*this, *Builder.getInt32(val)}; } Type mkFloat() { return Type(*this, Type::float32); } Type mkDouble() { return Type(*this, Type::float64); } //-------------------- Ops void mkRet(Value val) { Builder.CreateRet(val); } }; static llvm::LLVMContext &ContextRef = llvm::getGlobalContext(); static llvm::Module *ModuleOb = new llvm::Module("my compiler", ContextRef); int main(int argc, char *argv[]) { static llvm::IRBuilder<> BuilderObj(ContextRef); LLVMCodeGen cg(ContextRef, *ModuleOb, BuilderObj); auto gvar = cg.mkGlobalVar("x", cg.mkFloat()); auto f = cg.mkFunction("foo", cg.mkInt(), {{cg.mkInt(), "a"}, {cg.mkFloat(), "b"}}); auto entry = cg.mkBasicBlock(f, "entry"); entry.set(); auto constant = cg.mkInt(16); auto val = constant * f.arg(0); cg.mkRet(val); f.verify(); cg.dump(); return 0; } <commit_msg>move basic block creation under function<commit_after>#include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <vector> #include <string> struct LLVMCodeGen { using IRBuilder = llvm::IRBuilder<>; llvm::LLVMContext &Context; llvm::Module &M; IRBuilder &Builder; LLVMCodeGen(llvm::LLVMContext &context, llvm::Module &m, llvm::IRBuilder<> &builder) : Context(context), M(m), Builder(builder) {} void dump() const { M.dump(); } // ----------------------- Value ------------------------------------------- struct Value { LLVMCodeGen &CG; llvm::Value &V; Value(LLVMCodeGen &cg, llvm::Value &value) : CG(cg), V(value) {} operator llvm::Value *() { return &V; } Value operator*(Value R) const { return Value{CG, *CG.Builder.CreateMul(&V, R, "mul")}; } }; //----------------------- Type --------------------------------------------- struct Type { enum Kind { int32, float32, float64 }; LLVMCodeGen const &CG; Kind TypeKind; Type(LLVMCodeGen const &cg, Kind type_kind) : CG(cg), TypeKind(type_kind) {} operator llvm::Type *() const { switch (TypeKind) { case int32: return CG.Builder.getInt32Ty(); case float32: return CG.Builder.getFloatTy(); case float64: return CG.Builder.getDoubleTy(); default: assert(0 && "Must not happen"); } } size_t size() const { switch (TypeKind) { case int32: case float32: return 4; case float64: return 8; default: assert(0 && "Must not happen"); } return 0; } }; // --------------------- Global Variable ----------------------------------- struct GlobalVar { LLVMCodeGen &CG; llvm::GlobalVariable &Var; GlobalVar(LLVMCodeGen &cg, llvm::GlobalVariable &var) : CG(cg), Var(var) {} }; GlobalVar mkGlobalVar(std::string name, Type type) { M.getOrInsertGlobal(name, type); llvm::GlobalVariable *gvar = M.getNamedGlobal(name); gvar->setLinkage(llvm::GlobalValue::CommonLinkage); gvar->setAlignment(type.size()); return GlobalVar{*this, *gvar}; } //------------------- Basic Block ------------------------------------------- struct BasicBlock { LLVMCodeGen &CG; llvm::BasicBlock &BB; BasicBlock(LLVMCodeGen &cg, llvm::BasicBlock &bb) : CG(cg), BB(bb) {} operator llvm::BasicBlock *() { return &BB; } void set() { CG.Builder.SetInsertPoint(&BB); } }; //---------------------- Function ------------------------------------------- struct Function { LLVMCodeGen &CG; llvm::Function &F; std::vector<llvm::Value*> Args; Function(LLVMCodeGen &cg, llvm::Function &f) : CG(cg), F(f) { Args.reserve(16); for (auto &arg : F.args()) { Args.push_back(&arg); } } void verify() const { llvm::verifyFunction(F); } operator llvm::Function *() { return &F; } Value arg(size_t num) const { assert(num < Args.size()); return Value{CG, *Args[num]}; } BasicBlock mkBasicBlock(std::string name) { llvm::BasicBlock *bb = llvm::BasicBlock::Create(CG.Context, name, &F); return {CG, *bb}; } }; Function mkFunction(std::string name, Type ret_type, std::vector<std::pair<Type, std::string>> args = {}) { std::vector<llvm::Type*> args_type; args_type.reserve(args.size()); for (auto arg : args) { args_type.push_back(arg.first); } llvm::FunctionType *funcType = llvm::FunctionType::get(ret_type, args_type, false); llvm::Function *func = llvm::Function::Create( funcType, llvm::Function::ExternalLinkage, name, &M); int count = 0; for (auto &arg : func->args()) { arg.setName(args[count++].second); } return Function{*this, *func}; } // ------------- type & vals Type mkInt() { return Type(*this, Type::int32); } Value mkInt(int val) { return {*this, *Builder.getInt32(val)}; } Type mkFloat() { return Type(*this, Type::float32); } Type mkDouble() { return Type(*this, Type::float64); } //-------------------- Ops void mkRet(Value val) { Builder.CreateRet(val); } }; static llvm::LLVMContext &ContextRef = llvm::getGlobalContext(); static llvm::Module *ModuleOb = new llvm::Module("my compiler", ContextRef); int main(int argc, char *argv[]) { static llvm::IRBuilder<> BuilderObj(ContextRef); LLVMCodeGen cg(ContextRef, *ModuleOb, BuilderObj); auto gvar = cg.mkGlobalVar("x", cg.mkFloat()); auto f = cg.mkFunction("foo", cg.mkInt(), {{cg.mkInt(), "a"}, {cg.mkFloat(), "b"}}); auto entry = f.mkBasicBlock("entry"); entry.set(); auto constant = cg.mkInt(16); auto val = constant * f.arg(0); cg.mkRet(val); f.verify(); cg.dump(); return 0; } <|endoftext|>
<commit_before>/*************************************************************************** FilterPAB.cxx - description ------------------- begin : Fri Jun 30 2000 copyright : (C) 2000 by Hans Dijkema email : kmailcvt@hum.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "filter_pab.hxx" #include "pablib.hxx" #include <kfiledialog.h> FilterPAB::FilterPAB() : Filter(i18n("Import MS Exchange Personal Address Book (.PAB)"),"Hans Dijkema") { } FilterPAB::~FilterPAB() { } void FilterPAB::import(FilterInfo *info) { QString file; QWidget *parent=info->parent(); file=KFileDialog::getOpenFileName(QDir::homeDirPath(),"*.pab *.PAB *.Pab",parent); if (file.isEmpty()) { info->alert(i18n("No address book chosen")); return; } { pab PAB(QFile::encodeName(file),this,info); info->setFrom(file); info->setTo(i18n("KAddressBook")); info->setCurrent(i18n("Currently converting .PAB addresses to Kab")); PAB.convert(); info->setCurrent(i18n("Finished converting .PAB addresses to Kab")); } } // vim: ts=2 sw=2 et <commit_msg>Cleanup file filter code<commit_after>/*************************************************************************** FilterPAB.cxx - description ------------------- begin : Fri Jun 30 2000 copyright : (C) 2000 by Hans Dijkema email : kmailcvt@hum.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "filter_pab.hxx" #include "pablib.hxx" #include <kfiledialog.h> FilterPAB::FilterPAB() : Filter(i18n("Import MS Exchange Personal Address Book (.PAB)"),"Hans Dijkema") { } FilterPAB::~FilterPAB() { } void FilterPAB::import(FilterInfo *info) { QString file = KFileDialog::getOpenFileName(QDir::homeDirPath(),"*.[pP][aA][bB]|MS Personal Address Book Files (*.pab)", info->parent()); if (file.isEmpty()) { info->alert(i18n("No address book chosen")); return; } { pab PAB(QFile::encodeName(file),this,info); info->setFrom(file); info->setTo(i18n("KAddressBook")); info->setCurrent(i18n("Currently converting .PAB addresses to Kab")); PAB.convert(); info->setCurrent(i18n("Finished converting .PAB addresses to Kab")); } } // vim: ts=2 sw=2 et <|endoftext|>
<commit_before>/******************************************************************** * * Software License Agreement (BSD License) * * Copyright (c) 2012, Max-Planck-Gesellschaft * Copyright (c) 2012-2015, Inria * 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 holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ********************************************************************/ #ifndef GENERICSUBSCRIBER_HPP_ #define GENERICSUBSCRIBER_HPP_ #include <boost/thread/mutex.hpp> #include <semaphore.h> //#include <sys/sem.h> //#include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <ros/node_handle.h> #ifndef GENERATESEMAPHORENAME #define GENERATESEMAPHORENAME #endif class GenericSubscriber_base { public: static void resetSemaphore(sem_t* sem){ int valp; sem_getvalue(sem, &valp); while ( valp > 0){ sem_wait(sem); sem_getvalue(sem, &valp); } } static std::string generateSemaphoreName(std::string const & topicName) { std::string semName(topicName); if (topicName[0] == '/'){ semName.erase(0,1); } std::replace(semName.begin(), semName.end(), '/', '_'); semName = "slk." + semName; return semName; } }; template <class T_> class GenericSubscriber : public GenericSubscriber_base { protected: boost::shared_ptr<T_ const> lastMsg; mutable boost::mutex lastMsgLock; const std::string semName; sem_t * newMsg; // Subscriber ros::Subscriber sub; void msgCallback(boost::shared_ptr<T_ const> msg) { boost::mutex::scoped_lock lock(lastMsgLock); lastMsg = msg; sem_post(newMsg); } public: void resetSem(){ boost::mutex::scoped_lock lock(lastMsgLock); resetSemaphore(newMsg); } int waitMsg(const double timeout=-1){ if (timeout<0){ return sem_wait(newMsg); } else { const int wait_sec = (int) timeout; const int wait_nsec = (int)((timeout - (int)timeout)*1e9); timespec waitSpec; clock_gettime(CLOCK_REALTIME, &waitSpec); waitSpec.tv_sec += wait_sec; waitSpec.tv_nsec += wait_nsec; return sem_timedwait(newMsg, &waitSpec); } } GenericSubscriber(ros::NodeHandle handle, const std::string& topicName, int queue_size) : semName(generateSemaphoreName(topicName)), newMsg(sem_open(semName.c_str(), O_CREAT, 0644, 0)), sub(handle.subscribe(topicName, queue_size, &GenericSubscriber<T_>::msgCallback, this)){ // std::cout << "Opening semaphore in " << __func__ << " in file /dev/shm/sem." << semName << std::endl; if (newMsg == SEM_FAILED){ //TODO: ssSetErrorStatus(S, strerror(errno)); // std::cout << " returned SEM_FAILED with error: " << strerror(errno); } } virtual ~GenericSubscriber() { boost::mutex::scoped_lock lock(lastMsgLock); // lastMsg = boost::shared_ptr<T_ const> (new T_); sem_close(newMsg); sem_unlink(semName.c_str()); } boost::shared_ptr<T_ const> getLastMsg() const { boost::mutex::scoped_lock lock(lastMsgLock); return lastMsg; } }; #endif /* GENERICSUBSCRIBER_HPP_ */ <commit_msg>get topic name from generic subscriber<commit_after>/******************************************************************** * * Software License Agreement (BSD License) * * Copyright (c) 2012, Max-Planck-Gesellschaft * Copyright (c) 2012-2015, Inria * 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 holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ********************************************************************/ #ifndef GENERICSUBSCRIBER_HPP_ #define GENERICSUBSCRIBER_HPP_ #include <boost/thread/mutex.hpp> #include <semaphore.h> //#include <sys/sem.h> //#include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <ros/node_handle.h> #ifndef GENERATESEMAPHORENAME #define GENERATESEMAPHORENAME #endif class GenericSubscriber_base { public: static void resetSemaphore(sem_t* sem){ int valp; sem_getvalue(sem, &valp); while ( valp > 0){ sem_wait(sem); sem_getvalue(sem, &valp); } } static std::string generateSemaphoreName(std::string const & topicName) { std::string semName(topicName); if (topicName[0] == '/'){ semName.erase(0,1); } std::replace(semName.begin(), semName.end(), '/', '_'); semName = "slk." + semName; return semName; } }; template <class T_> class GenericSubscriber : public GenericSubscriber_base { protected: boost::shared_ptr<T_ const> lastMsg; mutable boost::mutex lastMsgLock; const std::string semName; sem_t * newMsg; const std::string tName; // Subscriber ros::Subscriber sub; void msgCallback(boost::shared_ptr<T_ const> msg) { boost::mutex::scoped_lock lock(lastMsgLock); lastMsg = msg; sem_post(newMsg); } public: std::string getTopicName(){return tName;}; void resetSem(){ boost::mutex::scoped_lock lock(lastMsgLock); resetSemaphore(newMsg); } int waitMsg(const double timeout=-1){ if (timeout<0){ return sem_wait(newMsg); } else { const int wait_sec = (int) timeout; const int wait_nsec = (int)((timeout - (int)timeout)*1e9); timespec waitSpec; clock_gettime(CLOCK_REALTIME, &waitSpec); waitSpec.tv_sec += wait_sec; waitSpec.tv_nsec += wait_nsec; return sem_timedwait(newMsg, &waitSpec); } } GenericSubscriber(ros::NodeHandle handle, const std::string& topicName, int queue_size) : semName(generateSemaphoreName(topicName)), newMsg(sem_open(semName.c_str(), O_CREAT, 0644, 0)), sub(handle.subscribe(topicName, queue_size, &GenericSubscriber<T_>::msgCallback, this)), tName(topicName){ // std::cout << "Opening semaphore in " << __func__ << " in file /dev/shm/sem." << semName << std::endl; if (newMsg == SEM_FAILED){ //TODO: ssSetErrorStatus(S, strerror(errno)); // std::cout << " returned SEM_FAILED with error: " << strerror(errno); } } virtual ~GenericSubscriber() { boost::mutex::scoped_lock lock(lastMsgLock); // lastMsg = boost::shared_ptr<T_ const> (new T_); sem_close(newMsg); sem_unlink(semName.c_str()); } boost::shared_ptr<T_ const> getLastMsg() const { boost::mutex::scoped_lock lock(lastMsgLock); return lastMsg; } }; #endif /* GENERICSUBSCRIBER_HPP_ */ <|endoftext|>
<commit_before>/* knrangefilter.cpp KNode, the KDE newsreader Copyright (c) 1999-2001 the KNode authors. See file AUTHORS for details This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US */ #include <qlabel.h> #include <qlayout.h> #include <qcheckbox.h> #include <qcombobox.h> #include <ksimpleconfig.h> #include <knuminput.h> #include "knrangefilter.h" bool KNRangeFilter::doFilter(int a) { bool ret=true; if(enabled) { switch (op1) { case gt: case gtoeq: if (op2 != dis) ret=( matchesOp(val1,op1,a) && matchesOp(a,op2,val2) ); else ret = matchesOp(val1,op1,a);; break; case eq: case lt: case ltoeq: ret = matchesOp(val1,op1,a); break; default: ret = false; } } return ret; } bool KNRangeFilter::matchesOp(int v1, Op o, int v2) { bool ret=false; switch(o) { case eq: ret=(v1==v2); break; case gt: ret=(v1<v2); break; case gtoeq: ret=(v1<=v2); break; case ltoeq: ret=(v1>=v2); break; case lt: ret=(v1>v2); break; default: ret=false; break; }; return ret; } void KNRangeFilter::load(KSimpleConfig *conf) { enabled=conf->readBoolEntry("enabled", false); val1=conf->readNumEntry("val1",0); op1=(Op) conf->readNumEntry("op1",0); val2=conf->readNumEntry("val2",0); op2=(Op) conf->readNumEntry("op2",0); } void KNRangeFilter::save(KSimpleConfig *conf) { conf->writeEntry("enabled", enabled); conf->writeEntry("val1", val1); conf->writeEntry("op1", (int)op1); conf->writeEntry("op2", (int)op2); conf->writeEntry("val2", val2); } //===================================================================================== //===================================================================================== KNRangeFilterWidget::KNRangeFilterWidget(const QString& value, int min, int max, QWidget* parent, const QString &unit) : QGroupBox(value, parent) { enabled=new QCheckBox(this); val1=new KIntSpinBox(min, max, 1, min, 10, this); val1->setSuffix(unit); val2=new KIntSpinBox(min, max, 1, min, 10, this); val2->setSuffix(unit); op1=new QComboBox(this); op1->insertItem("<"); op1->insertItem("<="); op1->insertItem("="); op1->insertItem(">="); op1->insertItem(">"); op2=new QComboBox(this); op2->insertItem(""); op2->insertItem("<"); op2->insertItem("<="); des=new QLabel(value, this); des->setAlignment(AlignCenter); QGridLayout *topL=new QGridLayout(this, 2,6, 8,5 ); topL->addRowSpacing(0, fontMetrics().lineSpacing()-4); topL->addWidget(enabled,1,0, Qt::AlignHCenter); topL->addColSpacing(0, 30); topL->addWidget(val1,1,1); topL->addWidget(op1,1,2); topL->addWidget(des,1,3); topL->addColSpacing(3, 45); topL->addWidget(op2,1,4); topL->addWidget(val2,1,5); topL->setColStretch(1,1); topL->setColStretch(5,1); connect(op1, SIGNAL(activated(int)), SLOT(slotOp1Changed(int))); connect(op2, SIGNAL(activated(int)), SLOT(slotOp2Changed(int))); connect(enabled, SIGNAL(toggled(bool)), SLOT(slotEnabled(bool))); slotEnabled(false); } KNRangeFilterWidget::~KNRangeFilterWidget() { } KNRangeFilter KNRangeFilterWidget::filter() { KNRangeFilter r; r.val1=val1->value(); r.val2=val2->value(); r.op1=(KNRangeFilter::Op) op1->currentItem(); if (op2->currentText().isEmpty()) r.op2=KNRangeFilter::dis; else if (op2->currentText()=="<") r.op2=KNRangeFilter::gt; else if (op2->currentText()=="<=") r.op2=KNRangeFilter::gtoeq; r.enabled=enabled->isChecked(); return r; } void KNRangeFilterWidget::setFilter(KNRangeFilter &f) { val1->setValue(f.val1); val2->setValue(f.val2); op1->setCurrentItem((int)f.op1); if (f.op2 == KNRangeFilter::dis) op2->setCurrentItem(0); else if (f.op2 == KNRangeFilter::gt) op2->setCurrentItem(1); else if (f.op2 == KNRangeFilter::gtoeq) op2->setCurrentItem(2); enabled->setChecked(f.enabled); } void KNRangeFilterWidget::clear() { val1->setValue(val1->minValue()); val2->setValue(val2->minValue()); enabled->setChecked(false); } void KNRangeFilterWidget::slotOp1Changed(int id) { op2->setEnabled(op1->isEnabled() && (id<2)); slotOp2Changed(op2->currentItem()); } void KNRangeFilterWidget::slotOp2Changed(int id) { val2->setEnabled(op1->isEnabled() && (op1->currentItem()<2) && (id>0)); } void KNRangeFilterWidget::slotEnabled(bool e) { op1->setEnabled(e); val1->setEnabled(e); des->setEnabled(e); slotOp1Changed(op1->currentItem()); } // ----------------------------------------------------------------------------- #include "knrangefilter.moc" <commit_msg>Minor fix<commit_after>/* knrangefilter.cpp KNode, the KDE newsreader Copyright (c) 1999-2001 the KNode authors. See file AUTHORS for details This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US */ #include <qlabel.h> #include <qlayout.h> #include <qcheckbox.h> #include <qcombobox.h> #include <ksimpleconfig.h> #include <knuminput.h> #include "knrangefilter.h" bool KNRangeFilter::doFilter(int a) { bool ret=true; if(enabled) { switch (op1) { case gt: case gtoeq: if (op2 != dis) ret=( matchesOp(val1,op1,a) && matchesOp(a,op2,val2) ); else ret = matchesOp(val1,op1,a);; break; case eq: case lt: case ltoeq: ret = matchesOp(val1,op1,a); break; default: ret = false; } } return ret; } bool KNRangeFilter::matchesOp(int v1, Op o, int v2) { bool ret=false; switch(o) { case eq: ret=(v1==v2); break; case gt: ret=(v1<v2); break; case gtoeq: ret=(v1<=v2); break; case ltoeq: ret=(v1>=v2); break; case lt: ret=(v1>v2); break; default: ret=false; break; }; return ret; } void KNRangeFilter::load(KSimpleConfig *conf) { enabled=conf->readBoolEntry("enabled", false); val1=conf->readNumEntry("val1",0); op1=(Op) conf->readNumEntry("op1",0); val2=conf->readNumEntry("val2",0); op2=(Op) conf->readNumEntry("op2",0); } void KNRangeFilter::save(KSimpleConfig *conf) { conf->writeEntry("enabled", enabled); conf->writeEntry("val1", val1); conf->writeEntry("op1", (int)op1); conf->writeEntry("op2", (int)op2); conf->writeEntry("val2", val2); } //===================================================================================== //===================================================================================== KNRangeFilterWidget::KNRangeFilterWidget(const QString& value, int min, int max, QWidget* parent, const QString &unit) : QGroupBox(value, parent) { enabled=new QCheckBox(this); val1=new KIntSpinBox(min, max, 1, min, 10, this); val1->setSuffix(unit); val2=new KIntSpinBox(min, max, 1, min, 10, this); val2->setSuffix(unit); op1=new QComboBox(this); op1->insertItem("<"); op1->insertItem("<="); op1->insertItem("="); op1->insertItem(">="); op1->insertItem(">"); op2=new QComboBox(this); op2->insertItem(""); op2->insertItem("<"); op2->insertItem("<="); des=new QLabel(value, this); des->setAlignment(AlignCenter); QGridLayout *topL=new QGridLayout(this, 2,6, 8,5 ); topL->addRowSpacing(0, fontMetrics().lineSpacing()-4); topL->addWidget(enabled,1,0, Qt::AlignHCenter); topL->addColSpacing(0, 30); topL->addWidget(val1,1,1); topL->addWidget(op1,1,2); topL->addWidget(des,1,3); topL->addColSpacing(3, 45); topL->addWidget(op2,1,4); topL->addWidget(val2,1,5); topL->setColStretch(1,1); topL->setColStretch(5,1); connect(op1, SIGNAL(activated(int)), SLOT(slotOp1Changed(int))); connect(op2, SIGNAL(activated(int)), SLOT(slotOp2Changed(int))); connect(enabled, SIGNAL(toggled(bool)), SLOT(slotEnabled(bool))); slotEnabled(false); } KNRangeFilterWidget::~KNRangeFilterWidget() { } KNRangeFilter KNRangeFilterWidget::filter() { KNRangeFilter r; r.val1=val1->value(); r.val2=val2->value(); r.op1=(KNRangeFilter::Op) op1->currentItem(); if (op2->currentText().isEmpty()) r.op2=KNRangeFilter::dis; else if (op2->currentText()=="<") r.op2=KNRangeFilter::gt; else if (op2->currentText()=="<=") r.op2=KNRangeFilter::gtoeq; r.enabled=enabled->isChecked(); return r; } void KNRangeFilterWidget::setFilter(KNRangeFilter &f) { val1->setValue(f.val1); val2->setValue(f.val2); op1->setCurrentItem((int)f.op1); if (f.op2 == KNRangeFilter::dis) op2->setCurrentItem(0); else if (f.op2 == KNRangeFilter::gt) op2->setCurrentItem(1); else if (f.op2 == KNRangeFilter::gtoeq) op2->setCurrentItem(2); enabled->setChecked(f.enabled); } void KNRangeFilterWidget::clear() { val1->setValue(val1->minValue()); val2->setValue(val2->minValue()); enabled->setChecked(false); } void KNRangeFilterWidget::slotOp1Changed(int id) { bool state = (op1->isEnabled() && (id<2)); op2->setEnabled(state); des->setEnabled(state); slotOp2Changed(op2->currentItem()); } void KNRangeFilterWidget::slotOp2Changed(int id) { val2->setEnabled(op1->isEnabled() && (op1->currentItem()<2) && (id>0)); } void KNRangeFilterWidget::slotEnabled(bool e) { op1->setEnabled(e); val1->setEnabled(e); des->setEnabled(e); slotOp1Changed(op1->currentItem()); } // ----------------------------------------------------------------------------- #include "knrangefilter.moc" <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qaccelerationsensor.h> QTM_BEGIN_NAMESPACE /*! \class QAccelerationReading \ingroup sensors \preliminary \brief The QAccelerationReading class represents one reading from the acceleration sensor. The acceleration sensor returns acceleration values along 3 axes. The scale of the values is milli-Gs. The axes are arranged as follows. \code +z | | +y | / |----/---- /| NOKIA /| //|--/--- / | // | / // / // |/ // / // '--------------- +x // // / // // / /---------/ / / O / / / / / ---------- / |_________!/ \endcode A monoblock device sitting at rest, face up on a desk will experience the force of gravity as approximately -1000 on the Z axis. */ /*! \fn QAccelerationReading::QAccelerationReading() \internal */ /*! \fn QAccelerationReading::QAccelerationReading(QTime timestamp, int x, int y, int z) \internal */ /*! \fn QAccelerationReading::QAccelerationReading(const QAccelerationReading &other) \internal */ /*! \fn QAccelerationReading::~QAccelerationReading() \internal */ /*! \fn QAccelerationReading::timestamp() const Returns the time when the reading was made. */ /*! \fn QAccelerationReading::x() const Returns the acceleration for the X axis. */ /*! \fn QAccelerationReading::y() const Returns the acceleration for the Y axis. */ /*! \fn QAccelerationReading::z() const Returns the acceleration for the Z axis. */ // ===================================================================== /*! \class QAccelerationListener \ingroup sensors \preliminary \brief The QAccelerationListener class provides an efficient callback facility for asynchronous notifications of acceleration changes. Since the accelerometer is typically accessed very frequently it may not by suitable to use signals and slots. The QAccelerationListener interface provides a way for the sensor to notify your class that a new acceleration reading is available more efficiently. */ /*! \fn QAccelerationListener::accelerationChanged(const QAccelerationReading &reading) This function is called when a new acceleration \a reading is available. */ // ===================================================================== /*! \class QAccelerationSensor \ingroup sensors \preliminary \brief The QAccelerationSensor class reports on linear acceleration along the X, Y and Z axes. The acceleration sensor returns acceleration values along 3 axes. The scale of the values is milli-Gs. The axes are arranged as follows. \code +z | | +y | / |----/---- /| NOKIA /| //|--/--- / | // | / // / // |/ // / // '--------------- +x // // / // // / /---------/ / / O / / / / / ---------- / |_________!/ \endcode A monoblock device sitting at rest, face up on a desk will experience the force of gravity as approximately -1000 on the Z axis. \sa QAccelerationReading */ /*! Construct a sensor instance with specified \a parent. If the \a id is passed the sensor will connect to that specific sensor, otherwise the default will be used. */ QAccelerationSensor::QAccelerationSensor(QObject *parent, const QSensorId &id) : QSensor(parent) { connectToBackend(id); } /*! \variable QAccelerationSensor::typeId */ const QString QAccelerationSensor::typeId("qt.Acceleration"); /*! \fn QAccelerationSensor::type() const \reimp */ /*! Add a \a listener to the sensor. The listener will be invoked every time a new reading is available. Note that the sensor does not take ownership of the listener. It is the caller's responsibility to ensure the listener remains valid until the sensor is destroyed or the listener is removed via QAccelerationSensor::removeListener(). */ void QAccelerationSensor::addListener(QAccelerationListener *listener) { Q_UNUSED(listener) } /*! Remove a \a listener from the sensor. If \a listener is 0, all listeners will be removed. */ void QAccelerationSensor::removeListener(QAccelerationListener *listener) { Q_UNUSED(listener) } /*! Returns the current acceleration reading. */ QAccelerationReading QAccelerationSensor::currentReading() const { return QAccelerationReading(); } /*! \fn QAccelerationSensor::accelerationChanged(const QAccelerationReading &reading) This signal is emitted when a new acceleration \a reading comes in. Note that this is done after the listeners have been called. If a listener blocks the reading then this signal will not be emitted. Also note that this signal should not be used if you are requesting high-frequency updates as signal delivery is quite slow. */ void QAccelerationSensor::newReadingAvailable() { /* QAccelerationReading reading = currentReading(); foreach (QAccelerationListener *listener, m_listeners) listener->accelerationChanged(reading); */ } #include "moc_qaccelerationsensor.cpp" QTM_END_NAMESPACE <commit_msg>fix out of sync documentation<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qaccelerationsensor.h> QTM_BEGIN_NAMESPACE /*! \class QAccelerationReading \ingroup sensors \preliminary \brief The QAccelerationReading class represents one reading from the acceleration sensor. The acceleration sensor returns acceleration values along 3 axes. The scale of the values is milli-Gs. The axes are arranged as follows. \code +z | | +y | / |----/---- /| NOKIA /| //|--/--- / | // | / // / // |/ // / // '--------------- +x // // / // // / /---------/ / / O / / / / / ---------- / |_________!/ \endcode A monoblock device sitting at rest, face up on a desk will experience the force of gravity as approximately -1000 on the Z axis. */ /*! \fn QAccelerationReading::QAccelerationReading() \internal */ /*! \fn QAccelerationReading::QAccelerationReading(QTime timestamp, int x, int y, int z) \internal */ /*! \fn QAccelerationReading::QAccelerationReading(const QAccelerationReading &other) \internal */ /*! \fn QAccelerationReading::~QAccelerationReading() \internal */ /*! \fn QAccelerationReading::timestamp() const Returns the time when the reading was made. */ /*! \fn QAccelerationReading::x() const Returns the acceleration for the X axis. */ /*! \fn QAccelerationReading::y() const Returns the acceleration for the Y axis. */ /*! \fn QAccelerationReading::z() const Returns the acceleration for the Z axis. */ // ===================================================================== /*! \class QAccelerationListener \ingroup sensors \preliminary \brief The QAccelerationListener class provides an efficient callback facility for asynchronous notifications of acceleration changes. Since the accelerometer is typically accessed very frequently it may not by suitable to use signals and slots. The QAccelerationListener interface provides a way for the sensor to notify your class that a new acceleration reading is available more efficiently. */ /*! \fn QAccelerationListener::accelerationChanged(const QAccelerationReading &reading) This function is called when a new acceleration \a reading is available. */ // ===================================================================== /*! \class QAccelerationSensor \ingroup sensors \preliminary \brief The QAccelerationSensor class reports on linear acceleration along the X, Y and Z axes. The acceleration sensor returns acceleration values along 3 axes. The scale of the values is milli-Gs. The axes are arranged as follows. \code +z | | +y | / |----/---- /| NOKIA /| //|--/--- / | // | / // / // |/ // / // '--------------- +x // // / // // / /---------/ / / O / / / / / ---------- / |_________!/ \endcode A monoblock device sitting at rest, face up on a desk will experience the force of gravity as approximately -1000 on the Z axis. \sa QAccelerationReading */ /*! Construct a sensor instance with specified \a parent. If the \a id is passed the sensor will connect to that specific sensor, otherwise the default will be used. */ QAccelerationSensor::QAccelerationSensor(QObject *parent, const QSensorId &id) : QSensor(parent) { connectToBackend(id); } /*! \variable QAccelerationSensor::typeId */ const QString QAccelerationSensor::typeId("qt.Acceleration"); /*! \fn QAccelerationSensor::type() const \reimp */ /*! Add a \a listener to the sensor. The listener will be invoked every time a new reading is available. Note that the sensor does not take ownership of the listener. It is the caller's responsibility to ensure the listener remains valid until the sensor is destroyed or the listener is removed via QAccelerationSensor::removeListener(). */ void QAccelerationSensor::addListener(QAccelerationListener *listener) { Q_UNUSED(listener) } /*! Remove a \a listener from the sensor. If \a listener is 0, all listeners will be removed. */ void QAccelerationSensor::removeListener(QAccelerationListener *listener) { Q_UNUSED(listener) } /*! Returns the current acceleration reading. */ QAccelerationReading QAccelerationSensor::currentReading() const { return QAccelerationReading(); } /*! \fn QAccelerationSensor::accelerationChanged(const QAccelerationReading &reading) This signal is emitted when a new acceleration \a reading comes in. Note that this signal should not be used if you are requesting high-frequency updates as signal delivery is quite slow. */ void QAccelerationSensor::newReadingAvailable() { /* QAccelerationReading reading = currentReading(); foreach (QAccelerationListener *listener, m_listeners) listener->accelerationChanged(reading); */ } #include "moc_qaccelerationsensor.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>// ------------------------------------------------------------------------ // eca-audio-time.cpp: Generic class for representing time in audio // environment. // Copyright (C) 2000 Kai Vehmanen (kaiv@wakkanet.fi) // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ------------------------------------------------------------------------ #include <cstdio> #include <cmath> #include <kvu_numtostr.h> #include "eca-audio-time.h" ECA_AUDIO_TIME::ECA_AUDIO_TIME(SAMPLE_SPECS::sample_pos_t samples, SAMPLE_SPECS::sample_rate_t sample_rate) { set_samples_per_second(sample_rate); set_samples(samples); } ECA_AUDIO_TIME::ECA_AUDIO_TIME(double time_in_seconds) { set_seconds(time_in_seconds); } ECA_AUDIO_TIME::ECA_AUDIO_TIME(format_type type, const std::string& time) { set(type, time); } ECA_AUDIO_TIME::ECA_AUDIO_TIME(void) : samples_rep(0), sample_rate_rep(44100) { } void ECA_AUDIO_TIME::set(format_type type, const std::string& time) { switch(type) { case format_hour_min_sec: { } case format_min_sec: { } case format_seconds: { samples_rep = static_cast<SAMPLE_SPECS::sample_pos_t>(sample_rate_rep * atof(time.c_str())); } case format_samples: { samples_rep = atol(time.c_str()); } default: { } } } void ECA_AUDIO_TIME::set_seconds(double seconds) { samples_rep = static_cast<SAMPLE_SPECS::sample_pos_t>(seconds * sample_rate_rep); } void ECA_AUDIO_TIME::set_samples(SAMPLE_SPECS::sample_pos_t samples) { samples_rep = samples; } void ECA_AUDIO_TIME::set_samples_per_second(SAMPLE_SPECS::sample_rate_t srate) { sample_rate_rep = srate; } std::string ECA_AUDIO_TIME::to_string(format_type type) const { switch(type) { case format_hour_min_sec: { return(""); } case format_min_sec: { return(""); } case format_seconds: { return(kvu_numtostr(seconds(), 3)); } case format_samples: { return(kvu_numtostr(samples_rep)); } default: { } } return(""); } double ECA_AUDIO_TIME::seconds(void) const { return(static_cast<double>(samples_rep) / sample_rate_rep); } SAMPLE_SPECS::sample_rate_t ECA_AUDIO_TIME::samples_per_second(void) const { return(sample_rate_rep); } SAMPLE_SPECS::sample_pos_t ECA_AUDIO_TIME::samples(void) const { return(samples_rep); } <commit_msg>Add fixmes.<commit_after>// ------------------------------------------------------------------------ // eca-audio-time.cpp: Generic class for representing time in audio // environment. // Copyright (C) 2000 Kai Vehmanen (kaiv@wakkanet.fi) // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ------------------------------------------------------------------------ #include <cstdio> #include <cmath> #include <kvu_numtostr.h> #include "eca-audio-time.h" ECA_AUDIO_TIME::ECA_AUDIO_TIME(SAMPLE_SPECS::sample_pos_t samples, SAMPLE_SPECS::sample_rate_t sample_rate) { set_samples_per_second(sample_rate); set_samples(samples); } ECA_AUDIO_TIME::ECA_AUDIO_TIME(double time_in_seconds) { set_seconds(time_in_seconds); } ECA_AUDIO_TIME::ECA_AUDIO_TIME(format_type type, const std::string& time) { set(type, time); } ECA_AUDIO_TIME::ECA_AUDIO_TIME(void) : samples_rep(0), sample_rate_rep(44100) { } void ECA_AUDIO_TIME::set(format_type type, const std::string& time) { /* FIXME: not implemented! */ switch(type) { case format_hour_min_sec: { } case format_min_sec: { } case format_seconds: { samples_rep = static_cast<SAMPLE_SPECS::sample_pos_t>(sample_rate_rep * atof(time.c_str())); } case format_samples: { samples_rep = atol(time.c_str()); } default: { } } } void ECA_AUDIO_TIME::set_seconds(double seconds) { samples_rep = static_cast<SAMPLE_SPECS::sample_pos_t>(seconds * sample_rate_rep); } void ECA_AUDIO_TIME::set_samples(SAMPLE_SPECS::sample_pos_t samples) { samples_rep = samples; } void ECA_AUDIO_TIME::set_samples_per_second(SAMPLE_SPECS::sample_rate_t srate) { sample_rate_rep = srate; } std::string ECA_AUDIO_TIME::to_string(format_type type) const { /* FIXME: not implemented */ switch(type) { case format_hour_min_sec: { return(""); } case format_min_sec: { return(""); } case format_seconds: { return(kvu_numtostr(seconds(), 3)); } case format_samples: { return(kvu_numtostr(samples_rep)); } default: { } } return(""); } double ECA_AUDIO_TIME::seconds(void) const { return(static_cast<double>(samples_rep) / sample_rate_rep); } SAMPLE_SPECS::sample_rate_t ECA_AUDIO_TIME::samples_per_second(void) const { return(sample_rate_rep); } SAMPLE_SPECS::sample_pos_t ECA_AUDIO_TIME::samples(void) const { return(samples_rep); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file qp_spline_path_optimizer.cc **/ #include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/common/util/file.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/tasks/qp_spline_path/qp_spline_path_generator.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; QpSplinePathOptimizer::QpSplinePathOptimizer() : PathOptimizer("QpSplinePathOptimizer") {} bool QpSplinePathOptimizer::Init(const PlanningConfig& config) { qp_spline_path_config_ = config.em_planner_config().qp_spline_path_config(); std::vector<double> init_knots; spline_generator_.reset(new Spline1dGenerator(init_knots, 5)); is_init_ = true; return true; } Status QpSplinePathOptimizer::Process(const SpeedData& speed_data, const ReferenceLine& reference_line, const common::TrajectoryPoint& init_point, PathData* const path_data) { if (!is_init_) { AERROR << "Please call Init() before Process."; return Status(ErrorCode::PLANNING_ERROR, "Not init."); } QpSplinePathGenerator path_generator(spline_generator_.get(), reference_line, qp_spline_path_config_); path_generator.SetDebugLogger(reference_line_info_->mutable_debug()); if (!path_generator.Generate( reference_line_info_->path_decision()->path_obstacles().Items(), speed_data, init_point, path_data)) { const std::string msg = "failed to generate spline path!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } } // namespace planning } // namespace apollo <commit_msg>planning: fix QP path order const with config value.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file qp_spline_path_optimizer.cc **/ #include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/common/util/file.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/tasks/qp_spline_path/qp_spline_path_generator.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; QpSplinePathOptimizer::QpSplinePathOptimizer() : PathOptimizer("QpSplinePathOptimizer") {} bool QpSplinePathOptimizer::Init(const PlanningConfig& config) { qp_spline_path_config_ = config.em_planner_config().qp_spline_path_config(); std::vector<double> init_knots; spline_generator_.reset(new Spline1dGenerator(init_knots, qp_spline_path_config_.spline_order())); is_init_ = true; return true; } Status QpSplinePathOptimizer::Process(const SpeedData& speed_data, const ReferenceLine& reference_line, const common::TrajectoryPoint& init_point, PathData* const path_data) { if (!is_init_) { AERROR << "Please call Init() before Process."; return Status(ErrorCode::PLANNING_ERROR, "Not init."); } QpSplinePathGenerator path_generator(spline_generator_.get(), reference_line, qp_spline_path_config_); path_generator.SetDebugLogger(reference_line_info_->mutable_debug()); if (!path_generator.Generate( reference_line_info_->path_decision()->path_obstacles().Items(), speed_data, init_point, path_data)) { const std::string msg = "failed to generate spline path!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>#include "HeatExchangeCoefficientPartitioning.h" template<> InputParameters validParams<HeatExchangeCoefficientPartitioning>() { InputParameters params = validParams<GeneralUserObject>(); params.addParam<Real>("k", 5, "Steepness of the exponential function"); params.addParam<Real>("lower", 0.001, "Lower cut-off limit"); params.addParam<Real>("upper", 0.999, "Upper cut-off limit"); return params; } HeatExchangeCoefficientPartitioning::HeatExchangeCoefficientPartitioning(const std::string & name, InputParameters parameters) : GeneralUserObject(name, parameters), _k(getParam<Real>("k")), _lower(getParam<Real>("lower")), _upper(getParam<Real>("upper")) { } HeatExchangeCoefficientPartitioning::~HeatExchangeCoefficientPartitioning() { } Real HeatExchangeCoefficientPartitioning::getPartition(Real alpha_liquid, Real dalpha_liquid_dt) const { Real c = 1; if ((alpha_liquid < _lower)) { if (dalpha_liquid_dt < 0) c = 1 - (1 - std::exp(-_k * (0.001 - alpha_liquid) / 0.001)); else c = 1 - std::exp(-_k * alpha_liquid / 0.001); } else if ((alpha_liquid > _upper)) { if (dalpha_liquid_dt > 0) c = 1 - (1 - std::exp(-_k * (alpha_liquid - 0.999) / 0.001)); else c = 1 - std::exp(-_k * (1 - alpha_liquid) / 0.001); } else c = 1.; return c; } <commit_msg>Fixing the heat exchange coefficient partitioning user object<commit_after>#include "HeatExchangeCoefficientPartitioning.h" template<> InputParameters validParams<HeatExchangeCoefficientPartitioning>() { InputParameters params = validParams<GeneralUserObject>(); params.addParam<Real>("k", 5, "Steepness of the exponential function"); params.addParam<Real>("lower", 0.001, "Lower cut-off limit"); params.addParam<Real>("upper", 0.999, "Upper cut-off limit"); return params; } HeatExchangeCoefficientPartitioning::HeatExchangeCoefficientPartitioning(const std::string & name, InputParameters parameters) : GeneralUserObject(name, parameters), _k(getParam<Real>("k")), _lower(getParam<Real>("lower")), _upper(getParam<Real>("upper")) { } HeatExchangeCoefficientPartitioning::~HeatExchangeCoefficientPartitioning() { } Real HeatExchangeCoefficientPartitioning::getPartition(Real alpha_liquid, Real dalpha_liquid_dt) const { Real c = 1; if ((alpha_liquid < _lower)) { if (dalpha_liquid_dt < 0) c = 1 - (1 - std::exp(-_k * (_lower - alpha_liquid) / _lower)); else c = 1 - std::exp(-_k * alpha_liquid / _lower); } else if ((alpha_liquid > _upper)) { if (dalpha_liquid_dt > 0) c = 1 - (1 - std::exp(-_k * (alpha_liquid - _upper) / _lower)); else c = 1 - std::exp(-_k * (1 - alpha_liquid) / _lower); } else c = 1.; return c; } <|endoftext|>
<commit_before>/* This file is part of libkdepim. Copyright (c) 2004 Bram Schoenmakers <bramschoenmakers@kde.nl> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdatetime.h> #include <qpopupmenu.h> #include <klocale.h> #include "kdatepickerpopup.h" KDatePickerPopup::KDatePickerPopup( int items, const QDate &date, QWidget *parent, const char *name ) : QPopupMenu( parent, name ) { mItems = items; mDatePicker = new KDatePicker(); mDatePicker->setCloseButton( false ); connect( mDatePicker, SIGNAL( dateEntered( QDate ) ), SLOT( slotDateChanged( QDate ) ) ); connect( mDatePicker, SIGNAL( dateSelected( QDate ) ), SLOT( slotDateChanged( QDate ) ) ); mDatePicker->setDate( date ); buildMenu(); } void KDatePickerPopup::buildMenu() { if ( isVisible() ) return; clear(); if ( mItems & DatePicker ) { insertItem( mDatePicker ); if ( ( mItems & NoDate ) || ( mItems & Words ) ) insertSeparator(); } if ( mItems & Words ) { insertItem( i18n("&Today"), this, SLOT( slotToday() ) ); insertItem( i18n("To&morrow"), this, SLOT( slotTomorrow() ) ); insertItem( i18n("&Friday"), this, SLOT( slotFriday() ) ); insertItem( i18n("&Sunday"), this, SLOT( slotSunday() ) ); insertItem( i18n("Next &Week"), this, SLOT( slotNextWeek() ) ); insertItem( i18n("Next M&onth"), this, SLOT( slotNextMonth() ) ); if ( mItems & NoDate ) insertSeparator(); } if ( mItems & NoDate ) insertItem( i18n("No Date"), this, SLOT( slotNoDate() ) ); } KDatePickerPopup::~KDatePickerPopup() { delete mDatePicker; } KDatePicker *KDatePickerPopup::datePicker() const { return mDatePicker; } #if 0 void KDatePickerPopup::setItems( int items ) { mItems = items; buildMenu(); } #endif void KDatePickerPopup::slotDateChanged( QDate date ) { emit dateChanged( date ); hide(); } void KDatePickerPopup::slotToday() { emit dateChanged( QDate::currentDate() ); } void KDatePickerPopup::slotTomorrow() { emit dateChanged( QDate::currentDate().addDays( 1 ) ); } void KDatePickerPopup::slotFriday() { QDate date = QDate::currentDate(); int day = date.dayOfWeek(); if ( day < 6 ) date = date.addDays( 5 - day ); else date = date.addDays( 5 - day + 7 ); emit dateChanged( date ); } void KDatePickerPopup::slotSunday() { QDate date = QDate::currentDate(); emit dateChanged( date.addDays( 7 - date.dayOfWeek() ) ); } void KDatePickerPopup::slotNoDate() { emit dateChanged( QDate() ); } void KDatePickerPopup::slotNextWeek() { emit dateChanged( QDate::currentDate().addDays( 7 ) ); } void KDatePickerPopup::slotNextMonth() { emit dateChanged( QDate::currentDate().addMonths( 1 ) ); } #include "kdatepickerpopup.moc" <commit_msg>setDate() implemented.<commit_after>/* This file is part of libkdepim. Copyright (c) 2004 Bram Schoenmakers <bramschoenmakers@kde.nl> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdatetime.h> #include <qpopupmenu.h> #include <klocale.h> #include "kdatepickerpopup.h" KDatePickerPopup::KDatePickerPopup( int items, const QDate &date, QWidget *parent, const char *name ) : QPopupMenu( parent, name ) { mItems = items; mDatePicker = new KDatePicker(); mDatePicker->setCloseButton( false ); connect( mDatePicker, SIGNAL( dateEntered( QDate ) ), SLOT( slotDateChanged( QDate ) ) ); connect( mDatePicker, SIGNAL( dateSelected( QDate ) ), SLOT( slotDateChanged( QDate ) ) ); mDatePicker->setDate( date ); buildMenu(); } void KDatePickerPopup::buildMenu() { if ( isVisible() ) return; clear(); if ( mItems & DatePicker ) { insertItem( mDatePicker ); if ( ( mItems & NoDate ) || ( mItems & Words ) ) insertSeparator(); } if ( mItems & Words ) { insertItem( i18n("&Today"), this, SLOT( slotToday() ) ); insertItem( i18n("To&morrow"), this, SLOT( slotTomorrow() ) ); insertItem( i18n("&Friday"), this, SLOT( slotFriday() ) ); insertItem( i18n("&Sunday"), this, SLOT( slotSunday() ) ); insertItem( i18n("Next &Week"), this, SLOT( slotNextWeek() ) ); insertItem( i18n("Next M&onth"), this, SLOT( slotNextMonth() ) ); if ( mItems & NoDate ) insertSeparator(); } if ( mItems & NoDate ) insertItem( i18n("No Date"), this, SLOT( slotNoDate() ) ); } KDatePickerPopup::~KDatePickerPopup() { delete mDatePicker; } KDatePicker *KDatePickerPopup::datePicker() const { return mDatePicker; } void KDatePickerPopup::setDate( const QDate &date ) { mDatePicker->setDate( date ); } #if 0 void KDatePickerPopup::setItems( int items ) { mItems = items; buildMenu(); } #endif void KDatePickerPopup::slotDateChanged( QDate date ) { emit dateChanged( date ); hide(); } void KDatePickerPopup::slotToday() { emit dateChanged( QDate::currentDate() ); } void KDatePickerPopup::slotTomorrow() { emit dateChanged( QDate::currentDate().addDays( 1 ) ); } void KDatePickerPopup::slotFriday() { QDate date = QDate::currentDate(); int day = date.dayOfWeek(); if ( day < 6 ) date = date.addDays( 5 - day ); else date = date.addDays( 5 - day + 7 ); emit dateChanged( date ); } void KDatePickerPopup::slotSunday() { QDate date = QDate::currentDate(); emit dateChanged( date.addDays( 7 - date.dayOfWeek() ) ); } void KDatePickerPopup::slotNoDate() { emit dateChanged( QDate() ); } void KDatePickerPopup::slotNextWeek() { emit dateChanged( QDate::currentDate().addDays( 7 ) ); } void KDatePickerPopup::slotNextMonth() { emit dateChanged( QDate::currentDate().addMonths( 1 ) ); } #include "kdatepickerpopup.moc" <|endoftext|>
<commit_before>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include <http_connection.hpp> #include <types.hpp> #include <iostream> namespace net { namespace http { void connection_manager::start(connection_ptr c) { m_connections.insert(c); c->start(); } void connection_manager::stop(connection_ptr c) { m_connections.erase(c); c->stop(); } void connection_manager::stop_all() { for (auto c : m_connections) c->stop(); m_connections.clear(); } connection::connection(boost::asio::ip::tcp::socket && socket, connection_manager& manager, request_handler& handler) : m_socket(std::move(socket)) , m_manager(manager) , m_handler(handler) , m_pos(0) { } void connection::read_some_more() { auto self(shared_from_this()); m_socket.async_read_some(boost::asio::buffer(m_buffer), [this, self](boost::system::error_code ec, std::size_t bytes_transferred) { if (!ec) { const char* data = m_buffer.data(); auto end = data + bytes_transferred; auto ret = m_parser.parse(data, end); if (ret == parser::finished) { auto header = m_parser.header(); std::cout << header; m_handler.handle(header, m_response); send_reply(); } else if (ret == parser::error) { m_handler.make_404(m_response); send_reply(); } else read_some_more(); } else if (ec != boost::asio::error::operation_aborted) { m_manager.stop(shared_from_this()); } }); } void connection::continue_sending(connection_ptr self, response_buffer buffer, boost::system::error_code ec, std::size_t) { if (!ec) { if (buffer.advance(self->m_response_chunk)) { boost::asio::async_write( self->m_socket, boost::asio::buffer(self->m_response_chunk), [self, buffer](boost::system::error_code ec, std::size_t size) { continue_sending(self, buffer, ec, size); }); return; } else { // Initiate graceful connection closure. boost::system::error_code ignored_ec; self->m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } } if (ec != boost::asio::error::operation_aborted) { self->m_manager.stop(self->shared_from_this()); } } void connection::send_reply() { auto self(shared_from_this()); continue_sending(self, m_response.get_data(), boost::system::error_code(), 0); } } } <commit_msg>Shorter debug output<commit_after>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include <http_connection.hpp> #include <types.hpp> #include <iostream> namespace net { namespace http { void connection_manager::start(connection_ptr c) { m_connections.insert(c); c->start(); } void connection_manager::stop(connection_ptr c) { m_connections.erase(c); c->stop(); } void connection_manager::stop_all() { for (auto c : m_connections) c->stop(); m_connections.clear(); } connection::connection(boost::asio::ip::tcp::socket && socket, connection_manager& manager, request_handler& handler) : m_socket(std::move(socket)) , m_manager(manager) , m_handler(handler) , m_pos(0) { } void connection::read_some_more() { auto self(shared_from_this()); m_socket.async_read_some(boost::asio::buffer(m_buffer), [this, self](boost::system::error_code ec, std::size_t bytes_transferred) { if (!ec) { const char* data = m_buffer.data(); auto end = data + bytes_transferred; auto ret = m_parser.parse(data, end); if (ret == parser::finished) { auto header = m_parser.header(); auto ua = header.find("user-agent"); std::ostringstream o; o << (http_request_line&) header; if (ua != header.end()) { o << " [ " << ua->value(); auto pui = header.find("x-av-physical-unit-info"); auto ci = header.find("x-av-client-info"); if (pui != header.end() || ci != header.end()) { o << " | "; if (pui != header.end()) { o << pui->value(); if (ci != header.end()) o << " | "; } if (ci != header.end()) { o << ci->value(); } } o << " ]\n"; } std::cout << o.str(); m_handler.handle(header, m_response); send_reply(); } else if (ret == parser::error) { m_handler.make_404(m_response); send_reply(); } else read_some_more(); } else if (ec != boost::asio::error::operation_aborted) { m_manager.stop(shared_from_this()); } }); } void connection::continue_sending(connection_ptr self, response_buffer buffer, boost::system::error_code ec, std::size_t) { if (!ec) { if (buffer.advance(self->m_response_chunk)) { boost::asio::async_write( self->m_socket, boost::asio::buffer(self->m_response_chunk), [self, buffer](boost::system::error_code ec, std::size_t size) { continue_sending(self, buffer, ec, size); }); return; } else { // Initiate graceful connection closure. boost::system::error_code ignored_ec; self->m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } } if (ec != boost::asio::error::operation_aborted) { self->m_manager.stop(self->shared_from_this()); } } void connection::send_reply() { auto self(shared_from_this()); continue_sending(self, m_response.get_data(), boost::system::error_code(), 0); } } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/nvdimm_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file nvdimm_utils.H /// @brief Subroutines to support nvdimm backup/restore process /// // *HWP HWP Owner: Tsung Yeung <tyeung@us.ibm.com> // *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <generic/memory/lib/utils/find.H> namespace mss { namespace nvdimm { /// /// @brief Helper for self_refresh_exit(). /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// @note Uses memdiag to read the port to force CKE back to high. /// Stolen from mss_lab_memdiags.C /// template< fapi2::TargetType T > fapi2::ReturnCode self_refresh_exit_helper( const fapi2::Target<T>& i_target ); /// /// @brief Disable refresh and put target into self-refresh /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode self_refresh_entry( const fapi2::Target<T>& i_target ); /// /// @brief Take the target out of self-refresh and restart refresh /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode self_refresh_exit( const fapi2::Target<T>& i_target ); /// /// @brief Latch write vref at per-dram basis /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode pda_vref_latch( const fapi2::Target<T>& i_target ); /// /// @brief Full post-restore transition for NVDIMM /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode post_restore_transition( const fapi2::Target<T>& i_target ); }//ns nvdimm }//ns mss <commit_msg>P9: Disable Maint Address Mode After Self-Refresh Exit on NVDIMM<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/nvdimm_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file nvdimm_utils.H /// @brief Subroutines to support nvdimm backup/restore process /// // *HWP HWP Owner: Tsung Yeung <tyeung@us.ibm.com> // *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <generic/memory/lib/utils/find.H> namespace mss { namespace nvdimm { /// /// @brief Disable maintenance address mode /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode maint_addr_mode_off( const fapi2::Target<T>& i_target ); /// /// @brief Helper for self_refresh_exit(). /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// @note Uses memdiag to read the port to force CKE back to high. /// Stolen from mss_lab_memdiags.C /// template< fapi2::TargetType T > fapi2::ReturnCode self_refresh_exit_helper( const fapi2::Target<T>& i_target ); /// /// @brief Disable refresh and put target into self-refresh /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode self_refresh_entry( const fapi2::Target<T>& i_target ); /// /// @brief Take the target out of self-refresh and restart refresh /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode self_refresh_exit( const fapi2::Target<T>& i_target ); /// /// @brief Latch write vref at per-dram basis /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode pda_vref_latch( const fapi2::Target<T>& i_target ); /// /// @brief Full post-restore transition for NVDIMM /// @tparam T the target type associated with this subroutine /// @param[in] i_target the target associated with this subroutine /// @return FAPI2_RC_SUCCESS iff setup was successful /// template< fapi2::TargetType T > fapi2::ReturnCode post_restore_transition( const fapi2::Target<T>& i_target ); }//ns nvdimm }//ns mss <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/graphics/HeatEffect.hpp> #include <swift2d/components/DrawableComponent.hpp> #include <swift2d/graphics/RendererPool.hpp> namespace swift { //////////////////////////////////////////////////////////////////////////////// HeatEffect::HeatEffect(RenderContext const& ctx) { if (ctx.heat_effect) { auto create_texture = [&]( oglplus::Texture& tex, int width, int height, oglplus::enums::PixelDataInternalFormat i_format, oglplus::enums::PixelDataFormat p_format) { ctx.gl.Bound(oglplus::Texture::Target::_2D, tex) .Image2D(0, i_format, width, height, 0, p_format, oglplus::PixelDataType::Float, nullptr) .MaxLevel(0) .MinFilter(oglplus::TextureMinFilter::Linear) .MagFilter(oglplus::TextureMagFilter::Linear) .WrapS(oglplus::TextureWrap::MirroredRepeat) .WrapT(oglplus::TextureWrap::MirroredRepeat); }; create_texture( heat_buffer_, ctx.g_buffer_size.x()/8, ctx.g_buffer_size.y()/8, oglplus::PixelDataInternalFormat::RG, oglplus::PixelDataFormat::RG ); heat_fbo_.Bind(oglplus::Framebuffer::Target::Draw); oglplus::Framebuffer::AttachColorTexture( oglplus::Framebuffer::Target::Draw, 0, heat_buffer_, 0 ); GLfloat clear[2] = {0.5f, 0.5f}; ctx.gl.ClearColorBuffer(0, clear); } } //////////////////////////////////////////////////////////////////////////////// void HeatEffect::process(ConstSerializedScenePtr const& scene, RenderContext const& ctx) { if (!scene->renderers().heat_particle_systems.empty()) { ctx.gl.BlendFunc( oglplus::BlendFunction::SrcAlpha, oglplus::BlendFunction::OneMinusSrcAlpha ); ctx.gl.Viewport(ctx.g_buffer_size.x()/8, ctx.g_buffer_size.y()/8); heat_fbo_.Bind(oglplus::Framebuffer::Target::Draw); ctx.gl.DrawBuffer(oglplus::FramebufferColorAttachment::_0); GLfloat clear[2] = {0.5f, 0.5f}; ctx.gl.ClearColorBuffer(0, clear); scene->renderers().process_heat(ctx); } } //////////////////////////////////////////////////////////////////////////////// int HeatEffect::bind_buffers(int start, RenderContext const& ctx) { oglplus::Texture::Active(start); ctx.gl.Bind(ose::_2D(), heat_buffer_); return start + 1; } //////////////////////////////////////////////////////////////////////////////// } <commit_msg>increased heatbuffer resolution<commit_after>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/graphics/HeatEffect.hpp> #include <swift2d/components/DrawableComponent.hpp> #include <swift2d/graphics/RendererPool.hpp> namespace swift { //////////////////////////////////////////////////////////////////////////////// HeatEffect::HeatEffect(RenderContext const& ctx) { if (ctx.heat_effect) { auto create_texture = [&]( oglplus::Texture& tex, int width, int height, oglplus::enums::PixelDataInternalFormat i_format, oglplus::enums::PixelDataFormat p_format) { ctx.gl.Bound(oglplus::Texture::Target::_2D, tex) .Image2D(0, i_format, width, height, 0, p_format, oglplus::PixelDataType::Float, nullptr) .MaxLevel(0) .MinFilter(oglplus::TextureMinFilter::Linear) .MagFilter(oglplus::TextureMagFilter::Linear) .WrapS(oglplus::TextureWrap::MirroredRepeat) .WrapT(oglplus::TextureWrap::MirroredRepeat); }; create_texture( heat_buffer_, ctx.g_buffer_size.x()/4, ctx.g_buffer_size.y()/4, oglplus::PixelDataInternalFormat::RG, oglplus::PixelDataFormat::RG ); heat_fbo_.Bind(oglplus::Framebuffer::Target::Draw); oglplus::Framebuffer::AttachColorTexture( oglplus::Framebuffer::Target::Draw, 0, heat_buffer_, 0 ); GLfloat clear[2] = {0.5f, 0.5f}; ctx.gl.ClearColorBuffer(0, clear); } } //////////////////////////////////////////////////////////////////////////////// void HeatEffect::process(ConstSerializedScenePtr const& scene, RenderContext const& ctx) { if (!scene->renderers().heat_particle_systems.empty()) { ctx.gl.BlendFunc( oglplus::BlendFunction::SrcAlpha, oglplus::BlendFunction::OneMinusSrcAlpha ); ctx.gl.Viewport(ctx.g_buffer_size.x()/4, ctx.g_buffer_size.y()/4); heat_fbo_.Bind(oglplus::Framebuffer::Target::Draw); ctx.gl.DrawBuffer(oglplus::FramebufferColorAttachment::_0); GLfloat clear[2] = {0.5f, 0.5f}; ctx.gl.ClearColorBuffer(0, clear); scene->renderers().process_heat(ctx); } } //////////////////////////////////////////////////////////////////////////////// int HeatEffect::bind_buffers(int start, RenderContext const& ctx) { oglplus::Texture::Active(start); ctx.gl.Bind(ose::_2D(), heat_buffer_); return start + 1; } //////////////////////////////////////////////////////////////////////////////// } <|endoftext|>
<commit_before>#include <bts/chain/operations.hpp> namespace bts { namespace chain { /** * Valid symbols have between 3 and 17 upper case characters * with at most a single "." that is not the first or last character. */ bool is_valid_symbol( const string& symbol ) { if( symbol.size() > 17 ) return false; if( symbol.size() < 3 ) return false; int dot_count = 0; for( auto c : symbol ) { if( c == '.' ) ++dot_count; else if( c < 'A' || c > 'Z' ) return false; } if( symbol[0] == '.' || symbol[symbol.size()-1] == '.' ) return false; return dot_count <= 1; } /** * Valid names are all lower case, start with [a-z] and may * have "." or "-" in the name along with a single '/'. The * next character after a "/", "." or "-" cannot be [0-9] or * another '.', '-'. * */ bool is_valid_name( const string& s ) { if( s.size() == 0 ) return true; if( s.size() < 3 ) return false; if( s.size() >= 64 ) return false; int num_slash = 0; char prev = ' '; for( auto c : s ) { if( c >= 'a' && c <= 'z' ){} else if( c >= '0' && c <= '9' ) { if( prev == ' ' || prev == '.' || prev == '-' || prev == '/' ) return false; } else switch( c ) { case '/': if( ++num_slash > 1 ) return false; case '.': case '-': if( prev == ' ' || prev == '/' || prev == '.' || prev == '-' ) return false; break; default: return false; } prev = c; } switch( s.back() ) { case '/': case '-': case '.': return false; default: return true; } } bool is_premium_name( const string& n ) { return false; } bool is_cheap_name( const string& n ) { for( auto c : n ) { if( c >= '0' && c <= '9' ) return true; if( c == '.' || c == '-' || c == '/' ) return true; } return false; } share_type account_create_operation::calculate_fee( const fee_schedule_type& schedule )const { auto bts_fee_required = schedule.at(account_create_fee_type); if( name.size() ) { uint32_t s = name.size(); if( is_premium_name( name ) ) s = 2; else if( is_cheap_name( name ) ) s = 63; while( s <= 8 ) { bts_fee_required *= 10; ++s; } } return bts_fee_required; } share_type account_update_operation::calculate_fee( const fee_schedule_type& schedule )const { return schedule.at(account_create_fee_type); } void account_update_operation::validate()const { FC_ASSERT( fee.amount > 0 ); FC_ASSERT( owner || active || voting_key || memo_key || vote ); if( vote && vote->size() > 1 ) { for( int i = 1; i < vote->size(); ++i ) FC_ASSERT( vote->at(i-1) < vote->at(i) ); } } share_type asset_create_operation::calculate_fee( const fee_schedule_type& schedule )const { auto bts_fee_required = schedule.at(asset_create_fee_type); uint32_t s = symbol.size(); while( s <= 6 ) { bts_fee_required *= 30; ++s; } return bts_fee_required; } share_type transfer_operation::calculate_fee( const fee_schedule_type& schedule )const { auto bts_fee_required = schedule.at( transfer_fee_type ); bts_fee_required += share_type((memo.size() * schedule.at( data_fee_type ).value)/1024); return bts_fee_required; } struct key_data_validate { typedef void result_type; void operator()( const address& a )const { FC_ASSERT( a != address() ); } void operator()( const public_key_type& a )const { FC_ASSERT( a != public_key_type() ); } }; void key_create_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); key_data.visit( key_data_validate() ); } void account_create_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( is_valid_name( name ) ); auto pos = name.find( '/' ); if( pos != string::npos ) { FC_ASSERT( owner.weight_threshold == 1 ); FC_ASSERT( owner.auths.size() == 1 ); } } share_type account_publish_feeds_operation::calculate_fee( const fee_schedule_type& schedule )const { auto bts_fee_required = schedule.at( publish_feed_fee_type ); return bts_fee_required; } void account_publish_feeds_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); optional<price> prev; for( auto item : feeds ) { FC_ASSERT( item.base.amount >= share_type(0) ); // prevent divide by 0 FC_ASSERT( item.quote.amount >= share_type(0) ); // prevent divide by 0 if( prev ) { FC_ASSERT( !(prev->base.asset_id == item.base.asset_id && prev->quote.asset_id == item.quote.asset_id) ); } else prev = item; } } void transfer_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( from != to ); FC_ASSERT( amount.amount > 0 ); } void asset_create_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( is_valid_symbol( symbol ) ); FC_ASSERT( max_supply <= BTS_MAX_SHARE_SUPPLY ); FC_ASSERT( max_supply > 0 ); FC_ASSERT( market_fee_percent <= BTS_MAX_MARKET_FEE_PERCENT ); FC_ASSERT( permissions <= market_issued ); FC_ASSERT( flags <= market_issued ); FC_ASSERT( core_exchange_rate.quote.asset_id == asset_id_type() ); FC_ASSERT( core_exchange_rate.base.asset_id == asset_id_type() ); FC_ASSERT( core_exchange_rate.base.amount > 0 ); FC_ASSERT( core_exchange_rate.quote.amount > 0 ); FC_ASSERT( !(flags & ~permissions ) ); if( permissions & market_issued ) { FC_ASSERT( !(permissions & ~(white_list) ) ); FC_ASSERT( !(permissions & ~(override_authority) ) ); FC_ASSERT( !(permissions & ~(halt_transfer) ) ); } } void asset_update_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( permissions <= market_issued ); FC_ASSERT( flags <= market_issued ); if( core_exchange_rate ) { FC_ASSERT( core_exchange_rate->base.amount >= share_type(0) ); FC_ASSERT( core_exchange_rate->base.asset_id == asset_id_type() ); FC_ASSERT( core_exchange_rate->quote.amount >= share_type(0) ); FC_ASSERT( core_exchange_rate->quote.asset_id == asset_to_update ); } } share_type asset_update_operation::calculate_fee( const fee_schedule_type& k )const { return k.at( asset_update_fee_type ); } void asset_issue_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( asset_to_issue.amount.value <= BTS_MAX_SHARE_SUPPLY ); FC_ASSERT( asset_to_issue.amount.value > 0 ); FC_ASSERT( asset_to_issue.asset_id != 0 ); } share_type asset_issue_operation::calculate_fee( const fee_schedule_type& k )const { return k.at( asset_issue_fee_type ); } share_type delegate_create_operation::calculate_fee( const fee_schedule_type& k )const { return k.at( delegate_create_fee_type ) ; } share_type delegate_update_operation::calculate_fee( const fee_schedule_type& k )const { return k.at( delegate_update_fee_type ) ; } void delegate_create_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( pay_rate <= 100 ); for( auto fee : fee_schedule ) FC_ASSERT( fee.value > 0 ); FC_ASSERT( max_block_size >= BTS_MIN_BLOCK_SIZE_LIMIT ); FC_ASSERT( max_transaction_size >= BTS_MIN_TRANSACTION_SIZE_LIMIT ); FC_ASSERT( block_interval_sec > 0 && block_interval_sec <= BTS_MAX_BLOCK_INTERVAL ); } void delegate_update_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( pay_rate <= 100 || pay_rate == 255 ); FC_ASSERT( fee_schedule || signing_key || pay_rate <= 100 ); if( fee_schedule ) for( auto fee : *fee_schedule ) FC_ASSERT( fee.value > 0 ); FC_ASSERT( max_block_size >= BTS_MIN_BLOCK_SIZE_LIMIT ); FC_ASSERT( max_transaction_size >= BTS_MIN_TRANSACTION_SIZE_LIMIT ); FC_ASSERT( block_interval_sec > 0 && block_interval_sec <= BTS_MAX_BLOCK_INTERVAL ); } void asset_fund_fee_pool_operation::validate() const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( fee.asset_id == asset_id_type() ); FC_ASSERT( amount > 0 ); } share_type asset_fund_fee_pool_operation::calculate_fee(const fee_schedule_type& k) const { return k.at( asset_fund_fee_pool_fee_type ); } } } // namespace bts::chain <commit_msg>Disallow max trx exp time less than block interval<commit_after>#include <bts/chain/operations.hpp> namespace bts { namespace chain { /** * Valid symbols have between 3 and 17 upper case characters * with at most a single "." that is not the first or last character. */ bool is_valid_symbol( const string& symbol ) { if( symbol.size() > 17 ) return false; if( symbol.size() < 3 ) return false; int dot_count = 0; for( auto c : symbol ) { if( c == '.' ) ++dot_count; else if( c < 'A' || c > 'Z' ) return false; } if( symbol[0] == '.' || symbol[symbol.size()-1] == '.' ) return false; return dot_count <= 1; } /** * Valid names are all lower case, start with [a-z] and may * have "." or "-" in the name along with a single '/'. The * next character after a "/", "." or "-" cannot be [0-9] or * another '.', '-'. * */ bool is_valid_name( const string& s ) { if( s.size() == 0 ) return true; if( s.size() < 3 ) return false; if( s.size() >= 64 ) return false; int num_slash = 0; char prev = ' '; for( auto c : s ) { if( c >= 'a' && c <= 'z' ){} else if( c >= '0' && c <= '9' ) { if( prev == ' ' || prev == '.' || prev == '-' || prev == '/' ) return false; } else switch( c ) { case '/': if( ++num_slash > 1 ) return false; case '.': case '-': if( prev == ' ' || prev == '/' || prev == '.' || prev == '-' ) return false; break; default: return false; } prev = c; } switch( s.back() ) { case '/': case '-': case '.': return false; default: return true; } } bool is_premium_name( const string& n ) { return false; } bool is_cheap_name( const string& n ) { for( auto c : n ) { if( c >= '0' && c <= '9' ) return true; if( c == '.' || c == '-' || c == '/' ) return true; } return false; } share_type account_create_operation::calculate_fee( const fee_schedule_type& schedule )const { auto bts_fee_required = schedule.at(account_create_fee_type); if( name.size() ) { uint32_t s = name.size(); if( is_premium_name( name ) ) s = 2; else if( is_cheap_name( name ) ) s = 63; while( s <= 8 ) { bts_fee_required *= 10; ++s; } } return bts_fee_required; } share_type account_update_operation::calculate_fee( const fee_schedule_type& schedule )const { return schedule.at(account_create_fee_type); } void account_update_operation::validate()const { FC_ASSERT( fee.amount > 0 ); FC_ASSERT( owner || active || voting_key || memo_key || vote ); if( vote && vote->size() > 1 ) { for( int i = 1; i < vote->size(); ++i ) FC_ASSERT( vote->at(i-1) < vote->at(i) ); } } share_type asset_create_operation::calculate_fee( const fee_schedule_type& schedule )const { auto bts_fee_required = schedule.at(asset_create_fee_type); uint32_t s = symbol.size(); while( s <= 6 ) { bts_fee_required *= 30; ++s; } return bts_fee_required; } share_type transfer_operation::calculate_fee( const fee_schedule_type& schedule )const { auto bts_fee_required = schedule.at( transfer_fee_type ); bts_fee_required += share_type((memo.size() * schedule.at( data_fee_type ).value)/1024); return bts_fee_required; } struct key_data_validate { typedef void result_type; void operator()( const address& a )const { FC_ASSERT( a != address() ); } void operator()( const public_key_type& a )const { FC_ASSERT( a != public_key_type() ); } }; void key_create_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); key_data.visit( key_data_validate() ); } void account_create_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( is_valid_name( name ) ); auto pos = name.find( '/' ); if( pos != string::npos ) { FC_ASSERT( owner.weight_threshold == 1 ); FC_ASSERT( owner.auths.size() == 1 ); } } share_type account_publish_feeds_operation::calculate_fee( const fee_schedule_type& schedule )const { auto bts_fee_required = schedule.at( publish_feed_fee_type ); return bts_fee_required; } void account_publish_feeds_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); optional<price> prev; for( auto item : feeds ) { FC_ASSERT( item.base.amount >= share_type(0) ); // prevent divide by 0 FC_ASSERT( item.quote.amount >= share_type(0) ); // prevent divide by 0 if( prev ) { FC_ASSERT( !(prev->base.asset_id == item.base.asset_id && prev->quote.asset_id == item.quote.asset_id) ); } else prev = item; } } void transfer_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( from != to ); FC_ASSERT( amount.amount > 0 ); } void asset_create_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( is_valid_symbol( symbol ) ); FC_ASSERT( max_supply <= BTS_MAX_SHARE_SUPPLY ); FC_ASSERT( max_supply > 0 ); FC_ASSERT( market_fee_percent <= BTS_MAX_MARKET_FEE_PERCENT ); FC_ASSERT( permissions <= market_issued ); FC_ASSERT( flags <= market_issued ); FC_ASSERT( core_exchange_rate.quote.asset_id == asset_id_type() ); FC_ASSERT( core_exchange_rate.base.asset_id == asset_id_type() ); FC_ASSERT( core_exchange_rate.base.amount > 0 ); FC_ASSERT( core_exchange_rate.quote.amount > 0 ); FC_ASSERT( !(flags & ~permissions ) ); if( permissions & market_issued ) { FC_ASSERT( !(permissions & ~(white_list) ) ); FC_ASSERT( !(permissions & ~(override_authority) ) ); FC_ASSERT( !(permissions & ~(halt_transfer) ) ); } } void asset_update_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( permissions <= market_issued ); FC_ASSERT( flags <= market_issued ); if( core_exchange_rate ) { FC_ASSERT( core_exchange_rate->base.amount >= share_type(0) ); FC_ASSERT( core_exchange_rate->base.asset_id == asset_id_type() ); FC_ASSERT( core_exchange_rate->quote.amount >= share_type(0) ); FC_ASSERT( core_exchange_rate->quote.asset_id == asset_to_update ); } } share_type asset_update_operation::calculate_fee( const fee_schedule_type& k )const { return k.at( asset_update_fee_type ); } void asset_issue_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( asset_to_issue.amount.value <= BTS_MAX_SHARE_SUPPLY ); FC_ASSERT( asset_to_issue.amount.value > 0 ); FC_ASSERT( asset_to_issue.asset_id != 0 ); } share_type asset_issue_operation::calculate_fee( const fee_schedule_type& k )const { return k.at( asset_issue_fee_type ); } share_type delegate_create_operation::calculate_fee( const fee_schedule_type& k )const { return k.at( delegate_create_fee_type ) ; } share_type delegate_update_operation::calculate_fee( const fee_schedule_type& k )const { return k.at( delegate_update_fee_type ) ; } void delegate_create_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( pay_rate <= 100 ); for( auto fee : fee_schedule ) FC_ASSERT( fee.value > 0 ); FC_ASSERT( max_block_size >= BTS_MIN_BLOCK_SIZE_LIMIT ); FC_ASSERT( max_transaction_size >= BTS_MIN_TRANSACTION_SIZE_LIMIT ); FC_ASSERT( block_interval_sec > 0 && block_interval_sec <= BTS_MAX_BLOCK_INTERVAL ); FC_ASSERT( max_sec_until_expiration > block_interval_sec ); } void delegate_update_operation::validate()const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( pay_rate <= 100 || pay_rate == 255 ); FC_ASSERT( fee_schedule || signing_key || pay_rate <= 100 ); if( fee_schedule ) for( auto fee : *fee_schedule ) FC_ASSERT( fee.value > 0 ); FC_ASSERT( max_block_size >= BTS_MIN_BLOCK_SIZE_LIMIT ); FC_ASSERT( max_transaction_size >= BTS_MIN_TRANSACTION_SIZE_LIMIT ); FC_ASSERT( block_interval_sec > 0 && block_interval_sec <= BTS_MAX_BLOCK_INTERVAL ); FC_ASSERT( max_sec_until_expiration > block_interval_sec ); } void asset_fund_fee_pool_operation::validate() const { FC_ASSERT( fee.amount >= 0 ); FC_ASSERT( fee.asset_id == asset_id_type() ); FC_ASSERT( amount > 0 ); } share_type asset_fund_fee_pool_operation::calculate_fee(const fee_schedule_type& k) const { return k.at( asset_fund_fee_pool_fee_type ); } } } // namespace bts::chain <|endoftext|>
<commit_before>#include <osg/Group> #include <osgDB/FileUtils> #include <osgDB/FileNameUtils> #include <osgDB/ReadFile> #include <osgDB/Registry> #include <sstream> #include "ZipArchive.h" class ReaderWriterZIP : public osgDB::ReaderWriter { public: ReaderWriterZIP() { supportsExtension("zip","Zip archive format"); osgDB::Registry::instance()->addArchiveExtension("zip"); } virtual const char* className() const { return "ZIP Database Reader/Writer"; } virtual ReadResult openArchive(const std::string& file,ArchiveStatus status, unsigned int indexBlockSize = 4096, const Options* options = NULL) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile(file, options); if (fileName.empty()) { //we do not support writing so the file must exist return ReadResult::FILE_NOT_FOUND; } // copy the incoming options if possible so that plugin options can be applied to files // inside the archive osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options? options->cloneOptions() : new osgDB::ReaderWriter::Options; osg::ref_ptr<ZipArchive> archive = new ZipArchive; if (!archive->open(fileName, osgDB::ReaderWriter::READ, local_options.get())) { return ReadResult(ReadResult::FILE_NOT_HANDLED); } return archive.get(); } /** open an archive for reading.*/ virtual ReadResult openArchive(std::istream& fin, const Options* options) const { osg::ref_ptr<ZipArchive> archive = new ZipArchive; if (!archive->open(fin, options)) { return ReadResult(ReadResult::FILE_NOT_HANDLED); } return archive.get(); } virtual osgDB::ReaderWriter::ReadResult readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const { osgDB::ReaderWriter::ReadResult result = openArchive(file, osgDB::Archive::READ); if (!result.validArchive()) return result; // copy the incoming options if possible so that plugin options can be applied to files // inside the archive osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options? options->cloneOptions() : new osgDB::ReaderWriter::Options; local_options->setDatabasePath(file); //todo- what should we read here? osgDB::ReaderWriter::ReadResult result_2 = result.getArchive()->readNode(result.getArchive()->getMasterFileName(),local_options.get()); if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES)) { // register the archive so that it is cached for future use. osgDB::Registry::instance()->addToArchiveCache(file, result.getArchive()); } return result_2; } virtual ReadResult readNode(std::istream& fin,const osgDB::ReaderWriter::Options* options) const { osgDB::ReaderWriter::ReadResult result = openArchive(fin, options); if (!result.validArchive()) return result; // copy the incoming options if possible so that plugin options can be applied to files // inside the archive osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options? options->cloneOptions() : new osgDB::ReaderWriter::Options; //todo- what should the database path be? //local_options->setDatabasePath(file); //todo- what should we read here? osgDB::ReaderWriter::ReadResult result_2 = result.getArchive()->readNode(result.getArchive()->getMasterFileName(),local_options.get()); //todo- what to do to cache the archive here? //if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES)) //{ // // register the archive so that it is cached for future use. // osgDB::Registry::instance()->addToArchiveCache(file, result.getArchive()); //} return result_2; } virtual ReadResult readImage(const std::string& file,const Options* options) const { ReadResult result = openArchive(file,osgDB::Archive::READ); if (!result.validArchive()) return result; // copy the incoming options if possible so that plugin options can be applied to files // inside the archive osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options? options->cloneOptions() : new osgDB::ReaderWriter::Options; local_options->setDatabasePath(file); ReadResult result_2 = result.getArchive()->readImage(result.getArchive()->getMasterFileName(),local_options.get()); if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES)) { // register the archive so that it is cached for future use. osgDB::Registry::instance()->addToArchiveCache(file, result.getArchive()); } return result_2; } }; // now register with sgRegistry to instantiate the above // reader/writer. REGISTER_OSGPLUGIN(zip, ReaderWriterZIP) <commit_msg>Added better handling of archives in ReaderWriterZip::readNode() so that if there is no master file definition it loads all the available nodes in the zip archive and returns an osg::Group containing all the nodes if there is more than one, or just returns the node if there is just one. Also implemented this functionality for ReaderWriterZip::readImage().<commit_after>#include <osg/Group> #include <osgDB/FileUtils> #include <osgDB/FileNameUtils> #include <osgDB/ReadFile> #include <osgDB/Registry> #include <sstream> #include "ZipArchive.h" class ReaderWriterZIP : public osgDB::ReaderWriter { public: ReaderWriterZIP() { supportsExtension("zip","Zip archive format"); osgDB::Registry::instance()->addArchiveExtension("zip"); } virtual const char* className() const { return "ZIP Database Reader/Writer"; } virtual ReadResult openArchive(const std::string& file,ArchiveStatus status, unsigned int indexBlockSize = 4096, const Options* options = NULL) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile(file, options); if (fileName.empty()) { //we do not support writing so the file must exist return ReadResult::FILE_NOT_FOUND; } // copy the incoming options if possible so that plugin options can be applied to files // inside the archive osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options? options->cloneOptions() : new osgDB::ReaderWriter::Options; osg::ref_ptr<ZipArchive> archive = new ZipArchive; if (!archive->open(fileName, osgDB::ReaderWriter::READ, local_options.get())) { return ReadResult(ReadResult::FILE_NOT_HANDLED); } return archive.get(); } /** open an archive for reading.*/ virtual ReadResult openArchive(std::istream& fin, const Options* options) const { osg::ref_ptr<ZipArchive> archive = new ZipArchive; if (!archive->open(fin, options)) { return ReadResult(ReadResult::FILE_NOT_HANDLED); } return archive.get(); } osgDB::ReaderWriter::ReadResult readNodeFromArchive(osgDB::Archive& archive, const osgDB::ReaderWriter::Options* options) const { osgDB::ReaderWriter::ReadResult result(osgDB::ReaderWriter::ReadResult::FILE_NOT_FOUND); if (!archive.getMasterFileName().empty()) { result = archive.readNode(archive.getMasterFileName(), options); } else { osgDB::Archive::FileNameList fileNameList; if (archive.getFileNames(fileNameList)) { typedef std::list< osg::ref_ptr<osg::Node> > Nodes; Nodes nodes; for(osgDB::Archive::FileNameList::iterator itr = fileNameList.begin(); itr != fileNameList.end(); ++itr) { result = archive.readNode(*itr, options); if (result.validNode()) nodes.push_back(result.getNode()); } if (!nodes.empty()) { if (nodes.size()==1) { result = osgDB::ReaderWriter::ReadResult(nodes.front().get()); } else { osg::ref_ptr<osg::Group> group = new osg::Group; for(Nodes::iterator itr = nodes.begin(); itr != nodes.end(); ++itr) { group->addChild(itr->get()); } result = osgDB::ReaderWriter::ReadResult(group.get()); } } } } return result; } virtual osgDB::ReaderWriter::ReadResult readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const { osgDB::ReaderWriter::ReadResult result = openArchive(file, osgDB::Archive::READ); if (!result.validArchive()) return result; osg::ref_ptr<osgDB::Archive> archive = result.getArchive(); if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES)) { // register the archive so that it is cached for future use. osgDB::Registry::instance()->addToArchiveCache(file, archive.get()); } // copy the incoming options if possible so that plugin options can be applied to files // inside the archive osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options? options->cloneOptions() : new osgDB::ReaderWriter::Options; local_options->setDatabasePath(file); return readNodeFromArchive(*archive, local_options.get()); } virtual ReadResult readNode(std::istream& fin,const osgDB::ReaderWriter::Options* options) const { osgDB::ReaderWriter::ReadResult result = openArchive(fin, options); if (!result.validArchive()) return result; osg::ref_ptr<osgDB::Archive> archive = result.getArchive(); // copy the incoming options if possible so that plugin options can be applied to files // inside the archive osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options? options->cloneOptions() : new osgDB::ReaderWriter::Options; return readNodeFromArchive(*archive, local_options.get()); } osgDB::ReaderWriter::ReadResult readImageFromArchive(osgDB::Archive& archive, const osgDB::ReaderWriter::Options* options) const { osgDB::ReaderWriter::ReadResult result(osgDB::ReaderWriter::ReadResult::FILE_NOT_FOUND); if (!archive.getMasterFileName().empty()) { result = archive.readImage(archive.getMasterFileName(), options); } else { osgDB::Archive::FileNameList fileNameList; if (archive.getFileNames(fileNameList)) { for(osgDB::Archive::FileNameList::iterator itr = fileNameList.begin(); itr != fileNameList.end() && !result.validImage(); ++itr) { result = archive.readImage(*itr, options); } } } return result; } virtual ReadResult readImage(const std::string& file,const Options* options) const { osgDB::ReaderWriter::ReadResult result = openArchive(file, osgDB::Archive::READ); if (!result.validArchive()) return result; osg::ref_ptr<osgDB::Archive> archive = result.getArchive(); if (!options || (options->getObjectCacheHint() & osgDB::ReaderWriter::Options::CACHE_ARCHIVES)) { // register the archive so that it is cached for future use. osgDB::Registry::instance()->addToArchiveCache(file, archive.get()); } // copy the incoming options if possible so that plugin options can be applied to files // inside the archive osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options? options->cloneOptions() : new osgDB::ReaderWriter::Options; local_options->setDatabasePath(file); return readImageFromArchive(*archive, local_options.get()); } virtual ReadResult readImage(std::istream& fin,const osgDB::ReaderWriter::Options* options) const { osgDB::ReaderWriter::ReadResult result = openArchive(fin, options); if (!result.validArchive()) return result; osg::ref_ptr<osgDB::Archive> archive = result.getArchive(); // copy the incoming options if possible so that plugin options can be applied to files // inside the archive osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options? options->cloneOptions() : new osgDB::ReaderWriter::Options; return readImageFromArchive(*archive, local_options.get()); } }; // now register with sgRegistry to instantiate the above // reader/writer. REGISTER_OSGPLUGIN(zip, ReaderWriterZIP) <|endoftext|>
<commit_before>//===-- SocketSyncClient.cpp - Socket Syncing for GameModel -------- c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/sync/ModelSync.h" #include "uwhd/model/GameModel.h" #include <cstring> #include <string> #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #include <memory> #include <cassert> static const int MAX_EVENTS = 16; using namespace uwhtimer; class SocketSyncClient : public ModelSync, GameModelManager { public: SocketSyncClient(const std::string &Host, const std::string &Port); virtual void Init() override; virtual void PushModel(GameModel M) override; virtual GameModel PullModel() override; virtual void setMgr(GameModelManager *M) override { assert(false); } virtual GameModelManager &getMgr() override { return *this; } virtual void setModel(GameModel Model) override; private: std::string Host; std::string Port; int SockFD; }; SocketSyncClient::SocketSyncClient(const std::string &Host, const std::string &Port) : Host(Host), Port(Port) { } void SocketSyncClient::Init() { SockFD = socket(AF_INET, SOCK_STREAM, 0); if (SockFD < 0) { perror("Error opening socket"); exit(1); } struct hostent *server = gethostbyname(Host.c_str()); if (server == nullptr) { fprintf(stderr, "ERROR, no such host\n"); exit(0); } struct sockaddr_in serv_addr; bzero(&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(atoi(Port.c_str())); if (connect(SockFD, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) { perror("ERROR connecting"); exit(1); } const char *test = "SB2W1T13E"; write(SockFD, test, strlen(test)); } void SocketSyncClient::PushModel(GameModel M) { } GameModel SocketSyncClient::PullModel() { return GameModel(); } void SocketSyncClient::setModel(GameModel Model) { std::string Ser = Model.serialize(); write(SockFD, Ser.c_str(), Ser.size()); } std::unique_ptr<ModelSync> uwhtimer::CreateSocketClient(const std::string &Host, const std::string &Port) { return std::unique_ptr<ModelSync>(new SocketSyncClient(Host, Port)); } <commit_msg>Print messages on send<commit_after>//===-- SocketSyncClient.cpp - Socket Syncing for GameModel -------- c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/sync/ModelSync.h" #include "uwhd/model/GameModel.h" #include <cstring> #include <string> #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #include <memory> #include <cassert> #include <iostream> static const int MAX_EVENTS = 16; using namespace uwhtimer; class SocketSyncClient : public ModelSync, GameModelManager { public: SocketSyncClient(const std::string &Host, const std::string &Port); virtual void Init() override; virtual void PushModel(GameModel M) override; virtual GameModel PullModel() override; virtual void setMgr(GameModelManager *M) override { assert(false); } virtual GameModelManager &getMgr() override { return *this; } virtual void setModel(GameModel Model) override; private: std::string Host; std::string Port; int SockFD; }; SocketSyncClient::SocketSyncClient(const std::string &Host, const std::string &Port) : Host(Host), Port(Port) { } void SocketSyncClient::Init() { SockFD = socket(AF_INET, SOCK_STREAM, 0); if (SockFD < 0) { perror("Error opening socket"); exit(1); } struct hostent *server = gethostbyname(Host.c_str()); if (server == nullptr) { fprintf(stderr, "ERROR, no such host\n"); exit(0); } struct sockaddr_in serv_addr; bzero(&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(atoi(Port.c_str())); if (connect(SockFD, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) { perror("ERROR connecting"); exit(1); } } void SocketSyncClient::PushModel(GameModel M) { } GameModel SocketSyncClient::PullModel() { return GameModel(); } void SocketSyncClient::setModel(GameModel Model) { std::string Ser = Model.serialize(); std::cout << "Sending: '" << Ser << "'\n"; write(SockFD, Ser.c_str(), Ser.size()); } std::unique_ptr<ModelSync> uwhtimer::CreateSocketClient(const std::string &Host, const std::string &Port) { return std::unique_ptr<ModelSync>(new SocketSyncClient(Host, Port)); } <|endoftext|>
<commit_before>//===-- SocketSyncClient.cpp - Socket Syncing for GameModel -------- c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/sync/ModelSync.h" #include "uwhd/model/GameModel.h" #include <cstring> #include <string> #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #include <memory> #include <cassert> #include <iostream> static const int MAX_EVENTS = 16; using namespace uwhtimer; class SocketSyncClient : public ModelSync, GameModelManager { public: SocketSyncClient(const std::string &Host, const std::string &Port); virtual void Init() override; virtual void PushModel(GameModel M) override; virtual GameModel PullModel() override; virtual void setMgr(GameModelManager *M) override { assert(false); } virtual GameModelManager &getMgr() override { return *this; } virtual void setModel(GameModel Model) override; private: std::string Host; std::string Port; int SockFD; }; SocketSyncClient::SocketSyncClient(const std::string &Host, const std::string &Port) : Host(Host), Port(Port) { } void SocketSyncClient::Init() { SockFD = socket(AF_INET, SOCK_STREAM, 0); if (SockFD < 0) { perror("Error opening socket"); exit(1); } struct hostent *server = gethostbyname(Host.c_str()); if (server == nullptr) { fprintf(stderr, "ERROR, no such host\n"); exit(0); } struct sockaddr_in serv_addr; bzero(&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(atoi(Port.c_str())); if (connect(SockFD, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) { perror("ERROR connecting"); exit(1); } } void SocketSyncClient::PushModel(GameModel M) { } GameModel SocketSyncClient::PullModel() { return GameModel(); } void SocketSyncClient::setModel(GameModel Model) { std::string Ser = Model.serialize(); std::cout << "Sending: '" << Ser << "'\n"; write(SockFD, Ser.c_str(), Ser.size()); GameModelManager::setModel(Model); } std::unique_ptr<ModelSync> uwhtimer::CreateSocketClient(const std::string &Host, const std::string &Port) { return std::unique_ptr<ModelSync>(new SocketSyncClient(Host, Port)); } <commit_msg>Make client start a new connection for every transaction<commit_after>//===-- SocketSyncClient.cpp - Socket Syncing for GameModel -------- c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/sync/ModelSync.h" #include "uwhd/model/GameModel.h" #include <cstring> #include <string> #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #include <memory> #include <cassert> #include <iostream> static const int MAX_EVENTS = 16; using namespace uwhtimer; class SocketSyncClient : public ModelSync, GameModelManager { public: SocketSyncClient(const std::string &Host, const std::string &Port); virtual void Init() override; virtual void PushModel(GameModel M) override; virtual GameModel PullModel() override; virtual void setMgr(GameModelManager *M) override { assert(false); } virtual GameModelManager &getMgr() override { return *this; } virtual void setModel(GameModel Model) override; private: std::string Host; std::string Port; }; SocketSyncClient::SocketSyncClient(const std::string &Host, const std::string &Port) : Host(Host), Port(Port) { } void SocketSyncClient::Init() { } void SocketSyncClient::PushModel(GameModel M) { } GameModel SocketSyncClient::PullModel() { return GameModel(); } void SocketSyncClient::setModel(GameModel Model) { int SockFD = socket(AF_INET, SOCK_STREAM, 0); if (SockFD < 0) { perror("Error opening socket"); exit(1); } struct hostent *server = gethostbyname(Host.c_str()); if (server == nullptr) { fprintf(stderr, "ERROR, no such host\n"); exit(0); } struct sockaddr_in serv_addr; bzero(&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(atoi(Port.c_str())); if (connect(SockFD, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) { perror("ERROR connecting"); exit(1); } std::string Ser = Model.serialize(); std::cout << "Sending: '" << Ser << "'\n"; write(SockFD, Ser.c_str(), Ser.size()); GameModelManager::setModel(Model); close(SockFD); } std::unique_ptr<ModelSync> uwhtimer::CreateSocketClient(const std::string &Host, const std::string &Port) { return std::unique_ptr<ModelSync>(new SocketSyncClient(Host, Port)); } <|endoftext|>
<commit_before>#include "pd_view.h" #include "pd_view.h" #include "pd_backend.h" #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <vector> #if defined(_WIN32) #define strcasecmp _stricmp #define strncasecmp _strnicmp #endif #ifdef __clang__ #pragma clang diagnostic ignored "-Wformat-nonliteral" //error: format string is not a string literal [-Werror,-Wformat-nonliteral] #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ConsoleData { ConsoleData() : historyPos(0), scrollToBottom(0) { memset(inputBuffer, 0, sizeof(inputBuffer)); } char inputBuffer[256]; std::vector<char*> items; std::vector<char*> commands; std::vector<char*> history; std::vector<char*> scripts; // TODO: Temp, for testing int historyPos; // -1: New Line, 0...history.size()-1 Browsing History bool scrollToBottom; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void clearLog(ConsoleData* consoleData) { for (size_t i = 0; i < consoleData->items.size(); ++i) free(consoleData->items[i]); consoleData->items.clear(); consoleData->scrollToBottom = true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void addLog(ConsoleData* consoleData, const char* fmt, ...) { char buffer[1024]; va_list args; va_start(args, fmt); int w = vsnprintf(buffer, 1024, fmt, args); (void)w; buffer[1024 - 1] = 0; va_end(args); consoleData->items.push_back(strdup(buffer)); consoleData->scrollToBottom = true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void execCommand(ConsoleData* consoleData, const char* commandLine) { // TODO: Hook up as PD event addLog(consoleData, "# %s\n", commandLine); // Insert history. First find match and delete it, so it can be pushed to the back. consoleData->historyPos = -1; for (int i = int(consoleData->history.size()) - 1; i >= 0; --i) { if (strcasecmp(consoleData->history[(size_t)i], commandLine) == 0) { free(consoleData->history[(size_t)i]); consoleData->history.erase(consoleData->history.begin() + i); break; } } consoleData->history.push_back(strdup(commandLine)); // Process the command if (strcasecmp(commandLine, "clear") == 0) { clearLog(consoleData); } else if (strcasecmp(commandLine, "help") == 0) { addLog(consoleData, "Commands:"); for (size_t i = 0; i < consoleData->commands.size(); i++) addLog(consoleData, "- %s", consoleData->commands[i]); } else if (strcasecmp(commandLine, "history") == 0) { for (size_t i = consoleData->history.size() >= 10 ? consoleData->history.size() - 10 : 0; i < consoleData->history.size(); i++) addLog(consoleData, "%3d: %s\n", i, consoleData->history[i]); } else if (strcasecmp(commandLine, "testText") == 0) // TODO: Temp for testing { addLog(consoleData, "Some text\nSome more text\nDisplay very important message here!\n"); } else if (strcasecmp(commandLine, "testError") == 0) // TODO: Temp for testing { addLog(consoleData, "[Error] Something went wrong!\n"); } else if (strcasecmp(commandLine, "testScript") == 0) // TODO: Temp for testing { consoleData->scripts.push_back((char*)"print(\"Hello ProDBG Lua World!\")"); } else { addLog(consoleData, "Unknown command: '%s'\n", commandLine); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void textEditCallbackStub(PDInputTextCallbackData* data) { ConsoleData* consoleData = (ConsoleData*)data->userData; //addLog(consoleData, "Cursor: %d, EventKey: %d, Selection: %d-%d", data->cursorPos, data->eventKey, data->selectionStart, data->selectionEnd); std::vector<const char*> candidates; const char* wordEnd = nullptr; const char* wordStart = nullptr; switch (data->eventKey) { default: break; // Tab Completion case PDKEY_TAB: { // Locate beginning of current word wordEnd = data->buffer + data->cursorPos; wordStart = wordEnd; while (wordStart > data->buffer) { const char c = wordStart[-1]; if (c == ' ' || c == '\t' || c == ',' || c == ';') break; wordStart--; } // Build a list of candidates for (size_t i = 0; i < consoleData->commands.size(); ++i) if (strncasecmp(consoleData->commands[i], wordStart, (size_t)(int(wordEnd - wordStart))) == 0) candidates.push_back(consoleData->commands[i]); if (candidates.size() == 0) { // No match addLog(consoleData, "No match for \"%.*s\"!\n", wordEnd - wordStart, wordStart); } else if (candidates.size() == 1) { // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing data->deleteChars(data, int(wordStart - data->buffer), int(wordEnd - wordStart)); data->insertChars(data, data->cursorPos, candidates[0], 0); data->insertChars(data, data->cursorPos, " ", 0); } else { // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" int matchLen = int(wordEnd - wordStart); while (true) { int c = 0; bool allCandidatesMatches = true; for (size_t i = 0; i < candidates.size() && allCandidatesMatches; i++) { if (i == 0) c = toupper(candidates[i][matchLen]); else if (c != toupper(candidates[i][matchLen])) allCandidatesMatches = false; } if (!allCandidatesMatches) break; matchLen++; } if (matchLen > 0) { data->deleteChars(data, int(wordStart - data->buffer), int(wordEnd - wordStart)); data->insertChars(data, data->cursorPos, candidates[0], candidates[0] + matchLen); } // List matches addLog(consoleData, "Possible matches:\n"); for (size_t i = 0; i < candidates.size(); i++) addLog(consoleData, "- %s\n", candidates[i]); } break; } // Command History case PDKEY_UP: case PDKEY_DOWN: { const int prevHistoryPos = consoleData->historyPos; if (data->eventKey == PDKEY_UP) { if (consoleData->historyPos == -1) consoleData->historyPos = int(consoleData->history.size()) - 1; else if (consoleData->historyPos > 0) consoleData->historyPos--; } else if (data->eventKey == PDKEY_DOWN) { if (consoleData->historyPos != -1) { if (++consoleData->historyPos >= int(consoleData->history.size())) consoleData->historyPos = -1; } } // TODO: A better implementation would preserve the data on the current input line along with cursor position if (prevHistoryPos != consoleData->historyPos) { strcpy(data->buffer, (consoleData->historyPos >= 0) ? consoleData->history[(size_t)consoleData->historyPos] : ""); data->bufferDirty = true; data->cursorPos = data->selectionStart = data->selectionEnd = int(strlen(data->buffer)); } break; } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc) { (void)serviceFunc; (void)uiFuncs; ConsoleData* consoleData = new ConsoleData; clearLog(consoleData); consoleData->historyPos = -1; consoleData->commands.push_back((char*)"HELP"); consoleData->commands.push_back((char*)"HISTORY"); consoleData->commands.push_back((char*)"CLEAR"); consoleData->commands.push_back((char*)"CLASSIFY"); // TODO: "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches. consoleData->commands.push_back((char*)"TESTTEXT"); // TODO: Temp, for testing consoleData->commands.push_back((char*)"TESTERROR"); // TODO: Temp, for testing consoleData->commands.push_back((char*)"TESTSCRIPT"); // TODO: Temp, for testing return consoleData; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void destroyInstance(void* userData) { ConsoleData* consoleData = (ConsoleData*)userData; clearLog(consoleData); free(consoleData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void showInUI(ConsoleData* consoleData, PDReader* reader, PDUI* uiFuncs) { (void)consoleData; (void)reader; uiFuncs->textWrapped("ProDBG Scripting Console"); uiFuncs->textWrapped("Enter 'HELP' for help. Press TAB to use text completion."); // TODO: display from bottom // TODO: clip manually if (PDUI_buttonSmall(uiFuncs, "Clear")) clearLog(consoleData); uiFuncs->sameLine(0, -1); uiFuncs->separator(); PDVec2 pad = { 0.0f, 0.0f }; uiFuncs->pushStyleVarV(PDStyleVar_FramePadding, pad); //static ImGuiTextFilter filter; //filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); if (uiFuncs->isItemHovered()) uiFuncs->setKeyboardFocusHere(-1); // Auto focus on hover uiFuncs->popStyleVar(1); uiFuncs->separator(); PDVec2 spacing = { 0, -uiFuncs->getTextLineSpacing() * 2 }; PDVec2 itemSpacing = { 4.0f, 1.0f }; uiFuncs->beginChild("ScrollingRegion", spacing, false, PDWindowFlags(0)); uiFuncs->pushStyleVarV(PDStyleVar_ItemSpacing, itemSpacing); // Tighten spacing for (size_t i = 0; i < consoleData->items.size(); i++) { const char* item = consoleData->items[i]; //if (!filter.PassFilter(item)) // continue; PDVec4 col = { 1.0f, 1.0f, 1.0f, 1.0f }; // A better implementation may store a type per-item. For now let's just parse the text. if (strstr(item, "[Error]")) col = { 1.0f, 0.4f, 0.4f, 1.0f }; else if (strncmp(item, "# ", 2) == 0) col = { 1.0f, 0.8f, 0.6f, 1.0f }; uiFuncs->textColored(col, item); } if (consoleData->scrollToBottom) uiFuncs->setScrollHere(); consoleData->scrollToBottom = false; uiFuncs->popStyleVar(1); uiFuncs->endChild(); uiFuncs->separator(); // Command Line if (uiFuncs->inputText("Input", consoleData->inputBuffer, sizeof(consoleData->inputBuffer), PDInputTextFlags_EnterReturnsTrue | PDInputTextFlags_CallbackCompletion | PDInputTextFlags_CallbackHistory, &textEditCallbackStub, (void*)consoleData)) { char* inputEnd = consoleData->inputBuffer + strlen(consoleData->inputBuffer); while (inputEnd > consoleData->inputBuffer && inputEnd[-1] == ' ') inputEnd--; *inputEnd = 0; if (consoleData->inputBuffer[0]) execCommand(consoleData, consoleData->inputBuffer); strcpy(consoleData->inputBuffer, ""); } if (uiFuncs->isItemHovered()) uiFuncs->setKeyboardFocusHere(-1); // Auto focus on hover } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* outEvents) { ConsoleData* consoleData = (ConsoleData*)userData; uint32_t event = 0; (void)event; /*while ((event = PDRead_getEvent(inEvents)) != 0) { switch (event) { case PDEventType_setConsole: { //showInUI((ConsoleData*)userData, inEvents, uiFuncs); break; } } }*/ showInUI(consoleData, inEvents, uiFuncs); for (size_t i = 0; i < consoleData->scripts.size(); ++i) { PDWrite_eventBegin(outEvents, PDEventType_executeConsole); PDWrite_string(outEvents, "command", consoleData->scripts[i]); // TODO: Remove me PDWrite_eventEnd(outEvents); //free(consoleData->scripts[i]); } consoleData->scripts.clear(); // Request console data PDWrite_eventBegin(outEvents, PDEventType_getConsole); PDWrite_u8(outEvents, "dummy_remove", 0); // TODO: Remove me PDWrite_eventEnd(outEvents); return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static PDViewPlugin plugin = { "Console", createInstance, destroyInstance, update, }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData) { registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } <commit_msg>Fail the build!<commit_after>#include "pd_view.h" #include "pd_view.h" #include "pd_backend.h" #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <vector> #if defined(_WIN32) #define strcasecmp _stricmp #define strncasecmp _strnicmp #endif #ifdef __clang__ #pragma clang diagnostic ignored "-Wformat-nonliteral" //error: format string is not a string literal [-Werror,-Wformat-nonliteral] #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ConsoleData { ConsoleData() : historyPos(0), scrollToBottom(0) { memset(inputBuffer, 0, sizeof(inputBuffer)); } char inputBuffer[256]; std::vector<char*> items; std::vector<char*> commands; std::vector<char*> history; std::vector<char*> scripts; // TODO: Temp, for testing int historyPos; // -1: New Line, 0...history.size()-1 Browsing History bool scrollToBottom; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void clearLog(ConsoleData* consoleData) { for (size_t i = 0; i < consoleData->items.size(); ++i) free(consoleData->items[i]); consoleData->items.clear(); consoleData->scrollToBottom = true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void addLog(ConsoleData* consoleData, const char* fmt, ...) { char buffer[1024]; va_list args; va_start(args, fmt); int w = vsnprintf(buffer, 1024, fmt, args); (void)w; buffer[1024 - 1] = 0; va_end(args); consoleData->items.push_back(strdup(buffer)); consoleData->scrollToBottom = true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void execCommand(ConsoleData* consoleData, const char* commandLine) { // TODO: Hook up as PD event addLog(consoleData, "# %s\n", commandLine); // Insert history. First find match and delete it, so it can be pushed to the back. consoleData->historyPos = -1; for (int i = int(consoleData->history.size()) - 1; i >= 0; --i) { if (strcasecmp(consoleData->history[(size_t)i], commandLine) == 0) { free(consoleData->history[(size_t)i]); consoleData->history.erase(consoleData->history.begin() + i); break; } } consoleData->history.push_back(strdup(commandLine)); // Process the command if (strcasecmp(commandLine, "clear") == 0) { clearLog(consoleData); } else if (strcasecmp(commandLine, "help") == 0) { addLog(consoleData, "Commands:"); for (size_t i = 0; i < consoleData->commands.size(); i++) addLog(consoleData, "- %s", consoleData->commands[i]); } else if (strcasecmp(commandLine, "history") == 0) { for (size_t i = consoleData->history.size() >= 10 ? consoleData->history.size() - 10 : 0; i < consoleData->history.size(); i++) addLog(consoleData, "%3d: %s\n", i, consoleData->history[i]); } else if (strcasecmp(commandLine, "testText") == 0) // TODO: Temp for testing { addLog(consoleData, "Some text\nSome more text\nDisplay very important message here!\n"); } else if (strcasecmp(commandLine, "testError") == 0) // TODO: Temp for testing { addLog(consoleData, "[Error] Something went wrong!\n"); } else if (strcasecmp(commandLine, "testScript") == 0) // TODO: Temp for testing { consoleData->scripts.push_back((char*)"print(\"Hello ProDBG Lua World!\")"); } else { addLog(consoleData, "Unknown command: '%s'\n", commandLine); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void textEditCallbackStub(PDInputTextCallbackData* data) { ConsoleData* consoleData = (ConsoleData*)data->userData; //addLog(consoleData, "Cursor: %d, EventKey: %d, Selection: %d-%d", data->cursorPos, data->eventKey, data->selectionStart, data->selectionEnd); std::vector<const char*> candidates; const char* wordEnd = nullptr; const char* wordStart = nullptr; switch (data->eventKey) { default: break; // Tab Completion case PDKEY_TAB: { // Locate beginning of current word wordEnd = data->buffer + data->cursorPos; wordStart = wordEnd; while (wordStart > data->buffer) { const char c = wordStart[-1]; if (c == ' ' || c == '\t' || c == ',' || c == ';') break; wordStart--; } // Build a list of candidates for (size_t i = 0; i < consoleData->commands.size(); ++i) if (strncasecmp(consoleData->commands[i], wordStart, (size_t)(int(wordEnd - wordStart))) == 0) candidates.push_back(consoleData->commands[i]); if (candidates.size() == 0) { // No match addLog(consoleData, "No match for \"%.*s\"!\n", wordEnd - wordStart, wordStart); } else if (candidates.size() == 1) { // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing data->deleteChars(data, int(wordStart - data->buffer), int(wordEnd - wordStart)); data->insertChars(data, data->cursorPos, candidates[0], 0); data->insertChars(data, data->cursorPos, " ", 0); } else { // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" int matchLen = int(wordEnd - wordStart); while (true) { int c = 0; bool allCandidatesMatches = true; for (size_t i = 0; i < candidates.size() && allCandidatesMatches; i++) { if (i == 0) c = toupper(candidates[i][matchLen]); else if (c != toupper(candidates[i][matchLen])) allCandidatesMatches = false; } if (!allCandidatesMatches) break; matchLen++; } if (matchLen > 0) { data->deleteChars(data, int(wordStart - data->buffer), int(wordEnd - wordStart)); data->insertChars(data, data->cursorPos, candidates[0], candidates[0] + matchLen); } // List matches addLog(consoleData, "Possible matches:\n"); for (size_t i = 0; i < candidates.size(); i++) addLog(consoleData, "- %s\n", candidates[i]); } break; } // Command History case PDKEY_UP: case PDKEY_DOWN: { const int prevHistoryPos = consoleData->historyPos; if (data->eventKey == PDKEY_UP) { if (consoleData->historyPos == -1) consoleData->historyPos = int(consoleData->history.size()) - 1; else if (consoleData->historyPos > 0) consoleData->historyPos--; } else if (data->eventKey == PDKEY_DOWN) { if (consoleData->historyPos != -1) { if (++consoleData->historyPos >= int(consoleData->history.size())) consoleData->historyPos = -1; } } // TODO: A better implementation would preserve the data on the current input line along with cursor position if (prevHistoryPos != consoleData->historyPos) { strcpy(data->buffer, (consoleData->historyPos >= 0) ? consoleData->history[(size_t)consoleData->historyPos] : ""); data->bufferDirty = true; data->cursorPos = data->selectionStart = data->selectionEnd = int(strlen(data->buffer)); } break; } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc) { (void)serviceFunc; (void)uiFuncs; ConsoleData* consoleData = new ConsoleData; clearLog(consoleData); consoleData->historyPos = -1; consoleData->commands.push_back((char*)"HELP"); consoleData->commands.push_back((char*)"HISTORY"); consoleData->commands.push_back((char*)"CLEAR"); consoleData->commands.push_back((char*)"CLASSIFY"); // TODO: "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches. consoleData->commands.push_back((char*)"TESTTEXT"); // TODO: Temp, for testing consoleData->commands.push_back((char*)"TESTERROR"); // TODO: Temp, for testing consoleData->commands.push_back((char*)"TESTSCRIPT"); // TODO: Temp, for testing return consoleData; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void destroyInstance(void* userData) { ConsoleData* consoleData = (ConsoleData*)userData; clearLog(consoleData); free(consoleData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void showInUI(ConsoleData* consoleData, PDReader* reader, PDUI* uiFuncs) { (void)consoleData; (void)reader; uiFuncs->textWrapped("ProDBG Scripting Console"); uiFuncs->textWrapped("Enter 'HELP' for help. Press TAB to use text completion."); // TODO: display from bottom // TODO: clip manually if (PDUI_buttonSmall(uiFuncs, "Clear")) clearLog(consoleData); uiFuncs->sameLine(0, -1); uiFuncs->separator(); PDVec2 pad = { 0.0f, 0.0f }; uiFuncs->pushStyleVarV(PDStyleVar_FramePadding, pad); //static ImGuiTextFilter filter; //filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); if (uiFuncs->isItemHovered()) uiFuncs->setKeyboardFocusHere(-1); // Auto focus on hover uiFuncs->popStyleVar(1); uiFuncs->separator(); PDVec2 spacing = { 0, -uiFuncs->getTextLineSpacing() * 2 }; PDVec2 itemSpacing = { 4.0f, 1.0f }; uiFuncs->beginChild("ScrollingRegion", spacing, false, PDWindowFlags(0)); uiFuncs->pushStyleVarV(PDStyleVar_ItemSpacing, itemSpacing); // Tighten spacing for (size_t i = 0; i < consoleData->items.size(); i++) { const char* item = consoleData->items[i]; //if (!filter.PassFilter(item)) // continue; PDVec4 col = { 1.0f, 1.0f, 1.0f, 1.0f }; // A better implementation may store a type per-item. For now let's just parse the text. if (strstr(item, "[Error]")) col = { 1.0f, 0.4f, 0.4f, 1.0f }; else if (strncmp(item, "# ", 2) == 0) col = { 1.0f, 0.8f, 0.6f, 1.0f }; uiFuncs->textColored(col, item); } if (consoleData->scrollToBottom) uiFuncs->setScrollHere(); consoleData->scrollToBottom = false; uiFuncs->popStyleVar(1); uiFuncs->endChild(); uiFuncs->separator(); // Command Line if (uiFuncs->inputText("Input", consoleData->inputBuffer, sizeof(consoleData->inputBuffer), PDInputTextFlags_EnterReturnsTrue | PDInputTextFlags_CallbackCompletion | PDInputTextFlags_CallbackHistory, &textEditCallbackStub, (void*)consoleData)) { char* inputEnd = consoleData->inputBuffer + strlen(consoleData->inputBuffer); while (inputEnd > consoleData->inputBuffer && inputEnd[-1] == ' ') inputEnd--; *inputEnd = 0; if (consoleData->inputBuffer[0]) execCommand(consoleData, consoleData->inputBuffer); strcpy(consoleData->inputBuffer, ""); } if (uiFuncs->isItemHovered()) uiFuncs->setKeyboardFocusHere(-1); // Auto focus on hover } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* outEvents) { ConsoleData* consoleData = (ConsoleData*)userData; onsteuhso uint32_t event = 0; (void)event; /*while ((event = PDRead_getEvent(inEvents)) != 0) { switch (event) { case PDEventType_setConsole: { //showInUI((ConsoleData*)userData, inEvents, uiFuncs); break; } } }*/ showInUI(consoleData, inEvents, uiFuncs); for (size_t i = 0; i < consoleData->scripts.size(); ++i) { PDWrite_eventBegin(outEvents, PDEventType_executeConsole); PDWrite_string(outEvents, "command", consoleData->scripts[i]); // TODO: Remove me PDWrite_eventEnd(outEvents); //free(consoleData->scripts[i]); } consoleData->scripts.clear(); // Request console data PDWrite_eventBegin(outEvents, PDEventType_getConsole); PDWrite_u8(outEvents, "dummy_remove", 0); // TODO: Remove me PDWrite_eventEnd(outEvents); return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static PDViewPlugin plugin = { "Console", createInstance, destroyInstance, update, }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData) { registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** **************************************************************************/ #include "moduleswindow.h" #include "moduleshandler.h" // for model roles #include <QtCore/QDebug> #include <QtCore/QProcess> #include <QtCore/QRegExp> #include <QtGui/QAction> #include <QtGui/QHeaderView> #include <QtGui/QMenu> #include <QtGui/QResizeEvent> #include <QtGui/QToolButton> #include <QtGui/QTreeWidget> /////////////////////////////////////////////////////////////////////////// // // ModulesWindow // /////////////////////////////////////////////////////////////////////////// using Debugger::Internal::ModulesWindow; ModulesWindow::ModulesWindow(QWidget *parent) : QTreeView(parent), m_alwaysResizeColumnsToContents(false) { setWindowTitle(tr("Modules")); setSortingEnabled(true); setAlternatingRowColors(true); setRootIsDecorated(false); setIconSize(QSize(10, 10)); connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(moduleActivated(QModelIndex))); } void ModulesWindow::moduleActivated(const QModelIndex &index) { qDebug() << "ACTIVATED: " << index.row() << index.column() << model()->data(index); emit fileOpenRequested(model()->data(index).toString()); } void ModulesWindow::resizeEvent(QResizeEvent *event) { //QHeaderView *hv = header(); //int totalSize = event->size().width() - 110; //hv->resizeSection(0, totalSize / 4); //hv->resizeSection(1, totalSize / 4); //hv->resizeSection(2, totalSize / 4); //hv->resizeSection(3, totalSize / 4); //hv->resizeSection(0, 60); //hv->resizeSection(1, (totalSize * 50) / 100); //hv->resizeSection(2, (totalSize * 50) / 100); //hv->resizeSection(3, 50); //setColumnHidden(3, true); QTreeView::resizeEvent(event); } void ModulesWindow::contextMenuEvent(QContextMenuEvent *ev) { QModelIndex index = indexAt(ev->pos()); index = index.sibling(index.row(), 0); QString name = model()->data(index).toString(); QMenu menu; QAction *act0 = new QAction(tr("Update module list"), &menu); QAction *act1 = new QAction(tr("Adjust column widths to contents"), &menu); QAction *act2 = new QAction(tr("Always adjust column widths to contents"), &menu); act2->setCheckable(true); act2->setChecked(m_alwaysResizeColumnsToContents); QAction *act3 = new QAction(tr("Show source files for module \"%1\"").arg(name), &menu); QAction *act4 = new QAction(tr("Load symbols for all modules"), &menu); QAction *act5 = 0; QAction *act6 = 0; QAction *act7 = 0; if (name.isEmpty()) { act5 = new QAction(tr("Load symbols for module"), &menu); act6 = new QAction(tr("Edit file"), &menu); act7 = new QAction(tr("Show symbols"), &menu); } else { act5 = new QAction(tr("Load symbols for module \"%1\"").arg(name), &menu); act6 = new QAction(tr("Edit file \"%1\"").arg(name), &menu); act7 = new QAction(tr("Show symbols in file \"%1\"").arg(name), &menu); } act5->setDisabled(name.isEmpty()); act6->setDisabled(name.isEmpty()); act7->setDisabled(name.isEmpty()); #ifndef Q_OS_LINUX act7->setDisabled(true)l #endif menu.addAction(act0); menu.addAction(act4); menu.addAction(act5); menu.addAction(act6); menu.addAction(act7); menu.addSeparator(); menu.addAction(act1); menu.addAction(act2); QAction *act = menu.exec(ev->globalPos()); if (act == act0) emit reloadModulesRequested(); else if (act == act1) resizeColumnsToContents(); else if (act == act2) setAlwaysResizeColumnsToContents(!m_alwaysResizeColumnsToContents); else if (act == act3) emit displaySourceRequested(name); else if (act == act4) emit loadAllSymbolsRequested(); else if (act == act5) emit loadSymbolsRequested(name); else if (act == act6) emit fileOpenRequested(name); else if (act == act7) showSymbols(name); } void ModulesWindow::resizeColumnsToContents() { resizeColumnToContents(0); resizeColumnToContents(1); resizeColumnToContents(2); } void ModulesWindow::setAlwaysResizeColumnsToContents(bool on) { m_alwaysResizeColumnsToContents = on; QHeaderView::ResizeMode mode = on ? QHeaderView::ResizeToContents : QHeaderView::Interactive; header()->setResizeMode(0, mode); header()->setResizeMode(1, mode); header()->setResizeMode(2, mode); header()->setResizeMode(3, mode); //setColumnHidden(3, true); } void ModulesWindow::setModel(QAbstractItemModel *model) { QTreeView::setModel(model); setAlwaysResizeColumnsToContents(true); } void ModulesWindow::showSymbols(const QString &name) { if (name.isEmpty()) return; QProcess proc; proc.start("nm", QStringList() << "-D" << name); proc.waitForFinished(); QTreeWidget *w = new QTreeWidget; w->setColumnCount(3); w->setRootIsDecorated(false); w->setAlternatingRowColors(true); //w->header()->hide(); w->setHeaderLabels(QStringList() << tr("Address") << tr("Code") << tr("Symbol")); w->setWindowTitle(tr("Symbols in \"%1\"").arg(name)); QString contents = QString::fromLocal8Bit(proc.readAllStandardOutput()); QRegExp re("([0-9a-f]+)?\\s+([^\\s]+)\\s+([^\\s]+)"); foreach (QString line, contents.split('\n')) { if (re.indexIn(line) != -1) { QTreeWidgetItem *it = new QTreeWidgetItem; it->setData(0, Qt::DisplayRole, re.cap(1)); it->setData(1, Qt::DisplayRole, re.cap(2)); it->setData(2, Qt::DisplayRole, re.cap(3)); w->addTopLevelItem(it); } else { qDebug() << "UNHANDLED LINE" << line; } } emit newDockRequested(w); } <commit_msg>Fixes: debugger: compile fix<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** **************************************************************************/ #include "moduleswindow.h" #include "moduleshandler.h" // for model roles #include <QtCore/QDebug> #include <QtCore/QProcess> #include <QtCore/QRegExp> #include <QtGui/QAction> #include <QtGui/QHeaderView> #include <QtGui/QMenu> #include <QtGui/QResizeEvent> #include <QtGui/QToolButton> #include <QtGui/QTreeWidget> /////////////////////////////////////////////////////////////////////////// // // ModulesWindow // /////////////////////////////////////////////////////////////////////////// using Debugger::Internal::ModulesWindow; ModulesWindow::ModulesWindow(QWidget *parent) : QTreeView(parent), m_alwaysResizeColumnsToContents(false) { setWindowTitle(tr("Modules")); setSortingEnabled(true); setAlternatingRowColors(true); setRootIsDecorated(false); setIconSize(QSize(10, 10)); connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(moduleActivated(QModelIndex))); } void ModulesWindow::moduleActivated(const QModelIndex &index) { qDebug() << "ACTIVATED: " << index.row() << index.column() << model()->data(index); emit fileOpenRequested(model()->data(index).toString()); } void ModulesWindow::resizeEvent(QResizeEvent *event) { //QHeaderView *hv = header(); //int totalSize = event->size().width() - 110; //hv->resizeSection(0, totalSize / 4); //hv->resizeSection(1, totalSize / 4); //hv->resizeSection(2, totalSize / 4); //hv->resizeSection(3, totalSize / 4); //hv->resizeSection(0, 60); //hv->resizeSection(1, (totalSize * 50) / 100); //hv->resizeSection(2, (totalSize * 50) / 100); //hv->resizeSection(3, 50); //setColumnHidden(3, true); QTreeView::resizeEvent(event); } void ModulesWindow::contextMenuEvent(QContextMenuEvent *ev) { QModelIndex index = indexAt(ev->pos()); index = index.sibling(index.row(), 0); QString name = model()->data(index).toString(); QMenu menu; QAction *act0 = new QAction(tr("Update module list"), &menu); QAction *act1 = new QAction(tr("Adjust column widths to contents"), &menu); QAction *act2 = new QAction(tr("Always adjust column widths to contents"), &menu); act2->setCheckable(true); act2->setChecked(m_alwaysResizeColumnsToContents); QAction *act3 = new QAction(tr("Show source files for module \"%1\"").arg(name), &menu); QAction *act4 = new QAction(tr("Load symbols for all modules"), &menu); QAction *act5 = 0; QAction *act6 = 0; QAction *act7 = 0; if (name.isEmpty()) { act5 = new QAction(tr("Load symbols for module"), &menu); act6 = new QAction(tr("Edit file"), &menu); act7 = new QAction(tr("Show symbols"), &menu); } else { act5 = new QAction(tr("Load symbols for module \"%1\"").arg(name), &menu); act6 = new QAction(tr("Edit file \"%1\"").arg(name), &menu); act7 = new QAction(tr("Show symbols in file \"%1\"").arg(name), &menu); } act5->setDisabled(name.isEmpty()); act6->setDisabled(name.isEmpty()); act7->setDisabled(name.isEmpty()); #ifndef Q_OS_LINUX act7->setDisabled(true); #endif menu.addAction(act0); menu.addAction(act4); menu.addAction(act5); menu.addAction(act6); menu.addAction(act7); menu.addSeparator(); menu.addAction(act1); menu.addAction(act2); QAction *act = menu.exec(ev->globalPos()); if (act == act0) emit reloadModulesRequested(); else if (act == act1) resizeColumnsToContents(); else if (act == act2) setAlwaysResizeColumnsToContents(!m_alwaysResizeColumnsToContents); else if (act == act3) emit displaySourceRequested(name); else if (act == act4) emit loadAllSymbolsRequested(); else if (act == act5) emit loadSymbolsRequested(name); else if (act == act6) emit fileOpenRequested(name); else if (act == act7) showSymbols(name); } void ModulesWindow::resizeColumnsToContents() { resizeColumnToContents(0); resizeColumnToContents(1); resizeColumnToContents(2); } void ModulesWindow::setAlwaysResizeColumnsToContents(bool on) { m_alwaysResizeColumnsToContents = on; QHeaderView::ResizeMode mode = on ? QHeaderView::ResizeToContents : QHeaderView::Interactive; header()->setResizeMode(0, mode); header()->setResizeMode(1, mode); header()->setResizeMode(2, mode); header()->setResizeMode(3, mode); //setColumnHidden(3, true); } void ModulesWindow::setModel(QAbstractItemModel *model) { QTreeView::setModel(model); setAlwaysResizeColumnsToContents(true); } void ModulesWindow::showSymbols(const QString &name) { if (name.isEmpty()) return; QProcess proc; proc.start("nm", QStringList() << "-D" << name); proc.waitForFinished(); QTreeWidget *w = new QTreeWidget; w->setColumnCount(3); w->setRootIsDecorated(false); w->setAlternatingRowColors(true); //w->header()->hide(); w->setHeaderLabels(QStringList() << tr("Address") << tr("Code") << tr("Symbol")); w->setWindowTitle(tr("Symbols in \"%1\"").arg(name)); QString contents = QString::fromLocal8Bit(proc.readAllStandardOutput()); QRegExp re("([0-9a-f]+)?\\s+([^\\s]+)\\s+([^\\s]+)"); foreach (QString line, contents.split('\n')) { if (re.indexIn(line) != -1) { QTreeWidgetItem *it = new QTreeWidgetItem; it->setData(0, Qt::DisplayRole, re.cap(1)); it->setData(1, Qt::DisplayRole, re.cap(2)); it->setData(2, Qt::DisplayRole, re.cap(3)); w->addTopLevelItem(it); } else { qDebug() << "UNHANDLED LINE" << line; } } emit newDockRequested(w); } <|endoftext|>
<commit_before>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL 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. QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Implementation of class IncrementalPlot * @author Lorenz Meier <mavteam@student.ethz.ch> * */ #include <qwt_plot.h> #include <qwt_plot_canvas.h> #include <qwt_plot_curve.h> #include <qwt_symbol.h> #include <qwt_plot_layout.h> #include <qwt_plot_grid.h> #include <qwt_scale_engine.h> #include "IncrementalPlot.h" #include <Scrollbar.h> #include <ScrollZoomer.h> #include <float.h> #include <qpaintengine.h> #include <QDebug> CurveData::CurveData(): d_count(0) { } void CurveData::append(double *x, double *y, int count) { int newSize = ( (d_count + count) / 1000 + 1 ) * 1000; if ( newSize > size() ) { d_x.resize(newSize); d_y.resize(newSize); } for ( register int i = 0; i < count; i++ ) { d_x[d_count + i] = x[i]; d_y[d_count + i] = y[i]; } d_count += count; } int CurveData::count() const { return d_count; } int CurveData::size() const { return d_x.size(); } const double* CurveData::x() const { return d_x.data(); } const double* CurveData::y() const { return d_y.data(); } IncrementalPlot::IncrementalPlot(QWidget *parent): ChartPlot(parent), symmetric(false) { setStyleText("solid crosses"); plotLayout()->setAlignCanvasToScales(true); QwtLinearScaleEngine* yScaleEngine = new QwtLinearScaleEngine(); setAxisScaleEngine(QwtPlot::yLeft, yScaleEngine); setAxisAutoScale(xBottom); setAxisAutoScale(yLeft); resetScaling(); legend = NULL; connect(this, SIGNAL(legendChecked(QwtPlotItem*,bool)), this, SLOT(handleLegendClick(QwtPlotItem*,bool))); } IncrementalPlot::~IncrementalPlot() { } /** * @param symmetric true will enforce that both axes have the same interval, * centered around the data plot. A circle will thus remain a circle if true, * if set to false it might become an ellipse because of axis scaling. */ void IncrementalPlot::setSymmetric(bool symmetric) { this->symmetric = symmetric; updateScale(); // Updates the scaling at replots } void IncrementalPlot::handleLegendClick(QwtPlotItem* item, bool on) { item->setVisible(!on); replot(); } void IncrementalPlot::showLegend(bool show) { if (show) { if (legend == NULL) { legend = new QwtLegend; legend->setFrameStyle(QFrame::Box); legend->setDefaultItemMode(QwtLegendData::Checkable); } insertLegend(legend, QwtPlot::RightLegend); } else { delete legend; legend = NULL; } updateScale(); // Updates the scaling at replots } /** * Set datapoint and line style. This interface is intented * to be directly connected to the UI and allows to parse * human-readable, textual descriptions into plot specs. * * Data points: Either "circles", "crosses" or the default "dots" * Lines: Either "dotted", ("solid"/"line") or no lines if not used * * No special formatting is needed, as long as the keywords are contained * in the string. Lower/uppercase is ignored as well. * * @param style Formatting string for line/data point style */ void IncrementalPlot::setStyleText(const QString &style) { styleText = style.toLower(); foreach (QwtPlotCurve* curve, curves) { updateStyle(curve); } replot(); } void IncrementalPlot::updateStyle(QwtPlotCurve *curve) { if(styleText.isNull()) return; // Since the symbols always use the same color as the curve line, we just use that color. // This saves us from having to deal with cases where the symbol is NULL. QColor oldColor = curve->pen().color(); // Update the symbol style QwtSymbol *newSymbol = NULL; if (styleText.contains("circles")) { newSymbol = new QwtSymbol(QwtSymbol::Ellipse, Qt::NoBrush, QPen(oldColor, symbolWidth), QSize(6, 6)); } else if (styleText.contains("crosses")) { newSymbol = new QwtSymbol(QwtSymbol::XCross, Qt::NoBrush, QPen(oldColor, symbolWidth), QSize(5, 5)); } else if (styleText.contains("rect")) { newSymbol = new QwtSymbol(QwtSymbol::Rect, Qt::NoBrush, QPen(oldColor, symbolWidth), QSize(6, 6)); } // Else-case already handled by NULL value, which indicates no symbol curve->setSymbol(newSymbol); // Update the line style if (styleText.contains("dotted")) { curve->setPen(QPen(oldColor, curveWidth, Qt::DotLine)); } else if (styleText.contains("dashed")) { curve->setPen(QPen(oldColor, curveWidth, Qt::DashLine)); } else if (styleText.contains("line") || styleText.contains("solid")) { curve->setPen(QPen(oldColor, curveWidth, Qt::SolidLine)); } else { curve->setPen(QPen(oldColor, curveWidth, Qt::NoPen)); } curve->setStyle(QwtPlotCurve::Lines); } void IncrementalPlot::resetScaling() { xmin = 0; xmax = 500; ymin = xmin; ymax = xmax; setAxisScale(xBottom, xmin+xmin*0.05, xmax+xmax*0.05); setAxisScale(yLeft, ymin+ymin*0.05, ymax+ymax*0.05); replot(); // Make sure the first data access hits these xmin = DBL_MAX; xmax = DBL_MIN; ymin = DBL_MAX; ymax = DBL_MIN; } /** * Updates the scale calculation and re-plots the whole plot */ void IncrementalPlot::updateScale() { const double margin = 0.05; if(xmin == DBL_MAX) return; double xMinRange = xmin-(qAbs(xmin*margin)); double xMaxRange = xmax+(qAbs(xmax*margin)); double yMinRange = ymin-(qAbs(ymin*margin)); double yMaxRange = ymax+(qAbs(ymax*margin)); if (symmetric) { double xRange = xMaxRange - xMinRange; double yRange = yMaxRange - yMinRange; // Get the aspect ratio of the plot float xSize = width(); if (legend != NULL) xSize -= legend->width(); float ySize = height(); float aspectRatio = xSize / ySize; if (xRange > yRange) { double yCenter = yMinRange + yRange/2.0; double xCenter = xMinRange + xRange/2.0; yMinRange = yCenter - xRange/2.0; yMaxRange = yCenter + xRange/2.0; xMinRange = xCenter - (xRange*aspectRatio)/2.0; xMaxRange = xCenter + (xRange*aspectRatio)/2.0; } else { double xCenter = xMinRange + xRange/2.0; xMinRange = xCenter - (yRange*aspectRatio)/2.0; xMaxRange = xCenter + (yRange*aspectRatio)/2.0; } } setAxisScale(xBottom, xMinRange, xMaxRange); setAxisScale(yLeft, yMinRange, yMaxRange); zoomer->setZoomBase(true); } void IncrementalPlot::appendData(const QString &key, double x, double y) { appendData(key, &x, &y, 1); } void IncrementalPlot::appendData(const QString &key, double *x, double *y, int size) { CurveData* data; QwtPlotCurve* curve; if (!d_data.contains(key)) { data = new CurveData; d_data.insert(key, data); } else { data = d_data.value(key); } // If this is a new curve, create it. if (!curves.contains(key)) { curve = new QwtPlotCurve(key); curves.insert(key, curve); curve->setStyle(QwtPlotCurve::NoCurve); curve->setPaintAttribute(QwtPlotCurve::FilterPoints); // Set the color. Only the pen needs to be set const QColor &c = getNextColor(); curve->setPen(c, symbolWidth); qDebug() << "Creating curve" << key << "with color" << c; updateStyle(curve); curve->attach(this); } else { curve = curves.value(key); } data->append(x, y, size); curve->setRawSamples(data->x(), data->y(), data->count()); bool scaleChanged = false; // Update scales for (int i = 0; i<size; i++) { if (x[i] < xmin) { xmin = x[i]; scaleChanged = true; } if (x[i] > xmax) { xmax = x[i]; scaleChanged = true; } if (y[i] < ymin) { ymin = y[i]; scaleChanged = true; } if (y[i] > ymax) { ymax = y[i]; scaleChanged = true; } } // setAxisScale(xBottom, xmin+xmin*0.05, xmax+xmax*0.05); // setAxisScale(yLeft, ymin+ymin*0.05, ymax+ymax*0.05); //#ifdef __GNUC__ //#warning better use QwtData //#endif //replot(); if(scaleChanged) { updateScale(); } else { QwtPlotCanvas *c = static_cast<QwtPlotCanvas*>(canvas()); const bool cacheMode = c->testPaintAttribute(QwtPlotCanvas::BackingStore); c->setPaintAttribute(QwtPlotCanvas::BackingStore, false); // FIXME Check if here all curves should be drawn // QwtPlotCurve* plotCurve; // foreach(plotCurve, curves) // { // plotCurve->draw(0, curve->dataSize()-1); // } // FIXME: Unsure what this call should be now. //curve->draw(curve->dataSize() - size, curve->dataSize() - 1); replot(); c->setPaintAttribute(QwtPlotCanvas::BackingStore, cacheMode); } } /** * @return Number of copied data points, 0 on failure */ int IncrementalPlot::data(const QString &key, double* r_x, double* r_y, int maxSize) { int result = 0; if (d_data.contains(key)) { CurveData* d = d_data.value(key); if (maxSize >= d->count()) { result = d->count(); memcpy(r_x, d->x(), sizeof(double) * d->count()); memcpy(r_y, d->y(), sizeof(double) * d->count()); } else { result = 0; } } return result; } /** * @param show true to show the grid, false else */ void IncrementalPlot::showGrid(bool show) { grid->setVisible(show); replot(); } bool IncrementalPlot::gridEnabled() const { return grid->isVisible(); } void IncrementalPlot::removeData() { foreach (QwtPlotCurve* curve, curves) { delete curve; } curves.clear(); foreach (CurveData* data, d_data) { delete data; } d_data.clear(); resetScaling(); replot(); } <commit_msg>Remove non-existent signal connection from IncrementalPlot. I don't think it's needed anywhere in QGC since this has been a bug for a long time.<commit_after>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL 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. QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Implementation of class IncrementalPlot * @author Lorenz Meier <mavteam@student.ethz.ch> * */ #include <qwt_plot.h> #include <qwt_plot_canvas.h> #include <qwt_plot_curve.h> #include <qwt_symbol.h> #include <qwt_plot_layout.h> #include <qwt_plot_grid.h> #include <qwt_scale_engine.h> #include "IncrementalPlot.h" #include <Scrollbar.h> #include <ScrollZoomer.h> #include <float.h> #include <qpaintengine.h> #include <QDebug> CurveData::CurveData(): d_count(0) { } void CurveData::append(double *x, double *y, int count) { int newSize = ( (d_count + count) / 1000 + 1 ) * 1000; if ( newSize > size() ) { d_x.resize(newSize); d_y.resize(newSize); } for ( register int i = 0; i < count; i++ ) { d_x[d_count + i] = x[i]; d_y[d_count + i] = y[i]; } d_count += count; } int CurveData::count() const { return d_count; } int CurveData::size() const { return d_x.size(); } const double* CurveData::x() const { return d_x.data(); } const double* CurveData::y() const { return d_y.data(); } IncrementalPlot::IncrementalPlot(QWidget *parent): ChartPlot(parent), symmetric(false) { setStyleText("solid crosses"); plotLayout()->setAlignCanvasToScales(true); QwtLinearScaleEngine* yScaleEngine = new QwtLinearScaleEngine(); setAxisScaleEngine(QwtPlot::yLeft, yScaleEngine); setAxisAutoScale(xBottom); setAxisAutoScale(yLeft); resetScaling(); legend = NULL; } IncrementalPlot::~IncrementalPlot() { } /** * @param symmetric true will enforce that both axes have the same interval, * centered around the data plot. A circle will thus remain a circle if true, * if set to false it might become an ellipse because of axis scaling. */ void IncrementalPlot::setSymmetric(bool symmetric) { this->symmetric = symmetric; updateScale(); // Updates the scaling at replots } void IncrementalPlot::handleLegendClick(QwtPlotItem* item, bool on) { item->setVisible(!on); replot(); } void IncrementalPlot::showLegend(bool show) { if (show) { if (legend == NULL) { legend = new QwtLegend; legend->setFrameStyle(QFrame::Box); legend->setDefaultItemMode(QwtLegendData::Checkable); } insertLegend(legend, QwtPlot::RightLegend); } else { delete legend; legend = NULL; } updateScale(); // Updates the scaling at replots } /** * Set datapoint and line style. This interface is intented * to be directly connected to the UI and allows to parse * human-readable, textual descriptions into plot specs. * * Data points: Either "circles", "crosses" or the default "dots" * Lines: Either "dotted", ("solid"/"line") or no lines if not used * * No special formatting is needed, as long as the keywords are contained * in the string. Lower/uppercase is ignored as well. * * @param style Formatting string for line/data point style */ void IncrementalPlot::setStyleText(const QString &style) { styleText = style.toLower(); foreach (QwtPlotCurve* curve, curves) { updateStyle(curve); } replot(); } void IncrementalPlot::updateStyle(QwtPlotCurve *curve) { if(styleText.isNull()) return; // Since the symbols always use the same color as the curve line, we just use that color. // This saves us from having to deal with cases where the symbol is NULL. QColor oldColor = curve->pen().color(); // Update the symbol style QwtSymbol *newSymbol = NULL; if (styleText.contains("circles")) { newSymbol = new QwtSymbol(QwtSymbol::Ellipse, Qt::NoBrush, QPen(oldColor, symbolWidth), QSize(6, 6)); } else if (styleText.contains("crosses")) { newSymbol = new QwtSymbol(QwtSymbol::XCross, Qt::NoBrush, QPen(oldColor, symbolWidth), QSize(5, 5)); } else if (styleText.contains("rect")) { newSymbol = new QwtSymbol(QwtSymbol::Rect, Qt::NoBrush, QPen(oldColor, symbolWidth), QSize(6, 6)); } // Else-case already handled by NULL value, which indicates no symbol curve->setSymbol(newSymbol); // Update the line style if (styleText.contains("dotted")) { curve->setPen(QPen(oldColor, curveWidth, Qt::DotLine)); } else if (styleText.contains("dashed")) { curve->setPen(QPen(oldColor, curveWidth, Qt::DashLine)); } else if (styleText.contains("line") || styleText.contains("solid")) { curve->setPen(QPen(oldColor, curveWidth, Qt::SolidLine)); } else { curve->setPen(QPen(oldColor, curveWidth, Qt::NoPen)); } curve->setStyle(QwtPlotCurve::Lines); } void IncrementalPlot::resetScaling() { xmin = 0; xmax = 500; ymin = xmin; ymax = xmax; setAxisScale(xBottom, xmin+xmin*0.05, xmax+xmax*0.05); setAxisScale(yLeft, ymin+ymin*0.05, ymax+ymax*0.05); replot(); // Make sure the first data access hits these xmin = DBL_MAX; xmax = DBL_MIN; ymin = DBL_MAX; ymax = DBL_MIN; } /** * Updates the scale calculation and re-plots the whole plot */ void IncrementalPlot::updateScale() { const double margin = 0.05; if(xmin == DBL_MAX) return; double xMinRange = xmin-(qAbs(xmin*margin)); double xMaxRange = xmax+(qAbs(xmax*margin)); double yMinRange = ymin-(qAbs(ymin*margin)); double yMaxRange = ymax+(qAbs(ymax*margin)); if (symmetric) { double xRange = xMaxRange - xMinRange; double yRange = yMaxRange - yMinRange; // Get the aspect ratio of the plot float xSize = width(); if (legend != NULL) xSize -= legend->width(); float ySize = height(); float aspectRatio = xSize / ySize; if (xRange > yRange) { double yCenter = yMinRange + yRange/2.0; double xCenter = xMinRange + xRange/2.0; yMinRange = yCenter - xRange/2.0; yMaxRange = yCenter + xRange/2.0; xMinRange = xCenter - (xRange*aspectRatio)/2.0; xMaxRange = xCenter + (xRange*aspectRatio)/2.0; } else { double xCenter = xMinRange + xRange/2.0; xMinRange = xCenter - (yRange*aspectRatio)/2.0; xMaxRange = xCenter + (yRange*aspectRatio)/2.0; } } setAxisScale(xBottom, xMinRange, xMaxRange); setAxisScale(yLeft, yMinRange, yMaxRange); zoomer->setZoomBase(true); } void IncrementalPlot::appendData(const QString &key, double x, double y) { appendData(key, &x, &y, 1); } void IncrementalPlot::appendData(const QString &key, double *x, double *y, int size) { CurveData* data; QwtPlotCurve* curve; if (!d_data.contains(key)) { data = new CurveData; d_data.insert(key, data); } else { data = d_data.value(key); } // If this is a new curve, create it. if (!curves.contains(key)) { curve = new QwtPlotCurve(key); curves.insert(key, curve); curve->setStyle(QwtPlotCurve::NoCurve); curve->setPaintAttribute(QwtPlotCurve::FilterPoints); // Set the color. Only the pen needs to be set const QColor &c = getNextColor(); curve->setPen(c, symbolWidth); qDebug() << "Creating curve" << key << "with color" << c; updateStyle(curve); curve->attach(this); } else { curve = curves.value(key); } data->append(x, y, size); curve->setRawSamples(data->x(), data->y(), data->count()); bool scaleChanged = false; // Update scales for (int i = 0; i<size; i++) { if (x[i] < xmin) { xmin = x[i]; scaleChanged = true; } if (x[i] > xmax) { xmax = x[i]; scaleChanged = true; } if (y[i] < ymin) { ymin = y[i]; scaleChanged = true; } if (y[i] > ymax) { ymax = y[i]; scaleChanged = true; } } // setAxisScale(xBottom, xmin+xmin*0.05, xmax+xmax*0.05); // setAxisScale(yLeft, ymin+ymin*0.05, ymax+ymax*0.05); //#ifdef __GNUC__ //#warning better use QwtData //#endif //replot(); if(scaleChanged) { updateScale(); } else { QwtPlotCanvas *c = static_cast<QwtPlotCanvas*>(canvas()); const bool cacheMode = c->testPaintAttribute(QwtPlotCanvas::BackingStore); c->setPaintAttribute(QwtPlotCanvas::BackingStore, false); // FIXME Check if here all curves should be drawn // QwtPlotCurve* plotCurve; // foreach(plotCurve, curves) // { // plotCurve->draw(0, curve->dataSize()-1); // } // FIXME: Unsure what this call should be now. //curve->draw(curve->dataSize() - size, curve->dataSize() - 1); replot(); c->setPaintAttribute(QwtPlotCanvas::BackingStore, cacheMode); } } /** * @return Number of copied data points, 0 on failure */ int IncrementalPlot::data(const QString &key, double* r_x, double* r_y, int maxSize) { int result = 0; if (d_data.contains(key)) { CurveData* d = d_data.value(key); if (maxSize >= d->count()) { result = d->count(); memcpy(r_x, d->x(), sizeof(double) * d->count()); memcpy(r_y, d->y(), sizeof(double) * d->count()); } else { result = 0; } } return result; } /** * @param show true to show the grid, false else */ void IncrementalPlot::showGrid(bool show) { grid->setVisible(show); replot(); } bool IncrementalPlot::gridEnabled() const { return grid->isVisible(); } void IncrementalPlot::removeData() { foreach (QwtPlotCurve* curve, curves) { delete curve; } curves.clear(); foreach (CurveData* data, d_data) { delete data; } d_data.clear(); resetScaling(); replot(); } <|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkFrontBufferedStream.h" #include "SkStream.h" #include "SkTemplates.h" class FrontBufferedStream : public SkStreamRewindable { public: // Called by Create. FrontBufferedStream(SkStream*, size_t bufferSize); virtual size_t read(void* buffer, size_t size) SK_OVERRIDE; virtual bool isAtEnd() const SK_OVERRIDE; virtual bool rewind() SK_OVERRIDE; virtual bool hasPosition() const SK_OVERRIDE { return true; } virtual size_t getPosition() const SK_OVERRIDE { return fOffset; } virtual bool hasLength() const SK_OVERRIDE { return fHasLength; } virtual size_t getLength() const SK_OVERRIDE { return fLength; } virtual SkStreamRewindable* duplicate() const SK_OVERRIDE { return NULL; } private: SkAutoTUnref<SkStream> fStream; const bool fHasLength; const size_t fLength; // Current offset into the stream. Always >= 0. size_t fOffset; // Amount that has been buffered by calls to read. Will always be less than // fBufferSize. size_t fBufferedSoFar; // Total size of the buffer. const size_t fBufferSize; // FIXME: SkAutoTMalloc throws on failure. Instead, Create should return a // NULL stream. SkAutoTMalloc<char> fBuffer; // Read up to size bytes from already buffered data, and copy to // dst, if non-NULL. Updates fOffset. Assumes that fOffset is less // than fBufferedSoFar. size_t readFromBuffer(char* dst, size_t size); // Buffer up to size bytes from the stream, and copy to dst if non- // NULL. Updates fOffset and fBufferedSoFar. Assumes that fOffset is // less than fBufferedSoFar, and size is greater than 0. size_t bufferAndWriteTo(char* dst, size_t size); // Read up to size bytes directly from the stream and into dst if non- // NULL. Updates fOffset. Assumes fOffset is at or beyond the buffered // data, and size is greater than 0. size_t readDirectlyFromStream(char* dst, size_t size); typedef SkStream INHERITED; }; SkStreamRewindable* SkFrontBufferedStream::Create(SkStream* stream, size_t bufferSize) { if (NULL == stream) { return NULL; } return SkNEW_ARGS(FrontBufferedStream, (stream, bufferSize)); } FrontBufferedStream::FrontBufferedStream(SkStream* stream, size_t bufferSize) : fStream(SkRef(stream)) , fHasLength(stream->hasPosition() && stream->hasLength()) , fLength(stream->getLength() - stream->getPosition()) , fOffset(0) , fBufferedSoFar(0) , fBufferSize(bufferSize) , fBuffer(bufferSize) {} bool FrontBufferedStream::isAtEnd() const { if (fOffset < fBufferedSoFar) { // Even if the underlying stream is at the end, this stream has been // rewound after buffering, so it is not at the end. return false; } return fStream->isAtEnd(); } bool FrontBufferedStream::rewind() { // Only allow a rewind if we have not exceeded the buffer. if (fOffset <= fBufferSize) { fOffset = 0; return true; } return false; } size_t FrontBufferedStream::readFromBuffer(char* dst, size_t size) { SkASSERT(fOffset < fBufferedSoFar); // Some data has already been copied to fBuffer. Read up to the // lesser of the size requested and the remainder of the buffered // data. const size_t bytesToCopy = SkTMin(size, fBufferedSoFar - fOffset); if (dst != NULL) { memcpy(dst, fBuffer + fOffset, bytesToCopy); } // Update fOffset to the new position. It is guaranteed to be // within the buffered data. fOffset += bytesToCopy; SkASSERT(fOffset <= fBufferedSoFar); return bytesToCopy; } size_t FrontBufferedStream::bufferAndWriteTo(char* dst, size_t size) { SkASSERT(size > 0); SkASSERT(fOffset >= fBufferedSoFar); SkASSERT(fBuffer); // Data needs to be buffered. Buffer up to the lesser of the size requested // and the remainder of the max buffer size. const size_t bytesToBuffer = SkTMin(size, fBufferSize - fBufferedSoFar); char* buffer = fBuffer + fOffset; const size_t buffered = fStream->read(buffer, bytesToBuffer); fBufferedSoFar += buffered; fOffset = fBufferedSoFar; SkASSERT(fBufferedSoFar <= fBufferSize); // Copy the buffer to the destination buffer and update the amount read. if (dst != NULL) { memcpy(dst, buffer, buffered); } return buffered; } size_t FrontBufferedStream::readDirectlyFromStream(char* dst, size_t size) { SkASSERT(size > 0); // If we get here, we have buffered all that can be buffered. SkASSERT(fBufferSize == fBufferedSoFar && fOffset >= fBufferSize); const size_t bytesReadDirectly = fStream->read(dst, size); fOffset += bytesReadDirectly; // If we have read past the end of the buffer, rewinding is no longer // supported, so we can go ahead and free the memory. if (bytesReadDirectly > 0) { sk_free(fBuffer.detach()); } return bytesReadDirectly; } size_t FrontBufferedStream::read(void* voidDst, size_t size) { // Cast voidDst to a char* for easy addition. char* dst = reinterpret_cast<char*>(voidDst); SkDEBUGCODE(const size_t totalSize = size;) const size_t start = fOffset; // First, read any data that was previously buffered. if (fOffset < fBufferedSoFar) { const size_t bytesCopied = this->readFromBuffer(dst, size); // Update the remaining number of bytes needed to read // and the destination buffer. size -= bytesCopied; SkASSERT(size + (fOffset - start) == totalSize); if (dst != NULL) { dst += bytesCopied; } } // Buffer any more data that should be buffered, and copy it to the // destination. if (size > 0 && fBufferedSoFar < fBufferSize) { const size_t buffered = this->bufferAndWriteTo(dst, size); // Update the remaining number of bytes needed to read // and the destination buffer. size -= buffered; SkASSERT(size + (fOffset - start) == totalSize); if (dst != NULL) { dst += buffered; } } if (size > 0 && !fStream->isAtEnd()) { SkDEBUGCODE(const size_t bytesReadDirectly =) this->readDirectlyFromStream(dst, size); SkDEBUGCODE(size -= bytesReadDirectly;) SkASSERT(size + (fOffset - start) == totalSize); } return fOffset - start; } <commit_msg>Check SkStream::isAtEnd before attempting to read.<commit_after>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkFrontBufferedStream.h" #include "SkStream.h" #include "SkTemplates.h" class FrontBufferedStream : public SkStreamRewindable { public: // Called by Create. FrontBufferedStream(SkStream*, size_t bufferSize); virtual size_t read(void* buffer, size_t size) SK_OVERRIDE; virtual bool isAtEnd() const SK_OVERRIDE; virtual bool rewind() SK_OVERRIDE; virtual bool hasPosition() const SK_OVERRIDE { return true; } virtual size_t getPosition() const SK_OVERRIDE { return fOffset; } virtual bool hasLength() const SK_OVERRIDE { return fHasLength; } virtual size_t getLength() const SK_OVERRIDE { return fLength; } virtual SkStreamRewindable* duplicate() const SK_OVERRIDE { return NULL; } private: SkAutoTUnref<SkStream> fStream; const bool fHasLength; const size_t fLength; // Current offset into the stream. Always >= 0. size_t fOffset; // Amount that has been buffered by calls to read. Will always be less than // fBufferSize. size_t fBufferedSoFar; // Total size of the buffer. const size_t fBufferSize; // FIXME: SkAutoTMalloc throws on failure. Instead, Create should return a // NULL stream. SkAutoTMalloc<char> fBuffer; // Read up to size bytes from already buffered data, and copy to // dst, if non-NULL. Updates fOffset. Assumes that fOffset is less // than fBufferedSoFar. size_t readFromBuffer(char* dst, size_t size); // Buffer up to size bytes from the stream, and copy to dst if non- // NULL. Updates fOffset and fBufferedSoFar. Assumes that fOffset is // less than fBufferedSoFar, and size is greater than 0. size_t bufferAndWriteTo(char* dst, size_t size); // Read up to size bytes directly from the stream and into dst if non- // NULL. Updates fOffset. Assumes fOffset is at or beyond the buffered // data, and size is greater than 0. size_t readDirectlyFromStream(char* dst, size_t size); typedef SkStream INHERITED; }; SkStreamRewindable* SkFrontBufferedStream::Create(SkStream* stream, size_t bufferSize) { if (NULL == stream) { return NULL; } return SkNEW_ARGS(FrontBufferedStream, (stream, bufferSize)); } FrontBufferedStream::FrontBufferedStream(SkStream* stream, size_t bufferSize) : fStream(SkRef(stream)) , fHasLength(stream->hasPosition() && stream->hasLength()) , fLength(stream->getLength() - stream->getPosition()) , fOffset(0) , fBufferedSoFar(0) , fBufferSize(bufferSize) , fBuffer(bufferSize) {} bool FrontBufferedStream::isAtEnd() const { if (fOffset < fBufferedSoFar) { // Even if the underlying stream is at the end, this stream has been // rewound after buffering, so it is not at the end. return false; } return fStream->isAtEnd(); } bool FrontBufferedStream::rewind() { // Only allow a rewind if we have not exceeded the buffer. if (fOffset <= fBufferSize) { fOffset = 0; return true; } return false; } size_t FrontBufferedStream::readFromBuffer(char* dst, size_t size) { SkASSERT(fOffset < fBufferedSoFar); // Some data has already been copied to fBuffer. Read up to the // lesser of the size requested and the remainder of the buffered // data. const size_t bytesToCopy = SkTMin(size, fBufferedSoFar - fOffset); if (dst != NULL) { memcpy(dst, fBuffer + fOffset, bytesToCopy); } // Update fOffset to the new position. It is guaranteed to be // within the buffered data. fOffset += bytesToCopy; SkASSERT(fOffset <= fBufferedSoFar); return bytesToCopy; } size_t FrontBufferedStream::bufferAndWriteTo(char* dst, size_t size) { SkASSERT(size > 0); SkASSERT(fOffset >= fBufferedSoFar); SkASSERT(fBuffer); // Data needs to be buffered. Buffer up to the lesser of the size requested // and the remainder of the max buffer size. const size_t bytesToBuffer = SkTMin(size, fBufferSize - fBufferedSoFar); char* buffer = fBuffer + fOffset; const size_t buffered = fStream->read(buffer, bytesToBuffer); fBufferedSoFar += buffered; fOffset = fBufferedSoFar; SkASSERT(fBufferedSoFar <= fBufferSize); // Copy the buffer to the destination buffer and update the amount read. if (dst != NULL) { memcpy(dst, buffer, buffered); } return buffered; } size_t FrontBufferedStream::readDirectlyFromStream(char* dst, size_t size) { SkASSERT(size > 0); // If we get here, we have buffered all that can be buffered. SkASSERT(fBufferSize == fBufferedSoFar && fOffset >= fBufferSize); const size_t bytesReadDirectly = fStream->read(dst, size); fOffset += bytesReadDirectly; // If we have read past the end of the buffer, rewinding is no longer // supported, so we can go ahead and free the memory. if (bytesReadDirectly > 0) { sk_free(fBuffer.detach()); } return bytesReadDirectly; } size_t FrontBufferedStream::read(void* voidDst, size_t size) { // Cast voidDst to a char* for easy addition. char* dst = reinterpret_cast<char*>(voidDst); SkDEBUGCODE(const size_t totalSize = size;) const size_t start = fOffset; // First, read any data that was previously buffered. if (fOffset < fBufferedSoFar) { const size_t bytesCopied = this->readFromBuffer(dst, size); // Update the remaining number of bytes needed to read // and the destination buffer. size -= bytesCopied; SkASSERT(size + (fOffset - start) == totalSize); if (dst != NULL) { dst += bytesCopied; } } // Buffer any more data that should be buffered, and copy it to the // destination. if (size > 0 && fBufferedSoFar < fBufferSize && !fStream->isAtEnd()) { const size_t buffered = this->bufferAndWriteTo(dst, size); // Update the remaining number of bytes needed to read // and the destination buffer. size -= buffered; SkASSERT(size + (fOffset - start) == totalSize); if (dst != NULL) { dst += buffered; } } if (size > 0 && !fStream->isAtEnd()) { SkDEBUGCODE(const size_t bytesReadDirectly =) this->readDirectlyFromStream(dst, size); SkDEBUGCODE(size -= bytesReadDirectly;) SkASSERT(size + (fOffset - start) == totalSize); } return fOffset - start; } <|endoftext|>
<commit_before>#pragma once #include <vector> #include <gtest/gtest.h> #include "../../../../include/cpp/gtest-array.hxx" #include "twosum.hxx" using std::vector; namespace { class AddTwoNumbersTest : public testing::Test { protected: AddTwoNumbersTest(void) {} virtual ~AddTwoNumbersTest(void) {} virtual void SetUp(void) {} virtual void TearDown(void) {} }; TEST(AddTwoNumbersTest, TwoSum1) { EXPECT_TRUE(true); } } <commit_msg>fixed include header<commit_after>#pragma once #include <vector> #include <gtest/gtest.h> #include "../../../../include/cpp/gtest-array.hxx" #include "addtwonumbers.hxx" using std::vector; namespace { class AddTwoNumbersTest : public testing::Test { protected: AddTwoNumbersTest(void) {} virtual ~AddTwoNumbersTest(void) {} virtual void SetUp(void) {} virtual void TearDown(void) {} }; TEST(AddTwoNumbersTest, TwoSum1) { EXPECT_TRUE(true); } } <|endoftext|>
<commit_before>//===- IndexBody.cpp - Indexing statements --------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IndexingContext.h" #include "clang/AST/RecursiveASTVisitor.h" using namespace clang; using namespace clang::index; namespace { class BodyIndexer : public RecursiveASTVisitor<BodyIndexer> { IndexingContext &IndexCtx; const NamedDecl *Parent; const DeclContext *ParentDC; SmallVector<Stmt*, 16> StmtStack; typedef RecursiveASTVisitor<BodyIndexer> base; public: BodyIndexer(IndexingContext &indexCtx, const NamedDecl *Parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { } bool shouldWalkTypesOfTypeLocs() const { return false; } bool dataTraverseStmtPre(Stmt *S) { StmtStack.push_back(S); return true; } bool dataTraverseStmtPost(Stmt *S) { assert(StmtStack.back() == S); StmtStack.pop_back(); return true; } bool TraverseTypeLoc(TypeLoc TL) { IndexCtx.indexTypeLoc(TL, Parent, ParentDC); return true; } bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { IndexCtx.indexNestedNameSpecifierLoc(NNS, Parent, ParentDC); return true; } SymbolRoleSet getRolesForRef(const Expr *E, SmallVectorImpl<SymbolRelation> &Relations) { SymbolRoleSet Roles{}; assert(!StmtStack.empty() && E == StmtStack.back()); if (StmtStack.size() == 1) return Roles; auto It = StmtStack.end()-2; while (isa<CastExpr>(*It) || isa<ParenExpr>(*It)) { if (auto ICE = dyn_cast<ImplicitCastExpr>(*It)) { if (ICE->getCastKind() == CK_LValueToRValue) Roles |= (unsigned)(unsigned)SymbolRole::Read; } if (It == StmtStack.begin()) break; --It; } const Stmt *Parent = *It; if (auto BO = dyn_cast<BinaryOperator>(Parent)) { if (BO->getOpcode() == BO_Assign && BO->getLHS()->IgnoreParenCasts() == E) Roles |= (unsigned)SymbolRole::Write; } else if (auto UO = dyn_cast<UnaryOperator>(Parent)) { if (UO->isIncrementDecrementOp()) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } else if (UO->getOpcode() == UO_AddrOf) { Roles |= (unsigned)SymbolRole::AddressOf; } } else if (auto CA = dyn_cast<CompoundAssignOperator>(Parent)) { if (CA->getLHS()->IgnoreParenCasts() == E) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } } else if (auto CE = dyn_cast<CallExpr>(Parent)) { if (CE->getCallee()->IgnoreParenCasts() == E) { addCallRole(Roles, Relations); if (auto *ME = dyn_cast<MemberExpr>(E)) { if (auto *CXXMD = dyn_cast_or_null<CXXMethodDecl>(ME->getMemberDecl())) if (CXXMD->isVirtual() && !ME->hasQualifier()) { Roles |= (unsigned)SymbolRole::Dynamic; auto BaseTy = ME->getBase()->IgnoreImpCasts()->getType(); if (!BaseTy.isNull()) if (auto *CXXRD = BaseTy->getPointeeCXXRecordDecl()) Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, CXXRD); } } } else if (auto CXXOp = dyn_cast<CXXOperatorCallExpr>(CE)) { if (CXXOp->getNumArgs() > 0 && CXXOp->getArg(0)->IgnoreParenCasts() == E) { OverloadedOperatorKind Op = CXXOp->getOperator(); if (Op == OO_Equal) { Roles |= (unsigned)SymbolRole::Write; } else if ((Op >= OO_PlusEqual && Op <= OO_PipeEqual) || Op == OO_LessLessEqual || Op == OO_GreaterGreaterEqual || Op == OO_PlusPlus || Op == OO_MinusMinus) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } else if (Op == OO_Amp) { Roles |= (unsigned)SymbolRole::AddressOf; } } } } return Roles; } void addCallRole(SymbolRoleSet &Roles, SmallVectorImpl<SymbolRelation> &Relations) { Roles |= (unsigned)SymbolRole::Call; if (auto *FD = dyn_cast<FunctionDecl>(ParentDC)) Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, FD); else if (auto *MD = dyn_cast<ObjCMethodDecl>(ParentDC)) Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, MD); } bool VisitDeclRefExpr(DeclRefExpr *E) { SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool VisitMemberExpr(MemberExpr *E) { SourceLocation Loc = E->getMemberLoc(); if (Loc.isInvalid()) Loc = E->getLocStart(); SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getMemberDecl(), Loc, Parent, ParentDC, Roles, Relations, E); } bool VisitDesignatedInitExpr(DesignatedInitExpr *E) { for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator() && D.getField()) return IndexCtx.handleReference(D.getField(), D.getFieldLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } return true; } bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool VisitObjCMessageExpr(ObjCMessageExpr *E) { auto isDynamic = [](const ObjCMessageExpr *MsgE)->bool { if (MsgE->getReceiverKind() != ObjCMessageExpr::Instance) return false; if (auto *RecE = dyn_cast<ObjCMessageExpr>( MsgE->getInstanceReceiver()->IgnoreParenCasts())) { if (RecE->getMethodFamily() == OMF_alloc) return false; } return true; }; if (ObjCMethodDecl *MD = E->getMethodDecl()) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); if (E->isImplicit()) Roles |= (unsigned)SymbolRole::Implicit; if (isDynamic(E)) { Roles |= (unsigned)SymbolRole::Dynamic; if (auto *RecD = E->getReceiverInterface()) Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, RecD); } return IndexCtx.handleReference(MD, E->getSelectorStartLoc(), Parent, ParentDC, Roles, Relations, E); } return true; } bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { if (E->isExplicitProperty()) return IndexCtx.handleReference(E->getExplicitProperty(), E->getLocation(), Parent, ParentDC, SymbolRoleSet(), {}, E); // No need to do a handleReference for the objc method, because there will // be a message expr as part of PseudoObjectExpr. return true; } bool VisitMSPropertyRefExpr(MSPropertyRefExpr *E) { return IndexCtx.handleReference(E->getPropertyDecl(), E->getMemberLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } bool VisitObjCProtocolExpr(ObjCProtocolExpr *E) { return IndexCtx.handleReference(E->getProtocol(), E->getProtocolIdLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } bool passObjCLiteralMethodCall(const ObjCMethodDecl *MD, const Expr *E) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); Roles |= (unsigned)SymbolRole::Implicit; return IndexCtx.handleReference(MD, E->getLocStart(), Parent, ParentDC, Roles, Relations, E); } bool VisitObjCBoxedExpr(ObjCBoxedExpr *E) { if (ObjCMethodDecl *MD = E->getBoxingMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitObjCArrayLiteral(ObjCArrayLiteral *E) { if (ObjCMethodDecl *MD = E->getArrayWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitCXXConstructExpr(CXXConstructExpr *E) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); return IndexCtx.handleReference(E->getConstructor(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *E, DataRecursionQueue *Q = nullptr) { if (E->getOperatorLoc().isInvalid()) return true; // implicit. return base::TraverseCXXOperatorCallExpr(E, Q); } bool VisitDeclStmt(DeclStmt *S) { if (IndexCtx.shouldIndexFunctionLocalSymbols()) { IndexCtx.indexDeclGroupRef(S->getDeclGroup()); return true; } DeclGroupRef DG = S->getDeclGroup(); for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { const Decl *D = *I; if (!D) continue; if (!IndexCtx.isFunctionLocalDecl(D)) IndexCtx.indexTopLevelDecl(D); } return true; } bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C, Expr *Init) { if (C->capturesThis() || C->capturesVLAType()) return true; if (C->capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols()) return IndexCtx.handleReference(C->getCapturedVar(), C->getLocation(), Parent, ParentDC, SymbolRoleSet()); // FIXME: Lambda init-captures. return true; } // RecursiveASTVisitor visits both syntactic and semantic forms, duplicating // the things that we visit. Make sure to only visit the semantic form. // Also visit things that are in the syntactic form but not the semantic one, // for example the indices in DesignatedInitExprs. bool TraverseInitListExpr(InitListExpr *S, DataRecursionQueue *Q = nullptr) { class SyntacticFormIndexer : public RecursiveASTVisitor<SyntacticFormIndexer> { IndexingContext &IndexCtx; const NamedDecl *Parent; const DeclContext *ParentDC; bool Visited = false; public: SyntacticFormIndexer(IndexingContext &indexCtx, const NamedDecl *Parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { } bool shouldWalkTypesOfTypeLocs() const { return false; } bool TraverseInitListExpr(InitListExpr *S, DataRecursionQueue *Q = nullptr) { // Don't visit nested InitListExprs, this visitor will be called again // later on for the nested ones. if (Visited) return true; Visited = true; InitListExpr *SyntaxForm = S->isSemanticForm() ? S->getSyntacticForm() : S; if (SyntaxForm) { for (Stmt *SubStmt : SyntaxForm->children()) { if (!TraverseStmt(SubStmt, Q)) return false; } } return true; } bool VisitDesignatedInitExpr(DesignatedInitExpr *E) { for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator()) return IndexCtx.handleReference(D.getField(), D.getFieldLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } return true; } }; auto visitForm = [&](InitListExpr *Form) { for (Stmt *SubStmt : Form->children()) { if (!TraverseStmt(SubStmt, Q)) return false; } return true; }; InitListExpr *SemaForm = S->isSemanticForm() ? S : S->getSemanticForm(); InitListExpr *SyntaxForm = S->isSemanticForm() ? S->getSyntacticForm() : S; if (SemaForm) { // Visit things present in syntactic form but not the semantic form. if (SyntaxForm) { SyntacticFormIndexer(IndexCtx, Parent, ParentDC).TraverseStmt(SyntaxForm); } return visitForm(SemaForm); } // No semantic, try the syntactic. if (SyntaxForm) { return visitForm(SyntaxForm); } return true; } }; } // anonymous namespace void IndexingContext::indexBody(const Stmt *S, const NamedDecl *Parent, const DeclContext *DC) { if (!S) return; if (!DC) DC = Parent->getLexicalDeclContext(); BodyIndexer(*this, Parent, DC).TraverseStmt(const_cast<Stmt*>(S)); } <commit_msg>[index] Avoid using a RecursiveASTVisitor for SyntacticFormIndexer and iterate the DesignatedInitExprs of the InitListExpr directly.<commit_after>//===- IndexBody.cpp - Indexing statements --------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IndexingContext.h" #include "clang/AST/RecursiveASTVisitor.h" using namespace clang; using namespace clang::index; namespace { class BodyIndexer : public RecursiveASTVisitor<BodyIndexer> { IndexingContext &IndexCtx; const NamedDecl *Parent; const DeclContext *ParentDC; SmallVector<Stmt*, 16> StmtStack; typedef RecursiveASTVisitor<BodyIndexer> base; public: BodyIndexer(IndexingContext &indexCtx, const NamedDecl *Parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { } bool shouldWalkTypesOfTypeLocs() const { return false; } bool dataTraverseStmtPre(Stmt *S) { StmtStack.push_back(S); return true; } bool dataTraverseStmtPost(Stmt *S) { assert(StmtStack.back() == S); StmtStack.pop_back(); return true; } bool TraverseTypeLoc(TypeLoc TL) { IndexCtx.indexTypeLoc(TL, Parent, ParentDC); return true; } bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { IndexCtx.indexNestedNameSpecifierLoc(NNS, Parent, ParentDC); return true; } SymbolRoleSet getRolesForRef(const Expr *E, SmallVectorImpl<SymbolRelation> &Relations) { SymbolRoleSet Roles{}; assert(!StmtStack.empty() && E == StmtStack.back()); if (StmtStack.size() == 1) return Roles; auto It = StmtStack.end()-2; while (isa<CastExpr>(*It) || isa<ParenExpr>(*It)) { if (auto ICE = dyn_cast<ImplicitCastExpr>(*It)) { if (ICE->getCastKind() == CK_LValueToRValue) Roles |= (unsigned)(unsigned)SymbolRole::Read; } if (It == StmtStack.begin()) break; --It; } const Stmt *Parent = *It; if (auto BO = dyn_cast<BinaryOperator>(Parent)) { if (BO->getOpcode() == BO_Assign && BO->getLHS()->IgnoreParenCasts() == E) Roles |= (unsigned)SymbolRole::Write; } else if (auto UO = dyn_cast<UnaryOperator>(Parent)) { if (UO->isIncrementDecrementOp()) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } else if (UO->getOpcode() == UO_AddrOf) { Roles |= (unsigned)SymbolRole::AddressOf; } } else if (auto CA = dyn_cast<CompoundAssignOperator>(Parent)) { if (CA->getLHS()->IgnoreParenCasts() == E) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } } else if (auto CE = dyn_cast<CallExpr>(Parent)) { if (CE->getCallee()->IgnoreParenCasts() == E) { addCallRole(Roles, Relations); if (auto *ME = dyn_cast<MemberExpr>(E)) { if (auto *CXXMD = dyn_cast_or_null<CXXMethodDecl>(ME->getMemberDecl())) if (CXXMD->isVirtual() && !ME->hasQualifier()) { Roles |= (unsigned)SymbolRole::Dynamic; auto BaseTy = ME->getBase()->IgnoreImpCasts()->getType(); if (!BaseTy.isNull()) if (auto *CXXRD = BaseTy->getPointeeCXXRecordDecl()) Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, CXXRD); } } } else if (auto CXXOp = dyn_cast<CXXOperatorCallExpr>(CE)) { if (CXXOp->getNumArgs() > 0 && CXXOp->getArg(0)->IgnoreParenCasts() == E) { OverloadedOperatorKind Op = CXXOp->getOperator(); if (Op == OO_Equal) { Roles |= (unsigned)SymbolRole::Write; } else if ((Op >= OO_PlusEqual && Op <= OO_PipeEqual) || Op == OO_LessLessEqual || Op == OO_GreaterGreaterEqual || Op == OO_PlusPlus || Op == OO_MinusMinus) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } else if (Op == OO_Amp) { Roles |= (unsigned)SymbolRole::AddressOf; } } } } return Roles; } void addCallRole(SymbolRoleSet &Roles, SmallVectorImpl<SymbolRelation> &Relations) { Roles |= (unsigned)SymbolRole::Call; if (auto *FD = dyn_cast<FunctionDecl>(ParentDC)) Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, FD); else if (auto *MD = dyn_cast<ObjCMethodDecl>(ParentDC)) Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, MD); } bool VisitDeclRefExpr(DeclRefExpr *E) { SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool VisitMemberExpr(MemberExpr *E) { SourceLocation Loc = E->getMemberLoc(); if (Loc.isInvalid()) Loc = E->getLocStart(); SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getMemberDecl(), Loc, Parent, ParentDC, Roles, Relations, E); } bool VisitDesignatedInitExpr(DesignatedInitExpr *E) { for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator() && D.getField()) return IndexCtx.handleReference(D.getField(), D.getFieldLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } return true; } bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool VisitObjCMessageExpr(ObjCMessageExpr *E) { auto isDynamic = [](const ObjCMessageExpr *MsgE)->bool { if (MsgE->getReceiverKind() != ObjCMessageExpr::Instance) return false; if (auto *RecE = dyn_cast<ObjCMessageExpr>( MsgE->getInstanceReceiver()->IgnoreParenCasts())) { if (RecE->getMethodFamily() == OMF_alloc) return false; } return true; }; if (ObjCMethodDecl *MD = E->getMethodDecl()) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); if (E->isImplicit()) Roles |= (unsigned)SymbolRole::Implicit; if (isDynamic(E)) { Roles |= (unsigned)SymbolRole::Dynamic; if (auto *RecD = E->getReceiverInterface()) Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, RecD); } return IndexCtx.handleReference(MD, E->getSelectorStartLoc(), Parent, ParentDC, Roles, Relations, E); } return true; } bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { if (E->isExplicitProperty()) return IndexCtx.handleReference(E->getExplicitProperty(), E->getLocation(), Parent, ParentDC, SymbolRoleSet(), {}, E); // No need to do a handleReference for the objc method, because there will // be a message expr as part of PseudoObjectExpr. return true; } bool VisitMSPropertyRefExpr(MSPropertyRefExpr *E) { return IndexCtx.handleReference(E->getPropertyDecl(), E->getMemberLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } bool VisitObjCProtocolExpr(ObjCProtocolExpr *E) { return IndexCtx.handleReference(E->getProtocol(), E->getProtocolIdLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } bool passObjCLiteralMethodCall(const ObjCMethodDecl *MD, const Expr *E) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); Roles |= (unsigned)SymbolRole::Implicit; return IndexCtx.handleReference(MD, E->getLocStart(), Parent, ParentDC, Roles, Relations, E); } bool VisitObjCBoxedExpr(ObjCBoxedExpr *E) { if (ObjCMethodDecl *MD = E->getBoxingMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitObjCArrayLiteral(ObjCArrayLiteral *E) { if (ObjCMethodDecl *MD = E->getArrayWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitCXXConstructExpr(CXXConstructExpr *E) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); return IndexCtx.handleReference(E->getConstructor(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *E, DataRecursionQueue *Q = nullptr) { if (E->getOperatorLoc().isInvalid()) return true; // implicit. return base::TraverseCXXOperatorCallExpr(E, Q); } bool VisitDeclStmt(DeclStmt *S) { if (IndexCtx.shouldIndexFunctionLocalSymbols()) { IndexCtx.indexDeclGroupRef(S->getDeclGroup()); return true; } DeclGroupRef DG = S->getDeclGroup(); for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { const Decl *D = *I; if (!D) continue; if (!IndexCtx.isFunctionLocalDecl(D)) IndexCtx.indexTopLevelDecl(D); } return true; } bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C, Expr *Init) { if (C->capturesThis() || C->capturesVLAType()) return true; if (C->capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols()) return IndexCtx.handleReference(C->getCapturedVar(), C->getLocation(), Parent, ParentDC, SymbolRoleSet()); // FIXME: Lambda init-captures. return true; } // RecursiveASTVisitor visits both syntactic and semantic forms, duplicating // the things that we visit. Make sure to only visit the semantic form. // Also visit things that are in the syntactic form but not the semantic one, // for example the indices in DesignatedInitExprs. bool TraverseInitListExpr(InitListExpr *S, DataRecursionQueue *Q = nullptr) { auto visitForm = [&](InitListExpr *Form) { for (Stmt *SubStmt : Form->children()) { if (!TraverseStmt(SubStmt, Q)) return false; } return true; }; auto visitSyntacticDesignatedInitExpr = [&](DesignatedInitExpr *E) -> bool { for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator()) return IndexCtx.handleReference(D.getField(), D.getFieldLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } return true; }; InitListExpr *SemaForm = S->isSemanticForm() ? S : S->getSemanticForm(); InitListExpr *SyntaxForm = S->isSemanticForm() ? S->getSyntacticForm() : S; if (SemaForm) { // Visit things present in syntactic form but not the semantic form. if (SyntaxForm) { for (Expr *init : SyntaxForm->inits()) { if (auto *DIE = dyn_cast<DesignatedInitExpr>(init)) visitSyntacticDesignatedInitExpr(DIE); } } return visitForm(SemaForm); } // No semantic, try the syntactic. if (SyntaxForm) { return visitForm(SyntaxForm); } return true; } }; } // anonymous namespace void IndexingContext::indexBody(const Stmt *S, const NamedDecl *Parent, const DeclContext *DC) { if (!S) return; if (!DC) DC = Parent->getLexicalDeclContext(); BodyIndexer(*this, Parent, DC).TraverseStmt(const_cast<Stmt*>(S)); } <|endoftext|>
<commit_before>// Copyright 2016 Peter Georg // // 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 "sendmemorywindow.hpp" #include "connection.hpp" pMR::ofi::SendMemoryWindow::SendMemoryWindow( std::shared_ptr<Connection> const connection, void *buffer, std::size_t const sizeByte) : mConnection(connection) , mMemoryRegion(connection->getDomain(), buffer, {sizeByte}, #ifdef OFI_RMA FI_WRITE) #else FI_SEND) #endif // OFI_RMA { mConnection->checkMessageSize({sizeByte}); } void pMR::ofi::SendMemoryWindow::init() { } void pMR::ofi::SendMemoryWindow::post(std::size_t const sizeByte) { #ifdef OFI_RMA mConnection->pollActiveRecv(); #else if(!mConnection->checkEagerSize(sizeByte)) { mConnection->pollActiveRecv(); } #endif // OFI_RMA #if defined OFI_RMA && !defined OFI_RMA_CONTROL mConnection->postRecvAddressToActive(); #elif !defined OFI_RMA || defined OFI_RMA_TARGET_RX mConnection->postRecvToActive(); #endif // OFI_RMA & !OFI_RMA_CONTROL // !OFI_RMA || OFI_RMA_TARGET_RX #ifdef OFI_RMA mConnection->postWriteToActive(mMemoryRegion, {sizeByte}); #else mConnection->postSendToActive(mMemoryRegion, {sizeByte}); #endif // OFI_RMA #ifndef OFI_RMA if(mConnection->checkEagerSize(sizeByte)) { mConnection->pollActiveRecv(); } #endif // !OFI_RMA } void pMR::ofi::SendMemoryWindow::wait() { mConnection->pollActiveSend(); } <commit_msg>Revert "Try to improve perf for eager"<commit_after>// Copyright 2016 Peter Georg // // 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 "sendmemorywindow.hpp" #include "connection.hpp" pMR::ofi::SendMemoryWindow::SendMemoryWindow( std::shared_ptr<Connection> const connection, void *buffer, std::size_t const sizeByte) : mConnection(connection) , mMemoryRegion(connection->getDomain(), buffer, {sizeByte}, #ifdef OFI_RMA FI_WRITE) #else FI_SEND) #endif // OFI_RMA { mConnection->checkMessageSize({sizeByte}); } void pMR::ofi::SendMemoryWindow::init() { } void pMR::ofi::SendMemoryWindow::post(std::size_t const sizeByte) { mConnection->pollActiveRecv(); #if defined OFI_RMA && !defined OFI_RMA_CONTROL mConnection->postRecvAddressToActive(); #elif !defined OFI_RMA || defined OFI_RMA_TARGET_RX mConnection->postRecvToActive(); #endif // OFI_RMA & !OFI_RMA_CONTROL // !OFI_RMA || OFI_RMA_TARGET_RX #ifdef OFI_RMA mConnection->postWriteToActive(mMemoryRegion, {sizeByte}); #else mConnection->postSendToActive(mMemoryRegion, {sizeByte}); #endif // OFI_RMA } void pMR::ofi::SendMemoryWindow::wait() { mConnection->pollActiveSend(); } <|endoftext|>
<commit_before>#include "providers/twitch/TwitchHelpers.hpp" #include "debug/Log.hpp" namespace chatterino { bool trimChannelName(const QString &channelName, QString &outChannelName) { if (channelName.length() < 3) { log("channel name length below 3"); return false; } outChannelName = channelName.mid(1); return true; } } // namespace chatterino <commit_msg>fix notices about "short channel name" channels being sent to all channels<commit_after>#include "providers/twitch/TwitchHelpers.hpp" #include "debug/Log.hpp" namespace chatterino { bool trimChannelName(const QString &channelName, QString &outChannelName) { if (channelName.length() < 2) { log("channel name length below 2"); return false; } outChannelName = channelName.mid(1); return true; } } // namespace chatterino <|endoftext|>
<commit_before>#include "bitmapimage.h" BitmapImage::BitmapImage() { m_Image = NULL; qDebug() << "Image drawn!" << endl; } BitmapImage::BitmapImage(const BitmapImage &image) { m_pixmap = image.m_pixmap; boundaries = image.boundaries; m_Color = image.m_Color; } BitmapImage::BitmapImage(Object *parent, QRect boundaries, QColor color) { myParent = parent; this->boundaries = boundaries; m_Image = new QImage(boundaries.size(), QImage::Format_ARGB32_Premultiplied); m_Image->fill(color.rgba()); } BitmapImage::BitmapImage(Object *parent, QRect boundaries, QImage image) { myParent = parent; this->boundaries = boundaries; m_Image = new QImage(image); if(m_Image->width() != boundaries.width() && m_Image->height() != boundaries.height()) qDebug() << "Error 0001: Failed to load Image" << endl; } BitmapImage::BitmapImage(QRect boundaries, QColor color) { this->boundaries = boundaries; QPixmap temp(boundaries.width(), boundaries.height()); temp.fill(color); QPainter painter(&temp); if(!temp.isNull()) { painter.drawPixmap(0, 0, temp); } painter.end(); m_pixmap = temp; } void BitmapImage::paintImage(QPainter &painter) { painter.drawPixmap(0, 0, m_pixmap); } void BitmapImage::paintImage(QPainter &painter, QPoint knownPoint, Brush brush, QPoint points[]) { painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); qDebug() << "Brush" << brush.getBrush() << endl; qDebug() << "Pen" << brush.getPen() << endl; painter.drawLine(points[1], knownPoint); qDebug() << "Color" << brush.getColor() << endl; qDebug() << "Drawing In progress" << endl; } void BitmapImage::paintImage(QPainter &painter, QTabletEvent *event, Brush brush, QPoint points[]) { /* painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); painter.drawLine(points[1], event->pos()); */ qDebug() << "Brush" << brush.getBrush() << endl; qDebug() << "Pen" << brush.getPen() << endl; qDebug() << "Color" << brush.getColor() << endl; //painter = QPainter(&m_pixmap); painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); painter.drawLine(points[1], event->pos()); } void BitmapImage::paintImage(QTabletEvent *event, Brush brush, QPoint points[]) { QPainter painter(&m_pixmap); painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); painter.drawLine(points[1], event->pos()); } void BitmapImage::paintImage(QMouseEvent *event, Brush brush, QPoint points[]) { QPainter painter(&m_pixmap); painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); qDebug() << brush.getBrush() << endl; qDebug() << brush.getPen() << endl; qDebug() << "Brush Width: " << brush.getPen().width() << endl; painter.drawLine(points[1], event->pos()); } <commit_msg>0.025c<commit_after>#include "bitmapimage.h" BitmapImage::BitmapImage() { m_Image = NULL; qDebug() << "Image drawn!" << endl; } BitmapImage::BitmapImage(const BitmapImage &image) { m_pixmap = image.m_pixmap; boundaries = image.boundaries; m_Color = image.m_Color; } BitmapImage::BitmapImage(Object *parent, QRect boundaries, QColor color) { myParent = parent; this->boundaries = boundaries; m_Image = new QImage(boundaries.size(), QImage::Format_ARGB32_Premultiplied); m_Image->fill(color.rgba()); } BitmapImage::BitmapImage(Object *parent, QRect boundaries, QImage image) { myParent = parent; this->boundaries = boundaries; m_Image = new QImage(image); if(m_Image->width() != boundaries.width() && m_Image->height() != boundaries.height()) qDebug() << "Error 0001: Failed to load Image" << endl; } BitmapImage::BitmapImage(QRect boundaries, QColor color) { this->boundaries = boundaries; QPixmap temp(boundaries.width(), boundaries.height()); temp.fill(color); QPainter painter(&temp); if(!temp.isNull()) { painter.drawPixmap(0, 0, temp); } painter.end(); m_pixmap = temp; } void BitmapImage::paintImage(QPainter &painter) { painter.drawPixmap(0, 0, m_pixmap); } void BitmapImage::paintImage(QPainter &painter, QPoint knownPoint, Brush brush, QPoint points[]) { painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); qDebug() << "Brush" << brush.getBrush() << endl; qDebug() << "Pen" << brush.getPen() << endl; painter.drawLine(points[1], knownPoint); qDebug() << "Color" << brush.getColor() << endl; qDebug() << "Drawing In progress" << endl; } void BitmapImage::paintImage(QPainter &painter, QTabletEvent *event, Brush brush, QPoint points[]) { /* painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); painter.drawLine(points[1], event->pos()); */ qDebug() << "Brush" << brush.getBrush() << endl; qDebug() << "Pen" << brush.getPen() << endl; qDebug() << "Color" << brush.getColor() << endl; //painter = QPainter(&m_pixmap); painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); painter.drawLine(points[1], event->pos()); } void BitmapImage::paintImage(QTabletEvent *event, Brush brush, QPoint points[]) { QPainter painter(&m_pixmap); painter.setRenderHint(QPainter::Antialiasing); painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); painter.drawLine(points[1], event->pos()); } void BitmapImage::paintImage(QMouseEvent *event, Brush brush, QPoint points[]) { QPainter painter(&m_pixmap); painter.setRenderHint(QPainter::Antialiasing); painter.setBrush(brush.getBrush()); painter.setPen(brush.getPen()); qDebug() << brush.getBrush() << endl; qDebug() << brush.getPen() << endl; qDebug() << "Brush Width: " << brush.getPen().width() << endl; painter.drawLine(points[1], event->pos()); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkIconGlyphFilter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkIconGlyphFilter.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkFloatArray.h" #include "vtkIdList.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPointLocator.h" #include "vtkPoints.h" #include "vtkPolyData.h" vtkCxxRevisionMacro(vtkIconGlyphFilter, "1.3"); vtkStandardNewMacro(vtkIconGlyphFilter); //----------------------------------------------------------------------------- vtkIconGlyphFilter::vtkIconGlyphFilter() { this->IconSize[0] = 1; this->IconSize[1] = 1; this->IconSheetSize[0] = 1; this->IconSheetSize[1] = 1; this->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS); } //----------------------------------------------------------------------------- vtkIconGlyphFilter::~vtkIconGlyphFilter() { } //----------------------------------------------------------------------------- void vtkIconGlyphFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "IconSize: " << IconSize[0] << " " << IconSize[1] << endl; os << indent << "IconSheetSize: " << IconSheetSize[0] << " " << IconSheetSize[1] << endl; } //----------------------------------------------------------------------------- int vtkIconGlyphFilter::RequestData(vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // Get the information object. vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // Get the data objects. vtkPointSet *input = vtkPointSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); int numPoints = input->GetNumberOfPoints(); if (numPoints <= 0) { // nothing to do... return 1; } vtkIntArray* scalars = vtkIntArray::SafeDownCast( this->GetInputArrayToProcess(0, inputVector)); if (!scalars) { vtkErrorMacro("Input Scalars must be specified to index into the icon sheet."); return 0; } double point[3], textureCoord[2]; double sheetXDim = this->IconSheetSize[0]/this->IconSize[0]; double sheetYDim = this->IconSheetSize[1]/this->IconSize[1]; int iconIndex = 0; int j, k; vtkPoints * outPoints = vtkPoints::New(); outPoints->Allocate(4 * numPoints); vtkCellArray * outCells = vtkCellArray::New(); outCells->Allocate(outCells->EstimateSize(numPoints, 4)); vtkFloatArray *outTCoords = vtkFloatArray::New(); outTCoords->SetNumberOfComponents(2); outTCoords->Allocate(8*numPoints); for(int i = 0; i < numPoints; i++) { iconIndex = scalars->GetValue(i); input->GetPoint(i, point); outPoints->InsertNextPoint(point[0] - 0.5, point[1] - 0.5, point[2]); this->IconConvertIndex(iconIndex, j, k); textureCoord[0] = j/sheetXDim; textureCoord[1] = k/sheetYDim; outTCoords->InsertTuple(i * 4, textureCoord); outPoints->InsertNextPoint(point[0] + 0.5, point[1] - 0.5, point[2]); this->IconConvertIndex(iconIndex, j, k); textureCoord[0] = (j + 1.0)/sheetXDim; textureCoord[1] = k/sheetYDim; outTCoords->InsertTuple(i * 4 + 1, textureCoord); outPoints->InsertNextPoint(point[0] + 0.5, point[1] + 0.5, point[2]); this->IconConvertIndex(iconIndex, j, k); textureCoord[0] = (j + 1.0)/sheetXDim; textureCoord[1] = (k + 1.0)/sheetYDim; outTCoords->InsertTuple(i * 4 + 2, textureCoord); outPoints->InsertNextPoint(point[0] - 0.5, point[1] + 0.5, point[2]); this->IconConvertIndex(iconIndex, j, k); textureCoord[0] = j/sheetXDim; textureCoord[1] = (k + 1.0)/sheetYDim; outTCoords->InsertTuple(i * 4 + 3, textureCoord); outCells->InsertNextCell(4); outCells->InsertCellPoint(i * 4); outCells->InsertCellPoint(i * 4 + 1); outCells->InsertCellPoint(i * 4 + 2); outCells->InsertCellPoint(i * 4 + 3); } output->SetPoints(outPoints); outPoints->Delete(); outTCoords->SetName("TextureCoordinates"); output->GetPointData()->SetTCoords(outTCoords); outTCoords->Delete(); output->SetPolys(outCells); outCells->Delete(); return 1; } <commit_msg>ENH: Fix PrintSelf test for vtkIconGlyphFilter.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkIconGlyphFilter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkIconGlyphFilter.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkFloatArray.h" #include "vtkIdList.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPointLocator.h" #include "vtkPoints.h" #include "vtkPolyData.h" vtkCxxRevisionMacro(vtkIconGlyphFilter, "1.4"); vtkStandardNewMacro(vtkIconGlyphFilter); //----------------------------------------------------------------------------- vtkIconGlyphFilter::vtkIconGlyphFilter() { this->IconSize[0] = 1; this->IconSize[1] = 1; this->IconSheetSize[0] = 1; this->IconSheetSize[1] = 1; this->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS); } //----------------------------------------------------------------------------- vtkIconGlyphFilter::~vtkIconGlyphFilter() { } //----------------------------------------------------------------------------- void vtkIconGlyphFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "IconSize: " << this->IconSize[0] << " " << this->IconSize[1] << endl; os << indent << "IconSheetSize: " << this->IconSheetSize[0] << " " << this->IconSheetSize[1] << endl; } //----------------------------------------------------------------------------- int vtkIconGlyphFilter::RequestData(vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // Get the information object. vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // Get the data objects. vtkPointSet *input = vtkPointSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); int numPoints = input->GetNumberOfPoints(); if (numPoints <= 0) { // nothing to do... return 1; } vtkIntArray* scalars = vtkIntArray::SafeDownCast( this->GetInputArrayToProcess(0, inputVector)); if (!scalars) { vtkErrorMacro("Input Scalars must be specified to index into the icon sheet."); return 0; } double point[3], textureCoord[2]; double sheetXDim = this->IconSheetSize[0]/this->IconSize[0]; double sheetYDim = this->IconSheetSize[1]/this->IconSize[1]; int iconIndex = 0; int j, k; vtkPoints * outPoints = vtkPoints::New(); outPoints->Allocate(4 * numPoints); vtkCellArray * outCells = vtkCellArray::New(); outCells->Allocate(outCells->EstimateSize(numPoints, 4)); vtkFloatArray *outTCoords = vtkFloatArray::New(); outTCoords->SetNumberOfComponents(2); outTCoords->Allocate(8*numPoints); for(int i = 0; i < numPoints; i++) { iconIndex = scalars->GetValue(i); input->GetPoint(i, point); outPoints->InsertNextPoint(point[0] - 0.5, point[1] - 0.5, point[2]); this->IconConvertIndex(iconIndex, j, k); textureCoord[0] = j/sheetXDim; textureCoord[1] = k/sheetYDim; outTCoords->InsertTuple(i * 4, textureCoord); outPoints->InsertNextPoint(point[0] + 0.5, point[1] - 0.5, point[2]); this->IconConvertIndex(iconIndex, j, k); textureCoord[0] = (j + 1.0)/sheetXDim; textureCoord[1] = k/sheetYDim; outTCoords->InsertTuple(i * 4 + 1, textureCoord); outPoints->InsertNextPoint(point[0] + 0.5, point[1] + 0.5, point[2]); this->IconConvertIndex(iconIndex, j, k); textureCoord[0] = (j + 1.0)/sheetXDim; textureCoord[1] = (k + 1.0)/sheetYDim; outTCoords->InsertTuple(i * 4 + 2, textureCoord); outPoints->InsertNextPoint(point[0] - 0.5, point[1] + 0.5, point[2]); this->IconConvertIndex(iconIndex, j, k); textureCoord[0] = j/sheetXDim; textureCoord[1] = (k + 1.0)/sheetYDim; outTCoords->InsertTuple(i * 4 + 3, textureCoord); outCells->InsertNextCell(4); outCells->InsertCellPoint(i * 4); outCells->InsertCellPoint(i * 4 + 1); outCells->InsertCellPoint(i * 4 + 2); outCells->InsertCellPoint(i * 4 + 3); } output->SetPoints(outPoints); outPoints->Delete(); outTCoords->SetName("TextureCoordinates"); output->GetPointData()->SetTCoords(outTCoords); outTCoords->Delete(); output->SetPolys(outCells); outCells->Delete(); return 1; } <|endoftext|>
<commit_before>/* * Copyright (C) 2016 Airbus Defence and Space * * 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 "CCPACSWingSparPosition.h" #include "CCPACSWingCSStructure.h" #include "CCPACSWingSegment.h" #include "CCPACSWingComponentSegment.h" #include "CCPACSWingSpars.h" #include "CTiglError.h" #include "CPACSWingRibPoint.h" #include "CPACSEtaXsiPoint.h" #include "CTiglUIDManager.h" namespace tigl { CCPACSWingSparPosition::CCPACSWingSparPosition(CCPACSWingSparPositions* sparPositions, CTiglUIDManager* uidMgr) : generated::CPACSSparPosition(sparPositions, uidMgr) {} bool CCPACSWingSparPosition::isOnInnerSectionElement() const { if (GetSparPositionEtaXsi_choice2()) { return GetEta() < 1.E-6; } else { return false; } } bool CCPACSWingSparPosition::isOnOuterSectionElement() const { if (GetSparPositionEtaXsi_choice2()) { return (1 - GetEta()) < 1.E-6; } else { return false; } } bool CCPACSWingSparPosition::isOnSectionElement() const { return isOnInnerSectionElement() || isOnOuterSectionElement(); } bool CCPACSWingSparPosition::isOnRib() const { return m_sparPositionRib_choice1 ? true : false; } const std::string& CCPACSWingSparPosition::GetReferenceUID() const { if (m_sparPositionRib_choice1) { return m_sparPositionRib_choice1->GetRibDefinitionUID(); } else if (m_sparPositionEtaXsi_choice2){ return m_sparPositionEtaXsi_choice2->GetReferenceUID(); } else { throw CTiglError("Invalid choice type"); } } double CCPACSWingSparPosition::GetEta() const { if (!m_sparPositionEtaXsi_choice2) { throw CTiglError("SparPosition is not defined via eta/xsi. Please check InputType first before calling CCPACSWingSparPosition::GetXsi()"); } return m_sparPositionEtaXsi_choice2->GetEta(); } double CCPACSWingSparPosition::GetXsi() const { if (m_sparPositionRib_choice1) { return m_sparPositionRib_choice1->GetXsi(); } else if (m_sparPositionEtaXsi_choice2) { return m_sparPositionEtaXsi_choice2->GetXsi(); } throw CTiglError("Invalid spar position type"); } const generated::CPACSEtaXsiPoint &CCPACSWingSparPosition::GetEtaXsiPoint() const { if (!GetSparPositionEtaXsi_choice2()) { throw CTiglError("No EtaXsiPoint definied in SparPosition '" + GetUID() + "'"); } return GetSparPositionEtaXsi_choice2().value(); } const generated::CPACSWingRibPoint& CCPACSWingSparPosition::GetRibPoint() const { if (!GetSparPositionRib_choice1()) { throw CTiglError("No RibPoint definied in SparPosition '" + GetUID() + "'"); } return GetSparPositionRib_choice1().value(); } int WingRibPointGetRibNumber(const generated::CPACSWingRibPoint& ribPoint) { return ribPoint.GetRibNumber().value_or(1); } std::string WingSparPosGetElementUID(const CCPACSWingSparPosition & pos) { if (!pos.isOnSectionElement()) { throw CTiglError("Spar Postitiong is not on section element"); } const CTiglUIDManager::TypedPtr tp = pos.GetUIDManager().ResolveObject(pos.GetEtaXsiPoint().GetReferenceUID()); if (tp.type == &typeid(CCPACSWingComponentSegment)) { const CCPACSWingComponentSegment& cs = *reinterpret_cast<CCPACSWingComponentSegment*>(tp.ptr); const SegmentList& segments = cs.GetSegmentList(); if (pos.isOnInnerSectionElement()) { return segments.front()->GetInnerSectionElementUID(); } else { return segments.back()->GetOuterSectionElementUID(); } } else if (tp.type == &typeid(CCPACSWingSegment)) { const CCPACSWingSegment& segment = *reinterpret_cast<CCPACSWingSegment*>(tp.ptr); if (pos.isOnInnerSectionElement()) { return segment.GetInnerSectionElementUID(); } else { return segment.GetOuterSectionElementUID(); } } else { throw CTiglError("'" + pos.GetEtaXsiPoint().GetReferenceUID() + "' in not a wing segment or a component segment."); } } } // end namespace tigl <commit_msg>Fixed typo<commit_after>/* * Copyright (C) 2016 Airbus Defence and Space * * 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 "CCPACSWingSparPosition.h" #include "CCPACSWingCSStructure.h" #include "CCPACSWingSegment.h" #include "CCPACSWingComponentSegment.h" #include "CCPACSWingSpars.h" #include "CTiglError.h" #include "CPACSWingRibPoint.h" #include "CPACSEtaXsiPoint.h" #include "CTiglUIDManager.h" namespace tigl { CCPACSWingSparPosition::CCPACSWingSparPosition(CCPACSWingSparPositions* sparPositions, CTiglUIDManager* uidMgr) : generated::CPACSSparPosition(sparPositions, uidMgr) {} bool CCPACSWingSparPosition::isOnInnerSectionElement() const { if (GetSparPositionEtaXsi_choice2()) { return GetEta() < 1.E-6; } else { return false; } } bool CCPACSWingSparPosition::isOnOuterSectionElement() const { if (GetSparPositionEtaXsi_choice2()) { return (1 - GetEta()) < 1.E-6; } else { return false; } } bool CCPACSWingSparPosition::isOnSectionElement() const { return isOnInnerSectionElement() || isOnOuterSectionElement(); } bool CCPACSWingSparPosition::isOnRib() const { return m_sparPositionRib_choice1 ? true : false; } const std::string& CCPACSWingSparPosition::GetReferenceUID() const { if (m_sparPositionRib_choice1) { return m_sparPositionRib_choice1->GetRibDefinitionUID(); } else if (m_sparPositionEtaXsi_choice2){ return m_sparPositionEtaXsi_choice2->GetReferenceUID(); } else { throw CTiglError("Invalid choice type"); } } double CCPACSWingSparPosition::GetEta() const { if (!m_sparPositionEtaXsi_choice2) { throw CTiglError("SparPosition is not defined via eta/xsi. Please check InputType first before calling CCPACSWingSparPosition::GetXsi()"); } return m_sparPositionEtaXsi_choice2->GetEta(); } double CCPACSWingSparPosition::GetXsi() const { if (m_sparPositionRib_choice1) { return m_sparPositionRib_choice1->GetXsi(); } else if (m_sparPositionEtaXsi_choice2) { return m_sparPositionEtaXsi_choice2->GetXsi(); } throw CTiglError("Invalid spar position type"); } const generated::CPACSEtaXsiPoint &CCPACSWingSparPosition::GetEtaXsiPoint() const { if (!GetSparPositionEtaXsi_choice2()) { throw CTiglError("No EtaXsiPoint definied in SparPosition '" + GetUID() + "'"); } return GetSparPositionEtaXsi_choice2().value(); } const generated::CPACSWingRibPoint& CCPACSWingSparPosition::GetRibPoint() const { if (!GetSparPositionRib_choice1()) { throw CTiglError("No RibPoint definied in SparPosition '" + GetUID() + "'"); } return GetSparPositionRib_choice1().value(); } int WingRibPointGetRibNumber(const generated::CPACSWingRibPoint& ribPoint) { return ribPoint.GetRibNumber().value_or(1); } std::string WingSparPosGetElementUID(const CCPACSWingSparPosition & pos) { if (!pos.isOnSectionElement()) { throw CTiglError("Spar positioning is not on section element"); } const CTiglUIDManager::TypedPtr tp = pos.GetUIDManager().ResolveObject(pos.GetEtaXsiPoint().GetReferenceUID()); if (tp.type == &typeid(CCPACSWingComponentSegment)) { const CCPACSWingComponentSegment& cs = *reinterpret_cast<CCPACSWingComponentSegment*>(tp.ptr); const SegmentList& segments = cs.GetSegmentList(); if (pos.isOnInnerSectionElement()) { return segments.front()->GetInnerSectionElementUID(); } else { return segments.back()->GetOuterSectionElementUID(); } } else if (tp.type == &typeid(CCPACSWingSegment)) { const CCPACSWingSegment& segment = *reinterpret_cast<CCPACSWingSegment*>(tp.ptr); if (pos.isOnInnerSectionElement()) { return segment.GetInnerSectionElementUID(); } else { return segment.GetOuterSectionElementUID(); } } else { throw CTiglError("'" + pos.GetEtaXsiPoint().GetReferenceUID() + "' in not a wing segment or a component segment."); } } } // end namespace tigl <|endoftext|>
<commit_before>//===--- ParseType.cpp - Swift Language Parser for Types ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Type Parsing and AST Building // //===----------------------------------------------------------------------===// #include "Parser.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Twine.h" using namespace swift; bool Parser::parseType(Type &Result) { return parseType(Result, "expected type"); } /// parseType /// type: /// type-simple /// type-function /// type-array /// /// type-function: /// type-simple '->' type /// /// type-simple: /// '__builtin_int32_type' /// identifier /// type-tuple /// type-oneof /// type-protocol /// bool Parser::parseType(Type &Result, const Twine &Message) { // Parse type-simple first. switch (Tok.getKind()) { case tok::identifier: { Identifier Name = Context.getIdentifier(Tok.getText()); Result = ScopeInfo.lookupOrInsertTypeName(Name, Tok.getLoc()); consumeToken(tok::identifier); break; } case tok::kw___builtin_float32_type: Result = Context.TheFloat32Type; consumeToken(tok::kw___builtin_float32_type); break; case tok::kw___builtin_float64_type: Result = Context.TheFloat64Type; consumeToken(tok::kw___builtin_float64_type); break; case tok::kw___builtin_int1_type: Result = Context.TheInt1Type; consumeToken(tok::kw___builtin_int1_type); break; case tok::kw___builtin_int8_type: Result = Context.TheInt8Type; consumeToken(tok::kw___builtin_int8_type); break; case tok::kw___builtin_int16_type: Result = Context.TheInt16Type; consumeToken(tok::kw___builtin_int16_type); break; case tok::kw___builtin_int32_type: Result = Context.TheInt32Type; consumeToken(tok::kw___builtin_int32_type); break; case tok::kw___builtin_int64_type: Result = Context.TheInt64Type; consumeToken(tok::kw___builtin_int64_type); break; case tok::l_paren: case tok::l_paren_space: { SMLoc LPLoc = consumeToken(); if (parseTypeTupleBody(LPLoc, Result)) return true; if (parseToken(tok::r_paren, "expected ')' at end of tuple list", tok::r_paren)) { note(LPLoc, "to match this opening '('"); return true; } break; } case tok::kw_oneof: if (parseTypeOneOf(Result)) return true; break; case tok::kw_protocol: if (parseTypeProtocol(Result)) return true; break; default: error(Tok.getLoc(), Message); return true; } while (1) { // If there is an arrow, parse the rest of the type. SMLoc TokLoc = Tok.getLoc(); if (consumeIf(tok::arrow)) { Type SecondHalf; if (parseType(SecondHalf, "expected type in result of function type")) return true; Result = FunctionType::get(Result, SecondHalf, Context); continue; } // If there is a square bracket, we have an array. if (consumeIf(tok::l_square)) { if (parseTypeArray(TokLoc, Result)) return true; continue; } break; } return false; } /// parseTypeTupleBody /// type-tuple: /// '(' type-tuple-body? ')' /// type-tuple-body: /// type-tuple-element (',' type-tuple-element)* /// type-tuple-element: /// identifier value-specifier /// type ('=' expr)? bool Parser::parseTypeTupleBody(SMLoc LPLoc, Type &Result) { SmallVector<TupleTypeElt, 8> Elements; if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::r_brace)) { bool HadError = false; do { Elements.push_back(TupleTypeElt()); TupleTypeElt &Result = Elements.back(); // If the tuple element starts with "ident :" or "ident =", then // the identifier is an element tag, and it is followed by a // value-specifier. if (Tok.is(tok::identifier) && (peekToken().is(tok::colon) || peekToken().is(tok::equal))) { parseIdentifier(Result.Name, ""); NullablePtr<Expr> Init; if ((HadError = parseValueSpecifier(Result.Ty, Init, /*single*/ true))) break; Result.Init = Init.getPtrOrNull(); continue; } // Otherwise, this has to be a type. if ((HadError = parseType(Result.Ty))) break; // Parse the optional default value expression. if (Tok.is(tok::colon)) { ParseResult<Expr> Init = parseSingleExpr("expected initializer expression after '='"); // Die if there was a parse error. if (Init) { HadError = true; break; } if (!Init.isSemaError()) { Result.Init = Init.get(); } } } while (consumeIf(tok::comma)); if (HadError) { skipUntil(tok::r_paren); if (Tok.is(tok::r_paren)) consumeToken(tok::r_paren); return true; } } Result = TupleType::get(Elements, Context); return false; } /// type-oneof: /// 'oneof' attribute-list oneof-body /// bool Parser::parseTypeOneOf(Type &Result) { SMLoc OneOfLoc = consumeToken(tok::kw_oneof); DeclAttributes Attributes; parseAttributeList(Attributes); return parseTypeOneOfBody(OneOfLoc, Attributes, Result); } /// oneof-body: /// '{' oneof-element (',' oneof-element)* '}' /// oneof-element: /// identifier /// identifier ':' type /// /// If TypeName is specified, it is the type that the constructors should be /// built with, so that they preserve the name of the oneof decl that contains /// this. bool Parser::parseTypeOneOfBody(SMLoc OneOfLoc, const DeclAttributes &Attrs, Type &Result, TypeAliasDecl *TypeName) { if (parseToken(tok::l_brace, "expected '{' in oneof")) return true; SmallVector<OneOfElementInfo, 8> ElementInfos; // Parse the comma separated list of oneof elements. while (Tok.is(tok::identifier)) { OneOfElementInfo ElementInfo; ElementInfo.Name = Tok.getText(); ElementInfo.NameLoc = Tok.getLoc(); ElementInfo.EltType = 0; consumeToken(tok::identifier); // See if we have a type specifier for this oneof element. If so, parse it. if (consumeIf(tok::colon) && parseType(ElementInfo.EltType, "expected type while parsing oneof element '" + ElementInfo.Name + "'")) { skipUntil(tok::r_brace); return true; } ElementInfos.push_back(ElementInfo); // Require comma separation. if (!consumeIf(tok::comma)) break; } parseToken(tok::r_brace, "expected '}' at end of oneof"); Result = actOnOneOfType(OneOfLoc, Attrs, ElementInfos, TypeName); return false; } OneOfType *Parser::actOnOneOfType(SMLoc OneOfLoc, const DeclAttributes &Attrs, ArrayRef<OneOfElementInfo> Elts, TypeAliasDecl *PrettyTypeName) { // No attributes are valid on oneof types at this time. if (!Attrs.empty()) error(Attrs.LSquareLoc, "oneof types are not allowed to have attributes"); llvm::SmallPtrSet<const char *, 16> SeenSoFar; SmallVector<OneOfElementDecl *, 16> EltDecls; // If we have a PrettyTypeName to use, use it. Otherwise, just assign the // constructors a temporary dummy type. Type TmpTy = TupleType::getEmpty(Context); if (PrettyTypeName) TmpTy = PrettyTypeName->getAliasType(Context); for (const OneOfElementInfo &Elt : Elts) { Identifier NameI = Context.getIdentifier(Elt.Name); // If this was multiply defined, reject it. if (!SeenSoFar.insert(NameI.get())) { error(Elt.NameLoc, "element named '" + Elt.Name + "' defined multiple times"); // Don't copy this element into NewElements. // TODO: QoI: add note for previous definition. continue; } Type EltTy = TmpTy; if (Type ArgTy = Elt.EltType) if (PrettyTypeName) EltTy = FunctionType::get(ArgTy, EltTy, Context); // Create a decl for each element, giving each a temporary type. EltDecls.push_back(new (Context) OneOfElementDecl(Elt.NameLoc, NameI, EltTy, Elt.EltType, CurDeclContext)); } OneOfType *Result = OneOfType::getNew(OneOfLoc, EltDecls, CurDeclContext); for (OneOfElementDecl *D : EltDecls) D->Context = Result; if (PrettyTypeName) { // If we have a pretty name for this, complete it to its actual type. assert(PrettyTypeName->UnderlyingTy.isNull() && "Not an incomplete decl to complete!"); PrettyTypeName->UnderlyingTy = Result; } else { // Now that the oneof type is created, we can go back and give proper types // to each element decl. for (OneOfElementDecl *Elt : EltDecls) { Type EltTy = Result; // If the OneOf Element takes a type argument, then it is actually a // function that takes the type argument and returns the OneOfType. if (Type ArgTy = Elt->ArgumentType) EltTy = FunctionType::get(ArgTy, EltTy, Context); Elt->Ty = EltTy; } } return Result; } /// parseTypeArray - The l_square has already been consumed. /// type-array: /// type '[' ']' /// type '[' expr ']' /// bool Parser::parseTypeArray(SMLoc LSquareLoc, Type &Result) { // Handle the [] production, and unsized array. if (consumeIf(tok::r_square)) { if (isa<ErrorType>(Result.getPointer())) return Result; return ArrayType::get(Result, 0, Context); } ParseResult<Expr> SizeEx; if ((SizeEx = parseSingleExpr("expected expression for array type size"))) return true; SMLoc RArrayTok = Tok.getLoc(); if (parseToken(tok::r_square, "expected ']' in array type")) { note(LSquareLoc, "to match this '['"); return true; } // If we had a semantic error on the size or if the base type is invalid, // propagate up an error type. if (SizeEx.isSemaError() || isa<ErrorType>(Result.getPointer())) { Result = ErrorType::get(Context); return false; } // Semantic analysis. Expr *Size = SizeEx.get(); // FIXME: Add real support for evaluating constant expressions for array // sizes. uint64_t SizeVal; if (IntegerLiteralExpr *IL = dyn_cast<IntegerLiteralExpr>(Size)) { SizeVal = IL->getValue(); } else { error(Size->getLocStart(), "invalid type size, not a constant"); return ErrorType::get(Context); } if (SizeVal == 0) { error(Size->getLocStart(), "array types must be larger than zero elements"); return ErrorType::get(Context); } Result = ArrayType::get(Result, SizeVal, Context); return false; } /// type-protocol: /// 'protocol' attribute-list protocol-body /// bool Parser::parseTypeProtocol(Type &Result) { SMLoc ProtocolLoc = consumeToken(tok::kw_protocol); DeclAttributes Attributes; parseAttributeList(Attributes); return parseTypeProtocolBody(ProtocolLoc, Attributes, Result); } /// protocol-body: /// '{' protocol-element* '}' /// protocol-element: /// decl-func /// decl-var-simple /// // 'typealias' identifier /// bool Parser::parseTypeProtocolBody(SMLoc ProtocolLoc, const DeclAttributes &Attributes, Type &Result, TypeAliasDecl *TypeName) { // Parse the body. if (parseToken(tok::l_brace, "expected '{' in protocol")) return true; SmallVector<Decl*, 8> Elements; // Parse the list of protocol elements. do { switch (Tok.getKind()) { default: error(Tok.getLoc(), "unexpected token in protocol body"); return true; case tok::r_brace: // End of protocol body. break; case tok::kw_func: Elements.push_back(parseDeclFunc(false)); if (Elements.back() == 0) return true; break; case tok::kw_var: Elements.push_back(parseDeclVarSimple()); if (Elements.back() == 0) return true; break; } } while (Tok.isNot(tok::r_brace)); consumeToken(tok::r_brace); // Act on what we've parsed. if (!Attributes.empty()) error(Attributes.LSquareLoc, "protocol types are not allowed to have attributes yet"); Result = ProtocolType::getNew(ProtocolLoc, Elements, CurDeclContext); if (TypeName) { // If we have a pretty name for this, complete it to its actual type. assert(TypeName->UnderlyingTy.isNull() && "Not an incomplete decl to complete!"); TypeName->UnderlyingTy = Result; } return false; } <commit_msg>protocol members shalt get the right declcontext and type.<commit_after>//===--- ParseType.cpp - Swift Language Parser for Types ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Type Parsing and AST Building // //===----------------------------------------------------------------------===// #include "Parser.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Twine.h" using namespace swift; bool Parser::parseType(Type &Result) { return parseType(Result, "expected type"); } /// parseType /// type: /// type-simple /// type-function /// type-array /// /// type-function: /// type-simple '->' type /// /// type-simple: /// '__builtin_int32_type' /// identifier /// type-tuple /// type-oneof /// type-protocol /// bool Parser::parseType(Type &Result, const Twine &Message) { // Parse type-simple first. switch (Tok.getKind()) { case tok::identifier: { Identifier Name = Context.getIdentifier(Tok.getText()); Result = ScopeInfo.lookupOrInsertTypeName(Name, Tok.getLoc()); consumeToken(tok::identifier); break; } case tok::kw___builtin_float32_type: Result = Context.TheFloat32Type; consumeToken(tok::kw___builtin_float32_type); break; case tok::kw___builtin_float64_type: Result = Context.TheFloat64Type; consumeToken(tok::kw___builtin_float64_type); break; case tok::kw___builtin_int1_type: Result = Context.TheInt1Type; consumeToken(tok::kw___builtin_int1_type); break; case tok::kw___builtin_int8_type: Result = Context.TheInt8Type; consumeToken(tok::kw___builtin_int8_type); break; case tok::kw___builtin_int16_type: Result = Context.TheInt16Type; consumeToken(tok::kw___builtin_int16_type); break; case tok::kw___builtin_int32_type: Result = Context.TheInt32Type; consumeToken(tok::kw___builtin_int32_type); break; case tok::kw___builtin_int64_type: Result = Context.TheInt64Type; consumeToken(tok::kw___builtin_int64_type); break; case tok::l_paren: case tok::l_paren_space: { SMLoc LPLoc = consumeToken(); if (parseTypeTupleBody(LPLoc, Result)) return true; if (parseToken(tok::r_paren, "expected ')' at end of tuple list", tok::r_paren)) { note(LPLoc, "to match this opening '('"); return true; } break; } case tok::kw_oneof: if (parseTypeOneOf(Result)) return true; break; case tok::kw_protocol: if (parseTypeProtocol(Result)) return true; break; default: error(Tok.getLoc(), Message); return true; } while (1) { // If there is an arrow, parse the rest of the type. SMLoc TokLoc = Tok.getLoc(); if (consumeIf(tok::arrow)) { Type SecondHalf; if (parseType(SecondHalf, "expected type in result of function type")) return true; Result = FunctionType::get(Result, SecondHalf, Context); continue; } // If there is a square bracket, we have an array. if (consumeIf(tok::l_square)) { if (parseTypeArray(TokLoc, Result)) return true; continue; } break; } return false; } /// parseTypeTupleBody /// type-tuple: /// '(' type-tuple-body? ')' /// type-tuple-body: /// type-tuple-element (',' type-tuple-element)* /// type-tuple-element: /// identifier value-specifier /// type ('=' expr)? bool Parser::parseTypeTupleBody(SMLoc LPLoc, Type &Result) { SmallVector<TupleTypeElt, 8> Elements; if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::r_brace)) { bool HadError = false; do { Elements.push_back(TupleTypeElt()); TupleTypeElt &Result = Elements.back(); // If the tuple element starts with "ident :" or "ident =", then // the identifier is an element tag, and it is followed by a // value-specifier. if (Tok.is(tok::identifier) && (peekToken().is(tok::colon) || peekToken().is(tok::equal))) { parseIdentifier(Result.Name, ""); NullablePtr<Expr> Init; if ((HadError = parseValueSpecifier(Result.Ty, Init, /*single*/ true))) break; Result.Init = Init.getPtrOrNull(); continue; } // Otherwise, this has to be a type. if ((HadError = parseType(Result.Ty))) break; // Parse the optional default value expression. if (Tok.is(tok::colon)) { ParseResult<Expr> Init = parseSingleExpr("expected initializer expression after '='"); // Die if there was a parse error. if (Init) { HadError = true; break; } if (!Init.isSemaError()) { Result.Init = Init.get(); } } } while (consumeIf(tok::comma)); if (HadError) { skipUntil(tok::r_paren); if (Tok.is(tok::r_paren)) consumeToken(tok::r_paren); return true; } } Result = TupleType::get(Elements, Context); return false; } /// type-oneof: /// 'oneof' attribute-list oneof-body /// bool Parser::parseTypeOneOf(Type &Result) { SMLoc OneOfLoc = consumeToken(tok::kw_oneof); DeclAttributes Attributes; parseAttributeList(Attributes); return parseTypeOneOfBody(OneOfLoc, Attributes, Result); } /// oneof-body: /// '{' oneof-element (',' oneof-element)* '}' /// oneof-element: /// identifier /// identifier ':' type /// /// If TypeName is specified, it is the type that the constructors should be /// built with, so that they preserve the name of the oneof decl that contains /// this. bool Parser::parseTypeOneOfBody(SMLoc OneOfLoc, const DeclAttributes &Attrs, Type &Result, TypeAliasDecl *TypeName) { if (parseToken(tok::l_brace, "expected '{' in oneof")) return true; SmallVector<OneOfElementInfo, 8> ElementInfos; // Parse the comma separated list of oneof elements. while (Tok.is(tok::identifier)) { OneOfElementInfo ElementInfo; ElementInfo.Name = Tok.getText(); ElementInfo.NameLoc = Tok.getLoc(); ElementInfo.EltType = 0; consumeToken(tok::identifier); // See if we have a type specifier for this oneof element. If so, parse it. if (consumeIf(tok::colon) && parseType(ElementInfo.EltType, "expected type while parsing oneof element '" + ElementInfo.Name + "'")) { skipUntil(tok::r_brace); return true; } ElementInfos.push_back(ElementInfo); // Require comma separation. if (!consumeIf(tok::comma)) break; } parseToken(tok::r_brace, "expected '}' at end of oneof"); Result = actOnOneOfType(OneOfLoc, Attrs, ElementInfos, TypeName); return false; } OneOfType *Parser::actOnOneOfType(SMLoc OneOfLoc, const DeclAttributes &Attrs, ArrayRef<OneOfElementInfo> Elts, TypeAliasDecl *PrettyTypeName) { // No attributes are valid on oneof types at this time. if (!Attrs.empty()) error(Attrs.LSquareLoc, "oneof types are not allowed to have attributes"); llvm::SmallPtrSet<const char *, 16> SeenSoFar; SmallVector<OneOfElementDecl *, 16> EltDecls; // If we have a PrettyTypeName to use, use it. Otherwise, just assign the // constructors a temporary dummy type. Type TmpTy = TupleType::getEmpty(Context); if (PrettyTypeName) TmpTy = PrettyTypeName->getAliasType(Context); for (const OneOfElementInfo &Elt : Elts) { Identifier NameI = Context.getIdentifier(Elt.Name); // If this was multiply defined, reject it. if (!SeenSoFar.insert(NameI.get())) { error(Elt.NameLoc, "element named '" + Elt.Name + "' defined multiple times"); // Don't copy this element into NewElements. // TODO: QoI: add note for previous definition. continue; } Type EltTy = TmpTy; if (Type ArgTy = Elt.EltType) if (PrettyTypeName) EltTy = FunctionType::get(ArgTy, EltTy, Context); // Create a decl for each element, giving each a temporary type. EltDecls.push_back(new (Context) OneOfElementDecl(Elt.NameLoc, NameI, EltTy, Elt.EltType, CurDeclContext)); } OneOfType *Result = OneOfType::getNew(OneOfLoc, EltDecls, CurDeclContext); for (OneOfElementDecl *D : EltDecls) D->Context = Result; if (PrettyTypeName) { // If we have a pretty name for this, complete it to its actual type. assert(PrettyTypeName->UnderlyingTy.isNull() && "Not an incomplete decl to complete!"); PrettyTypeName->UnderlyingTy = Result; } else { // Now that the oneof type is created, we can go back and give proper types // to each element decl. for (OneOfElementDecl *Elt : EltDecls) { Type EltTy = Result; // If the OneOf Element takes a type argument, then it is actually a // function that takes the type argument and returns the OneOfType. if (Type ArgTy = Elt->ArgumentType) EltTy = FunctionType::get(ArgTy, EltTy, Context); Elt->Ty = EltTy; } } return Result; } /// parseTypeArray - The l_square has already been consumed. /// type-array: /// type '[' ']' /// type '[' expr ']' /// bool Parser::parseTypeArray(SMLoc LSquareLoc, Type &Result) { // Handle the [] production, and unsized array. if (consumeIf(tok::r_square)) { if (isa<ErrorType>(Result.getPointer())) return Result; return ArrayType::get(Result, 0, Context); } ParseResult<Expr> SizeEx; if ((SizeEx = parseSingleExpr("expected expression for array type size"))) return true; SMLoc RArrayTok = Tok.getLoc(); if (parseToken(tok::r_square, "expected ']' in array type")) { note(LSquareLoc, "to match this '['"); return true; } // If we had a semantic error on the size or if the base type is invalid, // propagate up an error type. if (SizeEx.isSemaError() || isa<ErrorType>(Result.getPointer())) { Result = ErrorType::get(Context); return false; } // Semantic analysis. Expr *Size = SizeEx.get(); // FIXME: Add real support for evaluating constant expressions for array // sizes. uint64_t SizeVal; if (IntegerLiteralExpr *IL = dyn_cast<IntegerLiteralExpr>(Size)) { SizeVal = IL->getValue(); } else { error(Size->getLocStart(), "invalid type size, not a constant"); return ErrorType::get(Context); } if (SizeVal == 0) { error(Size->getLocStart(), "array types must be larger than zero elements"); return ErrorType::get(Context); } Result = ArrayType::get(Result, SizeVal, Context); return false; } /// type-protocol: /// 'protocol' attribute-list protocol-body /// bool Parser::parseTypeProtocol(Type &Result) { SMLoc ProtocolLoc = consumeToken(tok::kw_protocol); DeclAttributes Attributes; parseAttributeList(Attributes); return parseTypeProtocolBody(ProtocolLoc, Attributes, Result); } /// protocol-body: /// '{' protocol-element* '}' /// protocol-element: /// decl-func /// decl-var-simple /// // 'typealias' identifier /// bool Parser::parseTypeProtocolBody(SMLoc ProtocolLoc, const DeclAttributes &Attributes, Type &Result, TypeAliasDecl *TypeName) { // Parse the body. if (parseToken(tok::l_brace, "expected '{' in protocol")) return true; SmallVector<Decl*, 8> Elements; // Parse the list of protocol elements. do { switch (Tok.getKind()) { default: error(Tok.getLoc(), "unexpected token in protocol body"); return true; case tok::r_brace: // End of protocol body. break; case tok::kw_func: Elements.push_back(parseDeclFunc(false)); if (Elements.back() == 0) return true; break; case tok::kw_var: Elements.push_back(parseDeclVarSimple()); if (Elements.back() == 0) return true; break; } } while (Tok.isNot(tok::r_brace)); consumeToken(tok::r_brace); // Act on what we've parsed. if (!Attributes.empty()) error(Attributes.LSquareLoc, "protocol types are not allowed to have attributes yet"); ProtocolType *NewProto = ProtocolType::getNew(ProtocolLoc, Elements, CurDeclContext); TupleTypeElt ThisElt(NewProto, Context.getIdentifier("this")); TupleType *ThisTy = TupleType::get(ThisElt, Context); // Install all of the members of protocol into the protocol's DeclContext, and // give each ValueDecl member an implicit "this" argument. // FIXME: This isn't quite right, 'this' should be found by name lookup when // parsing the body of each of these. for (Decl *D : Elements) { // Install the right DeclContext. D->Context = NewProto; // Change the type of the value decls to be functions that return whatever // they were declared as. if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) VD->Ty = FunctionType::get(ThisTy, VD->Ty, Context); } if (TypeName) { // If we have a pretty name for this, complete it to its actual type. assert(TypeName->UnderlyingTy.isNull() && "Not an incomplete decl to complete!"); TypeName->UnderlyingTy = NewProto; } Result = NewProto; return false; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUNCTOR_FOR_EACH_HPP #define STAN_MATH_PRIM_FUNCTOR_FOR_EACH_HPP #include <stan/math/prim/meta.hpp> #include <functional> #include <tuple> #include <utility> namespace stan { namespace math { namespace internal { /** * Implementation of for_each. * @note The static cast to void is used in boost::hana's for_each impl * and is used to suppress unused value warnings from the compiler. */ template <typename F, typename T, size_t... Is> constexpr inline auto for_each(F&& f, T&& t, std::index_sequence<Is...>) { using Swallow = int[]; static_cast<void>(Swallow{ (static_cast<void>(std::forward<F>(f)(std::get<Is>(std::forward<T>(t)))), 0)...}); } /** * Implementation of Binary for_each. * @note The static cast to void is used in boost::hana's for_each impl * and is used to suppress unused value warnings from the compiler. */ template <typename F, typename T1, typename T2, size_t... Is> constexpr inline auto for_each(F&& f, T1&& t1, T2&& t2, std::index_sequence<Is...>) { using Swallow = int[]; static_cast<void>(Swallow{( static_cast<void>(std::forward<F>(f)(std::get<Is>(std::forward<T1>(t1)), std::get<Is>(std::forward<T2>(t2)))), 0)...}); } /** * Implementation of Trinary for_each. * @note The static cast to void is used in boost::hana's for_each impl * and is used to suppress unused value warnings from the compiler. */ template <typename F, typename T1, typename T2, typename T3, size_t... Is> constexpr inline auto for_each(F&& f, T1&& t1, T2&& t2, T3&& t3, std::index_sequence<Is...>) { using Swallow = int[]; static_cast<void>(Swallow{( static_cast<void>(std::forward<F>(f)(std::get<Is>(std::forward<T1>(t1)), std::get<Is>(std::forward<T2>(t2)), std::get<Is>(std::forward<T3>(t3)))), 0)...}); } } // namespace internal /** * Apply a function to each element of a tuple * @tparam F type with a valid `operator()` * @tparam T Tuple * @param f A functor to apply over each element of the tuple. * @param t A tuple */ template <typename F, typename T> constexpr inline auto for_each(F&& f, T&& t) { return internal::for_each( std::forward<F>(f), std::forward<T>(t), std::make_index_sequence<std::tuple_size<std::decay_t<T>>::value>()); } /** * Apply a function to each element of two tuples * @tparam F type with a valid `operator()` * @tparam T1 Tuple * @tparam T2 Another tuple * @param f A functor to apply over each element of the tuple. * @param t1 A tuple * @param t2 Another tuple */ template <typename F, typename T1, typename T2> constexpr inline auto for_each(F&& f, T1&& t1, T2&& t2) { constexpr auto t1_size = std::tuple_size<std::decay_t<T1>>::value; constexpr auto t2_size = std::tuple_size<std::decay_t<T2>>::value; static_assert(t1_size == t2_size, "Size Mismatch between t1 and t2 in for_each"); return internal::for_each( std::forward<F>(f), std::forward<T1>(t1), std::forward<T2>(t2), std::make_index_sequence<std::tuple_size<std::decay_t<T1>>::value>()); } /** * Apply a function to each element of three tuples * @tparam F type with a valid `operator()` * @tparam T1 Tuple * @tparam T2 Another tuple * @tparam T3 Another tuple * @param f A functor to apply over each element of the tuple. * @param t1 A tuple * @param t2 Another tuple * @param t3 Another tuple */ template <typename F, typename T1, typename T2, typename T3> constexpr inline auto for_each(F&& f, T1&& t1, T2&& t2, T3&& t3) { constexpr auto t1_size = std::tuple_size<std::decay_t<T1>>::value; constexpr auto t2_size = std::tuple_size<std::decay_t<T2>>::value; constexpr auto t3_size = std::tuple_size<std::decay_t<T3>>::value; static_assert(t1_size == t2_size, "Size Mismatch between t1 and t2 in for_each"); static_assert(t1_size == t3_size, "Size Mismatch between t1 and t3 in for_each"); return internal::for_each( std::forward<F>(f), std::forward<T1>(t1), std::forward<T2>(t2), std::forward<T3>(t3), std::make_index_sequence<std::tuple_size<std::decay_t<T1>>::value>()); } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_FUNCTOR_FOR_EACH_HPP #define STAN_MATH_PRIM_FUNCTOR_FOR_EACH_HPP #include <stan/math/prim/meta.hpp> #include <functional> #include <tuple> #include <utility> namespace stan { namespace math { namespace internal { /** * Implementation of for_each. * @note The static cast to void is used in boost::hana's for_each impl * and is used to suppress unused value warnings from the compiler. */ template <typename F, typename T, size_t... Is> constexpr inline auto for_each(F&& f, T&& t, std::index_sequence<Is...>) { using Swallow = int[]; static_cast<void>(Swallow{ (static_cast<void>(std::forward<F>(f)(std::get<Is>(std::forward<T>(t)))), 0)...}); } /** * Implementation of Binary for_each. * @note The static cast to void is used in boost::hana's for_each impl * and is used to suppress unused value warnings from the compiler. */ template <typename F, typename T1, typename T2, size_t... Is> constexpr inline auto for_each(F&& f, T1&& t1, T2&& t2, std::index_sequence<Is...>) { using Swallow = int[]; static_cast<void>(Swallow{( static_cast<void>(std::forward<F>(f)(std::get<Is>(std::forward<T1>(t1)), std::get<Is>(std::forward<T2>(t2)))), 0)...}); } /** * Implementation of Trinary for_each. * @note The static cast to void is used in boost::hana's for_each impl * and is used to suppress unused value warnings from the compiler. */ template <typename F, typename T1, typename T2, typename T3, size_t... Is> constexpr inline auto for_each(F&& f, T1&& t1, T2&& t2, T3&& t3, std::index_sequence<Is...>) { using Swallow = int[]; static_cast<void>(Swallow{( static_cast<void>(std::forward<F>(f)(std::get<Is>(std::forward<T1>(t1)), std::get<Is>(std::forward<T2>(t2)), std::get<Is>(std::forward<T3>(t3)))), 0)...}); } } // namespace internal /** * Apply a function to each element of a tuple * @tparam F type with a valid `operator()` * @tparam T Tuple * @param f A functor to apply over each element of the tuple. * @param t A tuple */ template <typename F, typename T> constexpr inline auto for_each(F&& f, T&& t) { return internal::for_each( std::forward<F>(f), std::forward<T>(t), std::make_index_sequence<std::tuple_size<std::decay_t<T>>::value>()); } /** * Apply a function to each element of two tuples * @tparam F type with a valid `operator()` * @tparam T1 Tuple * @tparam T2 Another tuple * @param f A functor to apply over each element of the tuple. * @param t1 A tuple * @param t2 Another tuple */ template <typename F, typename T1, typename T2> constexpr inline auto for_each(F&& f, T1&& t1, T2&& t2) { constexpr auto t1_size = std::tuple_size<std::decay_t<T1>>::value; constexpr auto t2_size = std::tuple_size<std::decay_t<T2>>::value; static_assert(t1_size == t2_size, "Size Mismatch between t1 and t2 in for_each"); return internal::for_each( std::forward<F>(f), std::forward<T1>(t1), std::forward<T2>(t2), std::make_index_sequence<std::tuple_size<std::decay_t<T1>>::value>()); } /** * Apply a function to each element of three tuples * @tparam F type with a valid `operator()` * @tparam T1 Tuple * @tparam T2 Another tuple * @tparam T3 Another tuple * @param f A functor to apply over each element of the tuple. * @param t1 A tuple * @param t2 Another tuple * @param t3 Another tuple */ template <typename F, typename T1, typename T2, typename T3> constexpr inline auto for_each(F&& f, T1&& t1, T2&& t2, T3&& t3) { constexpr auto t1_size = std::tuple_size<std::decay_t<T1>>::value; constexpr auto t2_size = std::tuple_size<std::decay_t<T2>>::value; constexpr auto t3_size = std::tuple_size<std::decay_t<T3>>::value; static_assert(t1_size == t2_size, "Size Mismatch between t1 and t2 in for_each"); static_assert(t1_size == t3_size, "Size Mismatch between t1 and t3 in for_each"); return internal::for_each( std::forward<F>(f), std::forward<T1>(t1), std::forward<T2>(t2), std::forward<T3>(t3), std::make_index_sequence<std::tuple_size<std::decay_t<T1>>::value>()); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Sergey Lisitsyn * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/preprocessor/ClassicMDS.h> #ifdef HAVE_LAPACK #include <shogun/preprocessor/DimensionReductionPreprocessor.h> #include <shogun/mathematics/lapack.h> #include <shogun/mathematics/arpack.h> #include <shogun/lib/common.h> #include <shogun/mathematics/Math.h> #include <shogun/io/SGIO.h> #include <shogun/distance/EuclidianDistance.h> #include <shogun/lib/Signal.h> using namespace shogun; CClassicMDS::CClassicMDS() : CDimensionReductionPreprocessor() { m_eigenvalues = SGVector<float64_t>(NULL,0,true); } CClassicMDS::~CClassicMDS() { m_eigenvalues.destroy_vector(); } bool CClassicMDS::init(CFeatures* data) { return true; } void CClassicMDS::cleanup() { } CSimpleFeatures<float64_t>* CClassicMDS::apply_to_distance(CDistance* distance) { ASSERT(distance); SGMatrix<float64_t> new_feature_matrix = embed_by_distance(distance); CSimpleFeatures<float64_t>* new_features = new CSimpleFeatures<float64_t>(new_feature_matrix); return new_features; } SGMatrix<float64_t> CClassicMDS::embed_by_distance(CDistance* distance) { ASSERT(distance->get_num_vec_lhs()==distance->get_num_vec_rhs()); int32_t N = distance->get_num_vec_lhs(); // loop variables int32_t i,j; // get distance matrix SGMatrix<float64_t> D_matrix = distance->get_distance_matrix(); // get D^2 matrix float64_t* Ds_matrix = SG_MALLOC(float64_t, N*N); for (i=0;i<N;i++) for (j=0;j<N;j++) Ds_matrix[i*N+j] = CMath::sq(D_matrix.matrix[i*N+j]); // centering matrix float64_t* H_matrix = SG_MALLOC(float64_t, N*N); for (i=0;i<N;i++) for (j=0;j<N;j++) H_matrix[i*N+j] = (i==j) ? 1.0-1.0/N : -1.0/N; // compute -1/2 H D^2 H (result in Ds_matrix) cblas_dgemm(CblasColMajor,CblasNoTrans,CblasNoTrans, N,N,N,1.0,H_matrix,N,Ds_matrix,N,0.0,D_matrix.matrix,N); cblas_dgemm(CblasColMajor,CblasNoTrans,CblasNoTrans, N,N,N,-0.5,D_matrix.matrix,N,H_matrix,N,0.0,Ds_matrix,N); // cleanup SG_FREE(D_matrix.matrix); SG_FREE(H_matrix); // feature matrix representing given distance float64_t* replace_feature_matrix = SG_MALLOC(float64_t, N*m_target_dim); // status of eigenproblem to be solved int eigenproblem_status = 0; #ifdef HAVE_ARPACK // using ARPACK float64_t* eigenvalues_vector = SG_MALLOC(float64_t, m_target_dim); // solve eigenproblem with ARPACK (faster) arpack_dsaupd(Ds_matrix, NULL, N, m_target_dim, "LM", 1, false, 0.0, eigenvalues_vector, replace_feature_matrix, eigenproblem_status); // check for failure ASSERT(eigenproblem_status == 0); // reverse eigenvectors order float64_t tmp; for (j=0; j<N; j++) { for (i=0; i<m_target_dim/2; i++) { tmp = replace_feature_matrix[j*m_target_dim+i]; replace_feature_matrix[j*m_target_dim+i] = replace_feature_matrix[j*m_target_dim+(m_target_dim-i-1)]; replace_feature_matrix[j*m_target_dim+(m_target_dim-i-1)] = tmp; } } // reverse eigenvalues order for (i=0; i<m_target_dim/2; i++) { tmp = eigenvalues_vector[i]; eigenvalues_vector[i] = eigenvalues_vector[m_target_dim-i-1]; eigenvalues_vector[m_target_dim-i-1] = tmp; } // finally construct embedding for (i=0; i<m_target_dim; i++) { for (j=0; j<N; j++) replace_feature_matrix[j*m_target_dim+i] *= CMath::sqrt(eigenvalues_vector[i]); } // set eigenvalues vector m_eigenvalues.destroy_vector(); m_eigenvalues = SGVector<float64_t>(eigenvalues_vector,m_target_dim,true); #else /* not HAVE_ARPACK */ // using LAPACK float64_t* eigenvalues_vector = SG_MALLOC(float64_t, N); // solve eigenproblem with LAPACK wrap_dsyevr('V','U',N,Ds_matrix,N,N-m_target_dim+1,N,eigenvalues_vector,Ds_matrix,&eigenproblem_status); // check for failure ASSERT(eigenproblem_status==0); // set eigenvalues vector m_eigenvalues.destroy_vector(); m_eigenvalues = SGVector<float64_t>(m_target_dim); // fill eigenvalues vector in backwards order for (i=0; i<m_target_dim; i++) m_eigenvalues.vector[i] = eigenvalues_vector[m_target_dim-i-1]; SG_FREE(eigenvalues_vector); // construct embedding for (i=0; i<m_target_dim; i++) { for (j=0; j<N; j++) { replace_feature_matrix[j*m_target_dim+i] = Ds_matrix[(m_target_dim-i-1)*N+j] * CMath::sqrt(m_eigenvalues.vector[i]); } } #endif /* HAVE_ARPACK else */ // warn user if there are negative or zero eigenvalues for (i=0; i<m_eigenvalues.vlen; i++) { if (m_eigenvalues.vector[i]<=0.0) { SG_WARNING("Embedding is not consistent: features %d-%d are wrong", i, m_eigenvalues.vlen); break; } } // cleanup SG_FREE(Ds_matrix); return SGMatrix<float64_t>(replace_feature_matrix,m_target_dim,N); } SGMatrix<float64_t> CClassicMDS::apply_to_feature_matrix(CFeatures* features) { CSimpleFeatures<float64_t>* simple_features = (CSimpleFeatures<float64_t>*) features; CDistance* distance = new CEuclidianDistance(simple_features,simple_features); SGMatrix<float64_t> new_feature_matrix = embed_by_distance(distance); simple_features->set_feature_matrix(new_feature_matrix); delete distance; return new_feature_matrix; } SGVector<float64_t> CClassicMDS::apply_to_feature_vector(SGVector<float64_t> vector) { SG_NOTIMPLEMENTED; return vector; } #endif /* HAVE_LAPACK */ <commit_msg>Fixed wrong attempt to reuse matrix while DSYEVR is called<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Sergey Lisitsyn * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/preprocessor/ClassicMDS.h> #ifdef HAVE_LAPACK #include <shogun/preprocessor/DimensionReductionPreprocessor.h> #include <shogun/mathematics/lapack.h> #include <shogun/mathematics/arpack.h> #include <shogun/lib/common.h> #include <shogun/mathematics/Math.h> #include <shogun/io/SGIO.h> #include <shogun/distance/EuclidianDistance.h> #include <shogun/lib/Signal.h> using namespace shogun; CClassicMDS::CClassicMDS() : CDimensionReductionPreprocessor() { m_eigenvalues = SGVector<float64_t>(NULL,0,true); } CClassicMDS::~CClassicMDS() { m_eigenvalues.destroy_vector(); } bool CClassicMDS::init(CFeatures* data) { return true; } void CClassicMDS::cleanup() { } CSimpleFeatures<float64_t>* CClassicMDS::apply_to_distance(CDistance* distance) { ASSERT(distance); SGMatrix<float64_t> new_feature_matrix = embed_by_distance(distance); CSimpleFeatures<float64_t>* new_features = new CSimpleFeatures<float64_t>(new_feature_matrix); return new_features; } SGMatrix<float64_t> CClassicMDS::embed_by_distance(CDistance* distance) { ASSERT(distance->get_num_vec_lhs()==distance->get_num_vec_rhs()); int32_t N = distance->get_num_vec_lhs(); // loop variables int32_t i,j; // get distance matrix SGMatrix<float64_t> D_matrix = distance->get_distance_matrix(); // get D^2 matrix float64_t* Ds_matrix = SG_MALLOC(float64_t, N*N); for (i=0;i<N;i++) for (j=0;j<N;j++) Ds_matrix[i*N+j] = CMath::sq(D_matrix.matrix[i*N+j]); // centering matrix float64_t* H_matrix = SG_MALLOC(float64_t, N*N); for (i=0;i<N;i++) for (j=0;j<N;j++) H_matrix[i*N+j] = (i==j) ? 1.0-1.0/N : -1.0/N; // compute -1/2 H D^2 H (result in Ds_matrix) cblas_dgemm(CblasColMajor,CblasNoTrans,CblasNoTrans, N,N,N,1.0,H_matrix,N,Ds_matrix,N,0.0,D_matrix.matrix,N); cblas_dgemm(CblasColMajor,CblasNoTrans,CblasNoTrans, N,N,N,-0.5,D_matrix.matrix,N,H_matrix,N,0.0,Ds_matrix,N); // cleanup SG_FREE(D_matrix.matrix); SG_FREE(H_matrix); // feature matrix representing given distance float64_t* replace_feature_matrix = SG_MALLOC(float64_t, N*m_target_dim); // status of eigenproblem to be solved int eigenproblem_status = 0; #ifdef HAVE_ARPACK // using ARPACK float64_t* eigenvalues_vector = SG_MALLOC(float64_t, m_target_dim); // solve eigenproblem with ARPACK (faster) arpack_dsaupd(Ds_matrix, NULL, N, m_target_dim, "LM", 1, false, 0.0, eigenvalues_vector, replace_feature_matrix, eigenproblem_status); // check for failure ASSERT(eigenproblem_status == 0); // reverse eigenvectors order float64_t tmp; for (j=0; j<N; j++) { for (i=0; i<m_target_dim/2; i++) { tmp = replace_feature_matrix[j*m_target_dim+i]; replace_feature_matrix[j*m_target_dim+i] = replace_feature_matrix[j*m_target_dim+(m_target_dim-i-1)]; replace_feature_matrix[j*m_target_dim+(m_target_dim-i-1)] = tmp; } } // reverse eigenvalues order for (i=0; i<m_target_dim/2; i++) { tmp = eigenvalues_vector[i]; eigenvalues_vector[i] = eigenvalues_vector[m_target_dim-i-1]; eigenvalues_vector[m_target_dim-i-1] = tmp; } // finally construct embedding for (i=0; i<m_target_dim; i++) { for (j=0; j<N; j++) replace_feature_matrix[j*m_target_dim+i] *= CMath::sqrt(eigenvalues_vector[i]); } // set eigenvalues vector m_eigenvalues.destroy_vector(); m_eigenvalues = SGVector<float64_t>(eigenvalues_vector,m_target_dim,true); #else /* not HAVE_ARPACK */ // using LAPACK float64_t* eigenvalues_vector = SG_MALLOC(float64_t, N); float64_t* eigenvectors = SG_MALLOC(float64_t, m_target_dim*N); // solve eigenproblem with LAPACK wrap_dsyevr('V','U',N,Ds_matrix,N,N-m_target_dim+1,N,eigenvalues_vector,eigenvectors,&eigenproblem_status); // check for failure ASSERT(eigenproblem_status==0); // set eigenvalues vector m_eigenvalues.destroy_vector(); m_eigenvalues = SGVector<float64_t>(m_target_dim); // fill eigenvalues vector in backwards order for (i=0; i<m_target_dim; i++) m_eigenvalues.vector[i] = eigenvalues_vector[m_target_dim-i-1]; SG_FREE(eigenvalues_vector); // construct embedding for (i=0; i<m_target_dim; i++) { for (j=0; j<N; j++) { replace_feature_matrix[j*m_target_dim+i] = eigenvectors[(m_target_dim-i-1)*N+j] * CMath::sqrt(m_eigenvalues.vector[i]); } } SG_FREE(eigenvectors); #endif /* HAVE_ARPACK else */ // warn user if there are negative or zero eigenvalues for (i=0; i<m_eigenvalues.vlen; i++) { if (m_eigenvalues.vector[i]<=0.0) { SG_WARNING("Embedding is not consistent (got neg eigenvalues): features %d-%d are wrong", i, m_eigenvalues.vlen); break; } } // cleanup SG_FREE(Ds_matrix); return SGMatrix<float64_t>(replace_feature_matrix,m_target_dim,N); } SGMatrix<float64_t> CClassicMDS::apply_to_feature_matrix(CFeatures* features) { CSimpleFeatures<float64_t>* simple_features = (CSimpleFeatures<float64_t>*) features; CDistance* distance = new CEuclidianDistance(simple_features,simple_features); SGMatrix<float64_t> new_feature_matrix = embed_by_distance(distance); simple_features->set_feature_matrix(new_feature_matrix); delete distance; return new_feature_matrix; } SGVector<float64_t> CClassicMDS::apply_to_feature_vector(SGVector<float64_t> vector) { SG_NOTIMPLEMENTED; return vector; } #endif /* HAVE_LAPACK */ <|endoftext|>
<commit_before> // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "software/SfMViewer/document.h" #include "openMVG/multiview/projection.hpp" #include "openMVG/image/image.hpp" using namespace openMVG; #include "third_party/cmdLine/cmdLine.h" #include "third_party/progress/progress.hpp" #include <stdlib.h> #include <stdio.h> #include <cmath> #include <iterator> #include <iomanip> bool exportToPMVSFormat( const Document & doc, const std::string & sOutDirectory, //Output PMVS files directory const std::string & sImagePath, // The images path const int resolution, const int CPU ) { bool bOk = true; if (!stlplus::is_folder(sOutDirectory)) { stlplus::folder_create(sOutDirectory); bOk = stlplus::is_folder(sOutDirectory); } // Create basis directory structure stlplus::folder_create( stlplus::folder_append_separator(sOutDirectory) + "models"); stlplus::folder_create( stlplus::folder_append_separator(sOutDirectory) + "txt"); stlplus::folder_create( stlplus::folder_append_separator(sOutDirectory) + "visualize"); if (bOk && stlplus::is_folder(stlplus::folder_append_separator(sOutDirectory) + "models") && stlplus::is_folder( stlplus::folder_append_separator(sOutDirectory) + "txt") && stlplus::is_folder( stlplus::folder_append_separator(sOutDirectory) + "visualize") ) { bOk = true; } else { std::cerr << "Cannot access to one of the desired output directory" << std::endl; } if (bOk) { C_Progress_display my_progress_bar( doc._map_camera.size()*2 ); // Export data : //Camera size_t count = 0; for (std::map<size_t, PinholeCamera>::const_iterator iter = doc._map_camera.begin(); iter != doc._map_camera.end(); ++iter, ++count, ++my_progress_bar) { const Mat34 & PMat = iter->second._P; std::ostringstream os; os << std::setw(8) << std::setfill('0') << count; std::ofstream file( stlplus::create_filespec(stlplus::folder_append_separator(sOutDirectory) + "txt", os.str() ,"txt").c_str()); file << "CONTOUR\n" << PMat.row(0) <<"\n"<< PMat.row(1) <<"\n"<< PMat.row(2) << std::endl; file.close(); } // Image count = 0; Image<RGBColor> image; for (std::map<size_t, PinholeCamera>::const_iterator iter = doc._map_camera.begin(); iter != doc._map_camera.end(); ++iter, ++count, ++my_progress_bar) { size_t imageIndex = iter->first; const std::string & sImageName = doc._vec_imageNames[imageIndex]; std::ostringstream os; os << std::setw(8) << std::setfill('0') << count; ReadImage( stlplus::create_filespec( sImagePath, sImageName).c_str(), &image ); std::string sCompleteImageName = stlplus::create_filespec( stlplus::folder_append_separator(sOutDirectory) + "visualize", os.str(),"jpg"); WriteImage( sCompleteImageName.c_str(), image); } //pmvs_options.txt std::ostringstream os; os << "level " << resolution << "\n" << "csize 2" << "\n" << "threshold 0.7" << "\n" << "wsize 7" << "\n" << "minImageNum 3" << "\n" << "CPU " << CPU << "\n" << "setEdge 0" << "\n" << "useBound 0" << "\n" << "useVisData 0" << "\n" << "sequence -1" << "\n" << "maxAngle 10" << "\n" << "quad 2.0" << "\n" << "timages -1 0 " << doc._map_camera.size() << "\n" << "oimages 0" << "\n"; // ? std::ofstream file(stlplus::create_filespec(sOutDirectory, "pmvs_options", "txt").c_str()); file << os.str(); file.close(); } return bOk; } bool exportToBundlerFormat( const Document & doc, const std::string & sOutFile, //Output Bundle.rd.out file const std::string & sOutListFile) //Output Bundler list.txt file { std::ofstream os(sOutFile.c_str() ); std::ofstream osList(sOutListFile.c_str() ); if (os.is_open() && osList.is_open()) { os << "# Bundle file v0.3" << std::endl << doc._map_camera.size() << " " << doc._tracks.size() << std::endl; size_t count = 0; for (std::map<size_t, PinholeCamera>::const_iterator iter = doc._map_camera.begin(); iter != doc._map_camera.end(); ++iter) { const PinholeCamera & PMat = iter->second; Mat3 D; D.fill(0.0); D .diagonal() = Vec3(1., -1., -1.); // mapping between our pinhole and Bundler convention Mat3 R = D * PMat._R; Vec3 t = D * PMat._t; double focal = PMat._K(0,0); double k1 = 0.0, k2 = 0.0; // distortion already removed os << focal << " " << k1 << " " << k2 << std::endl //f k1 k2 << R(0,0) << " " << R(0, 1) << " " << R(0, 2) << std::endl //R[0] << R(1,0) << " " << R(1, 1) << " " << R(1, 2) << std::endl //R[1] << R(2,0) << " " << R(2, 1) << " " << R(2, 2) << std::endl //R[2] << t(0) << " " << t(1) << " " << t(2) << std::endl; //t osList << doc._vec_imageNames[iter->first] << " 0 " << focal << std::endl; } for (std::map< size_t, tracks::submapTrack >::const_iterator iterTracks = doc._tracks.begin(); iterTracks != doc._tracks.end(); ++iterTracks) { const size_t trackId = iterTracks->first; const tracks::submapTrack & map_track = iterTracks->second; const size_t trackIndex = std::distance<std::map< size_t, tracks::submapTrack >::const_iterator>(doc._tracks.begin(), iterTracks); const float * ptr3D = & doc._vec_points[trackIndex*3]; os << ptr3D[0] << " " << ptr3D[1] << " " << ptr3D[2] << std::endl; os << "255 255 255" << std::endl; os << map_track.size() << " "; for (tracks::submapTrack::const_iterator iterTrack = map_track.begin(); iterTrack != map_track.end(); ++iterTrack) { const PinholeCamera & PMat = doc._map_camera.find(iterTrack->first)->second; Vec2 pt = PMat.Project(Vec3(ptr3D[0], ptr3D[1], ptr3D[2])); os << iterTrack->first << " " << iterTrack->second << " " << pt(0) << " " << pt(1) << " "; } os << std::endl; } os.close(); osList.close(); } else { return false; } return true; } int main(int argc, char *argv[]) { CmdLine cmd; std::string sSfMDir; std::string sOutDir = ""; int resolution = 1; int CPU = 8; cmd.add( make_option('i', sSfMDir, "sfmdir") ); cmd.add( make_option('o', sOutDir, "outdir") ); cmd.add( make_option('r', resolution, "resolution") ); cmd.add( make_option('c', CPU, "CPU") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << ' ' << "[-i|--sfmdir path, the SfM_output path] " << "[-o|--outdir path] " << "[-r|--resolution: divide image coefficient] " << "[-c|--nb core] " << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } // Create output dir if (!stlplus::folder_exists(sOutDir)) stlplus::folder_create( sOutDir ); Document m_doc; if (m_doc.load(sSfMDir)) { exportToPMVSFormat(m_doc, stlplus::folder_append_separator(sOutDir) + "PMVS", stlplus::folder_append_separator(sSfMDir) + "images", resolution, CPU ); exportToBundlerFormat(m_doc, stlplus::folder_append_separator(sOutDir) + stlplus::folder_append_separator("PMVS") + "bundle.rd.out", stlplus::folder_append_separator(sOutDir) + stlplus::folder_append_separator("PMVS") + "list.txt" ); return( EXIT_SUCCESS ); } // Exit program return( EXIT_FAILURE ); } <commit_msg>update file opening test @fabiencastan.<commit_after> // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "software/SfMViewer/document.h" #include "openMVG/multiview/projection.hpp" #include "openMVG/image/image.hpp" using namespace openMVG; #include "third_party/cmdLine/cmdLine.h" #include "third_party/progress/progress.hpp" #include <stdlib.h> #include <stdio.h> #include <cmath> #include <iterator> #include <iomanip> bool exportToPMVSFormat( const Document & doc, const std::string & sOutDirectory, //Output PMVS files directory const std::string & sImagePath, // The images path const int resolution, const int CPU ) { bool bOk = true; if (!stlplus::is_folder(sOutDirectory)) { stlplus::folder_create(sOutDirectory); bOk = stlplus::is_folder(sOutDirectory); } // Create basis directory structure stlplus::folder_create( stlplus::folder_append_separator(sOutDirectory) + "models"); stlplus::folder_create( stlplus::folder_append_separator(sOutDirectory) + "txt"); stlplus::folder_create( stlplus::folder_append_separator(sOutDirectory) + "visualize"); if (bOk && stlplus::is_folder(stlplus::folder_append_separator(sOutDirectory) + "models") && stlplus::is_folder( stlplus::folder_append_separator(sOutDirectory) + "txt") && stlplus::is_folder( stlplus::folder_append_separator(sOutDirectory) + "visualize") ) { bOk = true; } else { std::cerr << "Cannot access to one of the desired output directory" << std::endl; } if (bOk) { C_Progress_display my_progress_bar( doc._map_camera.size()*2 ); // Export data : //Camera size_t count = 0; for (std::map<size_t, PinholeCamera>::const_iterator iter = doc._map_camera.begin(); iter != doc._map_camera.end(); ++iter, ++count, ++my_progress_bar) { const Mat34 & PMat = iter->second._P; std::ostringstream os; os << std::setw(8) << std::setfill('0') << count; std::ofstream file( stlplus::create_filespec(stlplus::folder_append_separator(sOutDirectory) + "txt", os.str() ,"txt").c_str()); file << "CONTOUR\n" << PMat.row(0) <<"\n"<< PMat.row(1) <<"\n"<< PMat.row(2) << std::endl; file.close(); } // Image count = 0; Image<RGBColor> image; for (std::map<size_t, PinholeCamera>::const_iterator iter = doc._map_camera.begin(); iter != doc._map_camera.end(); ++iter, ++count, ++my_progress_bar) { size_t imageIndex = iter->first; const std::string & sImageName = doc._vec_imageNames[imageIndex]; std::ostringstream os; os << std::setw(8) << std::setfill('0') << count; ReadImage( stlplus::create_filespec( sImagePath, sImageName).c_str(), &image ); std::string sCompleteImageName = stlplus::create_filespec( stlplus::folder_append_separator(sOutDirectory) + "visualize", os.str(),"jpg"); WriteImage( sCompleteImageName.c_str(), image); } //pmvs_options.txt std::ostringstream os; os << "level " << resolution << "\n" << "csize 2" << "\n" << "threshold 0.7" << "\n" << "wsize 7" << "\n" << "minImageNum 3" << "\n" << "CPU " << CPU << "\n" << "setEdge 0" << "\n" << "useBound 0" << "\n" << "useVisData 0" << "\n" << "sequence -1" << "\n" << "maxAngle 10" << "\n" << "quad 2.0" << "\n" << "timages -1 0 " << doc._map_camera.size() << "\n" << "oimages 0" << "\n"; // ? std::ofstream file(stlplus::create_filespec(sOutDirectory, "pmvs_options", "txt").c_str()); file << os.str(); file.close(); } return bOk; } bool exportToBundlerFormat( const Document & doc, const std::string & sOutFile, //Output Bundle.rd.out file const std::string & sOutListFile) //Output Bundler list.txt file { std::ofstream os(sOutFile.c_str() ); std::ofstream osList(sOutListFile.c_str() ); if (! os.is_open() || ! osList.is_open()) { return false; } else { os << "# Bundle file v0.3" << std::endl << doc._map_camera.size() << " " << doc._tracks.size() << std::endl; size_t count = 0; for (std::map<size_t, PinholeCamera>::const_iterator iter = doc._map_camera.begin(); iter != doc._map_camera.end(); ++iter) { const PinholeCamera & PMat = iter->second; Mat3 D; D.fill(0.0); D .diagonal() = Vec3(1., -1., -1.); // mapping between our pinhole and Bundler convention Mat3 R = D * PMat._R; Vec3 t = D * PMat._t; double focal = PMat._K(0,0); double k1 = 0.0, k2 = 0.0; // distortion already removed os << focal << " " << k1 << " " << k2 << std::endl //f k1 k2 << R(0,0) << " " << R(0, 1) << " " << R(0, 2) << std::endl //R[0] << R(1,0) << " " << R(1, 1) << " " << R(1, 2) << std::endl //R[1] << R(2,0) << " " << R(2, 1) << " " << R(2, 2) << std::endl //R[2] << t(0) << " " << t(1) << " " << t(2) << std::endl; //t osList << doc._vec_imageNames[iter->first] << " 0 " << focal << std::endl; } for (std::map< size_t, tracks::submapTrack >::const_iterator iterTracks = doc._tracks.begin(); iterTracks != doc._tracks.end(); ++iterTracks) { const size_t trackId = iterTracks->first; const tracks::submapTrack & map_track = iterTracks->second; const size_t trackIndex = std::distance<std::map< size_t, tracks::submapTrack >::const_iterator>(doc._tracks.begin(), iterTracks); const float * ptr3D = & doc._vec_points[trackIndex*3]; os << ptr3D[0] << " " << ptr3D[1] << " " << ptr3D[2] << std::endl; os << "255 255 255" << std::endl; os << map_track.size() << " "; for (tracks::submapTrack::const_iterator iterTrack = map_track.begin(); iterTrack != map_track.end(); ++iterTrack) { const PinholeCamera & PMat = doc._map_camera.find(iterTrack->first)->second; Vec2 pt = PMat.Project(Vec3(ptr3D[0], ptr3D[1], ptr3D[2])); os << iterTrack->first << " " << iterTrack->second << " " << pt(0) << " " << pt(1) << " "; } os << std::endl; } os.close(); osList.close(); } return true; } int main(int argc, char *argv[]) { CmdLine cmd; std::string sSfMDir; std::string sOutDir = ""; int resolution = 1; int CPU = 8; cmd.add( make_option('i', sSfMDir, "sfmdir") ); cmd.add( make_option('o', sOutDir, "outdir") ); cmd.add( make_option('r', resolution, "resolution") ); cmd.add( make_option('c', CPU, "CPU") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << ' ' << "[-i|--sfmdir path, the SfM_output path] " << "[-o|--outdir path] " << "[-r|--resolution: divide image coefficient] " << "[-c|--nb core] " << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } // Create output dir if (!stlplus::folder_exists(sOutDir)) stlplus::folder_create( sOutDir ); Document m_doc; if (m_doc.load(sSfMDir)) { exportToPMVSFormat(m_doc, stlplus::folder_append_separator(sOutDir) + "PMVS", stlplus::folder_append_separator(sSfMDir) + "images", resolution, CPU ); exportToBundlerFormat(m_doc, stlplus::folder_append_separator(sOutDir) + stlplus::folder_append_separator("PMVS") + "bundle.rd.out", stlplus::folder_append_separator(sOutDir) + stlplus::folder_append_separator("PMVS") + "list.txt" ); return( EXIT_SUCCESS ); } // Exit program return( EXIT_FAILURE ); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAcosImageAdaptor.h" #include "itkAffineRegistrationTransform.h" #include "itkAffineTransform.h" #include "itkAffineTransformation.h" #include "itkArray.h" #include "itkAsinImageAdaptor.h" #include "itkAtanImageAdaptor.h" #include "itkBackwardDifferenceOperator.h" #include "itkBlueDataAccessor.h" #include "itkBoundingBox.h" #include "itkByteSwapper.h" #include "itkCellBoundary.h" #include "itkCellInterface.h" #include "itkCellInterfaceVisitor.h" #include "itkCentralDerivativeImageFunction.h" #include "itkColorTable.h" #include "itkCommand.h" #include "itkConceptChecking.h" #include "itkConstSliceIterator.h" #include "itkConstantBoundaryCondition.h" #include "itkContinuousImageFunction.h" #include "itkContinuousIndex.h" #include "itkCosImageAdaptor.h" #include "itkCovariantVector.h" #include "itkCreateObjectFunction.h" #include "itkDataAccessor.h" #include "itkDataObject.h" #include "itkDefaultDataAccessor.h" #include "itkDefaultDynamicMeshTraits.h" #include "itkDefaultImageTraits.h" #include "itkDefaultStaticMeshTraits.h" #include "itkDerivativeOperator.h" #include "itkDirectory.h" #include "itkDynamicLoader.h" #include "itkElasticBodySplineKernelTransform.h" #include "itkEntropyPreservingGradientMagnitudeImageFunction.h" #include "itkExceptionObject.h" #include "itkExpImageAdaptor.h" #include "itkFastMutexLock.h" #include "itkForwardDifferenceOperator.h" #include "itkGaussianOperator.h" #include "itkGreenDataAccessor.h" #include "itkHexahedronCell.h" #include "itkImage.h" #include "itkImageAdaptor.h" #include "itkImageBase.h" #include "itkImageBoundaryCondition.h" #include "itkImageBufferIterator.h" #include "itkImageConstIteratorWithIndex.h" #include "itkImageContainerInterface.h" #include "itkImageFunction.h" #include "itkImageIO.h" #include "itkImageIOCommon.h" #include "itkImageIterator.h" #include "itkImageIteratorWithIndex.h" #include "itkImageLinearConstIterator.h" #include "itkImageLinearIterator.h" #include "itkImageRegion.h" #include "itkImageRegionIterator.h" #include "itkImageSliceConstIterator.h" #include "itkImageSliceIterator.h" #include "itkImageSource.h" #include "itkImageToImageFilter.h" #include "itkImportImageContainer.h" #include "itkIndent.h" #include "itkIndex.h" #include "itkIndexedContainerInterface.h" #include "itkIntTypes.h" #include "itkKernelTransform.h" #include "itkLevelSetCurvatureFunction.h" #include "itkLightObject.h" #include "itkLightProcessObject.h" #include "itkLineCell.h" #include "itkLinearInterpolateImageFunction.h" #include "itkLog10ImageAdaptor.h" #include "itkLogImageAdaptor.h" #include "itkMacro.h" #include "itkMapContainer.h" #include "itkMatrix.h" #include "itkMesh.h" #include "itkMeshRegion.h" #include "itkMultiThreader.h" #include "itkMutexLock.h" #include "itkNeighborhood.h" #include "itkNeighborhoodAlgorithm.h" #include "itkNeighborhoodAllocator.h" #include "itkNeighborhoodIterator.h" #include "itkNeighborhoodOperator.h" #include "itkNthElementDataAccessor.h" #include "itkNthElementImageAdaptor.h" #include "itkNumericTraits.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkObjectFactoryBase.h" #include "itkOffset.h" #include "itkOutputWindow.h" #include "itkPhysicalImage.h" #include "itkPhysicalImageAdaptor.h" #include "itkPixelTraits.h" #include "itkPoint.h" #include "itkPointLocator.h" #include "itkPointSet.h" #include "itkProcessObject.h" #include "itkQuadrilateralCell.h" #include "itkRGBPixel.h" #include "itkRandomAccessNeighborhoodIterator.h" #include "itkRedDataAccessor.h" #include "itkRegion.h" #include "itkRegionBoundaryNeighborhoodIterator.h" #include "itkRegionNeighborhoodIterator.h" #include "itkRegionNonBoundaryNeighborhoodIterator.h" #include "itkRigid3DRegistrationTransform.h" #include "itkRigid3DTransform.h" #include "itkScalar.h" #include "itkScalarImageRegionIterator.h" #include "itkScalarVector.h" #include "itkSimpleImageRegionConstIterator.h" #include "itkSimpleImageRegionIterator.h" #include "itkSinImageAdaptor.h" #include "itkSize.h" #include "itkSliceIterator.h" #include "itkSmartPointer.h" #include "itkSmartPointerForwardReference.h" #include "itkSmartRegionNeighborhoodIterator.h" #include "itkSqrtImageAdaptor.h" #include "itkStatDenseHistogram.h" #include "itkStatHistogram.h" #include "itkStatSparseHistogram.h" #include "itkTanImageAdaptor.h" #include "itkTetrahedronCell.h" #include "itkThinPlateSplineKernelTransform.h" #include "itkTimeStamp.h" #include "itkTransformation.h" #include "itkTranslationRegistrationTransform.h" #include "itkTranslationTransform.h" #include "itkTriangleCell.h" #include "itkUpwindDerivativeImageFunction.h" #include "itkValarrayImageContainer.h" #include "itkVector.h" #include "itkVectorContainer.h" #include "itkVersion.h" #include "itkVertexCell.h" #include "itkWeakPointer.h" #include "itkWin32Header.h" #include "itkWin32OutputWindow.h" #include "itkZeroFluxNeumannBoundaryCondition.h" #include "itk_alloc.h" #include "itk_hash_map.h" #include "itk_hash_set.h" #include "itk_hashtable.h" #include "vcl_alloc.h" int main ( int argc, char* argv ) { return 0; } <commit_msg>ENH: Updated to latest headers<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAcosImageAdaptor.h" #include "itkAffineRegistrationTransform.h" #include "itkAffineTransform.h" #include "itkAffineTransformation.h" #include "itkArray.h" #include "itkAsinImageAdaptor.h" #include "itkAtanImageAdaptor.h" #include "itkBackwardDifferenceOperator.h" #include "itkBlueDataAccessor.h" #include "itkBoundingBox.h" #include "itkByteSwapper.h" #include "itkCellBoundary.h" #include "itkCellInterface.h" #include "itkCellInterfaceVisitor.h" #include "itkCentralDerivativeImageFunction.h" #include "itkColorTable.h" #include "itkCommand.h" #include "itkConceptChecking.h" #include "itkConstSliceIterator.h" #include "itkConstantBoundaryCondition.h" #include "itkContinuousImageFunction.h" #include "itkContinuousIndex.h" #include "itkCosImageAdaptor.h" #include "itkCovariantVector.h" #include "itkCreateObjectFunction.h" #include "itkDataAccessor.h" #include "itkDataObject.h" #include "itkDefaultDataAccessor.h" #include "itkDefaultDynamicMeshTraits.h" #include "itkDefaultImageTraits.h" #include "itkDefaultStaticMeshTraits.h" #include "itkDerivativeOperator.h" #include "itkDirectory.h" #include "itkDynamicLoader.h" #include "itkElasticBodySplineKernelTransform.h" #include "itkEntropyPreservingGradientMagnitudeImageFunction.h" #include "itkExceptionObject.h" #include "itkExpImageAdaptor.h" #include "itkFastMutexLock.h" #include "itkForwardDifferenceOperator.h" #include "itkGaussianOperator.h" #include "itkGreenDataAccessor.h" #include "itkHexahedronCell.h" #include "itkImage.h" #include "itkImageAdaptor.h" #include "itkImageBase.h" #include "itkImageBoundaryCondition.h" #include "itkImageBufferIterator.h" #include "itkImageConstIteratorWithIndex.h" #include "itkImageContainerInterface.h" #include "itkImageFunction.h" #include "itkImageIO.h" #include "itkImageIOCommon.h" #include "itkImageIterator.h" #include "itkImageIteratorWithIndex.h" #include "itkImageLinearConstIterator.h" #include "itkImageLinearIterator.h" #include "itkImageRegion.h" #include "itkImageRegionIterator.h" #include "itkImageSliceConstIterator.h" #include "itkImageSliceIterator.h" #include "itkImageSource.h" #include "itkImageToImageFilter.h" #include "itkImportImageContainer.h" #include "itkIndent.h" #include "itkIndex.h" #include "itkIndexedContainerInterface.h" #include "itkIntTypes.h" #include "itkKernelTransform.h" #include "itkLevelSetCurvatureFunction.h" #include "itkLightObject.h" #include "itkLightProcessObject.h" #include "itkLineCell.h" #include "itkLinearInterpolateImageFunction.h" #include "itkLog10ImageAdaptor.h" #include "itkLogImageAdaptor.h" #include "itkMacro.h" #include "itkMapContainer.h" #include "itkMatrix.h" #include "itkMesh.h" #include "itkMeshRegion.h" #include "itkMultiThreader.h" #include "itkMutexLock.h" #include "itkNeighborhood.h" #include "itkNeighborhoodAlgorithm.h" #include "itkNeighborhoodAllocator.h" #include "itkNeighborhoodIterator.h" #include "itkNeighborhoodOperator.h" #include "itkNthElementDataAccessor.h" #include "itkNthElementImageAdaptor.h" #include "itkNumericTraits.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkObjectFactoryBase.h" #include "itkOffset.h" #include "itkOutputWindow.h" #include "itkPhysicalImage.h" #include "itkPhysicalImageAdaptor.h" #include "itkPixelTraits.h" #include "itkPoint.h" #include "itkPointLocator.h" #include "itkPointSet.h" #include "itkProcessObject.h" #include "itkQuadrilateralCell.h" #include "itkRGBPixel.h" #include "itkRandomAccessNeighborhoodIterator.h" #include "itkRedDataAccessor.h" #include "itkRegion.h" #include "itkRegionBoundaryNeighborhoodIterator.h" #include "itkRegionNeighborhoodIterator.h" #include "itkRegionNonBoundaryNeighborhoodIterator.h" #include "itkRigid3DRegistrationTransform.h" #include "itkRigid3DTransform.h" #include "itkScalar.h" #include "itkScalarImageRegionIterator.h" #include "itkScalarVector.h" #include "itkSimpleImageRegionConstIterator.h" #include "itkSimpleImageRegionIterator.h" #include "itkSinImageAdaptor.h" #include "itkSize.h" #include "itkSliceIterator.h" #include "itkSmartPointer.h" #include "itkSmartPointerForwardReference.h" #include "itkSmartRegionNeighborhoodIterator.h" #include "itkSqrtImageAdaptor.h" #include "itkStatDenseHistogram.h" #include "itkStatHistogram.h" #include "itkStatSparseHistogram.h" #include "itkTanImageAdaptor.h" #include "itkTetrahedronCell.h" #include "itkThinPlateSplineKernelTransform.h" #include "itkTimeStamp.h" #include "itkTransformation.h" #include "itkTranslationRegistrationTransform.h" #include "itkTranslationTransform.h" #include "itkTriangleCell.h" #include "itkUpwindDerivativeImageFunction.h" #include "itkValarrayImageContainer.h" #include "itkVector.h" #include "itkVectorContainer.h" #include "itkVersion.h" #include "itkVertexCell.h" #include "itkWeakPointer.h" #include "itkZeroFluxNeumannBoundaryCondition.h" #include "itk_alloc.h" #include "itk_hash_map.h" #include "itk_hash_set.h" #include "itk_hashtable.h" #include "vcl_alloc.h" int main ( int argc, char* argv ) { return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkSmartPointerTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> #include "itkSmartPointer.h" class itkTestObject { public: typedef itk::SmartPointer<itkTestObject> Pointer; static itkTestObject::Pointer New(); virtual void Register() { std::cout << "Register " << *this << " count:" << (m_ReferenceCount+1) << " " << std::endl; m_ReferenceCount++; } virtual void UnRegister() { std::cout << "UnRegister " << this << " count:" << (m_ReferenceCount-1) << " " << std::endl; m_ReferenceCount--; if ( m_ReferenceCount == 0 ) { delete this; } } inline friend std::ostream &operator << (std::ostream &os, itkTestObject const& o) { os << "itkTestObject " << (void*)&o << " " << o.m_ReferenceCount; return os; } std::ostream& Print(std::ostream& os) const { os << "itkTestObject " << (void*)this << " " << this->m_ReferenceCount; return os; } protected: itkTestObject() { m_ReferenceCount = 0; std::cout << "construct itkTestObject " << *this << std::endl; } ~itkTestObject() { std::cout << "destruct itkTestObject " << *this << std::endl; } private: unsigned int m_ReferenceCount; }; itkTestObject::Pointer itkTestObject::New() { return itkTestObject::Pointer(new itkTestObject); } class itkTestObjectSubClass : public itkTestObject { public: typedef itk::SmartPointer<itkTestObjectSubClass> Pointer; static Pointer New(); }; itkTestObjectSubClass::Pointer itkTestObjectSubClass::New() { return itkTestObjectSubClass::Pointer(new itkTestObjectSubClass); } void TestUpCastPointer(itkTestObject::Pointer p) { } void TestUpCast(itkTestObject* p) { } int main() { itkTestObject::Pointer to(itkTestObjectSubClass::New()); itkTestObjectSubClass::Pointer sc = dynamic_cast<itkTestObjectSubClass*>((itkTestObject*)to); TestUpCast(sc); TestUpCastPointer(sc.GetPointer()); std::cout <<"second test" << std::endl; { itkTestObject::Pointer o1 = itkTestObject::New(); std::cout << "o1 " << &o1 << std::endl; itkTestObject::Pointer o2 = itkTestObject::New(); std::cout << "o2 " << &o2 << std::endl; itkTestObject::Pointer o3 = itkTestObject::New(); std::cout << "o3 " << &o3 << std::endl; itkTestObject::Pointer o4 = itkTestObject::New(); std::cout << "o4 " << &o4 << std::endl; o1 = o2; o2 = o3; o4 = o1; if ( o1 < o2 ) { std::cout << "o1 is < o2 " << o1 << " " << o2 << std::endl; } else { std::cout << "o1 is not < o2 " << &o1 << " " << &o2 << std::endl; } } std::cout <<"end second test" << std::endl << std::endl; std::cout <<"first test" << std::endl; { itkTestObject::Pointer o1 = itkTestObject::New(); } std::cout <<"end first test" << std::endl << std::endl; return 0; } <commit_msg>ENH: better comments/examples on smart pointer usage<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkSmartPointerTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> #include "itkSmartPointer.h" class itkTestObject { public: typedef itk::SmartPointer<itkTestObject> Pointer; static itkTestObject::Pointer New(); virtual void Register() { std::cout << "Register " << *this << " count:" << (m_ReferenceCount+1) << " " << std::endl; m_ReferenceCount++; } virtual void UnRegister() { std::cout << "UnRegister " << this << " count:" << (m_ReferenceCount-1) << " " << std::endl; m_ReferenceCount--; if ( m_ReferenceCount == 0 ) { delete this; } } inline friend std::ostream &operator << (std::ostream &os, itkTestObject const& o) { os << "itkTestObject " << (void*)&o << " " << o.m_ReferenceCount; return os; } std::ostream& Print(std::ostream& os) const { os << "itkTestObject " << (void*)this << " " << this->m_ReferenceCount; return os; } protected: itkTestObject() { m_ReferenceCount = 0; std::cout << "construct itkTestObject " << *this << std::endl; } ~itkTestObject() { std::cout << "destruct itkTestObject " << *this << std::endl; } private: unsigned int m_ReferenceCount; }; itkTestObject::Pointer itkTestObject::New() { return itkTestObject::Pointer(new itkTestObject); } class itkTestObjectSubClass : public itkTestObject { public: typedef itk::SmartPointer<itkTestObjectSubClass> Pointer; static Pointer New(); }; itkTestObjectSubClass::Pointer itkTestObjectSubClass::New() { return itkTestObjectSubClass::Pointer(new itkTestObjectSubClass); } // This SHOULD NOT be used in ITK, all functions // should take raw pointers as arguments void TestUpCastPointer(itkTestObject::Pointer p) { } // Test a function that takes an itkTestObject raw pointer void TestUpCast(itkTestObject* p) { } int main() { // Create a base class pointer to a child class itkTestObject::Pointer to(itkTestObjectSubClass::New()); // test the safe down cast and create a child class Pointer object itkTestObjectSubClass::Pointer sc = dynamic_cast<itkTestObjectSubClass*>(to.GetPointer()); // Test the up cast with a function that takes a pointer TestUpCast(sc); // Test calling a function that takes a SmartPointer as // an argument, note, that you have to get the raw pointer // for this to work TestUpCastPointer(sc.GetPointer()); // Test casting up the tree, note no explict cast is required itkTestObject::Pointer p = sc; std::cout <<"second test" << std::endl; { itkTestObject::Pointer o1 = itkTestObject::New(); std::cout << "o1 " << &o1 << std::endl; itkTestObject::Pointer o2 = itkTestObject::New(); std::cout << "o2 " << &o2 << std::endl; itkTestObject::Pointer o3 = itkTestObject::New(); std::cout << "o3 " << &o3 << std::endl; itkTestObject::Pointer o4 = itkTestObject::New(); std::cout << "o4 " << &o4 << std::endl; o1 = o2; o2 = o3; o4 = o1; if ( o1 < o2 ) { std::cout << "o1 is < o2 " << o1 << " " << o2 << std::endl; } else { std::cout << "o1 is not < o2 " << &o1 << " " << &o2 << std::endl; } } std::cout <<"end second test" << std::endl << std::endl; std::cout <<"first test" << std::endl; { itkTestObject::Pointer o1 = itkTestObject::New(); } std::cout <<"end first test" << std::endl << std::endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: thesdsp.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-09-17 03:56:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_linguistic.hxx" #ifndef INCLUDED_I18NPOOL_LANG_H #include <i18npool/lang.h> #endif #ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT #include <tools/debug.hxx> #endif #ifndef _SVTOOLS_LNGMISC_HXX_ #include <svtools/lngmisc.hxx> #endif #include <cppuhelper/factory.hxx> // helper for factories #include <com/sun/star/registry/XRegistryKey.hpp> #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include "thesdsp.hxx" #include "lngprops.hxx" using namespace utl; using namespace osl; using namespace rtl; using namespace com::sun::star; using namespace com::sun::star::beans; using namespace com::sun::star::lang; using namespace com::sun::star::uno; using namespace com::sun::star::linguistic2; using namespace linguistic; /////////////////////////////////////////////////////////////////////////// static BOOL SvcListHasLanguage( const Sequence< Reference< XThesaurus > > &rRefs, const Locale &rLocale ) { BOOL bHasLanguage = FALSE; const Reference< XThesaurus > *pRef = rRefs.getConstArray(); INT32 nLen = rRefs.getLength(); for (INT32 k = 0; k < nLen && !bHasLanguage; ++k) { if (pRef[k].is()) bHasLanguage = pRef[k]->hasLocale( rLocale ); } return bHasLanguage; } /////////////////////////////////////////////////////////////////////////// SeqLangSvcEntry_Thes::~SeqLangSvcEntry_Thes() { } SeqLangSvcEntry_Thes::SeqLangSvcEntry_Thes( const Sequence< OUString > &rSvcImplNames ) : aSvcImplNames ( rSvcImplNames ), aSvcRefs ( rSvcImplNames.getLength() ) { } /////////////////////////////////////////////////////////////////////////// ThesaurusDispatcher::ThesaurusDispatcher() { } ThesaurusDispatcher::~ThesaurusDispatcher() { ClearSvcList(); } void ThesaurusDispatcher::ClearSvcList() { // release memory for each table entry SeqLangSvcEntry_Thes *pItem = aSvcList.First(); while (pItem) { SeqLangSvcEntry_Thes *pTmp = pItem; pItem = aSvcList.Next(); delete pTmp; } } Sequence< Locale > SAL_CALL ThesaurusDispatcher::getLocales() throw(RuntimeException) { MutexGuard aGuard( GetLinguMutex() ); ULONG nCnt = aSvcList.Count(); Sequence< Locale > aLocales( nCnt ); Locale *pItem = aLocales.getArray(); SeqLangSvcEntry_Thes *pEntry = aSvcList.First(); for (ULONG i = 0; i < nCnt; i++) { DBG_ASSERT( pEntry, "lng : pEntry is NULL pointer" ); pItem[i] = CreateLocale( (LanguageType) aSvcList.GetKey( pEntry ) ); pEntry = aSvcList.Next(); } return aLocales; } sal_Bool SAL_CALL ThesaurusDispatcher::hasLocale( const Locale& rLocale ) throw(RuntimeException) { MutexGuard aGuard( GetLinguMutex() ); return 0 != aSvcList.Get( LocaleToLanguage( rLocale ) ); } Sequence< Reference< XMeaning > > SAL_CALL ThesaurusDispatcher::queryMeanings( const OUString& rTerm, const Locale& rLocale, const PropertyValues& rProperties ) throw(IllegalArgumentException, RuntimeException) { MutexGuard aGuard( GetLinguMutex() ); Sequence< Reference< XMeaning > > aMeanings; INT16 nLanguage = LocaleToLanguage( rLocale ); if (nLanguage == LANGUAGE_NONE || !rTerm.getLength()) return aMeanings; // search for entry with that language SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage ); if (!pEntry) { #ifdef LINGU_EXCEPTIONS throw IllegalArgumentException(); #endif } else { OUString aChkWord( rTerm ); aChkWord = aChkWord.replace( SVT_HARD_SPACE, ' ' ); RemoveHyphens( aChkWord ); if (IsIgnoreControlChars( rProperties, GetPropSet() )) RemoveControlChars( aChkWord ); INT32 nLen = pEntry->aSvcRefs.getLength(); DBG_ASSERT( nLen == pEntry->aSvcImplNames.getLength(), "lng : sequence length mismatch"); DBG_ASSERT( pEntry->aFlags.nLastTriedSvcIndex < nLen, "lng : index out of range"); INT32 i = 0; // try already instantiated services first { const Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getConstArray(); while (i <= pEntry->aFlags.nLastTriedSvcIndex && aMeanings.getLength() == 0) { if (pRef[i].is() && pRef[i]->hasLocale( rLocale )) aMeanings = pRef[i]->queryMeanings( aChkWord, rLocale, rProperties ); ++i; } } // if still no result instantiate new services and try those if (aMeanings.getLength() == 0 && pEntry->aFlags.nLastTriedSvcIndex < nLen - 1) { const OUString *pImplNames = pEntry->aSvcImplNames.getConstArray(); Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getArray(); Reference< XMultiServiceFactory > xMgr( getProcessServiceFactory() ); if (xMgr.is()) { // build service initialization argument Sequence< Any > aArgs(1); aArgs.getArray()[0] <<= GetPropSet(); while (i < nLen && aMeanings.getLength() == 0) { // create specific service via it's implementation name Reference< XThesaurus > xThes( xMgr->createInstanceWithArguments( pImplNames[i], aArgs ), UNO_QUERY ); pRef[i] = xThes; if (xThes.is() && xThes->hasLocale( rLocale )) aMeanings = xThes->queryMeanings( aChkWord, rLocale, rProperties ); pEntry->aFlags.nLastTriedSvcIndex = (INT16) i; ++i; } // if language is not supported by any of the services // remove it from the list. if (i == nLen && aMeanings.getLength() == 0) { if (!SvcListHasLanguage( pEntry->aSvcRefs, rLocale )) aSvcList.Remove( nLanguage ); } } } } return aMeanings; } void ThesaurusDispatcher::SetServiceList( const Locale &rLocale, const Sequence< OUString > &rSvcImplNames ) { MutexGuard aGuard( GetLinguMutex() ); INT16 nLanguage = LocaleToLanguage( rLocale ); if (0 == rSvcImplNames.getLength()) // remove entry aSvcList.Remove( nLanguage ); else { // modify/add entry SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage ); if (pEntry) { pEntry->aSvcImplNames = rSvcImplNames; pEntry->aSvcRefs = Sequence< Reference < XThesaurus > >( rSvcImplNames.getLength() ); pEntry->aFlags = SvcFlags(); } else { pEntry = new SeqLangSvcEntry_Thes( rSvcImplNames ); aSvcList.Insert( nLanguage, pEntry ); DBG_ASSERT( aSvcList.Get( nLanguage ), "lng : Insert failed" ); } } } Sequence< OUString > ThesaurusDispatcher::GetServiceList( const Locale &rLocale ) const { MutexGuard aGuard( GetLinguMutex() ); Sequence< OUString > aRes; // search for entry with that language and use data from that INT16 nLanguage = LocaleToLanguage( rLocale ); ThesaurusDispatcher *pThis = (ThesaurusDispatcher *) this; const SeqLangSvcEntry_Thes *pEntry = pThis->aSvcList.Get( nLanguage ); if (pEntry) aRes = pEntry->aSvcImplNames; return aRes; } ThesaurusDispatcher::DspType ThesaurusDispatcher::GetDspType() const { return DSP_THES; } /////////////////////////////////////////////////////////////////////////// <commit_msg>INTEGRATION: CWS tl51_DEV300 (1.12.52); FILE MERGED 2007/11/15 12:53:37 tl 1.12.52.1: #150990# catch exception from createInstance(WithArguments) calls<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: thesdsp.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2008-03-26 09:06:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_linguistic.hxx" #ifndef INCLUDED_I18NPOOL_LANG_H #include <i18npool/lang.h> #endif #ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT #include <tools/debug.hxx> #endif #ifndef _SVTOOLS_LNGMISC_HXX_ #include <svtools/lngmisc.hxx> #endif #include <cppuhelper/factory.hxx> // helper for factories #include <com/sun/star/registry/XRegistryKey.hpp> #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include "thesdsp.hxx" #include "lngprops.hxx" using namespace utl; using namespace osl; using namespace rtl; using namespace com::sun::star; using namespace com::sun::star::beans; using namespace com::sun::star::lang; using namespace com::sun::star::uno; using namespace com::sun::star::linguistic2; using namespace linguistic; /////////////////////////////////////////////////////////////////////////// static BOOL SvcListHasLanguage( const Sequence< Reference< XThesaurus > > &rRefs, const Locale &rLocale ) { BOOL bHasLanguage = FALSE; const Reference< XThesaurus > *pRef = rRefs.getConstArray(); INT32 nLen = rRefs.getLength(); for (INT32 k = 0; k < nLen && !bHasLanguage; ++k) { if (pRef[k].is()) bHasLanguage = pRef[k]->hasLocale( rLocale ); } return bHasLanguage; } /////////////////////////////////////////////////////////////////////////// SeqLangSvcEntry_Thes::~SeqLangSvcEntry_Thes() { } SeqLangSvcEntry_Thes::SeqLangSvcEntry_Thes( const Sequence< OUString > &rSvcImplNames ) : aSvcImplNames ( rSvcImplNames ), aSvcRefs ( rSvcImplNames.getLength() ) { } /////////////////////////////////////////////////////////////////////////// ThesaurusDispatcher::ThesaurusDispatcher() { } ThesaurusDispatcher::~ThesaurusDispatcher() { ClearSvcList(); } void ThesaurusDispatcher::ClearSvcList() { // release memory for each table entry SeqLangSvcEntry_Thes *pItem = aSvcList.First(); while (pItem) { SeqLangSvcEntry_Thes *pTmp = pItem; pItem = aSvcList.Next(); delete pTmp; } } Sequence< Locale > SAL_CALL ThesaurusDispatcher::getLocales() throw(RuntimeException) { MutexGuard aGuard( GetLinguMutex() ); ULONG nCnt = aSvcList.Count(); Sequence< Locale > aLocales( nCnt ); Locale *pItem = aLocales.getArray(); SeqLangSvcEntry_Thes *pEntry = aSvcList.First(); for (ULONG i = 0; i < nCnt; i++) { DBG_ASSERT( pEntry, "lng : pEntry is NULL pointer" ); pItem[i] = CreateLocale( (LanguageType) aSvcList.GetKey( pEntry ) ); pEntry = aSvcList.Next(); } return aLocales; } sal_Bool SAL_CALL ThesaurusDispatcher::hasLocale( const Locale& rLocale ) throw(RuntimeException) { MutexGuard aGuard( GetLinguMutex() ); return 0 != aSvcList.Get( LocaleToLanguage( rLocale ) ); } Sequence< Reference< XMeaning > > SAL_CALL ThesaurusDispatcher::queryMeanings( const OUString& rTerm, const Locale& rLocale, const PropertyValues& rProperties ) throw(IllegalArgumentException, RuntimeException) { MutexGuard aGuard( GetLinguMutex() ); Sequence< Reference< XMeaning > > aMeanings; INT16 nLanguage = LocaleToLanguage( rLocale ); if (nLanguage == LANGUAGE_NONE || !rTerm.getLength()) return aMeanings; // search for entry with that language SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage ); if (!pEntry) { #ifdef LINGU_EXCEPTIONS throw IllegalArgumentException(); #endif } else { OUString aChkWord( rTerm ); aChkWord = aChkWord.replace( SVT_HARD_SPACE, ' ' ); RemoveHyphens( aChkWord ); if (IsIgnoreControlChars( rProperties, GetPropSet() )) RemoveControlChars( aChkWord ); INT32 nLen = pEntry->aSvcRefs.getLength(); DBG_ASSERT( nLen == pEntry->aSvcImplNames.getLength(), "lng : sequence length mismatch"); DBG_ASSERT( pEntry->aFlags.nLastTriedSvcIndex < nLen, "lng : index out of range"); INT32 i = 0; // try already instantiated services first { const Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getConstArray(); while (i <= pEntry->aFlags.nLastTriedSvcIndex && aMeanings.getLength() == 0) { if (pRef[i].is() && pRef[i]->hasLocale( rLocale )) aMeanings = pRef[i]->queryMeanings( aChkWord, rLocale, rProperties ); ++i; } } // if still no result instantiate new services and try those if (aMeanings.getLength() == 0 && pEntry->aFlags.nLastTriedSvcIndex < nLen - 1) { const OUString *pImplNames = pEntry->aSvcImplNames.getConstArray(); Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getArray(); Reference< XMultiServiceFactory > xMgr( getProcessServiceFactory() ); if (xMgr.is()) { // build service initialization argument Sequence< Any > aArgs(1); aArgs.getArray()[0] <<= GetPropSet(); while (i < nLen && aMeanings.getLength() == 0) { // create specific service via it's implementation name Reference< XThesaurus > xThes; try { xThes = Reference< XThesaurus >( xMgr->createInstanceWithArguments( pImplNames[i], aArgs ), UNO_QUERY ); } catch (uno::Exception &) { DBG_ERROR( "createInstanceWithArguments failed" ); } pRef[i] = xThes; if (xThes.is() && xThes->hasLocale( rLocale )) aMeanings = xThes->queryMeanings( aChkWord, rLocale, rProperties ); pEntry->aFlags.nLastTriedSvcIndex = (INT16) i; ++i; } // if language is not supported by any of the services // remove it from the list. if (i == nLen && aMeanings.getLength() == 0) { if (!SvcListHasLanguage( pEntry->aSvcRefs, rLocale )) aSvcList.Remove( nLanguage ); } } } } return aMeanings; } void ThesaurusDispatcher::SetServiceList( const Locale &rLocale, const Sequence< OUString > &rSvcImplNames ) { MutexGuard aGuard( GetLinguMutex() ); INT16 nLanguage = LocaleToLanguage( rLocale ); if (0 == rSvcImplNames.getLength()) // remove entry aSvcList.Remove( nLanguage ); else { // modify/add entry SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage ); if (pEntry) { pEntry->aSvcImplNames = rSvcImplNames; pEntry->aSvcRefs = Sequence< Reference < XThesaurus > >( rSvcImplNames.getLength() ); pEntry->aFlags = SvcFlags(); } else { pEntry = new SeqLangSvcEntry_Thes( rSvcImplNames ); aSvcList.Insert( nLanguage, pEntry ); DBG_ASSERT( aSvcList.Get( nLanguage ), "lng : Insert failed" ); } } } Sequence< OUString > ThesaurusDispatcher::GetServiceList( const Locale &rLocale ) const { MutexGuard aGuard( GetLinguMutex() ); Sequence< OUString > aRes; // search for entry with that language and use data from that INT16 nLanguage = LocaleToLanguage( rLocale ); ThesaurusDispatcher *pThis = (ThesaurusDispatcher *) this; const SeqLangSvcEntry_Thes *pEntry = pThis->aSvcList.Get( nLanguage ); if (pEntry) aRes = pEntry->aSvcImplNames; return aRes; } ThesaurusDispatcher::DspType ThesaurusDispatcher::GetDspType() const { return DSP_THES; } /////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/** \file Microscope task. Acquire stacks for each marked tile in a plane. \author Nathan Clack <clackn@janelia.hhmi.org> \copyright Copyright 2010 Howard Hughes Medical Institute. All rights reserved. Use is subject to Janelia Farm Research Campus Software Copyright 1.1 license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html). */ #include "common.h" #include "AdaptiveTiledAcquisition.h" #include "StackAcquisition.h" #include "Video.h" #include "frame.h" #include "devices\digitizer.h" #include "devices\Microscope.h" #include "devices\tiling.h" #include "tasks\SurfaceFind.h" #if 1 // PROFILING #define TS_OPEN(name) timestream_t ts__=timestream_open(name) #define TS_TIC timestream_tic(ts__) #define TS_TOC timestream_toc(ts__) #define TS_CLOSE timestream_close(ts__) #else #define TS_OPEN(name) #define TS_TIC #define TS_TOC #define TS_CLOSE #endif #define CHKJMP(expr) if(!(expr)) {warning("%s(%d)"ENDL"\tExpression indicated failure:"ENDL"\t%s"ENDL,__FILE__,__LINE__,#expr); goto Error;} namespace fetch { namespace task { // // AdaptiveTiledAcquisition - microscope task // namespace microscope { //Upcasting unsigned int AdaptiveTiledAcquisition::config(IDevice *d) {return config(dynamic_cast<device::Microscope*>(d));} unsigned int AdaptiveTiledAcquisition::run (IDevice *d) {return run (dynamic_cast<device::Microscope*>(d));} unsigned int AdaptiveTiledAcquisition::config(device::Microscope *d) { static task::scanner::ScanStack<u16> grabstack; std::string filename; Guarded_Assert(d); //Assemble pipeline here IDevice *cur; cur = d->configPipeline(); CHKJMP(d->file_series.ensurePathExists()); d->file_series.inc(); filename = d->stack_filename(); IDevice::connect(&d->disk,0,cur,0); Guarded_Assert( d->disk.close()==0 ); //Guarded_Assert( d->disk.open(filename,"w")==0); d->__scan_agent.disarm(10000/*timeout_ms*/); int isok=d->__scan_agent.arm(&grabstack,&d->scanner)==0; d->stage()->tiling()->resetCursor(); // this is here so that run/stop cycles will pick up where they left off return isok; //success Error: return 0; } static int _handle_wait_for_result(DWORD result, const char *msg) { return_val_if( result == WAIT_OBJECT_0 , 0 ); return_val_if( result == WAIT_OBJECT_0+1, 1 ); Guarded_Assert_WinErr( result != WAIT_FAILED ); if(result == WAIT_ABANDONED_0) warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait 0 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg); if(result == WAIT_ABANDONED_0+1) warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait 1 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg); if(result == WAIT_TIMEOUT) warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait timeout"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg); Guarded_Assert_WinErr( result !=WAIT_FAILED ); return -1; } unsigned int AdaptiveTiledAcquisition::run(device::Microscope *dc) { SurfaceFind surface_find; std::string filename; unsigned int eflag = 0; // success Vector3f tilepos; float tiling_offset_acc_mm=0.0f; float nsamp=0; int adapt_count=0; int adapt_thresh=dc->get_config().adaptive_tiling().every(); int adapt_mindist=dc->get_config().adaptive_tiling().mindist(); TS_OPEN("timer-tiles.f32"); CHKJMP(dc->__scan_agent.is_runnable()); device::StageTiling* tiling = dc->stage()->tiling(); // 1. iterate over tiles to measure the average tile offset tiling->resetCursor(); while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos)) { if(adapt_mindist<=tiling->minDistTo( 0,0, // domain query -- do not restrict to a particular tile type device::StageTiling::Active,0)) // boundary query -- this is defines what is "outside" { if(++adapt_count>adapt_thresh) // is it time to try? { // M O V E Vector3f curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); dc->stage()->setPos(0.001f*tilepos); // convert um to mm curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); // A D A P T I V E #if 0 if (adapt_count>2*adapt_thresh) // have too many detections been missed { warning("Could not track surface. Giving up.\n"); goto Error; } #endif //surface_find.config(); -- arms stack task as scan agent...redundant eflag |= surface_find.run(dc); if(surface_find.hit()) { adapt_count=0; tiling_offset_acc_mm+=dc->stage()->tiling_z_offset_mm(); ++nsamp; } } } } if(nsamp==0) { warning("Could not track surface. Giving up.\n"); goto Error; } debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] Average tile offset (samples: %5d) %f"ENDL,__FILE__,__LINE__,(int)nsamp,tiling_offset_acc_mm/nsamp); dc->stage()->set_tiling_z_offset_mm(tiling_offset_acc_mm/nsamp); // retore connection between end of pipeline and disk IDevice::connect(&dc->disk,0,dc->_end_of_pipeline,0); // 2. iterate over tiles to image tiling->resetCursor(); while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos)) { TS_TIC; debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] tilepos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,tilepos[0],tilepos[1],tilepos[2]); filename = dc->stack_filename(); dc->file_series.ensurePathExists(); dc->disk.set_nchan(dc->scanner.get2d()->digitizer()->nchan()); eflag |= dc->disk.open(filename,"w"); if(eflag) { warning("Couldn't open file: %s"ENDL, filename.c_str()); return eflag; } // Move stage Vector3f curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); dc->stage()->setPos(0.001f*tilepos); // convert um to mm curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); eflag |= dc->runPipeline(); eflag |= dc->__scan_agent.run() != 1; { // Wait for stack to finish HANDLE hs[] = { dc->__scan_agent._thread, dc->__self_agent._notify_stop}; DWORD res; int t; // wait for scan to complete (or cancel) res = WaitForMultipleObjects(2,hs,FALSE,INFINITE); t = _handle_wait_for_result(res,"AdaptiveTiledAcquisition::run - Wait for scanner to finish."); switch(t) { case 0: // in this case, the scanner thread stopped. Nothing left to do. eflag |= dc->__scan_agent.last_run_result(); // check the run result eflag |= dc->__io_agent.last_run_result(); if(eflag==0) // remove this if statement to mark tiles as "error" tiles. In practice, it seems it's ok to go back and reimage, so the if statement stays tiling->markDone(eflag==0); // only mark the tile done if the scanner task completed normally case 1: // in this case, the stop event triggered and must be propagated. eflag |= dc->__scan_agent.stop(SCANNER2D_DEFAULT_TIMEOUT) != 1; break; default: // in this case, there was a timeout or abandoned wait eflag |= 1; // failure } } // end waiting block // Output and Increment files dc->write_stack_metadata(); // write the metadata eflag |= dc->disk.close(); dc->file_series.inc(); // increment regardless of completion status eflag |= dc->stopPipeline(); // wait till everything stops TS_TOC; } // end loop over tiles eflag |= dc->stopPipeline(); // wait till the pipeline stops TS_CLOSE; return eflag; Error: TS_CLOSE; return 1; } } // namespace microscope } // namespace task } // namespace fetch <commit_msg>[AdaptiveTiling] bug fix. retries to much on miss.<commit_after>/** \file Microscope task. Acquire stacks for each marked tile in a plane. \author Nathan Clack <clackn@janelia.hhmi.org> \copyright Copyright 2010 Howard Hughes Medical Institute. All rights reserved. Use is subject to Janelia Farm Research Campus Software Copyright 1.1 license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html). */ #include "common.h" #include "AdaptiveTiledAcquisition.h" #include "StackAcquisition.h" #include "Video.h" #include "frame.h" #include "devices\digitizer.h" #include "devices\Microscope.h" #include "devices\tiling.h" #include "tasks\SurfaceFind.h" #if 1 // PROFILING #define TS_OPEN(name) timestream_t ts__=timestream_open(name) #define TS_TIC timestream_tic(ts__) #define TS_TOC timestream_toc(ts__) #define TS_CLOSE timestream_close(ts__) #else #define TS_OPEN(name) #define TS_TIC #define TS_TOC #define TS_CLOSE #endif #define CHKJMP(expr) if(!(expr)) {warning("%s(%d)"ENDL"\tExpression indicated failure:"ENDL"\t%s"ENDL,__FILE__,__LINE__,#expr); goto Error;} namespace fetch { namespace task { // // AdaptiveTiledAcquisition - microscope task // namespace microscope { //Upcasting unsigned int AdaptiveTiledAcquisition::config(IDevice *d) {return config(dynamic_cast<device::Microscope*>(d));} unsigned int AdaptiveTiledAcquisition::run (IDevice *d) {return run (dynamic_cast<device::Microscope*>(d));} unsigned int AdaptiveTiledAcquisition::config(device::Microscope *d) { static task::scanner::ScanStack<u16> grabstack; std::string filename; Guarded_Assert(d); //Assemble pipeline here IDevice *cur; cur = d->configPipeline(); CHKJMP(d->file_series.ensurePathExists()); d->file_series.inc(); filename = d->stack_filename(); IDevice::connect(&d->disk,0,cur,0); Guarded_Assert( d->disk.close()==0 ); //Guarded_Assert( d->disk.open(filename,"w")==0); d->__scan_agent.disarm(10000/*timeout_ms*/); int isok=d->__scan_agent.arm(&grabstack,&d->scanner)==0; d->stage()->tiling()->resetCursor(); // this is here so that run/stop cycles will pick up where they left off return isok; //success Error: return 0; } static int _handle_wait_for_result(DWORD result, const char *msg) { return_val_if( result == WAIT_OBJECT_0 , 0 ); return_val_if( result == WAIT_OBJECT_0+1, 1 ); Guarded_Assert_WinErr( result != WAIT_FAILED ); if(result == WAIT_ABANDONED_0) warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait 0 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg); if(result == WAIT_ABANDONED_0+1) warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait 1 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg); if(result == WAIT_TIMEOUT) warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait timeout"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg); Guarded_Assert_WinErr( result !=WAIT_FAILED ); return -1; } unsigned int AdaptiveTiledAcquisition::run(device::Microscope *dc) { SurfaceFind surface_find; std::string filename; unsigned int eflag = 0; // success Vector3f tilepos; float tiling_offset_acc_mm=0.0f; float nsamp=0; int adapt_count=0; int adapt_thresh=dc->get_config().adaptive_tiling().every(); int adapt_mindist=dc->get_config().adaptive_tiling().mindist(); TS_OPEN("timer-tiles.f32"); CHKJMP(dc->__scan_agent.is_runnable()); device::StageTiling* tiling = dc->stage()->tiling(); // 1. iterate over tiles to measure the average tile offset tiling->resetCursor(); while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos)) { if(adapt_mindist<=tiling->minDistTo( 0,0, // domain query -- do not restrict to a particular tile type device::StageTiling::Active,0)) // boundary query -- this is defines what is "outside" { if(++adapt_count>adapt_thresh) // is it time to try? { adapt_count=0; // M O V E Vector3f curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); dc->stage()->setPos(0.001f*tilepos); // convert um to mm curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); // A D A P T I V E #if 0 if (adapt_count>2*adapt_thresh) // have too many detections been missed { warning("Could not track surface. Giving up.\n"); goto Error; } #endif //surface_find.config(); -- arms stack task as scan agent...redundant eflag |= surface_find.run(dc); if(surface_find.hit()) { tiling_offset_acc_mm+=dc->stage()->tiling_z_offset_mm(); ++nsamp; } } } } if(nsamp==0) { warning("Could not track surface. Giving up.\n"); goto Error; } debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] Average tile offset (samples: %5d) %f"ENDL,__FILE__,__LINE__,(int)nsamp,tiling_offset_acc_mm/nsamp); dc->stage()->set_tiling_z_offset_mm(tiling_offset_acc_mm/nsamp); // retore connection between end of pipeline and disk IDevice::connect(&dc->disk,0,dc->_end_of_pipeline,0); // 2. iterate over tiles to image tiling->resetCursor(); while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos)) { TS_TIC; debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] tilepos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,tilepos[0],tilepos[1],tilepos[2]); filename = dc->stack_filename(); dc->file_series.ensurePathExists(); dc->disk.set_nchan(dc->scanner.get2d()->digitizer()->nchan()); eflag |= dc->disk.open(filename,"w"); if(eflag) { warning("Couldn't open file: %s"ENDL, filename.c_str()); return eflag; } // Move stage Vector3f curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); dc->stage()->setPos(0.001f*tilepos); // convert um to mm curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); eflag |= dc->runPipeline(); eflag |= dc->__scan_agent.run() != 1; { // Wait for stack to finish HANDLE hs[] = { dc->__scan_agent._thread, dc->__self_agent._notify_stop}; DWORD res; int t; // wait for scan to complete (or cancel) res = WaitForMultipleObjects(2,hs,FALSE,INFINITE); t = _handle_wait_for_result(res,"AdaptiveTiledAcquisition::run - Wait for scanner to finish."); switch(t) { case 0: // in this case, the scanner thread stopped. Nothing left to do. eflag |= dc->__scan_agent.last_run_result(); // check the run result eflag |= dc->__io_agent.last_run_result(); if(eflag==0) // remove this if statement to mark tiles as "error" tiles. In practice, it seems it's ok to go back and reimage, so the if statement stays tiling->markDone(eflag==0); // only mark the tile done if the scanner task completed normally case 1: // in this case, the stop event triggered and must be propagated. eflag |= dc->__scan_agent.stop(SCANNER2D_DEFAULT_TIMEOUT) != 1; break; default: // in this case, there was a timeout or abandoned wait eflag |= 1; // failure } } // end waiting block // Output and Increment files dc->write_stack_metadata(); // write the metadata eflag |= dc->disk.close(); dc->file_series.inc(); // increment regardless of completion status eflag |= dc->stopPipeline(); // wait till everything stops TS_TOC; } // end loop over tiles eflag |= dc->stopPipeline(); // wait till the pipeline stops TS_CLOSE; return eflag; Error: TS_CLOSE; return 1; } } // namespace microscope } // namespace task } // namespace fetch <|endoftext|>
<commit_before>/* * Copyright 2016 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 "storeddockey.h" #include <mcbp/protocol/unsigned_leb128.h> #include <iomanip> #include <iostream> #include <sstream> StoredDocKey::StoredDocKey(const std::string& key, CollectionID cid) { cb::mcbp::unsigned_leb128<CollectionIDType> leb128(cid); keydata.resize(key.size() + leb128.size()); std::copy(key.begin(), key.end(), std::copy(leb128.begin(), leb128.end(), keydata.begin())); } CollectionID StoredDocKey::getCollectionID() const { return cb::mcbp::decode_unsigned_leb128<CollectionIDType>({data(), size()}) .first; } DocKey StoredDocKey::makeDocKeyWithoutCollectionID() const { auto decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {data(), size()}); return {decoded.second.data(), decoded.second.size(), DocKeyEncodesCollectionId::No}; } std::string StoredDocKey::to_string() const { std::stringstream ss; auto leb128 = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {reinterpret_cast<const uint8_t*>(keydata.data()), keydata.size()}); ss << "cid:0x" << std::hex << leb128.first << ":" << std::string(reinterpret_cast<const char*>(leb128.second.data()), leb128.second.size()); ss << ", size:" << size(); return ss.str(); } const char* StoredDocKey::c_str() const { // Locate the leb128 stop byte, and return pointer after that auto key = cb::mcbp::skip_unsigned_leb128<CollectionIDType>( {reinterpret_cast<const uint8_t*>(keydata.data()), keydata.size()}); if (key.size()) { return &keydata.c_str()[keydata.size() - key.size()]; } return nullptr; } std::ostream& operator<<(std::ostream& os, const StoredDocKey& key) { return os << key.to_string(); } CollectionID SerialisedDocKey::getCollectionID() const { return cb::mcbp::decode_unsigned_leb128<CollectionIDType>({bytes, length}) .first; } bool SerialisedDocKey::operator==(const DocKey& rhs) const { auto rhsIdAndData = rhs.getIdAndKey(); auto lhsIdAndData = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {data(), size()}); return lhsIdAndData.first == rhsIdAndData.first && lhsIdAndData.second.size() == rhsIdAndData.second.size() && std::equal(lhsIdAndData.second.begin(), lhsIdAndData.second.end(), rhsIdAndData.second.begin()); } SerialisedDocKey::SerialisedDocKey(cb::const_byte_buffer key, CollectionID cid) { cb::mcbp::unsigned_leb128<CollectionIDType> leb128(cid); length = gsl::narrow_cast<uint8_t>(key.size() + leb128.size()); std::copy(key.begin(), key.end(), std::copy(leb128.begin(), leb128.end(), bytes)); } std::ostream& operator<<(std::ostream& os, const SerialisedDocKey& key) { auto leb128 = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {reinterpret_cast<const uint8_t*>(key.data()), key.size()}); os << "cid:0x" << std::hex << leb128.first << ":" << std::string(reinterpret_cast<const char*>(leb128.second.data()), leb128.second.size()); os << ", size:" << key.size(); return os; } <commit_msg>StoredDocKey::to_string: don't print size<commit_after>/* * Copyright 2016 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 "storeddockey.h" #include <mcbp/protocol/unsigned_leb128.h> #include <iomanip> #include <iostream> #include <sstream> StoredDocKey::StoredDocKey(const std::string& key, CollectionID cid) { cb::mcbp::unsigned_leb128<CollectionIDType> leb128(cid); keydata.resize(key.size() + leb128.size()); std::copy(key.begin(), key.end(), std::copy(leb128.begin(), leb128.end(), keydata.begin())); } CollectionID StoredDocKey::getCollectionID() const { return cb::mcbp::decode_unsigned_leb128<CollectionIDType>({data(), size()}) .first; } DocKey StoredDocKey::makeDocKeyWithoutCollectionID() const { auto decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {data(), size()}); return {decoded.second.data(), decoded.second.size(), DocKeyEncodesCollectionId::No}; } std::string StoredDocKey::to_string() const { std::stringstream ss; auto leb128 = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {reinterpret_cast<const uint8_t*>(keydata.data()), keydata.size()}); ss << "cid:0x" << std::hex << leb128.first << std::dec << ":" << std::string(reinterpret_cast<const char*>(leb128.second.data()), leb128.second.size()); return ss.str(); } const char* StoredDocKey::c_str() const { // Locate the leb128 stop byte, and return pointer after that auto key = cb::mcbp::skip_unsigned_leb128<CollectionIDType>( {reinterpret_cast<const uint8_t*>(keydata.data()), keydata.size()}); if (key.size()) { return &keydata.c_str()[keydata.size() - key.size()]; } return nullptr; } std::ostream& operator<<(std::ostream& os, const StoredDocKey& key) { return os << key.to_string(); } CollectionID SerialisedDocKey::getCollectionID() const { return cb::mcbp::decode_unsigned_leb128<CollectionIDType>({bytes, length}) .first; } bool SerialisedDocKey::operator==(const DocKey& rhs) const { auto rhsIdAndData = rhs.getIdAndKey(); auto lhsIdAndData = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {data(), size()}); return lhsIdAndData.first == rhsIdAndData.first && lhsIdAndData.second.size() == rhsIdAndData.second.size() && std::equal(lhsIdAndData.second.begin(), lhsIdAndData.second.end(), rhsIdAndData.second.begin()); } SerialisedDocKey::SerialisedDocKey(cb::const_byte_buffer key, CollectionID cid) { cb::mcbp::unsigned_leb128<CollectionIDType> leb128(cid); length = gsl::narrow_cast<uint8_t>(key.size() + leb128.size()); std::copy(key.begin(), key.end(), std::copy(leb128.begin(), leb128.end(), bytes)); } std::ostream& operator<<(std::ostream& os, const SerialisedDocKey& key) { auto leb128 = cb::mcbp::decode_unsigned_leb128<CollectionIDType>( {reinterpret_cast<const uint8_t*>(key.data()), key.size()}); os << "cid:0x" << std::hex << leb128.first << ":" << std::string(reinterpret_cast<const char*>(leb128.second.data()), leb128.second.size()); os << ", size:" << key.size(); return os; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP #define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/stringify.hpp> #include <string> namespace stan { namespace math { namespace opencl_kernels { // \cond static const char* binomial_coefficient_log_device_function = "\n" "#ifndef " "STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG\n" "#define " "STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_" "LOG\n" STRINGIFY( // \endcond /** * Return the log of the binomial coefficient for the specified * arguments. * * The binomial coefficient, \f${n \choose k}\f$, read "n choose k", is * defined for \f$0 \leq k \leq n\f$ by * * \f${n \choose k} = \frac{n!}{k! (n-k)!}\f$. * * This function uses Gamma functions to define the log * and generalize the arguments to continuous n and k. * * \f$ \log {n \choose k} * = \log \ \Gamma(n+1) - \log \Gamma(k+1) - \log \Gamma(n-k+1)\f$. * * \f[ \mbox{binomial\_coefficient\_log}(x, y) = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or } y < -1 \textrm{ or } x < -1\\ \ln\Gamma(x+1) & \mbox{if } -1 < y < x + 1 \\ \quad -\ln\Gamma(y+1)& \\ \quad -\ln\Gamma(x-y+1)& \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{binomial\_coefficient\_log}(x, y)}{\partial x} = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or } y < -1 \textrm{ or } x < -1\\ \Psi(x+1) & \mbox{if } 0\leq y \leq x \\ \quad -\Psi(x-y+1)& \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{binomial\_coefficient\_log}(x, y)}{\partial y} = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or } y < -1 \textrm{ or } x < -1\\ -\Psi(y+1) & \mbox{if } 0\leq y \leq x \\ \quad +\Psi(x-y+1)& \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] * * This function is numerically more stable than naive evaluation via lgamma. * * @param n total number of objects. * @param k number of objects chosen. * @return log (n choose k). */ double binomial_coefficient_log(double n, double k) { if (isnan(n) || isnan(k)) { return NAN; } // Choosing the more stable of the symmetric branches if (n > -1 && k > n / 2.0 + 1e-8) { return binomial_coefficient_log(n, n - k); } double n_plus_1 = n + 1; double n_plus_1_mk = n_plus_1 - k; if (k == 0) { return 0; } else if (n_plus_1 < LGAMMA_STIRLING_DIFF_USEFUL) { return lgamma(n_plus_1) - lgamma(k + 1) - lgamma(n_plus_1_mk); } else { return -lbeta(n_plus_1_mk, k + 1) - log1p(n); } } // \cond ) "\n#endif\n"; // NOLINT // \endcond } // namespace opencl_kernels } // namespace math } // namespace stan #endif #endif // BINOMIAL_COEFFICIENT_LOG_HPP <commit_msg>remove recursion<commit_after>#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP #define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/stringify.hpp> #include <string> namespace stan { namespace math { namespace opencl_kernels { // \cond static const char* binomial_coefficient_log_device_function = "\n" "#ifndef " "STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG\n" "#define " "STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_" "LOG\n" STRINGIFY( // \endcond /** * Return the log of the binomial coefficient for the specified * arguments. * * The binomial coefficient, \f${n \choose k}\f$, read "n choose k", is * defined for \f$0 \leq k \leq n\f$ by * * \f${n \choose k} = \frac{n!}{k! (n-k)!}\f$. * * This function uses Gamma functions to define the log * and generalize the arguments to continuous n and k. * * \f$ \log {n \choose k} * = \log \ \Gamma(n+1) - \log \Gamma(k+1) - \log \Gamma(n-k+1)\f$. * * \f[ \mbox{binomial\_coefficient\_log}(x, y) = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or } y < -1 \textrm{ or } x < -1\\ \ln\Gamma(x+1) & \mbox{if } -1 < y < x + 1 \\ \quad -\ln\Gamma(y+1)& \\ \quad -\ln\Gamma(x-y+1)& \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{binomial\_coefficient\_log}(x, y)}{\partial x} = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or } y < -1 \textrm{ or } x < -1\\ \Psi(x+1) & \mbox{if } 0\leq y \leq x \\ \quad -\Psi(x-y+1)& \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{binomial\_coefficient\_log}(x, y)}{\partial y} = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or } y < -1 \textrm{ or } x < -1\\ -\Psi(y+1) & \mbox{if } 0\leq y \leq x \\ \quad +\Psi(x-y+1)& \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] * * This function is numerically more stable than naive evaluation via lgamma. * * @param n total number of objects. * @param k number of objects chosen. * @return log (n choose k). */ double binomial_coefficient_log(double n, double k) { if (isnan(n) || isnan(k)) { return NAN; } // Choosing the more stable of the symmetric branches if (n > -1 && k > n / 2.0 + 1e-8) { k = n - k; } double n_plus_1 = n + 1; double n_plus_1_mk = n_plus_1 - k; if (k == 0) { return 0; } else if (n_plus_1 < LGAMMA_STIRLING_DIFF_USEFUL) { return lgamma(n_plus_1) - lgamma(k + 1) - lgamma(n_plus_1_mk); } else { return -lbeta(n_plus_1_mk, k + 1) - log1p(n); } } // \cond ) "\n#endif\n"; // NOLINT // \endcond } // namespace opencl_kernels } // namespace math } // namespace stan #endif #endif // BINOMIAL_COEFFICIENT_LOG_HPP <|endoftext|>
<commit_before>/** * @file * @copyright defined in eos/LICENSE.txt */ #include <eos/chain_api_plugin/chain_api_plugin.hpp> #include <eos/chain/exceptions.hpp> #include <fc/io/json.hpp> namespace eos { using namespace eos; class chain_api_plugin_impl { public: chain_api_plugin_impl(chain_controller& db) : db(db) {} chain_controller& db; }; chain_api_plugin::chain_api_plugin(){} chain_api_plugin::~chain_api_plugin(){} void chain_api_plugin::set_program_options(options_description&, options_description&) {} void chain_api_plugin::plugin_initialize(const variables_map&) {} #define CALL(api_name, api_handle, api_namespace, call_name) \ {std::string("/v1/" #api_name "/" #call_name), \ [this, api_handle](string, string body, url_response_callback cb) mutable { \ try { \ if (body.empty()) body = "{}"; \ auto result = api_handle.call_name(fc::json::from_string(body).as<api_namespace::call_name ## _params>()); \ cb(201, fc::json::to_string(result)); \ } catch (chain::tx_missing_sigs& e) { \ error_results results{401, "UnAuthorized", e.to_string()}; \ cb(401, fc::json::to_string(results)); \ } catch (chain::tx_duplicate& e) { \ error_results results{409, "Conflict", e.to_string()}; \ cb(409, fc::json::to_string(results)); \ } catch (chain::transaction_exception& e) { \ error_results results{400, "Bad Request", e.to_string()}; \ cb(400, fc::json::to_string(results)); \ } catch (fc::eof_exception& e) { \ error_results results{400, "Bad Request", e.to_string()}; \ cb(400, fc::json::to_string(results)); \ elog("Unable to parse arguments: ${args}", ("args", body)); \ } catch (fc::exception& e) { \ error_results results{500, "Internal Service Error", e.to_detail_string()}; \ cb(500, fc::json::to_string(results)); \ elog("Exception encountered while processing ${call}: ${e}", ("call", #api_name "." #call_name)("e", e)); \ } \ }} #define CHAIN_RO_CALL(call_name) CALL(chain, ro_api, chain_apis::read_only, call_name) #define CHAIN_RW_CALL(call_name) CALL(chain, rw_api, chain_apis::read_write, call_name) void chain_api_plugin::plugin_startup() { ilog( "starting chain_api_plugin" ); my.reset(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().chain())); auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api(); auto rw_api = app().get_plugin<chain_plugin>().get_read_write_api(); app().get_plugin<http_plugin>().add_api({ CHAIN_RO_CALL(get_info), CHAIN_RO_CALL(get_block), CHAIN_RO_CALL(get_account), CHAIN_RO_CALL(get_code), CHAIN_RO_CALL(get_table_rows), CHAIN_RO_CALL(abi_json_to_bin), CHAIN_RO_CALL(abi_bin_to_json), CHAIN_RO_CALL(get_required_keys), CHAIN_RW_CALL(push_block), CHAIN_RW_CALL(push_transaction), CHAIN_RW_CALL(push_transactions) }); } void chain_api_plugin::plugin_shutdown() {} } <commit_msg>Revise chain API to return http response 200 or 202, as appropriate.<commit_after>/** * @file * @copyright defined in eos/LICENSE.txt */ #include <eos/chain_api_plugin/chain_api_plugin.hpp> #include <eos/chain/exceptions.hpp> #include <fc/io/json.hpp> namespace eos { using namespace eos; class chain_api_plugin_impl { public: chain_api_plugin_impl(chain_controller& db) : db(db) {} chain_controller& db; }; chain_api_plugin::chain_api_plugin(){} chain_api_plugin::~chain_api_plugin(){} void chain_api_plugin::set_program_options(options_description&, options_description&) {} void chain_api_plugin::plugin_initialize(const variables_map&) {} #define CALL(api_name, api_handle, api_namespace, call_name, http_response_code) \ {std::string("/v1/" #api_name "/" #call_name), \ [this, api_handle](string, string body, url_response_callback cb) mutable { \ try { \ if (body.empty()) body = "{}"; \ auto result = api_handle.call_name(fc::json::from_string(body).as<api_namespace::call_name ## _params>()); \ cb(http_response_code, fc::json::to_string(result)); \ } catch (chain::tx_missing_sigs& e) { \ error_results results{401, "UnAuthorized", e.to_string()}; \ cb(401, fc::json::to_string(results)); \ } catch (chain::tx_duplicate& e) { \ error_results results{409, "Conflict", e.to_string()}; \ cb(409, fc::json::to_string(results)); \ } catch (chain::transaction_exception& e) { \ error_results results{400, "Bad Request", e.to_string()}; \ cb(400, fc::json::to_string(results)); \ } catch (fc::eof_exception& e) { \ error_results results{400, "Bad Request", e.to_string()}; \ cb(400, fc::json::to_string(results)); \ elog("Unable to parse arguments: ${args}", ("args", body)); \ } catch (fc::exception& e) { \ error_results results{500, "Internal Service Error", e.to_detail_string()}; \ cb(500, fc::json::to_string(results)); \ elog("Exception encountered while processing ${call}: ${e}", ("call", #api_name "." #call_name)("e", e)); \ } \ }} #define CHAIN_RO_CALL(call_name, http_response_code) CALL(chain, ro_api, chain_apis::read_only, call_name, http_response_code) #define CHAIN_RW_CALL(call_name, http_response_code) CALL(chain, rw_api, chain_apis::read_write, call_name, http_response_code) void chain_api_plugin::plugin_startup() { ilog( "starting chain_api_plugin" ); my.reset(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().chain())); auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api(); auto rw_api = app().get_plugin<chain_plugin>().get_read_write_api(); app().get_plugin<http_plugin>().add_api({ CHAIN_RO_CALL(get_info, 200), CHAIN_RO_CALL(get_block, 200), CHAIN_RO_CALL(get_account, 200), CHAIN_RO_CALL(get_code, 200), CHAIN_RO_CALL(get_table_rows, 200), CHAIN_RO_CALL(abi_json_to_bin, 200), CHAIN_RO_CALL(abi_bin_to_json, 200), CHAIN_RO_CALL(get_required_keys, 200), CHAIN_RW_CALL(push_block, 202), CHAIN_RW_CALL(push_transaction, 202), CHAIN_RW_CALL(push_transactions, 202) }); } void chain_api_plugin::plugin_shutdown() {} } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Barrett Adair Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) HEADER GUARDS INTENTIONALLY OMITTED DO NOT INCLUDE THIS HEADER DIRECTLY BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS - the function-level qualifiers for the current inclusion (combinations of `const` `volatile` `&` `&&`, or nothing) BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE - the transaction_safe specifier for the current include (`transaction_safe` or nothing) BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE - `std::true_type` or `std::false_type`, tied on whether BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE is `transaction_safe` BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER - `transaction_safe` when BOOST_CLBL_TRTS_ENABLE_TRANSACTION_SAFE is defined, otherwise nothing BOOST_CLBL_TRTS_NOEXCEPT_SPEC - the noexcept specifier for the current include (`noexcept` or nothing) BOOST_CLBL_TRTS_IS_NOEXCEPT - `std::true_type` or `std::false_type`, tied on whether BOOST_CLBL_TRTS_NOEXCEPT_SPEC is `noexcept` BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER - `noexcept` if BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES is defined, otherwise nothing */ template<typename Return, typename T, typename... Args> struct pmf<Return(BOOST_CLBL_TRTS_CC T::*)(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC> : default_callable_traits<dummy BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS> { static constexpr bool value = true; using traits = pmf; using return_type = Return; using type = Return(BOOST_CLBL_TRTS_CC T::*)(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using invoke_type = typename std::conditional< std::is_rvalue_reference<T BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>::value, T BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS, typename std::add_lvalue_reference<T BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>::type >::type; using arg_types = std::tuple<invoke_type, Args...>; using non_invoke_arg_types = std::tuple<Args...>; using function_object_signature = Return(Args...); using function_type = Return(invoke_type, Args...); using qualified_function_type = Return(Args...) BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using remove_varargs = type; using add_varargs = Return(BOOST_CLBL_TRTS_VARARGS_CC T::*)(Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using is_noexcept = BOOST_CLBL_TRTS_IS_NOEXCEPT; using remove_noexcept = Return(BOOST_CLBL_TRTS_CC T::*)(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE; using add_noexcept = Return(BOOST_CLBL_TRTS_CC T::*)(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER; using is_transaction_safe = BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE; using remove_transaction_safe = Return(BOOST_CLBL_TRTS_CC T::*)(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using add_transaction_safe = Return(BOOST_CLBL_TRTS_CC T::*)(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using class_type = T; using qualifiers = default_callable_traits<dummy BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>; template<qualifier_flags Flags> using set_qualifiers = set_member_function_qualifiers< Flags, is_transaction_safe::value, is_noexcept::value, BOOST_CLBL_TRTS_CC_TAG, T, Return, Args...>; using remove_member_reference = set_qualifiers<qualifiers::cv_flags>; using add_member_lvalue_reference = set_qualifiers< collapse_flags<qualifiers::q_flags, lref_>::value>; using add_member_rvalue_reference = set_qualifiers< collapse_flags<qualifiers::q_flags, rref_>::value>; using add_member_const = set_qualifiers<qualifiers::q_flags | const_>; using add_member_volatile = set_qualifiers<qualifiers::q_flags | volatile_>; using add_member_cv = set_qualifiers<qualifiers::q_flags | cv_>; using remove_member_const = set_qualifiers< qualifiers::ref_flags | remove_const_flag<qualifiers::cv_flags>::value>; using remove_member_volatile = set_qualifiers< qualifiers::ref_flags | remove_volatile_flag<qualifiers::cv_flags>::value>; using remove_member_cv = set_qualifiers<qualifiers::ref_flags>; template<typename U> using apply_member_pointer = Return(BOOST_CLBL_TRTS_CC U::*)(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; template<typename NewReturn> using apply_return = NewReturn(BOOST_CLBL_TRTS_CC T::*)(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; template<template<class...> class Container> using expand_args = Container<invoke_type, Args...>; using is_member_pointer = std::true_type; }; <commit_msg>Delete pmf_4.hpp<commit_after><|endoftext|>
<commit_before>/* @Copyright Barrett Adair 2015-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_VOLATILE_HPP #define BOOST_CLBL_TRTS_REMOVE_MEMBER_VOLATILE_HPP #include <boost/callable_traits/detail/core.hpp> namespace boost { namespace callable_traits { //[ remove_member_volatile_hpp /*` [section:ref_remove_member_volatile remove_member_volatile] [heading Header] ``#include <boost/callable_traits/remove_member_volatile.hpp>`` [heading Definition] */ template<typename T> using remove_member_volatile_t = //see below //<- detail::try_but_fail_if_invalid< typename detail::traits<T>::remove_member_volatile, member_qualifiers_are_illegal_for_this_type>; namespace detail { template<typename T, typename = std::false_type> struct remove_member_volatile_impl {}; template<typename T> struct remove_member_volatile_impl <T, typename std::is_same< remove_member_volatile_t<T>, detail::dummy>::type> { using type = remove_member_volatile_t<T>; }; } //-> template<typename T> struct remove_member_volatile : detail::remove_member_volatile_impl<T> {}; //<- }} // namespace boost::callable_traits //-> /*` [heading Constraints] * `T` must be a function type or a member function pointer type * If `T` is a pointer, it may not be cv/ref qualified [heading Behavior] * A substitution failure occurs if the constraints are violated. * Removes the member `volatile` qualifier from `T`, if present. [heading Input/Output Examples] [table [[`T`] [`remove_member_volatile_t<T>`]] [[`int() volatile`] [`int()`]] [[`int(foo::*)() volatile`] [`int(foo::*)()`]] [[`int(foo::*)() volatile &`] [`int(foo::*)() &`]] [[`int(foo::*)() volatile &&`] [`int(foo::*)() &&`]] [[`int(foo::*)() volatile`] [`int(foo::*)()`]] [[`int(foo::*)() const volatile`] [`int(foo::*)() const`]] [[`int`] [(substitution failure)]] [[`int (&)()`] [(substitution failure)]] [[`int (*)()`] [(substitution failure)]] [[`int foo::*`] [(substitution failure)]] [[`int (foo::* const)()`] [(substitution failure)]] ] [heading Example Program] [import ../example/remove_member_volatile.cpp] [remove_member_volatile] [endsect] */ //] #endif // #ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_VOLATILE_HPP <commit_msg>Delete remove_member_volatile.hpp<commit_after><|endoftext|>
<commit_before>// Python module for playing audio // part of MusicPlayer, https://github.com/albertz/music-player // Copyright (c) 2012, Albert Zeyer, www.az2000.de // All rights reserved. // This code is under the 2-clause BSD license, see License.txt in the root directory of this project. // compile: // gcc -c musicplayer*.{c,cpp} -I /System/Library/Frameworks/Python.framework/Headers/ // libtool -dynamic -o musicplayer.so musicplayer*.o -framework Python -lavformat -lavutil -lavcodec -lswresample -lportaudio -lc // loosely based on ffplay.c // https://github.com/FFmpeg/ffmpeg/blob/master/ffplay.c // Similar to PyFFmpeg. http://code.google.com/p/pyffmpeg/ // This module is intended to be much simpler/high-level, though. // Pyton interface: // createPlayer() -> player object with: // queue: song generator // peekQueue(n): list of upcoming songs. this should not change the queue. this also might not be accurate but that doesn't matter. it might also return less. it is used for caching and gapless playback. if the queue returns other songs later, it will just ignore these peeked songs. otherwise, it will use these caches. // playing: True or False, initially False // volume: 1.0 is norm; this is just a factor to each sample. default is 0.9 // volumeSmoothClip: smooth clipping, see below. set to (1,1) to disable. default is (0.95,10) // curSong: current song (read only) // curSongPos: current song pos (read only) // curSongLen: current song len (read only) // curSongGainFactor: current song gain. read from song.gain (see below). can also be written // seekAbs(t) / seekRel(t): seeking functions (t in seconds, accepts float) // nextSong(): skip to next song function // song object expected interface: // readPacket(bufSize): should return some string // seekRaw(offset, whence): should seek and return the current pos // gain: some gain in decible, e.g. calculated by calcReplayGain. if not present, is ignored // url: some url, can be anything printable (not used at the moment) // and other functions, see their embedded doc ... #include "musicplayer.h" static PyMethodDef module_methods[] = { {"createPlayer", (PyCFunction)pyCreatePlayer, METH_NOARGS, "creates new player"}, {"getSoundDevices", (PyCFunction)pyGetSoundDevices, METH_NOARGS, "get list of sound device names"}, {"getMetadata", pyGetMetadata, METH_VARARGS, "get metadata for Song"}, {"calcAcoustIdFingerprint", pyCalcAcoustIdFingerprint, METH_VARARGS, "calculate AcoustID fingerprint for Song"}, {"calcBitmapThumbnail", (PyCFunction)pyCalcBitmapThumbnail, METH_VARARGS|METH_KEYWORDS, "calculate bitmap thumbnail for Song"}, {"calcReplayGain", (PyCFunction)pyCalcReplayGain, METH_VARARGS|METH_KEYWORDS, "calculate ReplayGain for Song"}, {"setFfmpegLogLevel", pySetFfmpegLogLevel, METH_VARARGS, "set FFmpeg log level (av_log_set_level)"}, {"enableDebugLog", (PyCFunction)pyEnableDebugLog, METH_VARARGS, "enable/disable debug log"}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "Music player."); static PyObject* EventClass = NULL; static void init() { PyEval_InitThreads(); /* Start the interpreter's thread-awareness */ initPlayerOutput(); initPlayerDecoder(); } PyMODINIT_FUNC initmusicplayer(void) { //printf("initmusicplayer\n"); init(); if (PyType_Ready(&Player_Type) < 0) Py_FatalError("Can't initialize player type"); PyObject* m = Py_InitModule3("musicplayer", module_methods, module_doc); if(!m) { Py_FatalError("Can't initialize musicplayer module"); return; } if(EventClass == NULL) { PyObject* classDict = PyDict_New(); assert(classDict); PyObject* className = PyString_FromString("Event"); assert(className); EventClass = PyClass_New(NULL, classDict, className); assert(EventClass); Py_XDECREF(classDict); classDict = NULL; Py_XDECREF(className); className = NULL; } if(EventClass) { Py_INCREF(EventClass); PyModule_AddObject(m, "Event", EventClass); // takes the ref } } <commit_msg>comment update<commit_after>// Python module for playing audio // part of MusicPlayer, https://github.com/albertz/music-player // Copyright (c) 2012, Albert Zeyer, www.az2000.de // All rights reserved. // This code is under the 2-clause BSD license, see License.txt in the root directory of this project. // compile: // gcc -c musicplayer*.cpp -I /System/Library/Frameworks/Python.framework/Headers/ // libtool -dynamic -o musicplayer.so musicplayer*.o -framework Python -lavformat -lavutil -lavcodec -lswresample -lportaudio -lc // loosely based on ffplay.c // https://github.com/FFmpeg/ffmpeg/blob/master/ffplay.c // Similar to PyFFmpeg. http://code.google.com/p/pyffmpeg/ // This module is intended to be much simpler/high-level, though. // Pyton interface: // createPlayer() -> player object with: // queue: song generator // peekQueue(n): list of upcoming songs. this should not change the queue. this also might not be accurate but that doesn't matter. it might also return less. it is used for caching and gapless playback. if the queue returns other songs later, it will just ignore these peeked songs. otherwise, it will use these caches. // playing: True or False, initially False // volume: 1.0 is norm; this is just a factor to each sample. default is 0.9 // volumeSmoothClip: smooth clipping, see below. set to (1,1) to disable. default is (0.95,10) // curSong: current song (read only) // curSongPos: current song pos (read only) // curSongLen: current song len (read only) // curSongGainFactor: current song gain. read from song.gain (see below). can also be written // seekAbs(t) / seekRel(t): seeking functions (t in seconds, accepts float) // nextSong(): skip to next song function // song object expected interface: // readPacket(bufSize): should return some string // seekRaw(offset, whence): should seek and return the current pos // gain: some gain in decible, e.g. calculated by calcReplayGain. if not present, is ignored // url: some url, can be anything printable (not used at the moment) // and other functions, see their embedded doc ... #include "musicplayer.h" static PyMethodDef module_methods[] = { {"createPlayer", (PyCFunction)pyCreatePlayer, METH_NOARGS, "creates new player"}, {"getSoundDevices", (PyCFunction)pyGetSoundDevices, METH_NOARGS, "get list of sound device names"}, {"getMetadata", pyGetMetadata, METH_VARARGS, "get metadata for Song"}, {"calcAcoustIdFingerprint", pyCalcAcoustIdFingerprint, METH_VARARGS, "calculate AcoustID fingerprint for Song"}, {"calcBitmapThumbnail", (PyCFunction)pyCalcBitmapThumbnail, METH_VARARGS|METH_KEYWORDS, "calculate bitmap thumbnail for Song"}, {"calcReplayGain", (PyCFunction)pyCalcReplayGain, METH_VARARGS|METH_KEYWORDS, "calculate ReplayGain for Song"}, {"setFfmpegLogLevel", pySetFfmpegLogLevel, METH_VARARGS, "set FFmpeg log level (av_log_set_level)"}, {"enableDebugLog", (PyCFunction)pyEnableDebugLog, METH_VARARGS, "enable/disable debug log"}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "Music player."); static PyObject* EventClass = NULL; static void init() { PyEval_InitThreads(); /* Start the interpreter's thread-awareness */ initPlayerOutput(); initPlayerDecoder(); } PyMODINIT_FUNC initmusicplayer(void) { //printf("initmusicplayer\n"); init(); if (PyType_Ready(&Player_Type) < 0) Py_FatalError("Can't initialize player type"); PyObject* m = Py_InitModule3("musicplayer", module_methods, module_doc); if(!m) { Py_FatalError("Can't initialize musicplayer module"); return; } if(EventClass == NULL) { PyObject* classDict = PyDict_New(); assert(classDict); PyObject* className = PyString_FromString("Event"); assert(className); EventClass = PyClass_New(NULL, classDict, className); assert(EventClass); Py_XDECREF(classDict); classDict = NULL; Py_XDECREF(className); className = NULL; } if(EventClass) { Py_INCREF(EventClass); PyModule_AddObject(m, "Event", EventClass); // takes the ref } } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ // Category: management //----------------------------------------------------------------------------- // Class AliMpManuStore // -------------------- // The container class for manu serial numbersd // Authors: Ivana Hrivnacova, IPN Orsay // Christian Finck, SUBATECH Nantes //----------------------------------------------------------------------------- #include "AliMpManuStore.h" #include "AliMpDEStore.h" #include "AliMpDEManager.h" #include "AliMpDetElement.h" #include "AliMpConstants.h" #include "AliMpDataStreams.h" #include "AliMpFiles.h" #include "AliMpHelper.h" #include "AliMpConstants.h" #include "AliMpEncodePair.h" #include "AliLog.h" #include <Riostream.h> #include <TClass.h> #include <TSystem.h> #include <TObjString.h> #include <TObjArray.h> #include <TMap.h> #include <fstream> #include <cstdlib> /// \cond CLASSIMP ClassImp(AliMpManuStore) /// \endcond AliMpManuStore* AliMpManuStore::fgInstance = 0; Bool_t AliMpManuStore::fgWarnIfDoublon = kFALSE; // // static methods // //______________________________________________________________________________ AliMpManuStore* AliMpManuStore::Instance(Bool_t warn) { /// Create the DDL store if it does not yet exist /// and return its instance if ( ! fgInstance && warn ) { AliWarningClass("Manu Store has not been loaded"); } return fgInstance; } //______________________________________________________________________________ AliMpManuStore* AliMpManuStore::ReadData(const AliMpDataStreams& dataStreams, Bool_t warn) { /// Load the DDL store from ASCII data files /// and return its instance if ( fgInstance ) { if ( warn ) AliWarningClass("DDL Store has been already loaded"); return fgInstance; } if ( dataStreams.GetReadFromFiles() ) AliInfoClass("Reading Manu Store from ASCII files."); fgInstance = new AliMpManuStore(dataStreams); return fgInstance; } // // ctors, dtor // //______________________________________________________________________________ AliMpManuStore::AliMpManuStore(const AliMpDataStreams& dataStreams) : TObject(), fkDataStreams(dataStreams), fManuToSerialNbs(), fSerialNbToManus(), fNofManusInDE(), fNofManus(0) { /// Standard constructor AliDebug(1,""); // Check if DE store is loaded if ( ! AliMpDEStore::Instance(false) ) { AliErrorStream() << "Mapping segmentation has not be loaded. Cannont load Manu store" << endl; return; } ReadManuSerial(); } //______________________________________________________________________________ AliMpManuStore::AliMpManuStore(TRootIOCtor* ioCtor) : TObject(), fkDataStreams(ioCtor), fManuToSerialNbs(), fSerialNbToManus(), fNofManusInDE(), fNofManus(0) { /// Constructor for IO AliDebug(1,""); } //______________________________________________________________________________ AliMpManuStore::~AliMpManuStore() { /// Destructor AliDebug(1,""); } // // private methods // //______________________________________________________________________________ Bool_t AliMpManuStore::ReadData(const AliMpDetElement* de, Int_t& nofManus) { /// Read manu serial numbers for the given detection element Int_t deId = de->GetId(); TString deName = de->GetDEName(); AliMp::StationType stationType = AliMpDEManager::GetStationType(de->GetId()); AliMq::Station12Type station12Type = AliMpDEManager::GetStation12Type(de->GetId()); // Nothing to be done for trigger if ( stationType == AliMp::kStationTrigger ) { nofManus = 0; return kTRUE; } static Int_t manuMask = AliMpConstants::ManuMask(AliMp::kNonBendingPlane); istream& in = fkDataStreams. CreateDataStream( AliMpFiles::ManuToSerialPath(deName, stationType, station12Type)); char line[80]; nofManus = 0; while ( in.getline(line,80) ) { if ( line[0] == '#' ) continue; TString tmp(AliMpHelper::Normalize(line)); TObjArray* stringList = tmp.Tokenize(TString(" ")); Int_t manuId = atoi( ((TObjString*)stringList->At(0))->GetName()); Int_t manuSerial = atoi( ((TObjString*)stringList->At(2))->GetName()); TString sPlane = ((TObjString*)stringList->At(1))->GetString(); // filling manuId <> manuSerial if (!sPlane.CompareTo(PlaneTypeName(AliMp::kBendingPlane))) AddManu(deId, manuId, manuSerial); else AddManu(deId, manuId + manuMask, manuSerial); ++nofManus; delete stringList; } return kTRUE; } //______________________________________________________________________________ Bool_t AliMpManuStore::ReadManuSerial() { /// Read data files for all detection elements. /// Return true if reading was successful. Bool_t isOk = kTRUE; // Loop over DE AliMpDEIterator it; for ( it.First(); ! it.IsDone(); it.Next() ) { AliMpDetElement* detElement = it.CurrentDE(); Int_t nofManus; Bool_t result = ReadData(detElement, nofManus); fNofManusInDE.Add(detElement->GetId(), nofManus); fNofManus += nofManus; AliDebugStream(2) << "Adding " << nofManus << " manus for de " << detElement->GetId() << endl; isOk = isOk && result; } return isOk; } //______________________________________________________________________________ void AliMpManuStore::ReplaceManu(Int_t detElemId, Int_t manuId, Int_t serialNb) { /// Replace manu in the map. /// As TExMap has no replcae function, we have to rebuild map once again. /// Not yet in use, declared private. Long_t index = AliMp::Pair(detElemId, manuId); TExMap newManuToSerialNbs; // Loop over map TExMapIter it(&fManuToSerialNbs); #if ROOT_SVN_REVISION >= 29598 Long64_t key; Long64_t value; #else Long_t key; Long_t value; #endif while ( ( it.Next(key, value) ) ) { if ( key != index ) newManuToSerialNbs.Add(key, value); else newManuToSerialNbs.Add(index, Long_t(serialNb)); } TExMap newSerialNbToManus; // Loop over map TExMapIter it2(&fSerialNbToManus); while ( ( it2.Next(key, value) ) ) { if ( value != index ) newSerialNbToManus.Add(key, value); else newSerialNbToManus.Add(Long_t(serialNb), index); } // And now replace the maps fManuToSerialNbs = newManuToSerialNbs; fSerialNbToManus = newManuToSerialNbs; } //______________________________________________________________________________ Bool_t AliMpManuStore::WriteData(const TString& outDir) { /// Write data files for all detection elements. /// Return true if reading was successful. /// Not yet in use, declared private. TString curDir = gSystem->pwd(); // Create top directory // if ( gSystem->OpenDirectory(outDir.Data()) ) { AliErrorStream() << "Directory " << outDir.Data() << " already exists" << endl; return kFALSE; } else { AliDebugStream(2) << "Making directory " << outDir.Data() << endl; gSystem->mkdir(outDir.Data()); } // Loop over DE AliMpDEIterator it; for ( it.First(); ! it.IsDone(); it.Next() ) { AliMpDetElement* detElement = it.CurrentDE(); Int_t detElemId = detElement->GetId(); TString deName = detElement->GetDEName(); AliMp::StationType stationType = AliMpDEManager::GetStationType(detElemId); AliMq::Station12Type station12Type = AliMpDEManager::GetStation12Type(detElemId); if ( stationType == AliMp::kStationTrigger ) continue; // Create directory if it does not yet exist // TString dirPath = outDir + AliMpFiles::StationDataDir(stationType, station12Type); if ( ! gSystem->OpenDirectory(dirPath.Data()) ) { AliDebugStream(2) << "Making directory " << dirPath.Data() << endl; gSystem->mkdir(dirPath.Data()); } // Compose output file path // string dataPath = AliMpFiles::ManuToSerialPath(deName, stationType, station12Type).Data(); string top = AliMpFiles::GetTop().Data(); if ( dataPath.find(top) != string::npos ) dataPath.erase(0, top.size()+1); dataPath.erase(0,dataPath.find('/')+1); TString dataPath1 = dataPath; TString filePath = outDir + "/" + dataPath1; // Open file // ofstream out(filePath.Data()); if ( ! out.good() ) { AliErrorStream() << "Cannot open output file " << filePath.Data() << endl; return kFALSE; } // Loop over map TExMapIter it2(&fManuToSerialNbs); #if ROOT_SVN_REVISION >= 29598 Long64_t key; Long64_t value; #else Long_t key; Long_t value; #endif while ( ( it2.Next(key, value) ) ) { Int_t pairFirst = AliMp::PairFirst(key); if ( pairFirst != detElemId ) continue; Int_t manuId = AliMp::PairSecond(key); AliDebugStream(3) << "Go to write " << key << " " << pairFirst << " " << manuId << " " << value << endl; static Int_t manuMask = AliMpConstants::ManuMask(AliMp::kNonBendingPlane); TString planeName = PlaneTypeName(AliMp::kBendingPlane); if ( manuId> manuMask ) { planeName = PlaneTypeName(AliMp::kNonBendingPlane); manuId -= manuMask; } out << manuId << " " << planeName.Data() << " " << value << endl; AliDebugStream(3) << manuId << " " << planeName.Data() << " " << value << endl; } out.close(); } gSystem->cd(curDir); return kTRUE; } // // public methods // //______________________________________________________________________________ Int_t AliMpManuStore::NofManus() const { /// Return total number of manus in the store return fNofManus; } //______________________________________________________________________________ Int_t AliMpManuStore::NofManus(Int_t detElemId) const { /// Return number of manus in given detection element if ( ! AliMpDEManager::IsValidDetElemId(detElemId, kTRUE) ) return 0; return fNofManusInDE.GetValue(detElemId); } //______________________________________________________________________________ Bool_t AliMpManuStore::AddManu(Int_t detElemId, Int_t manuId, Int_t serialNb) { /// Add manu to the map Long_t index = AliMp::Pair(detElemId, manuId); AliDebugStream(2) << "Adding (" << detElemId << "," << manuId << ") as index=" << index << " and serialNb=" << serialNb << endl; fManuToSerialNbs.Add(index, Long_t(serialNb)); Long_t value = fSerialNbToManus.GetValue(Long_t(serialNb)); if ( value ) { if ( fgWarnIfDoublon ) { AliWarningStream() << "Serial number " << serialNb << " already present for (detElemId, manuId) = " ; AliMp::PairPut(AliWarningStream(), (MpPair_t) value) << endl; } return kFALSE; } else { fSerialNbToManus.Add(Long_t(serialNb), index); return kTRUE; } } //______________________________________________________________________________ Int_t AliMpManuStore::GetManuSerial(Int_t detElemId, Int_t manuId) const { /// Return manu serial number for given detElemId and manuId Long_t index = AliMp::Pair(detElemId, manuId); // cout << index << " " << fManuToSerialNbs.GetValue(index) << endl; return fManuToSerialNbs.GetValue(index); } //______________________________________________________________________________ MpPair_t AliMpManuStore::GetDetElemIdManu(Int_t manuSerial) const { /// Return detElemId and manuId for given manu serial number /// as encoded pair return fSerialNbToManus.GetValue(Long_t(manuSerial)); } <commit_msg>Fixing memory leak in AliMpManuStore::ReadData (bug report #66668)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ // Category: management //----------------------------------------------------------------------------- // Class AliMpManuStore // -------------------- // The container class for manu serial numbersd // Authors: Ivana Hrivnacova, IPN Orsay // Christian Finck, SUBATECH Nantes //----------------------------------------------------------------------------- #include "AliMpManuStore.h" #include "AliMpDEStore.h" #include "AliMpDEManager.h" #include "AliMpDetElement.h" #include "AliMpConstants.h" #include "AliMpDataStreams.h" #include "AliMpFiles.h" #include "AliMpHelper.h" #include "AliMpConstants.h" #include "AliMpEncodePair.h" #include "AliLog.h" #include <Riostream.h> #include <TClass.h> #include <TSystem.h> #include <TObjString.h> #include <TObjArray.h> #include <TMap.h> #include <fstream> #include <cstdlib> /// \cond CLASSIMP ClassImp(AliMpManuStore) /// \endcond AliMpManuStore* AliMpManuStore::fgInstance = 0; Bool_t AliMpManuStore::fgWarnIfDoublon = kFALSE; // // static methods // //______________________________________________________________________________ AliMpManuStore* AliMpManuStore::Instance(Bool_t warn) { /// Create the DDL store if it does not yet exist /// and return its instance if ( ! fgInstance && warn ) { AliWarningClass("Manu Store has not been loaded"); } return fgInstance; } //______________________________________________________________________________ AliMpManuStore* AliMpManuStore::ReadData(const AliMpDataStreams& dataStreams, Bool_t warn) { /// Load the DDL store from ASCII data files /// and return its instance if ( fgInstance ) { if ( warn ) AliWarningClass("DDL Store has been already loaded"); return fgInstance; } if ( dataStreams.GetReadFromFiles() ) AliInfoClass("Reading Manu Store from ASCII files."); fgInstance = new AliMpManuStore(dataStreams); return fgInstance; } // // ctors, dtor // //______________________________________________________________________________ AliMpManuStore::AliMpManuStore(const AliMpDataStreams& dataStreams) : TObject(), fkDataStreams(dataStreams), fManuToSerialNbs(), fSerialNbToManus(), fNofManusInDE(), fNofManus(0) { /// Standard constructor AliDebug(1,""); // Check if DE store is loaded if ( ! AliMpDEStore::Instance(false) ) { AliErrorStream() << "Mapping segmentation has not be loaded. Cannont load Manu store" << endl; return; } ReadManuSerial(); } //______________________________________________________________________________ AliMpManuStore::AliMpManuStore(TRootIOCtor* ioCtor) : TObject(), fkDataStreams(ioCtor), fManuToSerialNbs(), fSerialNbToManus(), fNofManusInDE(), fNofManus(0) { /// Constructor for IO AliDebug(1,""); } //______________________________________________________________________________ AliMpManuStore::~AliMpManuStore() { /// Destructor AliDebug(1,""); } // // private methods // //______________________________________________________________________________ Bool_t AliMpManuStore::ReadData(const AliMpDetElement* de, Int_t& nofManus) { /// Read manu serial numbers for the given detection element Int_t deId = de->GetId(); TString deName = de->GetDEName(); AliMp::StationType stationType = AliMpDEManager::GetStationType(de->GetId()); AliMq::Station12Type station12Type = AliMpDEManager::GetStation12Type(de->GetId()); // Nothing to be done for trigger if ( stationType == AliMp::kStationTrigger ) { nofManus = 0; return kTRUE; } static Int_t manuMask = AliMpConstants::ManuMask(AliMp::kNonBendingPlane); istream& in = fkDataStreams. CreateDataStream( AliMpFiles::ManuToSerialPath(deName, stationType, station12Type)); char line[80]; nofManus = 0; while ( in.getline(line,80) ) { if ( line[0] == '#' ) continue; TString tmp(AliMpHelper::Normalize(line)); TObjArray* stringList = tmp.Tokenize(TString(" ")); Int_t manuId = atoi( ((TObjString*)stringList->At(0))->GetName()); Int_t manuSerial = atoi( ((TObjString*)stringList->At(2))->GetName()); TString sPlane = ((TObjString*)stringList->At(1))->GetString(); // filling manuId <> manuSerial if (!sPlane.CompareTo(PlaneTypeName(AliMp::kBendingPlane))) AddManu(deId, manuId, manuSerial); else AddManu(deId, manuId + manuMask, manuSerial); ++nofManus; delete stringList; } delete &in; return kTRUE; } //______________________________________________________________________________ Bool_t AliMpManuStore::ReadManuSerial() { /// Read data files for all detection elements. /// Return true if reading was successful. Bool_t isOk = kTRUE; // Loop over DE AliMpDEIterator it; for ( it.First(); ! it.IsDone(); it.Next() ) { AliMpDetElement* detElement = it.CurrentDE(); Int_t nofManus; Bool_t result = ReadData(detElement, nofManus); fNofManusInDE.Add(detElement->GetId(), nofManus); fNofManus += nofManus; AliDebugStream(2) << "Adding " << nofManus << " manus for de " << detElement->GetId() << endl; isOk = isOk && result; } return isOk; } //______________________________________________________________________________ void AliMpManuStore::ReplaceManu(Int_t detElemId, Int_t manuId, Int_t serialNb) { /// Replace manu in the map. /// As TExMap has no replcae function, we have to rebuild map once again. /// Not yet in use, declared private. Long_t index = AliMp::Pair(detElemId, manuId); TExMap newManuToSerialNbs; // Loop over map TExMapIter it(&fManuToSerialNbs); #if ROOT_SVN_REVISION >= 29598 Long64_t key; Long64_t value; #else Long_t key; Long_t value; #endif while ( ( it.Next(key, value) ) ) { if ( key != index ) newManuToSerialNbs.Add(key, value); else newManuToSerialNbs.Add(index, Long_t(serialNb)); } TExMap newSerialNbToManus; // Loop over map TExMapIter it2(&fSerialNbToManus); while ( ( it2.Next(key, value) ) ) { if ( value != index ) newSerialNbToManus.Add(key, value); else newSerialNbToManus.Add(Long_t(serialNb), index); } // And now replace the maps fManuToSerialNbs = newManuToSerialNbs; fSerialNbToManus = newManuToSerialNbs; } //______________________________________________________________________________ Bool_t AliMpManuStore::WriteData(const TString& outDir) { /// Write data files for all detection elements. /// Return true if reading was successful. /// Not yet in use, declared private. TString curDir = gSystem->pwd(); // Create top directory // if ( gSystem->OpenDirectory(outDir.Data()) ) { AliErrorStream() << "Directory " << outDir.Data() << " already exists" << endl; return kFALSE; } else { AliDebugStream(2) << "Making directory " << outDir.Data() << endl; gSystem->mkdir(outDir.Data()); } // Loop over DE AliMpDEIterator it; for ( it.First(); ! it.IsDone(); it.Next() ) { AliMpDetElement* detElement = it.CurrentDE(); Int_t detElemId = detElement->GetId(); TString deName = detElement->GetDEName(); AliMp::StationType stationType = AliMpDEManager::GetStationType(detElemId); AliMq::Station12Type station12Type = AliMpDEManager::GetStation12Type(detElemId); if ( stationType == AliMp::kStationTrigger ) continue; // Create directory if it does not yet exist // TString dirPath = outDir + AliMpFiles::StationDataDir(stationType, station12Type); if ( ! gSystem->OpenDirectory(dirPath.Data()) ) { AliDebugStream(2) << "Making directory " << dirPath.Data() << endl; gSystem->mkdir(dirPath.Data()); } // Compose output file path // string dataPath = AliMpFiles::ManuToSerialPath(deName, stationType, station12Type).Data(); string top = AliMpFiles::GetTop().Data(); if ( dataPath.find(top) != string::npos ) dataPath.erase(0, top.size()+1); dataPath.erase(0,dataPath.find('/')+1); TString dataPath1 = dataPath; TString filePath = outDir + "/" + dataPath1; // Open file // ofstream out(filePath.Data()); if ( ! out.good() ) { AliErrorStream() << "Cannot open output file " << filePath.Data() << endl; return kFALSE; } // Loop over map TExMapIter it2(&fManuToSerialNbs); #if ROOT_SVN_REVISION >= 29598 Long64_t key; Long64_t value; #else Long_t key; Long_t value; #endif while ( ( it2.Next(key, value) ) ) { Int_t pairFirst = AliMp::PairFirst(key); if ( pairFirst != detElemId ) continue; Int_t manuId = AliMp::PairSecond(key); AliDebugStream(3) << "Go to write " << key << " " << pairFirst << " " << manuId << " " << value << endl; static Int_t manuMask = AliMpConstants::ManuMask(AliMp::kNonBendingPlane); TString planeName = PlaneTypeName(AliMp::kBendingPlane); if ( manuId> manuMask ) { planeName = PlaneTypeName(AliMp::kNonBendingPlane); manuId -= manuMask; } out << manuId << " " << planeName.Data() << " " << value << endl; AliDebugStream(3) << manuId << " " << planeName.Data() << " " << value << endl; } out.close(); } gSystem->cd(curDir); return kTRUE; } // // public methods // //______________________________________________________________________________ Int_t AliMpManuStore::NofManus() const { /// Return total number of manus in the store return fNofManus; } //______________________________________________________________________________ Int_t AliMpManuStore::NofManus(Int_t detElemId) const { /// Return number of manus in given detection element if ( ! AliMpDEManager::IsValidDetElemId(detElemId, kTRUE) ) return 0; return fNofManusInDE.GetValue(detElemId); } //______________________________________________________________________________ Bool_t AliMpManuStore::AddManu(Int_t detElemId, Int_t manuId, Int_t serialNb) { /// Add manu to the map Long_t index = AliMp::Pair(detElemId, manuId); AliDebugStream(2) << "Adding (" << detElemId << "," << manuId << ") as index=" << index << " and serialNb=" << serialNb << endl; fManuToSerialNbs.Add(index, Long_t(serialNb)); Long_t value = fSerialNbToManus.GetValue(Long_t(serialNb)); if ( value ) { if ( fgWarnIfDoublon ) { AliWarningStream() << "Serial number " << serialNb << " already present for (detElemId, manuId) = " ; AliMp::PairPut(AliWarningStream(), (MpPair_t) value) << endl; } return kFALSE; } else { fSerialNbToManus.Add(Long_t(serialNb), index); return kTRUE; } } //______________________________________________________________________________ Int_t AliMpManuStore::GetManuSerial(Int_t detElemId, Int_t manuId) const { /// Return manu serial number for given detElemId and manuId Long_t index = AliMp::Pair(detElemId, manuId); // cout << index << " " << fManuToSerialNbs.GetValue(index) << endl; return fManuToSerialNbs.GetValue(index); } //______________________________________________________________________________ MpPair_t AliMpManuStore::GetDetElemIdManu(Int_t manuSerial) const { /// Return detElemId and manuId for given manu serial number /// as encoded pair return fSerialNbToManus.GetValue(Long_t(manuSerial)); } <|endoftext|>
<commit_before>/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** 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 chemkit project 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 "uridineminimizationbenchmark.h" #include <chemkit/molecule.h> #include <chemkit/forcefield.h> #include <chemkit/moleculefile.h> const std::string dataPath = "../../data/"; void UridineMinimizationBenchmark::benchmark() { boost::shared_ptr<chemkit::Molecule> molecule = chemkit::MoleculeFile::quickRead(dataPath + "uridine.mol2"); QVERIFY(molecule != 0); chemkit::ForceField *forceField = chemkit::ForceField::create("uff"); QVERIFY(forceField != 0); forceField->setMolecule(molecule.get()); bool ok = forceField->setup(); QVERIFY(ok); QBENCHMARK { for(;;){ // converge when rmsg = 0.1 bool converged = forceField->minimizationStep(0.1); if(converged){ break; } } } delete forceField; } QTEST_APPLESS_MAIN(UridineMinimizationBenchmark) <commit_msg>Use MoleculeGeometryOptimizer in UridineMinimizationBenchmark<commit_after>/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** 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 chemkit project 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 "uridineminimizationbenchmark.h" #include <chemkit/molecule.h> #include <chemkit/moleculefile.h> #include <chemkit/moleculegeometryoptimizer.h> const std::string dataPath = "../../data/"; void UridineMinimizationBenchmark::benchmark() { boost::shared_ptr<chemkit::Molecule> molecule = chemkit::MoleculeFile::quickRead(dataPath + "uridine.mol2"); QVERIFY(molecule != 0); chemkit::MoleculeGeometryOptimizer optimizer; optimizer.setForceField("uff"); optimizer.setMolecule(molecule.get()); bool ok = optimizer.setup(); QVERIFY(ok); QBENCHMARK { for(;;){ // converge when rmsg = 0.1 bool converged = optimizer.step(); if(converged){ break; } } } } QTEST_APPLESS_MAIN(UridineMinimizationBenchmark) <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2008 by Daniel Schwen * * daniel@schwen.de * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <queue> #include <iostream> #include <fstream> #include <sstream> #include "simconf.h" #include "element.h" #include "material.h" #include "sample_wire.h" #include "sample_burried_wire.h" #include "ion.h" #include "trim.h" #include "invert.h" #include <r250.h> #include "functions.h" using namespace std; int main(int argc, char *argv[]) { char fname[200]; if( argc != 6 ) { cerr << "syntax: " << argv[0] << " basename angle[deg] diameter(nm) burried[0,1] numbermultiplier" << endl; return 1; } double theta = atof(argv[2]) * M_PI/180.0; // 0 = parallel to wire double diameter = 10.0*atof(argv[3]); double length = 11000.0; // 1.1 mu bool burried = ( atoi(argv[4]) != 0 ); double mult = atof(argv[5]); // ion series const int nstep = 5; double ion_dose[nstep] = { 3.0e13, 2.2e13, 1.5e13, 1.2e13, 2.5e13 }; // in ions/cm^2 int ion_count[nstep]; ionBase* ion_prototype[nstep]; ion_prototype[0] = new ionBase( 5, 11.0 , 320.0e3 ); // Z,m,E ion_prototype[1] = new ionBase( 5, 11.0 , 220.0e3 ); // Z,m,E ion_prototype[2] = new ionBase( 5, 11.0 , 160.0e3 ); // Z,m,E ion_prototype[3] = new ionBase( 5, 11.0 , 120.0e3 ); // Z,m,E ion_prototype[4] = new ionBase( 15, 31.0 , 250.0e3 ); // Z,m,E // seed randomnumber generator from system entropy pool FILE *urand = fopen( "/dev/random", "r" ); int seed; fread( &seed, sizeof(int), 1, urand ); fclose( urand ); r250_init( seed<0 ? -seed : seed ); // random generator goes haywire with neg. seed // initialize global parameter structure and read data tables from file simconf = new simconfType; // initialize sample structure sampleWire *sample; if( burried ) sample = new sampleBurriedWire( diameter, diameter, length ); else { sample = new sampleWire( diameter, diameter, length ); sample->bc[2] = sampleWire::CUT; } // calculate actual ion numbers for( int s = 0; s < nstep; ++s ) { double A; // irradiated area in Ang^2 if( burried ) A =( 2.0*length + sample->w[0] ) * ( 2.0*length + sample->w[1] ); else A = cos(theta) * M_PI * 0.25 * sample->w[0] * sample->w[1] + // slanted top face sin(theta) * length * sample->w[0]; // + projected side // 1cm^2 = 1e16 Ang**2, 1Ang^2 = 1e-16cm^2 ion_count[s] = ion_dose[s] * A * 1.0e-16 * mult; cerr << "Ion " << s << ' ' << ion_count[s] << endl; } // initialize trim engine for the sample /* const int z1 = 31; const int z2 = 33; trimVacMap *trim = new trimVacMap( sample, z1, z2 ); // GaAs*/ //trimBase *trim = new trimBase( sample ); trimBase *trim = new trimPrimaries( sample ); materialBase *material; elementBase *element; // Si material = new materialBase( 2.329 ); // rho element = new elementBase; element->z = 14; // Si element->m = 28.0; element->t = 1.0; material->element.push_back( element ); material->prepare(); // all materials added sample->material.push_back( material ); // add material to sample // SiO2 (material[1] for the cover layer in SampleBurriedWire) material = new materialBase( 2.634 ); // rho element = new elementBase; element->z = 14; // Si element->m = 28.0; element->t = 1.0; material->element.push_back( element ); element = new elementBase; element->z = 8; // O element->m = 16.0; element->t = 2.0; material->element.push_back( element ); material->prepare(); // all materials added sample->material.push_back( material ); // add material to sample // create a FIFO for recoils queue<ionBase*> recoils; double norm; double jmp = 2.7; // diffusion jump distance int jumps; double dif[3]; //snprintf( fname, 199, "%s.Erec", argv[1] ); //FILE *erec = fopen( fname, "wt" ); //snprintf( fname, 199, "%s.dist", argv[1] ); //FILE *rdist = fopen( fname, "wt" ); ionBase *pka; // map concentration along length int *lbins[2]; int lx = 100; // 100 bins int dl = length/double(lx); lbins[1] = new int[lx]; // P z=15 for( int i = 0; i < 2; ++i ) { lbins[i] = new int[lx]; // 0=B (z=5), 1=P (z=15) for( int l = 0; l < lx; ++l ) lbins[i][l] = 0; } // xyz data int xyz_lines = 0; stringstream xyz_data; for( int s = 0; s < nstep; ++s ) { for( int n = 0; n < ion_count[s]; ++n ) { if( n % 10000 == 0 ) cerr << "pka #" << n+1 << endl; // generate new PKA from prototype ion pka = new ionBase( ion_prototype[s] ); pka->gen = 0; // generation (0 = PKA) pka->tag = -1; pka->md = 0; pka->dir[0] = 0.0; pka->dir[1] = sin( theta ); pka->dir[2] = cos( theta ); v_norm( pka->dir ); if( burried ) { // cannot anticipate the straggling in the burrial layer, thus have to shoot onto a big surface // TODO: take theta into account! pka->pos[0] = dr250() * ( 2.0*length + sample->w[0] ) - ( length + 0.5 * sample->w[0] ) ; pka->pos[1] = dr250() * ( 2.0*length + sample->w[1] ) - ( length + 0.5 * sample->w[1] ) ; pka->pos[2] = -250.0; // overcoat thickness } else { if( theta == 0.0 ) { // 0 degrees => start on top of wire! pka->pos[2] = 0.0; do { pka->pos[0] = dr250() * sample->w[0]; pka->pos[1] = dr250() * sample->w[1]; } while( sample->lookupMaterial(pka->pos ) == 0 ); } else { // start on side _or_ top! double vpos[3], t; do { do { vpos[0] = dr250() * sample->w[0]; vpos[1] = 0.0; vpos[2] = ( dr250() * ( length + diameter/tan(theta) ) ) - diameter/tan(theta); t = ( 1.0 - sqrt( 1.0 - sqr( 2*vpos[0]/diameter - 1.0 ) ) ) * diameter/(2.0*pka->dir[1]); // if we start beyond wire length (that would be inside the substrate) then retry } while( t*pka->dir[2] + vpos[2] >= length ); // if first intersection with cylinder is at z<0 then check if we hit the top face instead if( t*pka->dir[2] + vpos[2] < 0.0 ) t = -vpos[2]/pka->dir[2]; // start PKA at calculated intersection point for( int i = 0; i < 3; i++ ) pka->pos[i] = t*pka->dir[i] + vpos[i]; } while( sample->lookupMaterial(pka->pos ) == 0 ); } } //cout << "START " << pka->pos[0] << ' ' << pka->pos[1] << ' ' << pka->pos[2] << ' ' << endl; //continue; pka->set_ef(); recoils.push( pka ); while( !recoils.empty() ) { pka = recoils.front(); recoils.pop(); sample->averages( pka ); // do ion analysis/processing BEFORE the cascade here if( pka->z1 == ion_prototype[s]->z1 ) { //printf( "p1 %f\t%f\t%f\n", pka->pos[0], pka->pos[1], pka->pos[2] ); } // follow this ion's trajectory and store recoils trim->trim( pka, recoils ); // do ion analysis/processing AFTER the cascade here // ion is in the wire if( sample->lookupMaterial( pka->pos ) == sample->material[0] ) { xyz_data << simconf->scoef[pka->z1-1].sym << ' ' << pka->pos[0]/100.0 << ' ' << pka->pos[1]/100.0 << ' ' << pka->pos[2]/100.0 << endl; xyz_lines++; int l = pka->pos[2] / dl; if( l >=0 && l < lx ) lbins[ pka->z1 == 5 ? 0 : 1 ][l]++; } // done with this recoil delete pka; } } } // write xyz file stringstream xyz_name; xyz_name << argv[1] << ".xyz"; ofstream xyz( xyz_name.str().c_str() ); xyz << xyz_lines << endl << endl << xyz_data.str(); xyz.close(); // write lbins file (atoms per nm wire length) stringstream ldat_name; ldat_name << argv[1] << ".ldat"; ofstream ldat( ldat_name.str().c_str() ); for( int l = 0; l < lx; ++l ) ldat << l*dl << ' ' << lbins[0][l]/(mult*0.1*dl) << ' ' << lbins[1][l]/(mult*0.1*dl) << endl; ldat.close(); delete[] lbins[0]; delete[] lbins[1]; return EXIT_SUCCESS; } <commit_msg>output concentration per nm^3<commit_after>/*************************************************************************** * Copyright (C) 2008 by Daniel Schwen * * daniel@schwen.de * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <queue> #include <iostream> #include <fstream> #include <sstream> #include "simconf.h" #include "element.h" #include "material.h" #include "sample_wire.h" #include "sample_burried_wire.h" #include "ion.h" #include "trim.h" #include "invert.h" #include <r250.h> #include "functions.h" using namespace std; int main(int argc, char *argv[]) { char fname[200]; if( argc != 6 ) { cerr << "syntax: " << argv[0] << " basename angle[deg] diameter(nm) burried[0,1] numbermultiplier" << endl; return 1; } double theta = atof(argv[2]) * M_PI/180.0; // 0 = parallel to wire double diameter = 10.0*atof(argv[3]); double length = 11000.0; // 1.1 mu bool burried = ( atoi(argv[4]) != 0 ); double mult = atof(argv[5]); // ion series const int nstep = 5; double ion_dose[nstep] = { 3.0e13, 2.2e13, 1.5e13, 1.2e13, 2.5e13 }; // in ions/cm^2 int ion_count[nstep]; ionBase* ion_prototype[nstep]; ion_prototype[0] = new ionBase( 5, 11.0 , 320.0e3 ); // Z,m,E ion_prototype[1] = new ionBase( 5, 11.0 , 220.0e3 ); // Z,m,E ion_prototype[2] = new ionBase( 5, 11.0 , 160.0e3 ); // Z,m,E ion_prototype[3] = new ionBase( 5, 11.0 , 120.0e3 ); // Z,m,E ion_prototype[4] = new ionBase( 15, 31.0 , 250.0e3 ); // Z,m,E // seed randomnumber generator from system entropy pool FILE *urand = fopen( "/dev/random", "r" ); int seed; fread( &seed, sizeof(int), 1, urand ); fclose( urand ); r250_init( seed<0 ? -seed : seed ); // random generator goes haywire with neg. seed // initialize global parameter structure and read data tables from file simconf = new simconfType; // initialize sample structure sampleWire *sample; if( burried ) sample = new sampleBurriedWire( diameter, diameter, length ); else { sample = new sampleWire( diameter, diameter, length ); sample->bc[2] = sampleWire::CUT; } // calculate actual ion numbers for( int s = 0; s < nstep; ++s ) { double A; // irradiated area in Ang^2 if( burried ) A =( 2.0*length + sample->w[0] ) * ( 2.0*length + sample->w[1] ); else A = cos(theta) * M_PI * 0.25 * sample->w[0] * sample->w[1] + // slanted top face sin(theta) * length * sample->w[0]; // + projected side // 1cm^2 = 1e16 Ang**2, 1Ang^2 = 1e-16cm^2 ion_count[s] = ion_dose[s] * A * 1.0e-16 * mult; cerr << "Ion " << s << ' ' << ion_count[s] << endl; } // initialize trim engine for the sample /* const int z1 = 31; const int z2 = 33; trimVacMap *trim = new trimVacMap( sample, z1, z2 ); // GaAs*/ //trimBase *trim = new trimBase( sample ); trimBase *trim = new trimPrimaries( sample ); materialBase *material; elementBase *element; // Si material = new materialBase( 2.329 ); // rho element = new elementBase; element->z = 14; // Si element->m = 28.0; element->t = 1.0; material->element.push_back( element ); material->prepare(); // all materials added sample->material.push_back( material ); // add material to sample // SiO2 (material[1] for the cover layer in SampleBurriedWire) material = new materialBase( 2.634 ); // rho element = new elementBase; element->z = 14; // Si element->m = 28.0; element->t = 1.0; material->element.push_back( element ); element = new elementBase; element->z = 8; // O element->m = 16.0; element->t = 2.0; material->element.push_back( element ); material->prepare(); // all materials added sample->material.push_back( material ); // add material to sample // create a FIFO for recoils queue<ionBase*> recoils; double norm; double jmp = 2.7; // diffusion jump distance int jumps; double dif[3]; //snprintf( fname, 199, "%s.Erec", argv[1] ); //FILE *erec = fopen( fname, "wt" ); //snprintf( fname, 199, "%s.dist", argv[1] ); //FILE *rdist = fopen( fname, "wt" ); ionBase *pka; // map concentration along length int *lbins[2]; int lx = 100; // 100 bins int dl = length/double(lx); lbins[1] = new int[lx]; // P z=15 for( int i = 0; i < 2; ++i ) { lbins[i] = new int[lx]; // 0=B (z=5), 1=P (z=15) for( int l = 0; l < lx; ++l ) lbins[i][l] = 0; } // xyz data int xyz_lines = 0; stringstream xyz_data; for( int s = 0; s < nstep; ++s ) { for( int n = 0; n < ion_count[s]; ++n ) { if( n % 10000 == 0 ) cerr << "pka #" << n+1 << endl; // generate new PKA from prototype ion pka = new ionBase( ion_prototype[s] ); pka->gen = 0; // generation (0 = PKA) pka->tag = -1; pka->md = 0; pka->dir[0] = 0.0; pka->dir[1] = sin( theta ); pka->dir[2] = cos( theta ); v_norm( pka->dir ); if( burried ) { // cannot anticipate the straggling in the burrial layer, thus have to shoot onto a big surface // TODO: take theta into account! pka->pos[0] = dr250() * ( 2.0*length + sample->w[0] ) - ( length + 0.5 * sample->w[0] ) ; pka->pos[1] = dr250() * ( 2.0*length + sample->w[1] ) - ( length + 0.5 * sample->w[1] ) ; pka->pos[2] = -250.0; // overcoat thickness } else { if( theta == 0.0 ) { // 0 degrees => start on top of wire! pka->pos[2] = 0.0; do { pka->pos[0] = dr250() * sample->w[0]; pka->pos[1] = dr250() * sample->w[1]; } while( sample->lookupMaterial(pka->pos ) == 0 ); } else { // start on side _or_ top! double vpos[3], t; do { do { vpos[0] = dr250() * sample->w[0]; vpos[1] = 0.0; vpos[2] = ( dr250() * ( length + diameter/tan(theta) ) ) - diameter/tan(theta); t = ( 1.0 - sqrt( 1.0 - sqr( 2*vpos[0]/diameter - 1.0 ) ) ) * diameter/(2.0*pka->dir[1]); // if we start beyond wire length (that would be inside the substrate) then retry } while( t*pka->dir[2] + vpos[2] >= length ); // if first intersection with cylinder is at z<0 then check if we hit the top face instead if( t*pka->dir[2] + vpos[2] < 0.0 ) t = -vpos[2]/pka->dir[2]; // start PKA at calculated intersection point for( int i = 0; i < 3; i++ ) pka->pos[i] = t*pka->dir[i] + vpos[i]; } while( sample->lookupMaterial(pka->pos ) == 0 ); } } //cout << "START " << pka->pos[0] << ' ' << pka->pos[1] << ' ' << pka->pos[2] << ' ' << endl; //continue; pka->set_ef(); recoils.push( pka ); while( !recoils.empty() ) { pka = recoils.front(); recoils.pop(); sample->averages( pka ); // do ion analysis/processing BEFORE the cascade here if( pka->z1 == ion_prototype[s]->z1 ) { //printf( "p1 %f\t%f\t%f\n", pka->pos[0], pka->pos[1], pka->pos[2] ); } // follow this ion's trajectory and store recoils trim->trim( pka, recoils ); // do ion analysis/processing AFTER the cascade here // ion is in the wire if( sample->lookupMaterial( pka->pos ) == sample->material[0] ) { xyz_data << simconf->scoef[pka->z1-1].sym << ' ' << pka->pos[0]/100.0 << ' ' << pka->pos[1]/100.0 << ' ' << pka->pos[2]/100.0 << endl; xyz_lines++; int l = pka->pos[2] / dl; if( l >=0 && l < lx ) lbins[ pka->z1 == 5 ? 0 : 1 ][l]++; } // done with this recoil delete pka; } } } // write xyz file stringstream xyz_name; xyz_name << argv[1] << ".xyz"; ofstream xyz( xyz_name.str().c_str() ); xyz << xyz_lines << endl << endl << xyz_data.str(); xyz.close(); // write lbins file (atoms per nm^3) stringstream ldat_name; ldat_name << argv[1] << ".ldat"; ofstream ldat( ldat_name.str().c_str() ); double dv = 1e-3 * dl * M_PI * 0.25 *sample->w[0] * sample->w[1]; // volume per bin in nm^3 for( int l = 0; l < lx; ++l ) ldat << l*dl << ' ' << lbins[0][l]/(mult*dv) << ' ' << lbins[1][l]/(mult*dv) << endl; ldat.close(); delete[] lbins[0]; delete[] lbins[1]; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** ** Non-Open Source Usage ** ** Licensees may use this file in accordance with the Qt Beta Version ** License Agreement, Agreement version 2.2 provided with the Software or, ** alternatively, in accordance with the terms contained in a written ** agreement between you and Nokia. ** ** GNU General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU General ** Public License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the packaging ** of this file. Please review the following information to ensure GNU ** General Public Licensing requirements will be met: ** ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt GPL Exception ** version 1.3, included in the file GPL_EXCEPTION.txt in this package. ** ***************************************************************************/ #include "LookupContext.h" #include "ResolveExpression.h" #include "Overview.h" #include <CoreTypes.h> #include <Symbols.h> #include <Literals.h> #include <Names.h> #include <Scope.h> #include <Control.h> #include <QtDebug> using namespace CPlusPlus; bool LookupContext::isNameCompatibleWithIdentifier(Name *name, Identifier *id) { if (! name) { return false; } else if (NameId *nameId = name->asNameId()) { Identifier *identifier = nameId->identifier(); return identifier->isEqualTo(id); } else if (DestructorNameId *nameId = name->asDestructorNameId()) { Identifier *identifier = nameId->identifier(); return identifier->isEqualTo(id); } else if (TemplateNameId *templNameId = name->asTemplateNameId()) { Identifier *identifier = templNameId->identifier(); return identifier->isEqualTo(id); } return false; } ///////////////////////////////////////////////////////////////////// // LookupContext ///////////////////////////////////////////////////////////////////// LookupContext::LookupContext(Control *control) : _control(control), _symbol(0) { } LookupContext::LookupContext(Symbol *symbol, Document::Ptr expressionDocument, Document::Ptr thisDocument, const Snapshot &documents) : _symbol(symbol), _expressionDocument(expressionDocument), _thisDocument(thisDocument), _documents(documents) { _control = _expressionDocument->control(); _visibleScopes = buildVisibleScopes(); } LookupContext::LookupContext(Symbol *symbol, const LookupContext &context) : _control(context._control), _symbol(symbol), _expressionDocument(context._expressionDocument), _documents(context._documents) { const QString fn = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength()); _thisDocument = _documents.value(fn); _visibleScopes = buildVisibleScopes(); } LookupContext::LookupContext(Symbol *symbol, Document::Ptr thisDocument, const LookupContext &context) : _control(context._control), _symbol(symbol), _expressionDocument(context._expressionDocument), _thisDocument(thisDocument), _documents(context._documents) { _visibleScopes = buildVisibleScopes(); } bool LookupContext::isValid() const { return _control != 0; } LookupContext::operator bool() const { return _control != 0; } Control *LookupContext::control() const { return _control; } Symbol *LookupContext::symbol() const { return _symbol; } Document::Ptr LookupContext::expressionDocument() const { return _expressionDocument; } Document::Ptr LookupContext::thisDocument() const { return _thisDocument; } Document::Ptr LookupContext::document(const QString &fileName) const { return _documents.value(fileName); } Identifier *LookupContext::identifier(Name *name) const { if (NameId *nameId = name->asNameId()) return nameId->identifier(); else if (TemplateNameId *templId = name->asTemplateNameId()) return templId->identifier(); else if (DestructorNameId *dtorId = name->asDestructorNameId()) return dtorId->identifier(); else if (QualifiedNameId *q = name->asQualifiedNameId()) return identifier(q->unqualifiedNameId()); return 0; } bool LookupContext::maybeValidSymbol(Symbol *symbol, ResolveMode mode, const QList<Symbol *> &candidates) { if (((mode & ResolveNamespace) && symbol->isNamespace()) || ((mode & ResolveClass) && symbol->isClass()) || (mode & ResolveSymbol)) { return ! candidates.contains(symbol); } return false; } QList<Symbol *> LookupContext::resolve(Name *name, const QList<Scope *> &visibleScopes, ResolveMode mode) const { if (QualifiedNameId *q = name->asQualifiedNameId()) { QList<Symbol *> candidates; QList<Scope *> scopes = visibleScopes; for (unsigned i = 0; i < q->nameCount(); ++i) { Name *name = q->nameAt(i); if (i + 1 == q->nameCount()) candidates = resolve(name, scopes, mode); else candidates = resolveClassOrNamespace(name, scopes); if (candidates.isEmpty() || i + 1 == q->nameCount()) break; scopes.clear(); foreach (Symbol *candidate, candidates) { if (ScopedSymbol *scoped = candidate->asScopedSymbol()) { expand(scoped->members(), visibleScopes, &scopes); } } } Identifier *id = identifier(name); foreach (Scope *scope, visibleScopes) { Symbol *symbol = scope->lookat(id); for (; symbol; symbol = symbol->next()) { if (! symbol->name()) continue; else if (! maybeValidSymbol(symbol, mode, candidates)) continue; QualifiedNameId *qq = symbol->name()->asQualifiedNameId(); if (! qq) continue; if (q->nameCount() > qq->nameCount()) continue; for (int i = q->nameCount() - 1; i != -1; --i) { Name *a = q->nameAt(i); Name *b = qq->nameAt(i); if (! a->isEqualTo(b)) break; else if (i == 0) candidates.append(symbol); } } } return candidates; } QList<Symbol *> candidates; if (Identifier *id = identifier(name)) { for (int scopeIndex = 0; scopeIndex < visibleScopes.size(); ++scopeIndex) { Scope *scope = visibleScopes.at(scopeIndex); for (Symbol *symbol = scope->lookat(id); symbol; symbol = symbol->next()) { if (! symbol->name()) { continue; } else if (! maybeValidSymbol(symbol, mode, candidates)) { continue; } else if (QualifiedNameId *q = symbol->name()->asQualifiedNameId()) { if (! q->unqualifiedNameId()->isEqualTo(name)) continue; if (q->nameCount() > 1) { Name *classOrNamespaceName = control()->qualifiedNameId(q->names(), q->nameCount() - 1); const QList<Symbol *> resolvedClassOrNamespace = resolveClassOrNamespace(classOrNamespaceName, visibleScopes); bool good = false; foreach (Symbol *classOrNamespace, resolvedClassOrNamespace) { ScopedSymbol *scoped = classOrNamespace->asScopedSymbol(); if (visibleScopes.contains(scoped->members())) { good = true; break; } } if (! good) continue; } } else if (! isNameCompatibleWithIdentifier(symbol->name(), id)) { continue; } else if (symbol->name()->isDestructorNameId() != name->isDestructorNameId()) { continue; } candidates.append(symbol); } } } else if (OperatorNameId *opId = name->asOperatorNameId()) { for (int scopeIndex = 0; scopeIndex < visibleScopes.size(); ++scopeIndex) { Scope *scope = visibleScopes.at(scopeIndex); for (Symbol *symbol = scope->lookat(opId->kind()); symbol; symbol = symbol->next()) { if (! opId->isEqualTo(symbol->name())) continue; else if (! candidates.contains(symbol)) candidates.append(symbol); } } } return candidates; } QList<Scope *> LookupContext::buildVisibleScopes() { QList<Scope *> scopes; if (_symbol) { for (Scope *scope = _symbol->scope(); scope; scope = scope->enclosingScope()) { scopes.append(scope); } } QSet<QString> processed; processed.insert(_thisDocument->fileName()); QList<QString> todo = _thisDocument->includedFiles(); while (! todo.isEmpty()) { QString fn = todo.last(); todo.removeLast(); if (processed.contains(fn)) continue; processed.insert(fn); if (Document::Ptr doc = document(fn)) { scopes.append(doc->globalNamespace()->members()); todo += doc->includedFiles(); } } while (true) { QList<Scope *> expandedScopes; expand(scopes, &expandedScopes); if (expandedScopes.size() == scopes.size()) return expandedScopes; scopes = expandedScopes; } return scopes; } QList<Scope *> LookupContext::visibleScopes(const QPair<FullySpecifiedType, Symbol *> &result) const { Symbol *symbol = result.second; QList<Scope *> scopes; for (Scope *scope = symbol->scope(); scope; scope = scope->enclosingScope()) scopes.append(scope); scopes += visibleScopes(); scopes = expand(scopes); return scopes; } QList<Scope *> LookupContext::expand(const QList<Scope *> &scopes) const { QList<Scope *> expanded; expand(scopes, &expanded); return expanded; } void LookupContext::expand(const QList<Scope *> &scopes, QList<Scope *> *expandedScopes) const { for (int i = 0; i < scopes.size(); ++i) { expand(scopes.at(i), scopes, expandedScopes); } } void LookupContext::expandNamespace(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { Namespace *ns = scope->owner()->asNamespace(); if (! ns) return; if (Name *nsName = ns->name()) { const QList<Symbol *> namespaceList = resolveNamespace(nsName, visibleScopes); foreach (Symbol *otherNs, namespaceList) { if (otherNs == ns) continue; expand(otherNs->asNamespace()->members(), visibleScopes, expandedScopes); } } for (unsigned i = 0; i < scope->symbolCount(); ++i) { // ### make me fast Symbol *symbol = scope->symbolAt(i); if (Namespace *ns = symbol->asNamespace()) { if (! ns->name()) { expand(ns->members(), visibleScopes, expandedScopes); } } else if (UsingNamespaceDirective *u = symbol->asUsingNamespaceDirective()) { const QList<Symbol *> candidates = resolveNamespace(u->name(), visibleScopes); for (int j = 0; j < candidates.size(); ++j) { expand(candidates.at(j)->asNamespace()->members(), visibleScopes, expandedScopes); } } else if (Enum *e = symbol->asEnum()) { expand(e->members(), visibleScopes, expandedScopes); } } } void LookupContext::expandClass(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { Class *klass = scope->owner()->asClass(); if (! klass) return; for (unsigned i = 0; i < scope->symbolCount(); ++i) { Symbol *symbol = scope->symbolAt(i); if (Class *nestedClass = symbol->asClass()) { if (! nestedClass->name()) { expand(nestedClass->members(), visibleScopes, expandedScopes); } } else if (Enum *e = symbol->asEnum()) { expand(e->members(), visibleScopes, expandedScopes); } } if (klass->baseClassCount()) { QList<Scope *> classVisibleScopes = visibleScopes; for (Scope *scope = klass->scope(); scope; scope = scope->enclosingScope()) { if (scope->isNamespaceScope()) { Namespace *enclosingNamespace = scope->owner()->asNamespace(); if (enclosingNamespace->name()) { const QList<Symbol *> nsList = resolveNamespace(enclosingNamespace->name(), visibleScopes); foreach (Symbol *ns, nsList) { expand(ns->asNamespace()->members(), classVisibleScopes, &classVisibleScopes); } } } } for (unsigned i = 0; i < klass->baseClassCount(); ++i) { BaseClass *baseClass = klass->baseClassAt(i); Name *baseClassName = baseClass->name(); const QList<Symbol *> baseClassCandidates = resolveClass(baseClassName, classVisibleScopes); if (baseClassCandidates.isEmpty()) { Overview overview; qDebug() << "unresolved base class:" << overview.prettyName(baseClassName); } for (int j = 0; j < baseClassCandidates.size(); ++j) { if (Class *baseClassSymbol = baseClassCandidates.at(j)->asClass()) expand(baseClassSymbol->members(), visibleScopes, expandedScopes); } } } } void LookupContext::expandBlock(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { for (unsigned i = 0; i < scope->symbolCount(); ++i) { Symbol *symbol = scope->symbolAt(i); if (UsingNamespaceDirective *u = symbol->asUsingNamespaceDirective()) { const QList<Symbol *> candidates = resolveNamespace(u->name(), visibleScopes); for (int j = 0; j < candidates.size(); ++j) { expand(candidates.at(j)->asNamespace()->members(), visibleScopes, expandedScopes); } } } } void LookupContext::expandFunction(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { Function *function = scope->owner()->asFunction(); if (! expandedScopes->contains(function->arguments())) expandedScopes->append(function->arguments()); if (QualifiedNameId *q = function->name()->asQualifiedNameId()) { Name *nestedNameSpec = 0; if (q->nameCount() == 1 && q->isGlobal()) nestedNameSpec = q->nameAt(0); else nestedNameSpec = control()->qualifiedNameId(q->names(), q->nameCount() - 1, q->isGlobal()); const QList<Symbol *> candidates = resolveClassOrNamespace(nestedNameSpec, visibleScopes); for (int j = 0; j < candidates.size(); ++j) { expand(candidates.at(j)->asScopedSymbol()->members(), visibleScopes, expandedScopes); } } } void LookupContext::expand(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { if (expandedScopes->contains(scope)) return; expandedScopes->append(scope); if (scope->isNamespaceScope()) { expandNamespace(scope, visibleScopes, expandedScopes); } else if (scope->isClassScope()) { expandClass(scope, visibleScopes, expandedScopes); } else if (scope->isBlockScope()) { expandBlock(scope, visibleScopes, expandedScopes); } else if (scope->isFunctionScope()) { expandFunction(scope, visibleScopes, expandedScopes); } else if (scope->isPrototypeScope()) { //qDebug() << "prototype scope" << overview.prettyName(scope->owner()->name()); } } <commit_msg>Fixed crash in lookup context due to null-name<commit_after>/*************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** ** Non-Open Source Usage ** ** Licensees may use this file in accordance with the Qt Beta Version ** License Agreement, Agreement version 2.2 provided with the Software or, ** alternatively, in accordance with the terms contained in a written ** agreement between you and Nokia. ** ** GNU General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU General ** Public License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the packaging ** of this file. Please review the following information to ensure GNU ** General Public Licensing requirements will be met: ** ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt GPL Exception ** version 1.3, included in the file GPL_EXCEPTION.txt in this package. ** ***************************************************************************/ #include "LookupContext.h" #include "ResolveExpression.h" #include "Overview.h" #include <CoreTypes.h> #include <Symbols.h> #include <Literals.h> #include <Names.h> #include <Scope.h> #include <Control.h> #include <QtDebug> using namespace CPlusPlus; bool LookupContext::isNameCompatibleWithIdentifier(Name *name, Identifier *id) { if (! name) { return false; } else if (NameId *nameId = name->asNameId()) { Identifier *identifier = nameId->identifier(); return identifier->isEqualTo(id); } else if (DestructorNameId *nameId = name->asDestructorNameId()) { Identifier *identifier = nameId->identifier(); return identifier->isEqualTo(id); } else if (TemplateNameId *templNameId = name->asTemplateNameId()) { Identifier *identifier = templNameId->identifier(); return identifier->isEqualTo(id); } return false; } ///////////////////////////////////////////////////////////////////// // LookupContext ///////////////////////////////////////////////////////////////////// LookupContext::LookupContext(Control *control) : _control(control), _symbol(0) { } LookupContext::LookupContext(Symbol *symbol, Document::Ptr expressionDocument, Document::Ptr thisDocument, const Snapshot &documents) : _symbol(symbol), _expressionDocument(expressionDocument), _thisDocument(thisDocument), _documents(documents) { _control = _expressionDocument->control(); _visibleScopes = buildVisibleScopes(); } LookupContext::LookupContext(Symbol *symbol, const LookupContext &context) : _control(context._control), _symbol(symbol), _expressionDocument(context._expressionDocument), _documents(context._documents) { const QString fn = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength()); _thisDocument = _documents.value(fn); _visibleScopes = buildVisibleScopes(); } LookupContext::LookupContext(Symbol *symbol, Document::Ptr thisDocument, const LookupContext &context) : _control(context._control), _symbol(symbol), _expressionDocument(context._expressionDocument), _thisDocument(thisDocument), _documents(context._documents) { _visibleScopes = buildVisibleScopes(); } bool LookupContext::isValid() const { return _control != 0; } LookupContext::operator bool() const { return _control != 0; } Control *LookupContext::control() const { return _control; } Symbol *LookupContext::symbol() const { return _symbol; } Document::Ptr LookupContext::expressionDocument() const { return _expressionDocument; } Document::Ptr LookupContext::thisDocument() const { return _thisDocument; } Document::Ptr LookupContext::document(const QString &fileName) const { return _documents.value(fileName); } Identifier *LookupContext::identifier(Name *name) const { if (NameId *nameId = name->asNameId()) return nameId->identifier(); else if (TemplateNameId *templId = name->asTemplateNameId()) return templId->identifier(); else if (DestructorNameId *dtorId = name->asDestructorNameId()) return dtorId->identifier(); else if (QualifiedNameId *q = name->asQualifiedNameId()) return identifier(q->unqualifiedNameId()); return 0; } bool LookupContext::maybeValidSymbol(Symbol *symbol, ResolveMode mode, const QList<Symbol *> &candidates) { if (((mode & ResolveNamespace) && symbol->isNamespace()) || ((mode & ResolveClass) && symbol->isClass()) || (mode & ResolveSymbol)) { return ! candidates.contains(symbol); } return false; } QList<Symbol *> LookupContext::resolve(Name *name, const QList<Scope *> &visibleScopes, ResolveMode mode) const { QList<Symbol *> candidates; if (!name) return candidates; if (QualifiedNameId *q = name->asQualifiedNameId()) { QList<Scope *> scopes = visibleScopes; for (unsigned i = 0; i < q->nameCount(); ++i) { Name *name = q->nameAt(i); if (i + 1 == q->nameCount()) candidates = resolve(name, scopes, mode); else candidates = resolveClassOrNamespace(name, scopes); if (candidates.isEmpty() || i + 1 == q->nameCount()) break; scopes.clear(); foreach (Symbol *candidate, candidates) { if (ScopedSymbol *scoped = candidate->asScopedSymbol()) { expand(scoped->members(), visibleScopes, &scopes); } } } Identifier *id = identifier(name); foreach (Scope *scope, visibleScopes) { Symbol *symbol = scope->lookat(id); for (; symbol; symbol = symbol->next()) { if (! symbol->name()) continue; else if (! maybeValidSymbol(symbol, mode, candidates)) continue; QualifiedNameId *qq = symbol->name()->asQualifiedNameId(); if (! qq) continue; if (q->nameCount() > qq->nameCount()) continue; for (int i = q->nameCount() - 1; i != -1; --i) { Name *a = q->nameAt(i); Name *b = qq->nameAt(i); if (! a->isEqualTo(b)) break; else if (i == 0) candidates.append(symbol); } } } return candidates; } if (Identifier *id = identifier(name)) { for (int scopeIndex = 0; scopeIndex < visibleScopes.size(); ++scopeIndex) { Scope *scope = visibleScopes.at(scopeIndex); for (Symbol *symbol = scope->lookat(id); symbol; symbol = symbol->next()) { if (! symbol->name()) { continue; } else if (! maybeValidSymbol(symbol, mode, candidates)) { continue; } else if (QualifiedNameId *q = symbol->name()->asQualifiedNameId()) { if (! q->unqualifiedNameId()->isEqualTo(name)) continue; if (q->nameCount() > 1) { Name *classOrNamespaceName = control()->qualifiedNameId(q->names(), q->nameCount() - 1); const QList<Symbol *> resolvedClassOrNamespace = resolveClassOrNamespace(classOrNamespaceName, visibleScopes); bool good = false; foreach (Symbol *classOrNamespace, resolvedClassOrNamespace) { ScopedSymbol *scoped = classOrNamespace->asScopedSymbol(); if (visibleScopes.contains(scoped->members())) { good = true; break; } } if (! good) continue; } } else if (! isNameCompatibleWithIdentifier(symbol->name(), id)) { continue; } else if (symbol->name()->isDestructorNameId() != name->isDestructorNameId()) { continue; } candidates.append(symbol); } } } else if (OperatorNameId *opId = name->asOperatorNameId()) { for (int scopeIndex = 0; scopeIndex < visibleScopes.size(); ++scopeIndex) { Scope *scope = visibleScopes.at(scopeIndex); for (Symbol *symbol = scope->lookat(opId->kind()); symbol; symbol = symbol->next()) { if (! opId->isEqualTo(symbol->name())) continue; else if (! candidates.contains(symbol)) candidates.append(symbol); } } } return candidates; } QList<Scope *> LookupContext::buildVisibleScopes() { QList<Scope *> scopes; if (_symbol) { for (Scope *scope = _symbol->scope(); scope; scope = scope->enclosingScope()) { scopes.append(scope); } } QSet<QString> processed; processed.insert(_thisDocument->fileName()); QList<QString> todo = _thisDocument->includedFiles(); while (! todo.isEmpty()) { QString fn = todo.last(); todo.removeLast(); if (processed.contains(fn)) continue; processed.insert(fn); if (Document::Ptr doc = document(fn)) { scopes.append(doc->globalNamespace()->members()); todo += doc->includedFiles(); } } while (true) { QList<Scope *> expandedScopes; expand(scopes, &expandedScopes); if (expandedScopes.size() == scopes.size()) return expandedScopes; scopes = expandedScopes; } return scopes; } QList<Scope *> LookupContext::visibleScopes(const QPair<FullySpecifiedType, Symbol *> &result) const { Symbol *symbol = result.second; QList<Scope *> scopes; for (Scope *scope = symbol->scope(); scope; scope = scope->enclosingScope()) scopes.append(scope); scopes += visibleScopes(); scopes = expand(scopes); return scopes; } QList<Scope *> LookupContext::expand(const QList<Scope *> &scopes) const { QList<Scope *> expanded; expand(scopes, &expanded); return expanded; } void LookupContext::expand(const QList<Scope *> &scopes, QList<Scope *> *expandedScopes) const { for (int i = 0; i < scopes.size(); ++i) { expand(scopes.at(i), scopes, expandedScopes); } } void LookupContext::expandNamespace(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { Namespace *ns = scope->owner()->asNamespace(); if (! ns) return; if (Name *nsName = ns->name()) { const QList<Symbol *> namespaceList = resolveNamespace(nsName, visibleScopes); foreach (Symbol *otherNs, namespaceList) { if (otherNs == ns) continue; expand(otherNs->asNamespace()->members(), visibleScopes, expandedScopes); } } for (unsigned i = 0; i < scope->symbolCount(); ++i) { // ### make me fast Symbol *symbol = scope->symbolAt(i); if (Namespace *ns = symbol->asNamespace()) { if (! ns->name()) { expand(ns->members(), visibleScopes, expandedScopes); } } else if (UsingNamespaceDirective *u = symbol->asUsingNamespaceDirective()) { const QList<Symbol *> candidates = resolveNamespace(u->name(), visibleScopes); for (int j = 0; j < candidates.size(); ++j) { expand(candidates.at(j)->asNamespace()->members(), visibleScopes, expandedScopes); } } else if (Enum *e = symbol->asEnum()) { expand(e->members(), visibleScopes, expandedScopes); } } } void LookupContext::expandClass(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { Class *klass = scope->owner()->asClass(); if (! klass) return; for (unsigned i = 0; i < scope->symbolCount(); ++i) { Symbol *symbol = scope->symbolAt(i); if (Class *nestedClass = symbol->asClass()) { if (! nestedClass->name()) { expand(nestedClass->members(), visibleScopes, expandedScopes); } } else if (Enum *e = symbol->asEnum()) { expand(e->members(), visibleScopes, expandedScopes); } } if (klass->baseClassCount()) { QList<Scope *> classVisibleScopes = visibleScopes; for (Scope *scope = klass->scope(); scope; scope = scope->enclosingScope()) { if (scope->isNamespaceScope()) { Namespace *enclosingNamespace = scope->owner()->asNamespace(); if (enclosingNamespace->name()) { const QList<Symbol *> nsList = resolveNamespace(enclosingNamespace->name(), visibleScopes); foreach (Symbol *ns, nsList) { expand(ns->asNamespace()->members(), classVisibleScopes, &classVisibleScopes); } } } } for (unsigned i = 0; i < klass->baseClassCount(); ++i) { BaseClass *baseClass = klass->baseClassAt(i); Name *baseClassName = baseClass->name(); const QList<Symbol *> baseClassCandidates = resolveClass(baseClassName, classVisibleScopes); if (baseClassCandidates.isEmpty()) { Overview overview; qDebug() << "unresolved base class:" << overview.prettyName(baseClassName); } for (int j = 0; j < baseClassCandidates.size(); ++j) { if (Class *baseClassSymbol = baseClassCandidates.at(j)->asClass()) expand(baseClassSymbol->members(), visibleScopes, expandedScopes); } } } } void LookupContext::expandBlock(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { for (unsigned i = 0; i < scope->symbolCount(); ++i) { Symbol *symbol = scope->symbolAt(i); if (UsingNamespaceDirective *u = symbol->asUsingNamespaceDirective()) { const QList<Symbol *> candidates = resolveNamespace(u->name(), visibleScopes); for (int j = 0; j < candidates.size(); ++j) { expand(candidates.at(j)->asNamespace()->members(), visibleScopes, expandedScopes); } } } } void LookupContext::expandFunction(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { Function *function = scope->owner()->asFunction(); if (! expandedScopes->contains(function->arguments())) expandedScopes->append(function->arguments()); if (QualifiedNameId *q = function->name()->asQualifiedNameId()) { Name *nestedNameSpec = 0; if (q->nameCount() == 1 && q->isGlobal()) nestedNameSpec = q->nameAt(0); else nestedNameSpec = control()->qualifiedNameId(q->names(), q->nameCount() - 1, q->isGlobal()); const QList<Symbol *> candidates = resolveClassOrNamespace(nestedNameSpec, visibleScopes); for (int j = 0; j < candidates.size(); ++j) { expand(candidates.at(j)->asScopedSymbol()->members(), visibleScopes, expandedScopes); } } } void LookupContext::expand(Scope *scope, const QList<Scope *> &visibleScopes, QList<Scope *> *expandedScopes) const { if (expandedScopes->contains(scope)) return; expandedScopes->append(scope); if (scope->isNamespaceScope()) { expandNamespace(scope, visibleScopes, expandedScopes); } else if (scope->isClassScope()) { expandClass(scope, visibleScopes, expandedScopes); } else if (scope->isBlockScope()) { expandBlock(scope, visibleScopes, expandedScopes); } else if (scope->isFunctionScope()) { expandFunction(scope, visibleScopes, expandedScopes); } else if (scope->isPrototypeScope()) { //qDebug() << "prototype scope" << overview.prettyName(scope->owner()->name()); } } <|endoftext|>
<commit_before>#include <okui/applications/Native.h> #include <okui/applications/SDL.h> #include <okui/StateMachine.h> class Application : public okui::applications::Native<okui::applications::SDL> { public: virtual std::string name() const override { return "StateMachine Example"; } virtual std::string organization() const override { return "BitTorrent Inc."; } }; struct State { double x, y, opacity; constexpr auto members() { return std::tie(x, y, opacity); } }; class View : public okui::View, public okui::StateMachine<State> { public: View() : okui::StateMachine<State>("Above") { addUpdateHook("StateMachine", [&]{ drive(); }); setTransition("Above", "Normal", 200ms, okui::interpolation::Quadratic::EaseOut); setTransition("Normal", "Left", 200ms, okui::interpolation::Quadratic::EaseIn); } private: virtual void update(stdts::string_view id, State& state, bool& isAnimated) override { state.opacity = id == "Normal" ? 1.0 : 0.0; state.x = id == "Left" ? -100.0 : 300.0; state.y = id == "Above" ? -100.0 : 300.0; } virtual void apply(const State& state) override { setOpacity(state.opacity); setBounds(state.x, state.y, 100.0, 100.0); } }; int main() { Application application; okui::Window window{&application}; window.open(); View view; view.setBackgroundColor(okui::Color::kBlue); window.contentView()->addSubview(&view); view.asyncAfter(2s, [&] { view.setState("Normal"); }); view.asyncAfter(4s, [&] { view.setState("Left"); }); application.run(); return 0; } <commit_msg>add final specifier to quiet analysis<commit_after>#include <okui/applications/Native.h> #include <okui/applications/SDL.h> #include <okui/StateMachine.h> class Application : public okui::applications::Native<okui::applications::SDL> { public: virtual std::string name() const override { return "StateMachine Example"; } virtual std::string organization() const override { return "BitTorrent Inc."; } }; struct State { double x, y, opacity; constexpr auto members() { return std::tie(x, y, opacity); } }; class View final : public okui::View, public okui::StateMachine<State> { public: View() : okui::StateMachine<State>("Above") { addUpdateHook("StateMachine", [&]{ drive(); }); setTransition("Above", "Normal", 200ms, okui::interpolation::Quadratic::EaseOut); setTransition("Normal", "Left", 200ms, okui::interpolation::Quadratic::EaseIn); } private: virtual void update(stdts::string_view id, State& state, bool& isAnimated) override { state.opacity = id == "Normal" ? 1.0 : 0.0; state.x = id == "Left" ? -100.0 : 300.0; state.y = id == "Above" ? -100.0 : 300.0; } virtual void apply(const State& state) override { setOpacity(state.opacity); setBounds(state.x, state.y, 100.0, 100.0); } }; int main() { Application application; okui::Window window{&application}; window.open(); View view; view.setBackgroundColor(okui::Color::kBlue); window.contentView()->addSubview(&view); view.asyncAfter(2s, [&] { view.setState("Normal"); }); view.asyncAfter(4s, [&] { view.setState("Left"); }); application.run(); return 0; } <|endoftext|>
<commit_before>/* Generic Console Output Support Copyright (C) 1998-2001 by Jorrit Tyberghein Copyright (c) 2004-2005 by Frank Richter This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include <stdio.h> #include "cssysdef.h" #include "csutil/ansiparse.h" #include "csutil/csstring.h" #include "csutil/csuctransform.h" #include "csutil/sysfunc.h" // Replacement for printf(); exact same prototype/functionality as printf() int csPrintf (char const* str, ...) { va_list args; va_start (args, str); int const rc = csPrintfV (str, args); va_end (args); return rc; } static int cs_fputsn (FILE* file, const char* str, size_t len) { size_t wstrSize = len + 1; CS_ALLOC_STACK_ARRAY(wchar_t, wstr, wstrSize); csUnicodeTransform::UTF8toWC (wstr, wstrSize, (utf8_char*)str, len); int n = 0; const wchar_t* wcsPtr = wstr; #if defined(CS_HAVE_FPUTWS) && defined(CS_HAVE_FWIDE) \ && defined(CS_HAVE_WCSRTOMBS) if (fwide (file, 0) > 0) { return fputws (wstr, file); } else { mbstate_t mbs; memset (&mbs, 0, sizeof (mbs)); char mbstr[64]; size_t mbslen; while (wcsPtr != 0) { memset (mbstr, 0, sizeof (mbstr)); mbslen = wcsrtombs (mbstr, &wcsPtr, sizeof (mbstr) - 1, &mbs); if (mbslen == (size_t)-1) { if (errno == EILSEQ) { // Catch char that couldn't be encoded, print ? instead if (fputs (mbstr, file) == EOF) return EOF; if (fputc ('?', file) == EOF) return EOF; if (CS_UC_IS_HIGH_SURROGATE (*wcsPtr)) { wcsPtr++; if (CS_UC_IS_LOW_SURROGATE (*wcsPtr)) wcsPtr++; } else wcsPtr++; continue; } break; } if (fputs (mbstr, file) == EOF) return EOF; } if (wcsPtr == 0) return (int)len; } #endif // Use a cheap Wide-to-ASCII conversion. const wchar_t* ch = wcsPtr; while (len-- > 0) { if (*ch < 0x80) { if (fputc ((char)*ch, file) == EOF) return EOF; n++; } else { if (fputc ('?', file) == EOF) return EOF; n++; } ch++; } return n; } static int csFPutStr (FILE* file, const char* str) { bool isTTY = isatty (fileno (file)); int ret = 0; size_t ansiCommandLen; csAnsiParser::CommandClass cmdClass; size_t textLen; // Check for ANSI codes while (csAnsiParser::ParseAnsi (str, ansiCommandLen, cmdClass, textLen)) { int rc; if (isTTY && (cmdClass == csAnsiParser::classFormat)) { // Only let formatting codes through rc = cs_fputsn (file, str, ansiCommandLen); if (rc == EOF) return EOF; ret += rc; } if (textLen > 0) { rc = cs_fputsn (file, str + ansiCommandLen, textLen); if (rc == EOF) return EOF; ret += rc; } str += ansiCommandLen + textLen; } return ret; } // Replacement for vprintf() int csPrintfV(char const* str, va_list args) { csString temp; temp.FormatV (str, args); return csFPutStr (stdout, temp); } int csFPrintf (FILE* file, const char* str, ...) { va_list args; va_start (args, str); int const rc = csFPrintfV (file, str, args); va_end (args); return rc; } int csFPrintfV (FILE* file, const char* str, va_list args) { csString temp; temp.FormatV (str, args); return csFPutStr (file, temp); } int csPrintfErrV (const char* str, va_list arg) { int rc = csFPrintfV (stderr, str, arg); fflush (stderr); return rc; } int csPrintfErr (const char* str, ...) { va_list args; va_start (args, str); int const rc = csFPrintfV (stderr, str, args); va_end (args); return rc; } <commit_msg>res made some tweaks to the lighter2 TUI to better work on Linux. res fixed the lighter2 tui and Win32 ANSI support for the fact that cursor positions are 1-based, not 0-based.<commit_after>/* Generic Console Output Support Copyright (C) 1998-2001 by Jorrit Tyberghein Copyright (c) 2004-2005 by Frank Richter This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include <stdio.h> #include "cssysdef.h" #include "csutil/ansiparse.h" #include "csutil/csstring.h" #include "csutil/csuctransform.h" #include "csutil/sysfunc.h" // Replacement for printf(); exact same prototype/functionality as printf() int csPrintf (char const* str, ...) { va_list args; va_start (args, str); int const rc = csPrintfV (str, args); va_end (args); return rc; } static int cs_fputsn (FILE* file, const char* str, size_t len) { size_t wstrSize = len + 1; CS_ALLOC_STACK_ARRAY(wchar_t, wstr, wstrSize); csUnicodeTransform::UTF8toWC (wstr, wstrSize, (utf8_char*)str, len); int n = 0; const wchar_t* wcsPtr = wstr; #if defined(CS_HAVE_FPUTWS) && defined(CS_HAVE_FWIDE) \ && defined(CS_HAVE_WCSRTOMBS) if (fwide (file, 0) > 0) { return fputws (wstr, file); } else { mbstate_t mbs; memset (&mbs, 0, sizeof (mbs)); char mbstr[64]; size_t mbslen; while (wcsPtr != 0) { memset (mbstr, 0, sizeof (mbstr)); mbslen = wcsrtombs (mbstr, &wcsPtr, sizeof (mbstr) - 1, &mbs); if (mbslen == (size_t)-1) { if (errno == EILSEQ) { // Catch char that couldn't be encoded, print ? instead if (fputs (mbstr, file) == EOF) return EOF; if (fputc ('?', file) == EOF) return EOF; if (CS_UC_IS_HIGH_SURROGATE (*wcsPtr)) { wcsPtr++; if (CS_UC_IS_LOW_SURROGATE (*wcsPtr)) wcsPtr++; } else wcsPtr++; continue; } break; } if (fputs (mbstr, file) == EOF) return EOF; } if (wcsPtr == 0) return (int)len; } #endif // Use a cheap Wide-to-ASCII conversion. const wchar_t* ch = wcsPtr; while (len-- > 0) { if (*ch < 0x80) { if (fputc ((char)*ch, file) == EOF) return EOF; n++; } else { if (fputc ('?', file) == EOF) return EOF; n++; } ch++; } return n; } static int csFPutStr (FILE* file, const char* str) { bool isTTY = isatty (fileno (file)); int ret = 0; size_t ansiCommandLen; csAnsiParser::CommandClass cmdClass; size_t textLen; // Check for ANSI codes while (csAnsiParser::ParseAnsi (str, ansiCommandLen, cmdClass, textLen)) { int rc; if (isTTY && (cmdClass != csAnsiParser::classNone) && (cmdClass != csAnsiParser::classUnknown)) { // Only let known codes through rc = cs_fputsn (file, str, ansiCommandLen); if (rc == EOF) return EOF; ret += rc; } if (textLen > 0) { rc = cs_fputsn (file, str + ansiCommandLen, textLen); if (rc == EOF) return EOF; ret += rc; } str += ansiCommandLen + textLen; } return ret; } // Replacement for vprintf() int csPrintfV(char const* str, va_list args) { csString temp; temp.FormatV (str, args); return csFPutStr (stdout, temp); } int csFPrintf (FILE* file, const char* str, ...) { va_list args; va_start (args, str); int const rc = csFPrintfV (file, str, args); va_end (args); return rc; } int csFPrintfV (FILE* file, const char* str, va_list args) { csString temp; temp.FormatV (str, args); return csFPutStr (file, temp); } int csPrintfErrV (const char* str, va_list arg) { int rc = csFPrintfV (stderr, str, arg); fflush (stderr); return rc; } int csPrintfErr (const char* str, ...) { va_list args; va_start (args, str); int const rc = csFPrintfV (stderr, str, args); va_end (args); return rc; } <|endoftext|>
<commit_before>// // Copyright (c) 2017 Kimball Thurston // All rights reserved. // Copyrights licensed under the MIT License. // See the accompanying LICENSE.txt file for terms // #if defined(HAVE_PYTHON2) || defined(HAVE_PYTHON3) # define HAVE_PYTHON 1 #endif #ifdef HAVE_PYTHON #pragma GCC diagnostic ignored "-Wreserved-id-macro" #pragma GCC diagnostic ignored "-Wold-style-cast" #include <Python.h> #endif #if PY_MAJOR_VERSION <= 1 #error python 2 or higher is required #else # if PY_MAJOR_VERSION < 3 # define IS_PYTHON2 1 # elif PY_MAJOR_VERSION < 4 # define IS_PYTHON3 1 # endif #endif #include "context.h" #include <stdexcept> #include <atomic> #include <map> //////////////////////////////////////// namespace python_bridge { #ifdef HAVE_PYTHON static std::atomic_flag _active_context = ATOMIC_FLAG_INIT; class context::priv_Impl { public: priv_Impl( const std::string &argv0 ) { if ( _active_context.test_and_set( std::memory_order_acquire ) ) throw std::runtime_error( "Current version of python does not allow multiple active contexts at once" ); #ifdef IS_PYTHON2 _progname = strdup( argv0.c_str() ); #else _progname = Py_DecodeLocale( argv0.c_str(), nullptr ); if ( ! _progname ) throw std::runtime_error( "Unable to decode argv[0]" ); #endif Py_SetProgramName( _progname ); Py_Initialize(); } ~priv_Impl( void ) { #ifdef IS_PYTHON2 Py_Finalize(); if ( _progname ) ::free( _progname ); #else if ( Py_FinalizeEx() < 0 ) std::cerr << "ERROR shutting down python interpreter" << std::endl; if ( _progname ) PyMem_RawFree( _progname ); #endif _active_context.clear( std::memory_order_release ); } bool load_module( const char *fn, const std::string &tag ) { auto i = _glob_modules.find( tag ); if ( i != _glob_modules.end() ) Py_DECREF( i->second ); #ifdef IS_PYTHON2 PyObject *pName = PyString_FromString( fn ); #else PyObject *pName = PyUnicode_DecodeFSDefault( fn ); #endif // TODO: add error checks PyObject *pModule = PyImport_Import( pName ); Py_DECREF( pName ); if ( pModule ) { _glob_modules[tag] = pModule; return true; } return false; } private: #ifdef IS_PYTHON2 char *_progname = nullptr; #else wchar_t *_progname = nullptr; #endif std::map<std::string, PyObject *> _glob_modules; }; #endif //////////////////////////////////////// context::context( const std::string &argv0 ) #ifdef HAVE_PYTHON : _impl( new priv_Impl( argv0 ) ) #endif { } //////////////////////////////////////// context::~context( void ) { } //////////////////////////////////////// bool context::run( const std::string &fn ) { #ifdef HAVE_PYTHON return _impl->load_module( fn.c_str(), fn ); #else return false; #endif } //////////////////////////////////////// bool context::run( const base::uri &u ) { #ifdef HAVE_PYTHON throw std::logic_error( "Not Yet Implemented" ); #else return false; #endif } //////////////////////////////////////// void context::push_eval_lookup( lookup &l ) { #ifdef HAVE_PYTHON #endif } //////////////////////////////////////// void context::pop_eval_lookup( void ) { #ifdef HAVE_PYTHON #endif } //////////////////////////////////////// bool context::evaluate( bool &result, const char *s ) { #ifdef HAVE_PYTHON #else return false; #endif } //////////////////////////////////////// bool context::evaluate( int &result, const char *s ) { #ifdef HAVE_PYTHON #else return false; #endif } //////////////////////////////////////// bool context::evaluate( float &result, const char *s ) { #ifdef HAVE_PYTHON #else return false; #endif } //////////////////////////////////////// bool context::evaluate( double &result, const char *s ) { #ifdef HAVE_PYTHON #else return false; #endif } //////////////////////////////////////// bool context::evaluate( int64_t &result, const char *s ) { #ifdef HAVE_PYTHON #else return false; #endif } //////////////////////////////////////// bool context::evaluate( std::string &result, const char *s ) { #ifdef HAVE_PYTHON #else return false; #endif } //////////////////////////////////////// bool context::evaluate( std::wstring &result, const char *s ) { #ifdef HAVE_PYTHON #else return false; #endif } //////////////////////////////////////// } // namespace python_bridge <commit_msg>fix includes for prototype<commit_after>// // Copyright (c) 2017 Kimball Thurston // All rights reserved. // Copyrights licensed under the MIT License. // See the accompanying LICENSE.txt file for terms // #if defined(HAVE_PYTHON2) || defined(HAVE_PYTHON3) # define HAVE_PYTHON 1 #endif #ifdef HAVE_PYTHON # if defined(__clang__) # pragma GCC diagnostic ignored "-Wreserved-id-macro" # pragma GCC diagnostic ignored "-Wold-style-cast" # endif # include <Python.h> # if PY_MAJOR_VERSION <= 1 # error python 2 or higher is required # else # if PY_MAJOR_VERSION < 3 # define IS_PYTHON2 1 # elif PY_MAJOR_VERSION < 4 # define IS_PYTHON3 1 # endif # endif #endif #include "context.h" #include <stdexcept> #include <atomic> #include <map> //////////////////////////////////////// namespace python_bridge { #ifdef HAVE_PYTHON static std::atomic_flag _active_context = ATOMIC_FLAG_INIT; class context::priv_Impl { public: priv_Impl( const std::string &argv0 ) { if ( _active_context.test_and_set( std::memory_order_acquire ) ) throw std::runtime_error( "Current version of python does not allow multiple active contexts at once" ); #ifdef IS_PYTHON2 _progname = strdup( argv0.c_str() ); #else _progname = Py_DecodeLocale( argv0.c_str(), nullptr ); if ( ! _progname ) throw std::runtime_error( "Unable to decode argv[0]" ); #endif Py_SetProgramName( _progname ); Py_Initialize(); } ~priv_Impl( void ) { #ifdef IS_PYTHON2 Py_Finalize(); if ( _progname ) ::free( _progname ); #else if ( Py_FinalizeEx() < 0 ) std::cerr << "ERROR shutting down python interpreter" << std::endl; if ( _progname ) PyMem_RawFree( _progname ); #endif _active_context.clear( std::memory_order_release ); } bool load_module( const char *fn, const std::string &tag ) { auto i = _glob_modules.find( tag ); if ( i != _glob_modules.end() ) Py_DECREF( i->second ); #ifdef IS_PYTHON2 PyObject *pName = PyString_FromString( fn ); #else PyObject *pName = PyUnicode_DecodeFSDefault( fn ); #endif // TODO: add error checks PyObject *pModule = PyImport_Import( pName ); Py_DECREF( pName ); if ( pModule ) { _glob_modules[tag] = pModule; return true; } return false; } private: #ifdef IS_PYTHON2 char *_progname = nullptr; #else wchar_t *_progname = nullptr; #endif std::map<std::string, PyObject *> _glob_modules; }; #endif //////////////////////////////////////// context::context( const std::string &argv0 ) #ifdef HAVE_PYTHON : _impl( new priv_Impl( argv0 ) ) #endif { } //////////////////////////////////////// context::~context( void ) { } //////////////////////////////////////// bool context::run( const std::string &fn ) { #ifdef HAVE_PYTHON return _impl->load_module( fn.c_str(), fn ); #else return false; #endif } //////////////////////////////////////// bool context::run( const base::uri &u ) { #ifdef HAVE_PYTHON throw std::logic_error( "Not Yet Implemented" ); #else return false; #endif } //////////////////////////////////////// void context::push_eval_lookup( lookup &l ) { #ifdef HAVE_PYTHON #endif } //////////////////////////////////////// void context::pop_eval_lookup( void ) { #ifdef HAVE_PYTHON #endif } //////////////////////////////////////// bool context::evaluate( bool &result, const char *s ) { #ifdef HAVE_PYTHON return true; #else return false; #endif } //////////////////////////////////////// bool context::evaluate( int &result, const char *s ) { #ifdef HAVE_PYTHON return true; #else return false; #endif } //////////////////////////////////////// bool context::evaluate( float &result, const char *s ) { #ifdef HAVE_PYTHON return true; #else return false; #endif } //////////////////////////////////////// bool context::evaluate( double &result, const char *s ) { #ifdef HAVE_PYTHON return true; #else return false; #endif } //////////////////////////////////////// bool context::evaluate( int64_t &result, const char *s ) { #ifdef HAVE_PYTHON return true; #else return false; #endif } //////////////////////////////////////// bool context::evaluate( std::string &result, const char *s ) { #ifdef HAVE_PYTHON return true; #else return false; #endif } //////////////////////////////////////// bool context::evaluate( std::wstring &result, const char *s ) { #ifdef HAVE_PYTHON return true; #else return false; #endif } //////////////////////////////////////// } // namespace python_bridge <|endoftext|>
<commit_before>#include "ui/socket_item.h" #include <QApplication> #include <QCursor> #include <QDebug> #include <QDrag> #include <QGraphicsSceneMouseEvent> #include <QGraphicsWidget> #include <QMimeData> #include <QWidget> #include "elements/package.h" #include "ui/colors.h" #include "ui/link_item.h" #include "ui/package_view.h" SocketItem::SocketItem(Type a_type, QGraphicsItem *const a_parent) : QGraphicsItem{ a_parent } , m_type{ a_type } { m_font.setFamily("Consolas"); m_font.setPointSize(12); setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemSendsScenePositionChanges); setAcceptHoverEvents(true); setAcceptedMouseButtons(Qt::LeftButton); setZValue(1); if (a_type == Type::eOutput) setCursor(Qt::OpenHandCursor); else setAcceptDrops(true); } QRectF SocketItem::boundingRect() const { return QRectF{ -(static_cast<qreal>(SIZE) / 2.), 0, static_cast<qreal>(SIZE), static_cast<qreal>(SIZE) }; } void SocketItem::paint(QPainter *a_painter, const QStyleOptionGraphicsItem *a_option, QWidget *a_widget) { Q_UNUSED(a_option); Q_UNUSED(a_widget); QRectF const rect{ boundingRect() }; QPen pen{ get_color(Color::eSocketBorder) }; pen.setWidth(2); QBrush brush{}; if (m_isHover) brush.setColor(get_color(Color::eSocketHover)); else if (m_isDrop) brush.setColor(get_color(Color::eSocketDrop)); else if (m_isSignalOn) brush.setColor(m_colorSignalOn); else if (!m_isSignalOn) brush.setColor(m_colorSignalOff); // else if (m_type == Type::eInput) // brush.setColor(config.getColor(Config::Color::eSocketInput)); // else if (m_type == Type::eOutput) // brush.setColor(config.getColor(Config::Color::eSocketOutput)); brush.setStyle(Qt::SolidPattern); a_painter->setPen(pen); a_painter->setBrush(brush); a_painter->drawEllipse(rect); if (m_used) { a_painter->save(); a_painter->setPen(Qt::NoPen); a_painter->setBrush(pen.color()); a_painter->drawEllipse(rect.adjusted(4, 4, -4, -4)); a_painter->restore(); } if (!m_nameHidden) { pen.setColor(get_color(Color::eFontName)); a_painter->setPen(pen); QFont font{ a_painter->font() }; font.setPointSize(12); a_painter->setFont(font); QFontMetrics const metrics{ font }; if (m_type == Type::eInput) a_painter->drawText(static_cast<int>(rect.width()) - 2, 13, m_name); else a_painter->drawText(-metrics.width(m_name) - 14, 13, m_name); } } void SocketItem::hoverEnterEvent(QGraphicsSceneHoverEvent *a_event) { Q_UNUSED(a_event); m_isHover = true; for (auto const link : m_links) link->setHover(m_isHover); } void SocketItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *a_event) { Q_UNUSED(a_event); m_isHover = false; for (auto const link : m_links) link->setHover(m_isHover); } void SocketItem::dragEnterEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); if (m_used) { a_event->ignore(); return; } PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ view->dragLink() }; if (!linkItem || m_valueType != linkItem->valueType()) { a_event->ignore(); return; } linkItem->setTo(this); m_isDrop = true; } void SocketItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); m_isDrop = false; PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ view->dragLink() }; if (!linkItem) return; linkItem->setTo(nullptr); } void SocketItem::dragMoveEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); } void SocketItem::dropEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); PackageView *const packageView{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ packageView->dragLink() }; if (!linkItem) return; m_links.push_back(linkItem); linkItem->setTo(this); m_used = true; m_isDrop = false; packageView->acceptDragLink(); auto const package = packageView->package(); auto const from = linkItem->from(); package->connect(from->elementId(), from->socketId(), m_elementId, m_socketId); } void SocketItem::mousePressEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; setCursor(Qt::ClosedHandCursor); } void SocketItem::mouseMoveEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; if (QLineF(a_event->screenPos(), a_event->buttonDownScreenPos(Qt::LeftButton)).length() < QApplication::startDragDistance()) return; // QRectF const rect{ boundingRect() }; QDrag *const drag = new QDrag(a_event->widget()); QMimeData *const mime = new QMimeData; // mime->setData("data/x-element", QByteArray()); drag->setMimeData(mime); LinkItem *linkItem{ new LinkItem }; linkItem->setColors(m_colorSignalOff, m_colorSignalOn); linkItem->setFrom(this); scene()->addItem(linkItem); PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; view->setDragLink(linkItem); Qt::DropAction const action{ drag->exec() }; if (action == Qt::IgnoreAction) view->cancelDragLink(); else { m_links.push_back(linkItem); m_used = true; } setCursor(Qt::OpenHandCursor); } void SocketItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; setCursor(Qt::OpenHandCursor); } QVariant SocketItem::itemChange(QGraphicsItem::GraphicsItemChange a_change, const QVariant &a_value) { if (a_change == QGraphicsItem::ItemScenePositionHasChanged) { for (LinkItem *const link : m_links) link->trackNodes(); } return QGraphicsItem::itemChange(a_change, a_value); } int SocketItem::nameWidth() const { QFontMetrics const metrics{ m_font }; return metrics.width(m_name); } void SocketItem::setColors(QColor const a_signalOff, QColor const a_signalOn) { m_colorSignalOff = a_signalOff; m_colorSignalOn = a_signalOn; } void SocketItem::setSignal(const bool a_signal) { m_isSignalOn = a_signal; if (m_type == Type::eOutput) { for (LinkItem *const link : m_links) link->setSignal(a_signal); } } void SocketItem::connect(SocketItem *const a_other) { auto const linkItem = new LinkItem; linkItem->setColors(m_colorSignalOff, m_colorSignalOn); linkItem->setFrom(this); linkItem->setTo(a_other); m_links.push_back(linkItem); m_used = true; a_other->m_links.push_back(linkItem); a_other->m_used = true; a_other->m_isDrop = false; scene()->addItem(linkItem); } <commit_msg>Call setSignal in SocketItem::dropEvent<commit_after>#include "ui/socket_item.h" #include <QApplication> #include <QCursor> #include <QDebug> #include <QDrag> #include <QGraphicsSceneMouseEvent> #include <QGraphicsWidget> #include <QMimeData> #include <QWidget> #include "elements/package.h" #include "ui/colors.h" #include "ui/link_item.h" #include "ui/package_view.h" SocketItem::SocketItem(Type a_type, QGraphicsItem *const a_parent) : QGraphicsItem{ a_parent } , m_type{ a_type } { m_font.setFamily("Consolas"); m_font.setPointSize(12); setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemSendsScenePositionChanges); setAcceptHoverEvents(true); setAcceptedMouseButtons(Qt::LeftButton); setZValue(1); if (a_type == Type::eOutput) setCursor(Qt::OpenHandCursor); else setAcceptDrops(true); } QRectF SocketItem::boundingRect() const { return QRectF{ -(static_cast<qreal>(SIZE) / 2.), 0, static_cast<qreal>(SIZE), static_cast<qreal>(SIZE) }; } void SocketItem::paint(QPainter *a_painter, const QStyleOptionGraphicsItem *a_option, QWidget *a_widget) { Q_UNUSED(a_option); Q_UNUSED(a_widget); QRectF const rect{ boundingRect() }; QPen pen{ get_color(Color::eSocketBorder) }; pen.setWidth(2); QBrush brush{}; if (m_isHover) brush.setColor(get_color(Color::eSocketHover)); else if (m_isDrop) brush.setColor(get_color(Color::eSocketDrop)); else if (m_isSignalOn) brush.setColor(m_colorSignalOn); else if (!m_isSignalOn) brush.setColor(m_colorSignalOff); // else if (m_type == Type::eInput) // brush.setColor(config.getColor(Config::Color::eSocketInput)); // else if (m_type == Type::eOutput) // brush.setColor(config.getColor(Config::Color::eSocketOutput)); brush.setStyle(Qt::SolidPattern); a_painter->setPen(pen); a_painter->setBrush(brush); a_painter->drawEllipse(rect); if (m_used) { a_painter->save(); a_painter->setPen(Qt::NoPen); a_painter->setBrush(pen.color()); a_painter->drawEllipse(rect.adjusted(4, 4, -4, -4)); a_painter->restore(); } if (!m_nameHidden) { pen.setColor(get_color(Color::eFontName)); a_painter->setPen(pen); QFont font{ a_painter->font() }; font.setPointSize(12); a_painter->setFont(font); QFontMetrics const metrics{ font }; if (m_type == Type::eInput) a_painter->drawText(static_cast<int>(rect.width()) - 2, 13, m_name); else a_painter->drawText(-metrics.width(m_name) - 14, 13, m_name); } } void SocketItem::hoverEnterEvent(QGraphicsSceneHoverEvent *a_event) { Q_UNUSED(a_event); m_isHover = true; for (auto const link : m_links) link->setHover(m_isHover); } void SocketItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *a_event) { Q_UNUSED(a_event); m_isHover = false; for (auto const link : m_links) link->setHover(m_isHover); } void SocketItem::dragEnterEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); if (m_used) { a_event->ignore(); return; } PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ view->dragLink() }; if (!linkItem || m_valueType != linkItem->valueType()) { a_event->ignore(); return; } linkItem->setTo(this); m_isDrop = true; } void SocketItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); m_isDrop = false; PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ view->dragLink() }; if (!linkItem) return; linkItem->setTo(nullptr); } void SocketItem::dragMoveEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); } void SocketItem::dropEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); PackageView *const packageView{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ packageView->dragLink() }; if (!linkItem) return; m_links.push_back(linkItem); linkItem->setTo(this); m_used = true; m_isDrop = false; packageView->acceptDragLink(); auto const package = packageView->package(); auto const from = linkItem->from(); package->connect(from->elementId(), from->socketId(), m_elementId, m_socketId); setSignal(linkItem->isSignalOn()); } void SocketItem::mousePressEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; setCursor(Qt::ClosedHandCursor); } void SocketItem::mouseMoveEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; if (QLineF(a_event->screenPos(), a_event->buttonDownScreenPos(Qt::LeftButton)).length() < QApplication::startDragDistance()) return; // QRectF const rect{ boundingRect() }; QDrag *const drag = new QDrag(a_event->widget()); QMimeData *const mime = new QMimeData; // mime->setData("data/x-element", QByteArray()); drag->setMimeData(mime); LinkItem *linkItem{ new LinkItem }; linkItem->setColors(m_colorSignalOff, m_colorSignalOn); linkItem->setFrom(this); scene()->addItem(linkItem); PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; view->setDragLink(linkItem); Qt::DropAction const action{ drag->exec() }; if (action == Qt::IgnoreAction) view->cancelDragLink(); else { m_links.push_back(linkItem); m_used = true; } setCursor(Qt::OpenHandCursor); } void SocketItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; setCursor(Qt::OpenHandCursor); } QVariant SocketItem::itemChange(QGraphicsItem::GraphicsItemChange a_change, const QVariant &a_value) { if (a_change == QGraphicsItem::ItemScenePositionHasChanged) { for (LinkItem *const link : m_links) link->trackNodes(); } return QGraphicsItem::itemChange(a_change, a_value); } int SocketItem::nameWidth() const { QFontMetrics const metrics{ m_font }; return metrics.width(m_name); } void SocketItem::setColors(QColor const a_signalOff, QColor const a_signalOn) { m_colorSignalOff = a_signalOff; m_colorSignalOn = a_signalOn; } void SocketItem::setSignal(const bool a_signal) { m_isSignalOn = a_signal; if (m_type == Type::eOutput) { for (LinkItem *const link : m_links) link->setSignal(a_signal); } } void SocketItem::connect(SocketItem *const a_other) { auto const linkItem = new LinkItem; linkItem->setColors(m_colorSignalOff, m_colorSignalOn); linkItem->setFrom(this); linkItem->setTo(a_other); m_links.push_back(linkItem); m_used = true; a_other->m_links.push_back(linkItem); a_other->m_used = true; a_other->m_isDrop = false; scene()->addItem(linkItem); } <|endoftext|>
<commit_before>#ifdef NG_PYTHON #include <boost/python.hpp> #include <boost/python/slice.hpp> #include <mystdlib.h> #include "meshing.hpp" using namespace netgen; namespace bp = boost::python; ////////////////////////////////////////////////////////////////////// // Lambda to function pointer conversion template <typename Function> struct function_traits : public function_traits<decltype(&Function::operator())> {}; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...) const> { typedef ReturnType (*pointer)(Args...); typedef ReturnType return_type; }; template <typename Function> typename function_traits<Function>::pointer FunctionPointer (const Function& lambda) { return static_cast<typename function_traits<Function>::pointer>(lambda); } template <class T> inline string ToString (const T& t) { stringstream ss; ss << t; return ss.str(); } template <typename T, int BASE = 0, typename TIND = int> void ExportArray () { string name = string("Array_") + typeid(T).name(); bp::class_<Array<T,BASE,TIND>,boost::noncopyable>(name.c_str()) .def ("__len__", &Array<T,BASE,TIND>::Size) .def ("__getitem__", FunctionPointer ([](Array<T,BASE,TIND> & self, TIND i) -> T& { if (i < BASE || i >= BASE+self.Size()) bp::exec("raise IndexError()\n"); return self[i]; }), bp::return_value_policy<bp::reference_existing_object>()) .def ("__iter__", bp::range (FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE]; }), FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE+self.Size()]; }))) ; } void ExportNetgenMeshing() { std::string nested_name = "meshing"; if( bp::scope() ) nested_name = bp::extract<std::string>(bp::scope().attr("__name__") + ".meshing"); bp::object module(bp::handle<>(bp::borrowed(PyImport_AddModule(nested_name.c_str())))); cout << "exporting meshing " << nested_name << endl; bp::object parent = bp::scope() ? bp::scope() : bp::import("__main__"); parent.attr("meshing") = module ; bp::scope local_scope(module); bp::class_<PointIndex>("PointId", bp::init<int>()) .def("__repr__", &ToString<PointIndex>) .def("__str__", &ToString<PointIndex>) .add_property("nr", &PointIndex::operator int) ; bp::class_<Point<3>> ("Point") .def(bp::init<double,double,double>()) ; bp::class_<MeshPoint,bp::bases<Point<3>>>("MeshPoint") .def(bp::init<Point<3>>()) .add_property("p", FunctionPointer([](const MeshPoint & self) { bp::list l; l.append ( (self)[0] ); l.append ( (self)[1] ); l.append ( (self)[2] ); return l; })) ; bp::class_<Element>("Element3D") .add_property("index", &Element::GetIndex, &Element::SetIndex) .add_property("vertices", FunctionPointer ([](const Element & self) -> bp::list { bp::list li; for (int i = 0; i < self.GetNV(); i++) li.append (self[i]); return li; })) ; ExportArray<Element>(); ExportArray<Element2d>(); ExportArray<MeshPoint,PointIndex::BASE,PointIndex>(); ; bp::class_<Mesh,shared_ptr<Mesh>,boost::noncopyable>("Mesh") .def("__str__", &ToString<Mesh>) .def("Load", static_cast<void(Mesh::*)(const string & name)>(&Mesh::Load)) .def("Save", static_cast<void(Mesh::*)(const string & name)const>(&Mesh::Save)) .def("Elements3D", static_cast<Array<Element>&(Mesh::*)()> (& &Mesh::VolumeElements), bp::return_value_policy<bp::reference_existing_object>()) .def("Elements2D", static_cast<Array<Element2d>&(Mesh::*)()> (& &Mesh::SurfaceElements), bp::return_value_policy<bp::reference_existing_object>()) .def("Points", static_cast<Mesh::T_POINTS&(Mesh::*)()> (& &Mesh::Points), bp::return_value_policy<bp::reference_existing_object>()) .def("__getitem__", FunctionPointer ([](const Mesh & self, PointIndex pi) { return self[pi]; })) .def ("Add", FunctionPointer ([](Mesh & self, MeshPoint p) { return self.AddPoint (Point3d(p)); })) ; typedef MeshingParameters MP; bp::class_<MP> ("MeshingParameters") .def("__str__", &ToString<MP>) .add_property("maxh", FunctionPointer ([](const MP & mp ) { return mp.maxh; }), FunctionPointer ([](MP & mp, double maxh) { return mp.maxh = maxh; })) ; } BOOST_PYTHON_MODULE(libmesh) { ExportNetgenMeshing(); } #endif <commit_msg>removed & &<commit_after>#ifdef NG_PYTHON #include <boost/python.hpp> #include <boost/python/slice.hpp> #include <mystdlib.h> #include "meshing.hpp" using namespace netgen; namespace bp = boost::python; ////////////////////////////////////////////////////////////////////// // Lambda to function pointer conversion template <typename Function> struct function_traits : public function_traits<decltype(&Function::operator())> {}; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...) const> { typedef ReturnType (*pointer)(Args...); typedef ReturnType return_type; }; template <typename Function> typename function_traits<Function>::pointer FunctionPointer (const Function& lambda) { return static_cast<typename function_traits<Function>::pointer>(lambda); } template <class T> inline string ToString (const T& t) { stringstream ss; ss << t; return ss.str(); } template <typename T, int BASE = 0, typename TIND = int> void ExportArray () { string name = string("Array_") + typeid(T).name(); bp::class_<Array<T,BASE,TIND>,boost::noncopyable>(name.c_str()) .def ("__len__", &Array<T,BASE,TIND>::Size) .def ("__getitem__", FunctionPointer ([](Array<T,BASE,TIND> & self, TIND i) -> T& { if (i < BASE || i >= BASE+self.Size()) bp::exec("raise IndexError()\n"); return self[i]; }), bp::return_value_policy<bp::reference_existing_object>()) .def ("__iter__", bp::range (FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE]; }), FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE+self.Size()]; }))) ; } void ExportNetgenMeshing() { std::string nested_name = "meshing"; if( bp::scope() ) nested_name = bp::extract<std::string>(bp::scope().attr("__name__") + ".meshing"); bp::object module(bp::handle<>(bp::borrowed(PyImport_AddModule(nested_name.c_str())))); cout << "exporting meshing " << nested_name << endl; bp::object parent = bp::scope() ? bp::scope() : bp::import("__main__"); parent.attr("meshing") = module ; bp::scope local_scope(module); bp::class_<PointIndex>("PointId", bp::init<int>()) .def("__repr__", &ToString<PointIndex>) .def("__str__", &ToString<PointIndex>) .add_property("nr", &PointIndex::operator int) ; bp::class_<Point<3>> ("Point") .def(bp::init<double,double,double>()) ; bp::class_<MeshPoint,bp::bases<Point<3>>>("MeshPoint") .def(bp::init<Point<3>>()) .add_property("p", FunctionPointer([](const MeshPoint & self) { bp::list l; l.append ( (self)[0] ); l.append ( (self)[1] ); l.append ( (self)[2] ); return l; })) ; bp::class_<Element>("Element3D") .add_property("index", &Element::GetIndex, &Element::SetIndex) .add_property("vertices", FunctionPointer ([](const Element & self) -> bp::list { bp::list li; for (int i = 0; i < self.GetNV(); i++) li.append (self[i]); return li; })) ; ExportArray<Element>(); ExportArray<Element2d>(); ExportArray<MeshPoint,PointIndex::BASE,PointIndex>(); ; bp::class_<Mesh,shared_ptr<Mesh>,boost::noncopyable>("Mesh") .def("__str__", &ToString<Mesh>) .def("Load", static_cast<void(Mesh::*)(const string & name)>(&Mesh::Load)) .def("Save", static_cast<void(Mesh::*)(const string & name)const>(&Mesh::Save)) .def("Elements3D", static_cast<Array<Element>&(Mesh::*)()> (&Mesh::VolumeElements), bp::return_value_policy<bp::reference_existing_object>()) .def("Elements2D", static_cast<Array<Element2d>&(Mesh::*)()> (&Mesh::SurfaceElements), bp::return_value_policy<bp::reference_existing_object>()) .def("Points", static_cast<Mesh::T_POINTS&(Mesh::*)()> (&Mesh::Points), bp::return_value_policy<bp::reference_existing_object>()) .def("__getitem__", FunctionPointer ([](const Mesh & self, PointIndex pi) { return self[pi]; })) .def ("Add", FunctionPointer ([](Mesh & self, MeshPoint p) { return self.AddPoint (Point3d(p)); })) ; typedef MeshingParameters MP; bp::class_<MP> ("MeshingParameters") .def("__str__", &ToString<MP>) .add_property("maxh", FunctionPointer ([](const MP & mp ) { return mp.maxh; }), FunctionPointer ([](MP & mp, double maxh) { return mp.maxh = maxh; })) ; } BOOST_PYTHON_MODULE(libmesh) { ExportNetgenMeshing(); } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 MLBA-Team. All rights reserved. * * @MLBA_OPEN_LICENSE_HEADER_START@ * * 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. * * @MLBA_OPEN_LICENSE_HEADER_END@ */ #include <iostream> #include <stdlib.h> #include "xdispatch_internal.h" __XDISPATCH_USE_NAMESPACE iteration_wrap::iteration_wrap ( iteration_operation *o, size_t ct ) : op( o ), ref( ct ) { XDISPATCH_ASSERT( o ); } iteration_wrap::~iteration_wrap () { if( op && op->auto_delete() ) delete op; } iteration_operation * iteration_wrap::operation() { return op; } bool iteration_wrap::deref() { return dispatch_atomic_dec( &ref ) == 0; } void set_debugger_threadname() { #ifdef DEBUG #endif } extern "C" void _xdispatch_run_operation( void *dt ) { XDISPATCH_ASSERT( dt ); operation *w = static_cast< operation * > ( dt ); XDISPATCH_ASSERT( w ); try { ( *w )(); } catch( const std::exception &e ) { std::cerr << "##################################################################" << std::endl; std::cerr << " Queue '" << xdispatch::current_queue().label() << "'" << std::endl; std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl; std::cerr << " not recommended, please make sure to catch them before:\n" << std::endl; std::cerr << e.what() << std::endl; std::cerr << "##################################################################" << std::endl; throw; } catch( ... ) { std::cerr << "##################################################################" << std::endl; std::cerr << " Queue '" << xdispatch::current_queue().label() << "'" << std::endl; std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl; std::cerr << " not recommended, please make sure to catch them before!" << std::endl; std::cerr << "##################################################################" << std::endl; std::terminate(); } if( w->auto_delete() ) delete w; } // _xdispatch_run_operation extern "C" void _xdispatch_run_iter_wrap( void *dt, size_t index ) { XDISPATCH_ASSERT( dt ); iteration_wrap *wrap = static_cast< iteration_wrap * > ( dt ); XDISPATCH_ASSERT( wrap ); try { ( *( wrap->operation() ) )( index ); } catch( const std::exception &e ) { std::cerr << "##################################################################" << std::endl; std::cerr << " Queue '" << xdispatch::current_queue().label() << "'" << std::endl; std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl; std::cerr << " not recommended, please make sure to catch them before:\n" << std::endl; std::cerr << e.what() << std::endl; std::cerr << "##################################################################" << std::endl; throw; } catch( ... ) { std::cerr << "##################################################################" << std::endl; std::cerr << " Queue '" << xdispatch::current_queue().label() << "'" << std::endl; std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl; std::cerr << " not recommended, please make sure to catch them before!" << std::endl; std::cerr << "##################################################################" << std::endl; std::terminate(); } } // _xdispatch_run_iter_wrap <commit_msg>Set threadname according to queue<commit_after>/* * Copyright (c) 2011-2013 MLBA-Team. All rights reserved. * * @MLBA_OPEN_LICENSE_HEADER_START@ * * 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. * * @MLBA_OPEN_LICENSE_HEADER_END@ */ #include <iostream> #include <stdlib.h> #include "xdispatch_internal.h" __XDISPATCH_USE_NAMESPACE iteration_wrap::iteration_wrap ( iteration_operation *o, size_t ct ) : op( o ), ref( ct ) { XDISPATCH_ASSERT( o ); } iteration_wrap::~iteration_wrap () { if( op && op->auto_delete() ) delete op; } iteration_operation * iteration_wrap::operation() { return op; } bool iteration_wrap::deref() { return dispatch_atomic_dec( &ref ) == 0; } inline void set_debugger_threadname( const std::string& name = std::string() ) { #if (defined DEBUG) && (defined __APPLE__ || defined __linux__) # if (defined __linux__) prctl(PR_SET_NAME, (unsigned long)( name.c_str() ), 0, 0, 0); # elif (defined __APPLE__) pthread_setname_np( name.c_str() ); # endif #endif } extern "C" void _xdispatch_run_operation( void *dt ) { XDISPATCH_ASSERT( dt ); operation *w = static_cast< operation * > ( dt ); XDISPATCH_ASSERT( w ); try { set_debugger_threadname( xdispatch::current_queue().label() ); ( *w )(); set_debugger_threadname(); } catch( const std::exception &e ) { std::cerr << "##################################################################" << std::endl; std::cerr << " Queue '" << xdispatch::current_queue().label() << "'" << std::endl; std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl; std::cerr << " not recommended, please make sure to catch them before:\n" << std::endl; std::cerr << e.what() << std::endl; std::cerr << "##################################################################" << std::endl; throw; } catch( ... ) { std::cerr << "##################################################################" << std::endl; std::cerr << " Queue '" << xdispatch::current_queue().label() << "'" << std::endl; std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl; std::cerr << " not recommended, please make sure to catch them before!" << std::endl; std::cerr << "##################################################################" << std::endl; std::terminate(); } if( w->auto_delete() ) delete w; } // _xdispatch_run_operation extern "C" void _xdispatch_run_iter_wrap( void *dt, size_t index ) { XDISPATCH_ASSERT( dt ); iteration_wrap *wrap = static_cast< iteration_wrap * > ( dt ); XDISPATCH_ASSERT( wrap ); try { set_debugger_threadname( xdispatch::current_queue().label() ); ( *( wrap->operation() ) )( index ); set_debugger_threadname(); } catch( const std::exception &e ) { std::cerr << "##################################################################" << std::endl; std::cerr << " Queue '" << xdispatch::current_queue().label() << "'" << std::endl; std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl; std::cerr << " not recommended, please make sure to catch them before:\n" << std::endl; std::cerr << e.what() << std::endl; std::cerr << "##################################################################" << std::endl; throw; } catch( ... ) { std::cerr << "##################################################################" << std::endl; std::cerr << " Queue '" << xdispatch::current_queue().label() << "'" << std::endl; std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl; std::cerr << " not recommended, please make sure to catch them before!" << std::endl; std::cerr << "##################################################################" << std::endl; std::terminate(); } } // _xdispatch_run_iter_wrap <|endoftext|>
<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #if !BOOST_PP_IS_ITERATING #ifndef LUABIND_CALL_MEMBER_HPP_INCLUDED #define LUABIND_CALL_MEMBER_HPP_INCLUDED #include <luabind/config.hpp> #include <luabind/detail/convert_to_lua.hpp> #include <luabind/detail/pcall.hpp> #include <luabind/detail/stack_utils.hpp> #include <luabind/error.hpp> #include <luabind/detail/object.hpp> // TODO: REMOVE DEPENDENCY #include <boost/mpl/apply_wrap.hpp> #include <boost/preprocessor/control/if.hpp> #include <boost/preprocessor/facilities/expand.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/tuple/tuple.hpp> namespace luabind { namespace detail { namespace mpl = boost::mpl; // if the proxy_member_caller returns non-void template<class Ret, class Tuple> class proxy_member_caller { // friend class luabind::object; public: proxy_member_caller(lua_State* L_, const Tuple args) : L(L_) , m_args(args) , m_called(false) { } proxy_member_caller(const proxy_member_caller& rhs) : L(rhs.L) , m_args(rhs.m_args) , m_called(rhs.m_called) { rhs.m_called = true; } ~proxy_member_caller() { if (m_called) return; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters push_args_from_tuple<1>::apply(L, m_args); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); } operator Ret() { typename mpl::apply_wrap2<default_policy,Ret,lua_to_cpp>::type converter; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters push_args_from_tuple<1>::apply(L, m_args); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw cast_failed(L, typeid(Ret)); #else cast_failed_callback_fun e = get_cast_failed_callback(); if (e) e(L, typeid(Ret)); assert(0 && "the lua function's return value could not be converted." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1); } template<class Policies> Ret operator[](const Policies& p) { typedef typename find_conversion_policy<0, Policies>::type converter_policy; typename mpl::apply_wrap2<converter_policy,Ret,lua_to_cpp>::type converter; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters detail::push_args_from_tuple<1>::apply(L, m_args, p); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw cast_failed(L, typeid(Ret)); #else cast_failed_callback_fun e = get_cast_failed_callback(); if (e) e(L, typeid(Ret)); assert(0 && "the lua function's return value could not be converted." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1); } private: lua_State* L; Tuple m_args; mutable bool m_called; }; // if the proxy_member_caller returns void template<class Tuple> class proxy_member_void_caller { friend class luabind::object; public: proxy_member_void_caller(lua_State* L_, const Tuple args) : L(L_) , m_args(args) , m_called(false) { } proxy_member_void_caller(const proxy_member_void_caller& rhs) : L(rhs.L) , m_args(rhs.m_args) , m_called(rhs.m_called) { rhs.m_called = true; } ~proxy_member_void_caller() { if (m_called) return; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters push_args_from_tuple<1>::apply(L, m_args); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); } template<class Policies> void operator[](const Policies& p) { m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters detail::push_args_from_tuple<1>::apply(L, m_args, p); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); } private: lua_State* L; Tuple m_args; mutable bool m_called; }; } // detail #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, <luabind/detail/call_member.hpp>, 1)) #include BOOST_PP_ITERATE() } #endif // LUABIND_CALL_MEMBER_HPP_INCLUDED #else #if BOOST_PP_ITERATION_FLAGS() == 1 #define LUABIND_TUPLE_PARAMS(z, n, data) const A##n * #define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n template<class R BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)> typename boost::mpl::if_<boost::is_void<R> , luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > , luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type call_member(object const& obj, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _)) { typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t; #if BOOST_PP_ITERATION() == 0 tuple_t args; #else tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a)); #endif typedef typename boost::mpl::if_<boost::is_void<R> , luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > , luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type; // this will be cleaned up by the proxy object // once the call has been made // get the function obj.push(obj.interpreter()); lua_pushstring(obj.interpreter(), name); lua_gettable(obj.interpreter(), -2); // duplicate the self-object lua_pushvalue(obj.interpreter(), -2); // remove the bottom self-object lua_remove(obj.interpreter(), -3); // now the function and self objects // are on the stack. These will both // be popped by pcall return proxy_type(obj.interpreter(), args); } #undef LUABIND_OPERATOR_PARAMS #undef LUABIND_TUPLE_PARAMS #endif #endif <commit_msg>Fix missing LUABIND_MAY_THROW in member caller.<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #if !BOOST_PP_IS_ITERATING #ifndef LUABIND_CALL_MEMBER_HPP_INCLUDED #define LUABIND_CALL_MEMBER_HPP_INCLUDED #include <luabind/config.hpp> #include <luabind/detail/convert_to_lua.hpp> #include <luabind/detail/pcall.hpp> #include <luabind/detail/stack_utils.hpp> #include <luabind/error.hpp> #include <luabind/detail/object.hpp> // TODO: REMOVE DEPENDENCY #include <boost/mpl/apply_wrap.hpp> #include <boost/preprocessor/control/if.hpp> #include <boost/preprocessor/facilities/expand.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/tuple/tuple.hpp> namespace luabind { namespace detail { namespace mpl = boost::mpl; // if the proxy_member_caller returns non-void template<class Ret, class Tuple> class proxy_member_caller { // friend class luabind::object; public: proxy_member_caller(lua_State* L_, const Tuple args) : L(L_) , m_args(args) , m_called(false) { } proxy_member_caller(const proxy_member_caller& rhs) : L(rhs.L) , m_args(rhs.m_args) , m_called(rhs.m_called) { rhs.m_called = true; } ~proxy_member_caller() LUABIND_MAY_THROW { if (m_called) return; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters push_args_from_tuple<1>::apply(L, m_args); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); } operator Ret() { typename mpl::apply_wrap2<default_policy,Ret,lua_to_cpp>::type converter; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters push_args_from_tuple<1>::apply(L, m_args); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw cast_failed(L, typeid(Ret)); #else cast_failed_callback_fun e = get_cast_failed_callback(); if (e) e(L, typeid(Ret)); assert(0 && "the lua function's return value could not be converted." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1); } template<class Policies> Ret operator[](const Policies& p) { typedef typename find_conversion_policy<0, Policies>::type converter_policy; typename mpl::apply_wrap2<converter_policy,Ret,lua_to_cpp>::type converter; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters detail::push_args_from_tuple<1>::apply(L, m_args, p); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw cast_failed(L, typeid(Ret)); #else cast_failed_callback_fun e = get_cast_failed_callback(); if (e) e(L, typeid(Ret)); assert(0 && "the lua function's return value could not be converted." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1); } private: lua_State* L; Tuple m_args; mutable bool m_called; }; // if the proxy_member_caller returns void template<class Tuple> class proxy_member_void_caller { friend class luabind::object; public: proxy_member_void_caller(lua_State* L_, const Tuple args) : L(L_) , m_args(args) , m_called(false) { } proxy_member_void_caller(const proxy_member_void_caller& rhs) : L(rhs.L) , m_args(rhs.m_args) , m_called(rhs.m_called) { rhs.m_called = true; } ~proxy_member_void_caller() { if (m_called) return; m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters push_args_from_tuple<1>::apply(L, m_args); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw luabind::error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); } template<class Policies> void operator[](const Policies& p) { m_called = true; // don't count the function and self-reference // since those will be popped by pcall int top = lua_gettop(L) - 2; // pcall will pop the function and self reference // and all the parameters detail::push_args_from_tuple<1>::apply(L, m_args, p); if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0)) { assert(lua_gettop(L) == top + 1); #ifndef LUABIND_NO_EXCEPTIONS throw error(L); #else error_callback_fun e = get_error_callback(); if (e) e(L); assert(0 && "the lua function threw an error and exceptions are disabled." "If you want to handle this error use luabind::set_error_callback()"); std::terminate(); #endif } // pops the return values from the function stack_pop pop(L, lua_gettop(L) - top); } private: lua_State* L; Tuple m_args; mutable bool m_called; }; } // detail #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, <luabind/detail/call_member.hpp>, 1)) #include BOOST_PP_ITERATE() } #endif // LUABIND_CALL_MEMBER_HPP_INCLUDED #else #if BOOST_PP_ITERATION_FLAGS() == 1 #define LUABIND_TUPLE_PARAMS(z, n, data) const A##n * #define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n template<class R BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)> typename boost::mpl::if_<boost::is_void<R> , luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > , luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type call_member(object const& obj, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _)) { typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t; #if BOOST_PP_ITERATION() == 0 tuple_t args; #else tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a)); #endif typedef typename boost::mpl::if_<boost::is_void<R> , luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > , luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type; // this will be cleaned up by the proxy object // once the call has been made // get the function obj.push(obj.interpreter()); lua_pushstring(obj.interpreter(), name); lua_gettable(obj.interpreter(), -2); // duplicate the self-object lua_pushvalue(obj.interpreter(), -2); // remove the bottom self-object lua_remove(obj.interpreter(), -3); // now the function and self objects // are on the stack. These will both // be popped by pcall return proxy_type(obj.interpreter(), args); } #undef LUABIND_OPERATOR_PARAMS #undef LUABIND_TUPLE_PARAMS #endif #endif <|endoftext|>
<commit_before>#include "WatchdogProcessView.h" #include "ui_WatchdogProcessView.h" WatchdogProcessView::WatchdogProcessView(QWidget *parent) : QWidget(parent), m_ui(new Ui::WatchdogProcessView) { m_ui->setupUi(this); } WatchdogProcessView::~WatchdogProcessView() { delete m_ui; } void WatchdogProcessView::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } <commit_msg>Fixed minor compile error<commit_after>#include "WatchdogProcessView.h" #include "ui_WatchdogProcessView.h" WatchdogProcessView::WatchdogProcessView(int processid, QWidget *parent) : QWidget(parent), m_ui(new Ui::WatchdogProcessView) { m_ui->setupUi(this); } WatchdogProcessView::~WatchdogProcessView() { delete m_ui; } void WatchdogProcessView::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/browser_extension_window_controller.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/window_controller_list.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_id.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/extensions/extension.h" BrowserExtensionWindowController::BrowserExtensionWindowController( Browser* browser) : extensions::WindowController(browser->window(), browser->profile()), browser_(browser) { extensions::WindowControllerList::GetInstance()->AddExtensionWindow(this); } BrowserExtensionWindowController::~BrowserExtensionWindowController() { extensions::WindowControllerList::GetInstance()->RemoveExtensionWindow(this); } int BrowserExtensionWindowController::GetWindowId() const { return static_cast<int>(browser_->session_id().id()); } namespace keys = extensions::tabs_constants; std::string BrowserExtensionWindowController::GetWindowTypeText() const { if (browser_->is_type_popup()) return keys::kWindowTypeValuePopup; if (browser_->is_type_panel()) return keys::kWindowTypeValuePanel; if (browser_->is_app()) return keys::kWindowTypeValueApp; return keys::kWindowTypeValueNormal; } base::DictionaryValue* BrowserExtensionWindowController::CreateWindowValue() const { DictionaryValue* result = extensions::WindowController::CreateWindowValue(); return result; } base::DictionaryValue* BrowserExtensionWindowController::CreateWindowValueWithTabs( const extensions::Extension* extension) const { DictionaryValue* result = CreateWindowValue(); result->Set(keys::kTabsKey, ExtensionTabUtil::CreateTabList(browser_, extension)); return result; } bool BrowserExtensionWindowController::CanClose(Reason* reason) const { // Don't let an extension remove the window if the user is dragging tabs // in that window. if (!chrome::IsTabStripEditable(browser_)) { *reason = extensions::WindowController::REASON_NOT_EDITABLE; return false; } return true; } void BrowserExtensionWindowController::SetFullscreenMode( bool is_fullscreen, const GURL& extension_url) const { if (browser_->window()->IsFullscreen() != is_fullscreen) browser_->ToggleFullscreenModeWithExtension(extension_url); } Browser* BrowserExtensionWindowController::GetBrowser() const { return browser_; } bool BrowserExtensionWindowController::IsVisibleToExtension( const extensions::Extension* extension) const { // Platform apps can only see their own windows. // TODO(mihaip): what about non-Aura panels? return !extension->is_platform_app(); } <commit_msg>Remove obsolete TODO about browser-based panels.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/browser_extension_window_controller.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/window_controller_list.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_id.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/extensions/extension.h" BrowserExtensionWindowController::BrowserExtensionWindowController( Browser* browser) : extensions::WindowController(browser->window(), browser->profile()), browser_(browser) { extensions::WindowControllerList::GetInstance()->AddExtensionWindow(this); } BrowserExtensionWindowController::~BrowserExtensionWindowController() { extensions::WindowControllerList::GetInstance()->RemoveExtensionWindow(this); } int BrowserExtensionWindowController::GetWindowId() const { return static_cast<int>(browser_->session_id().id()); } namespace keys = extensions::tabs_constants; std::string BrowserExtensionWindowController::GetWindowTypeText() const { if (browser_->is_type_popup()) return keys::kWindowTypeValuePopup; if (browser_->is_type_panel()) return keys::kWindowTypeValuePanel; if (browser_->is_app()) return keys::kWindowTypeValueApp; return keys::kWindowTypeValueNormal; } base::DictionaryValue* BrowserExtensionWindowController::CreateWindowValue() const { DictionaryValue* result = extensions::WindowController::CreateWindowValue(); return result; } base::DictionaryValue* BrowserExtensionWindowController::CreateWindowValueWithTabs( const extensions::Extension* extension) const { DictionaryValue* result = CreateWindowValue(); result->Set(keys::kTabsKey, ExtensionTabUtil::CreateTabList(browser_, extension)); return result; } bool BrowserExtensionWindowController::CanClose(Reason* reason) const { // Don't let an extension remove the window if the user is dragging tabs // in that window. if (!chrome::IsTabStripEditable(browser_)) { *reason = extensions::WindowController::REASON_NOT_EDITABLE; return false; } return true; } void BrowserExtensionWindowController::SetFullscreenMode( bool is_fullscreen, const GURL& extension_url) const { if (browser_->window()->IsFullscreen() != is_fullscreen) browser_->ToggleFullscreenModeWithExtension(extension_url); } Browser* BrowserExtensionWindowController::GetBrowser() const { return browser_; } bool BrowserExtensionWindowController::IsVisibleToExtension( const extensions::Extension* extension) const { // Platform apps can only see their own windows. return !extension->is_platform_app(); } <|endoftext|>
<commit_before>#ifdef NL_DATA_CONTAINER_H_ #include "NL_DataContainer.h" namespace NLE { namespace Core { template<typename T> DataContainer<T>::DataContainer() : _sysId(-1), _dataPool(), _data(_dataPool), _updateQueue(), _distributor(nullptr) { } template<typename T> DataContainer<T>::~DataContainer() { } template<typename T> bool DataContainer<T>::initialize(uint_fast8_t sysId, uint_fast8_t initSize) { _sysId = sysId; _data.reserve(initSize); return true; } template<typename T> void DataContainer<T>::release() { _data.clear(); _dataPool.recycle(); } template<typename T> void DataContainer<T>::bindDistributor(DataDistributor<T>* distributor) { _distributor = distributor; } template<typename T> inline void add(T data) { _data.push_back(data); } template<typename T> void DataContainer<T>::remove(uint_fast8_t index) { uint_fast8_t size = _data.size(); if (index < size) { uint_fast8_t lastOccupied = size - 1; if (index != lastOccupied) { _data[index] = _data[lastOccupied]; } _data.pop_back(); } } template<typename T> void DataContainer<T>::modify(uint_fast8_t index, T data) { _data[index] = data; if (_distributor) { _distributor->queue({ _sysId, index, data }); } } template<typename T> inline void DataContainer<T>::clear() { _data.clear(); } template<typename T> inline uint_fast8_t DataContainer<T>::size() { return _data.size(); } template<typename T> inline T& DataContainer<T>::get(uint_fast8_t index) { return _data[index]; } template<typename T> inline void DataContainer<T>::queuePacket(DataPacket<T> packet) { _updateQueue.push(packet); } template<typename T> void DataContainer<T>::applyUpdates() { DataPacket<T> packet; while (_updateQueue.try_pop(packet)) { modify(packet.getItemNumber(), packet.getData()); } } } } #endif<commit_msg>bug fix: applying container update distributes data<commit_after>#ifdef NL_DATA_CONTAINER_H_ #include "NL_DataContainer.h" namespace NLE { namespace Core { template<typename T> DataContainer<T>::DataContainer() : _sysId(-1), _dataPool(), _data(_dataPool), _updateQueue(), _distributor(nullptr) { } template<typename T> DataContainer<T>::~DataContainer() { } template<typename T> bool DataContainer<T>::initialize(uint_fast8_t sysId, uint_fast8_t initSize) { _sysId = sysId; _data.reserve(initSize); return true; } template<typename T> void DataContainer<T>::release() { _data.clear(); _dataPool.recycle(); } template<typename T> void DataContainer<T>::bindDistributor(DataDistributor<T>* distributor) { _distributor = distributor; } template<typename T> inline void add(T data) { _data.push_back(data); } template<typename T> void DataContainer<T>::remove(uint_fast8_t index) { uint_fast8_t size = _data.size(); if (index < size) { uint_fast8_t lastOccupied = size - 1; if (index != lastOccupied) { _data[index] = _data[lastOccupied]; } _data.pop_back(); } } template<typename T> void DataContainer<T>::modify(uint_fast8_t index, T data) { _data[index] = data; if (_distributor) { _distributor->queue({ _sysId, index, data }); } } template<typename T> inline void DataContainer<T>::clear() { _data.clear(); } template<typename T> inline uint_fast8_t DataContainer<T>::size() { return _data.size(); } template<typename T> inline T& DataContainer<T>::get(uint_fast8_t index) { return _data[index]; } template<typename T> inline void DataContainer<T>::queuePacket(DataPacket<T> packet) { _updateQueue.push(packet); } template<typename T> void DataContainer<T>::applyUpdates() { DataPacket<T> packet; while (_updateQueue.try_pop(packet)) { _data[packet.getItemNumber()] = packet.getData(); } } } } #endif<|endoftext|>
<commit_before>#include "unit_tests/suite/lumix_unit_tests.h" #include "engine/log.h" #ifdef _WIN32 #include "engine/win/simple_win.h" #endif #include <cstdio> namespace Lumix { namespace UnitTest { void outputToVS(const char* system, const char* message) { char tmp[2048]; copyString(tmp, system); catString(tmp, ": "); catString(tmp, message); catString(tmp, "\r"); #ifdef _WIN32 OutputDebugString(tmp); #endif } void outputToConsole(const char* system, const char* message) { printf("%s: %s\n", system, message); } void App::init() { g_log_info.getCallback().bind<outputToVS>(); g_log_warning.getCallback().bind<outputToVS>(); g_log_error.getCallback().bind<outputToVS>(); g_log_info.getCallback().bind<outputToConsole>(); g_log_warning.getCallback().bind<outputToConsole>(); g_log_error.getCallback().bind<outputToConsole>(); } void App::run(int argc, const char *argv[]) { Manager::instance().dumpTests(); Manager::instance().runTests("unit_tests/engine/universe/hierarchy3"); Manager::instance().dumpResults(); } void App::exit() { Manager::release(); } } //~UnitTest } //~UnitTest<commit_msg>fixed unit tests<commit_after>#include "unit_tests/suite/lumix_unit_tests.h" #include "engine/log.h" #ifdef _WIN32 #include "engine/win/simple_win.h" #endif #include <cstdio> namespace Lumix { namespace UnitTest { void outputToVS(const char* system, const char* message) { char tmp[2048]; copyString(tmp, system); catString(tmp, ": "); catString(tmp, message); catString(tmp, "\r"); #ifdef _WIN32 OutputDebugString(tmp); #endif } void outputToConsole(const char* system, const char* message) { printf("%s: %s\n", system, message); } void App::init() { g_log_info.getCallback().bind<outputToVS>(); g_log_warning.getCallback().bind<outputToVS>(); g_log_error.getCallback().bind<outputToVS>(); g_log_info.getCallback().bind<outputToConsole>(); g_log_warning.getCallback().bind<outputToConsole>(); g_log_error.getCallback().bind<outputToConsole>(); } void App::run(int argc, const char *argv[]) { Manager::instance().dumpTests(); Manager::instance().runTests("*"); Manager::instance().dumpResults(); } void App::exit() { Manager::release(); } } //~UnitTest } //~UnitTest<|endoftext|>
<commit_before>#include "NL_ImguiEditorUiManager.h" #include "NL_ThreadLocal.h" #include "NL_EngineServices.h" #include "NL_SharedData.h" #include "NL_SystemServices.h" #include "NL_InputEvents.h" #include "NL_ImguiInputMap.h" #include <assert.h> #include <string> #include <iostream> #include <algorithm> namespace NLE { namespace UI { ImguiEditorUiManager::ImguiEditorUiManager( EngineServices& eServices, CONSOLE::IConsoleQueue& consoleQueue, IWindowManager& windowManager, GAME::IGameManager& gameManager, INPUT::IInputProcessor& inputProcessor, GRAPHICS::IRenderingEngine& renderingEngine, SCRIPT::IScriptingEngine& scriptingEngine) : _eServices(eServices), _consoleQueue(consoleQueue), _windowManager(windowManager), _gameManager(gameManager), _inputProcessor(inputProcessor), _renderingEngine(renderingEngine), _scriptingEngine(scriptingEngine), _showEditor(true), _showEditorSettings(false), _windowBgColor(0.0f, 0.0f, 1.0f, 0.5f), _textColor(0.0f, 1.0f, 0.0f, 1.0f), _borderColor(0.0f, 1.0f, 0.0f, 1.0f), _itemColor(0.0f, 0.0f, 1.0f, 0.5f), _itemHoverColor(0.0f, 0.0f, 1.0f, 0.8f), _itemActiveColor(0.0f, 0.0f, 1.0f, 0.8f), _selectionColor(1.0f, 1.0f, 1.0f, 0.8f) { } ImguiEditorUiManager::~ImguiEditorUiManager() { } bool ImguiEditorUiManager::initialize() { return true; } int ImguiEditorUiManager::getScancodeForKeyEvent(INPUT::Event event) { assert(event.eventType == INPUT::EVENT_KEY); ImGuiIO& io = ImGui::GetIO(); auto key = INPUT::NLEtoImguiKey(event.eventData.keyEvent.key); if (key == -1) return event.eventData.keyEvent.scancode; if (io.KeyMap[key] == -1) io.KeyMap[key] = event.eventData.keyEvent.scancode; return io.KeyMap[key]; } ImDrawData* ImguiEditorUiManager::getDrawData() { return ImGui::GetDrawData(); } void ImguiEditorUiManager::queueKeyAndCharEvent(INPUT::Event event) { _keyAndCharEvents.push(event); } void ImguiEditorUiManager::update(SystemServices* sServices, double deltaT, Size2D screenSize) { NLE::TLS::PerformanceTimer::reference timer = NLE::TLS::performanceTimer.local(); timer.deltaT(); DATA::SharedData& data = _eServices.data->getData(); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2((float)screenSize.width, (float)screenSize.height); io.DeltaTime = (float)(deltaT * 0.000000001); //Need crossplatform implementation // Hide OS mouse cursor if ImGui is drawing it //SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW)); captureInput(sServices, deltaT, screenSize); ImGui::NewFrame(); drawUI(sServices, screenSize); ImGui::Render(); data.sysExecutionTimes.set(UI_MANAGER, timer.deltaT()); } void ImguiEditorUiManager::captureInput(SystemServices* sServices, double deltaT, Size2D screenSize) { DATA::SharedData& data = _eServices.data->getData(); ImGuiIO& io = ImGui::GetIO(); io.MouseDown[0] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_LEFT]; io.MouseDown[1] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_RIGHT]; io.MouseDown[2] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_MIDDLE]; io.MouseWheel += (float)data.scrollOffset.get()[1]; io.MousePos.x = (float)data.mouseCursorPosition.get()[0]; io.MousePos.y = (float)data.mouseCursorPosition.get()[1]; INPUT::Event event; while (_keyAndCharEvents.pop(event)) { if (event.eventType == INPUT::EVENT_KEY) { int scancode = getScancodeForKeyEvent(event); io.KeysDown[scancode] = event.eventData.keyEvent.action == INPUT::ACTION_PRESS ? 1 : 0; } else { io.AddInputCharacter((unsigned short)event.eventData.charEvent.code); } } io.KeyCtrl = data.keyModsPressed.get()[INPUT::KEY_MOD_CONTROL]; io.KeyShift = data.keyModsPressed.get()[INPUT::KEY_MOD_SHIFT]; io.KeyAlt = data.keyModsPressed.get()[INPUT::KEY_MOD_ALT]; io.KeySuper = data.keyModsPressed.get()[INPUT::KEY_MOD_SUPER]; } void ImguiEditorUiManager::drawUI(SystemServices* sServices, Size2D screenSize) { ImGuiWindowFlags window_flags = 0; window_flags |= ImGuiWindowFlags_NoTitleBar; window_flags |= ImGuiWindowFlags_NoResize; window_flags |= ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoScrollbar; window_flags |= ImGuiWindowFlags_NoCollapse; window_flags |= ImGuiWindowFlags_MenuBar; window_flags |= ImGuiWindowFlags_NoSavedSettings; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus; ImGui::SetNextWindowPos(ImVec2(0,0)); ImGui::SetNextWindowSize(ImVec2((float)screenSize.width, (float)screenSize.height), ImGuiSetCond_FirstUseEver); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); applyColorScheme(true); ImGui::Begin("Engine UI Overlay Window", &_showEditor, window_flags); if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) { ImGui::EndMenu(); } if (ImGui::BeginMenu("View")) { ImGui::MenuItem("Editor", NULL, &_showEditorSettings); ImGui::EndMenu(); } ImGui::EndMenuBar(); } ImGui::End(); restoreColorScheme(); ImGui::PopStyleVar(); if(_showEditorSettings) showEditorSettings(sServices, screenSize); } void ImguiEditorUiManager::showEditorSettings(SystemServices* sServices, Size2D screenSize) { ImGuiWindowFlags window_flags = 0; window_flags |= ImGuiWindowFlags_NoSavedSettings; window_flags |= ImGuiWindowFlags_AlwaysAutoResize; ImGui::SetNextWindowPos(ImVec2((float)screenSize.width / 2, (float)screenSize.height / 2), ImGuiSetCond_FirstUseEver); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); applyColorScheme(false); ImGui::Begin("Editor Settings", &_showEditorSettings, window_flags); if (ImGui::CollapsingHeader("Color Scheme")) { ImGui::ColorEdit4("Window Background", (float*)&_windowBgColor); ImGui::ColorEdit4("Text Color", (float*)&_textColor); ImGui::ColorEdit4("Border Color", (float*)&_borderColor); ImGui::ColorEdit4("Item Color", (float*)&_itemColor); ImGui::ColorEdit4("Item Hover Color", (float*)&_itemHoverColor); ImGui::ColorEdit4("Item Active Color", (float*)&_itemActiveColor); ImGui::ColorEdit4("Selection Color", (float*)&_selectionColor); } ImGui::End(); restoreColorScheme(); ImGui::PopStyleVar(); } void ImguiEditorUiManager::applyColorScheme(bool root) { if(root) ImGui::PushStyleColor(ImGuiCol_WindowBg, ImColor(0.0f, 0.0f, 0.0f, 0.0f)); else ImGui::PushStyleColor(ImGuiCol_WindowBg, _windowBgColor); ImGui::PushStyleColor(ImGuiCol_MenuBarBg, _windowBgColor); ImGui::PushStyleColor(ImGuiCol_Text, _textColor); ImGui::PushStyleColor(ImGuiCol_Border, _borderColor); ImGui::PushStyleColor(ImGuiCol_Button, _itemColor); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, _itemHoverColor); ImGui::PushStyleColor(ImGuiCol_ButtonActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_Header, _itemColor); ImGui::PushStyleColor(ImGuiCol_HeaderHovered, _itemHoverColor); ImGui::PushStyleColor(ImGuiCol_HeaderActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_FrameBg, _itemColor); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, _itemHoverColor); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_TitleBg, _itemColor); ImGui::PushStyleColor(ImGuiCol_TitleBgCollapsed, _itemColor); ImGui::PushStyleColor(ImGuiCol_TitleBgActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_CloseButton, _itemColor); ImGui::PushStyleColor(ImGuiCol_CloseButtonHovered, _itemHoverColor); ImGui::PushStyleColor(ImGuiCol_CloseButtonActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_TextSelectedBg, _selectionColor); } void ImguiEditorUiManager::restoreColorScheme() { ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); } void ImguiEditorUiManager::show(bool show) { _showEditor = show; } } }<commit_msg>added borders and fps counter<commit_after>#include "NL_ImguiEditorUiManager.h" #include "NL_ThreadLocal.h" #include "NL_EngineServices.h" #include "NL_SharedData.h" #include "NL_SystemServices.h" #include "NL_InputEvents.h" #include "NL_ImguiInputMap.h" #include <assert.h> #include <string> #include <iostream> #include <algorithm> namespace NLE { namespace UI { ImguiEditorUiManager::ImguiEditorUiManager( EngineServices& eServices, CONSOLE::IConsoleQueue& consoleQueue, IWindowManager& windowManager, GAME::IGameManager& gameManager, INPUT::IInputProcessor& inputProcessor, GRAPHICS::IRenderingEngine& renderingEngine, SCRIPT::IScriptingEngine& scriptingEngine) : _eServices(eServices), _consoleQueue(consoleQueue), _windowManager(windowManager), _gameManager(gameManager), _inputProcessor(inputProcessor), _renderingEngine(renderingEngine), _scriptingEngine(scriptingEngine), _showEditor(true), _showEditorSettings(false), _windowBgColor(0.0f, 0.0f, 1.0f, 0.5f), _textColor(0.0f, 1.0f, 0.0f, 1.0f), _borderColor(0.0f, 1.0f, 0.0f, 1.0f), _itemColor(0.0f, 0.0f, 1.0f, 0.5f), _itemHoverColor(0.0f, 0.0f, 1.0f, 0.8f), _itemActiveColor(0.0f, 0.0f, 1.0f, 0.8f), _selectionColor(1.0f, 1.0f, 1.0f, 0.8f) { } ImguiEditorUiManager::~ImguiEditorUiManager() { } bool ImguiEditorUiManager::initialize() { return true; } int ImguiEditorUiManager::getScancodeForKeyEvent(INPUT::Event event) { assert(event.eventType == INPUT::EVENT_KEY); ImGuiIO& io = ImGui::GetIO(); auto key = INPUT::NLEtoImguiKey(event.eventData.keyEvent.key); if (key == -1) return event.eventData.keyEvent.scancode; if (io.KeyMap[key] == -1) io.KeyMap[key] = event.eventData.keyEvent.scancode; return io.KeyMap[key]; } ImDrawData* ImguiEditorUiManager::getDrawData() { return ImGui::GetDrawData(); } void ImguiEditorUiManager::queueKeyAndCharEvent(INPUT::Event event) { _keyAndCharEvents.push(event); } void ImguiEditorUiManager::update(SystemServices* sServices, double deltaT, Size2D screenSize) { NLE::TLS::PerformanceTimer::reference timer = NLE::TLS::performanceTimer.local(); timer.deltaT(); DATA::SharedData& data = _eServices.data->getData(); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2((float)screenSize.width, (float)screenSize.height); io.DeltaTime = (float)(deltaT * 0.000000001); //Need crossplatform implementation // Hide OS mouse cursor if ImGui is drawing it //SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW)); captureInput(sServices, deltaT, screenSize); ImGui::NewFrame(); drawUI(sServices, screenSize); ImGui::Render(); data.sysExecutionTimes.set(UI_MANAGER, timer.deltaT()); } void ImguiEditorUiManager::captureInput(SystemServices* sServices, double deltaT, Size2D screenSize) { DATA::SharedData& data = _eServices.data->getData(); ImGuiIO& io = ImGui::GetIO(); io.MouseDown[0] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_LEFT]; io.MouseDown[1] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_RIGHT]; io.MouseDown[2] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_MIDDLE]; io.MouseWheel += (float)data.scrollOffset.get()[1]; io.MousePos.x = (float)data.mouseCursorPosition.get()[0]; io.MousePos.y = (float)data.mouseCursorPosition.get()[1]; INPUT::Event event; while (_keyAndCharEvents.pop(event)) { if (event.eventType == INPUT::EVENT_KEY) { int scancode = getScancodeForKeyEvent(event); io.KeysDown[scancode] = event.eventData.keyEvent.action == INPUT::ACTION_PRESS ? 1 : 0; } else { io.AddInputCharacter((unsigned short)event.eventData.charEvent.code); } } io.KeyCtrl = data.keyModsPressed.get()[INPUT::KEY_MOD_CONTROL]; io.KeyShift = data.keyModsPressed.get()[INPUT::KEY_MOD_SHIFT]; io.KeyAlt = data.keyModsPressed.get()[INPUT::KEY_MOD_ALT]; io.KeySuper = data.keyModsPressed.get()[INPUT::KEY_MOD_SUPER]; } void ImguiEditorUiManager::drawUI(SystemServices* sServices, Size2D screenSize) { ImGuiWindowFlags window_flags = 0; window_flags |= ImGuiWindowFlags_NoTitleBar; window_flags |= ImGuiWindowFlags_NoResize; window_flags |= ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoScrollbar; window_flags |= ImGuiWindowFlags_NoCollapse; window_flags |= ImGuiWindowFlags_MenuBar; window_flags |= ImGuiWindowFlags_NoSavedSettings; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus; ImGui::SetNextWindowPos(ImVec2(0,0)); ImGui::SetNextWindowSize(ImVec2((float)screenSize.width, (float)screenSize.height), ImGuiSetCond_FirstUseEver); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); applyColorScheme(true); ImGui::Begin("Engine UI Overlay Window", &_showEditor, window_flags); if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) { ImGui::EndMenu(); } if (ImGui::BeginMenu("View")) { ImGui::MenuItem("Editor", NULL, &_showEditorSettings); ImGui::EndMenu(); } ImGui::SameLine(ImGui::GetWindowWidth() - 100); ImGui::Text("%.1f FPS", ImGui::GetIO().Framerate); ImGui::EndMenuBar(); } ImGui::End(); restoreColorScheme(); ImGui::PopStyleVar(); if(_showEditorSettings) showEditorSettings(sServices, screenSize); } void ImguiEditorUiManager::showEditorSettings(SystemServices* sServices, Size2D screenSize) { ImGuiWindowFlags window_flags = 0; window_flags |= ImGuiWindowFlags_NoSavedSettings; window_flags |= ImGuiWindowFlags_AlwaysAutoResize; window_flags |= ImGuiWindowFlags_ShowBorders; ImGui::SetNextWindowPos(ImVec2((float)screenSize.width / 2, (float)screenSize.height / 2), ImGuiSetCond_FirstUseEver); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); applyColorScheme(false); ImGui::Begin("Editor Settings", &_showEditorSettings, window_flags); if (ImGui::CollapsingHeader("Color Scheme")) { ImGui::ColorEdit4("Window Background", (float*)&_windowBgColor); ImGui::ColorEdit4("Text Color", (float*)&_textColor); ImGui::ColorEdit4("Border Color", (float*)&_borderColor); ImGui::ColorEdit4("Item Color", (float*)&_itemColor); ImGui::ColorEdit4("Item Hover Color", (float*)&_itemHoverColor); ImGui::ColorEdit4("Item Active Color", (float*)&_itemActiveColor); ImGui::ColorEdit4("Selection Color", (float*)&_selectionColor); } ImGui::End(); restoreColorScheme(); ImGui::PopStyleVar(); } void ImguiEditorUiManager::applyColorScheme(bool root) { if(root) ImGui::PushStyleColor(ImGuiCol_WindowBg, ImColor(0.0f, 0.0f, 0.0f, 0.0f)); else ImGui::PushStyleColor(ImGuiCol_WindowBg, _windowBgColor); ImGui::PushStyleColor(ImGuiCol_MenuBarBg, _windowBgColor); ImGui::PushStyleColor(ImGuiCol_Text, _textColor); ImGui::PushStyleColor(ImGuiCol_Border, _borderColor); ImGui::PushStyleColor(ImGuiCol_Button, _itemColor); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, _itemHoverColor); ImGui::PushStyleColor(ImGuiCol_ButtonActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_Header, _itemColor); ImGui::PushStyleColor(ImGuiCol_HeaderHovered, _itemHoverColor); ImGui::PushStyleColor(ImGuiCol_HeaderActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_FrameBg, _itemColor); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, _itemHoverColor); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_TitleBg, _itemColor); ImGui::PushStyleColor(ImGuiCol_TitleBgCollapsed, _itemColor); ImGui::PushStyleColor(ImGuiCol_TitleBgActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_CloseButton, _itemColor); ImGui::PushStyleColor(ImGuiCol_CloseButtonHovered, _itemHoverColor); ImGui::PushStyleColor(ImGuiCol_CloseButtonActive, _itemActiveColor); ImGui::PushStyleColor(ImGuiCol_TextSelectedBg, _selectionColor); } void ImguiEditorUiManager::restoreColorScheme() { ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); } void ImguiEditorUiManager::show(bool show) { _showEditor = show; } } }<|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2013-2018 Igor Zinken - http://www.igorski.nl * * 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 "sequencercontroller.h" #include "sequencer.h" #include "audioengine.h" #include <definitions/notifications.h> #include <messaging/notifier.h> #include <utilities/utils.h> #include <utilities/diskwriter.h> #include <utilities/volumeutil.h> namespace MWEngine { /* constructor / destructor */ SequencerController::SequencerController() { // by default, function as a sixteen step sequencer stepsPerBar = 16; AudioEngine::max_step_position = stepsPerBar - 1; }; SequencerController::~SequencerController() { setPlaying( false ); }; /* public methods */ void SequencerController::prepare( float aQueuedTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit ) { // calculate buffers and ranges if ( aQueuedTempo > 0 ) { setTempo( aQueuedTempo, aTimeSigBeatAmount, aTimeSigBeatUnit ); AudioEngine::handleTempoUpdate( aQueuedTempo, false ); // just to initialize all buffer sizes setLoopRange( 0, ( AudioEngine::amount_of_bars * AudioEngine::samples_per_bar ) - 1, stepsPerBar ); } }; float SequencerController::getTempo() { return AudioEngine::tempo; } void SequencerController::setTempo( float aTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit ) { AudioEngine::queuedTempo = aTempo; AudioEngine::queuedTime_sig_beat_amount = aTimeSigBeatAmount; AudioEngine::queuedTime_sig_beat_unit = aTimeSigBeatUnit; } void SequencerController::setTempoNow( float aTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit ) { setTempo( aTempo, aTimeSigBeatAmount, aTimeSigBeatUnit ); updateStepsPerBar( stepsPerBar ); AudioEngine::handleTempoUpdate( AudioEngine::queuedTempo, true ); } void SequencerController::setVolume( float aVolume ) { AudioEngine::volume = VolumeUtil::toLog( aVolume ); } void SequencerController::setPlaying( bool aIsPlaying ) { Sequencer::playing = aIsPlaying; } void SequencerController::setLoopRange( int aStartPosition, int aEndPosition ) { setLoopRange( aStartPosition, aEndPosition, stepsPerBar ); } /** * make the sequencer loop between two given points * * @param aStartPosition {int} buffer offset of the loops startpoint (starts at 0 !) * @param aEndPosition {int} buffer offset of the loops endpoint * @param aStepsPerBar {int} the amount of individual segments the sequencer subdivides a single bar into * this is used for periodic notifications when the sequencer switches step */ void SequencerController::setLoopRange( int aStartPosition, int aEndPosition, int aStepsPerBar ) { AudioEngine::min_buffer_position = aStartPosition; AudioEngine::max_buffer_position = aEndPosition; // keep current buffer read pointer within the new loop range if ( AudioEngine::bufferPosition < AudioEngine::min_buffer_position || AudioEngine::bufferPosition > AudioEngine::max_buffer_position ) { AudioEngine::bufferPosition = AudioEngine::min_buffer_position; } AudioEngine::min_step_position = ( int ) round(( aStartPosition / AudioEngine::samples_per_bar ) * aStepsPerBar ); AudioEngine::max_step_position = ( int ) round(((( float ) aEndPosition / ( float ) AudioEngine::samples_per_bar ) * aStepsPerBar ) - 1 ); // keep current sequencer step within the new loop range if ( AudioEngine::stepPosition < AudioEngine::min_step_position || AudioEngine::stepPosition > AudioEngine::max_step_position ) { AudioEngine::stepPosition = AudioEngine::min_step_position; } updateStepsPerBar( aStepsPerBar ); } int SequencerController::getStepPosition() { return AudioEngine::stepPosition; } int SequencerController::getBufferPosition() { return AudioEngine::bufferPosition; } void SequencerController::setBufferPosition( int aPosition ) { // keep position within the sequences range (see "setLoopRange") if ( aPosition < AudioEngine::min_buffer_position || aPosition > AudioEngine::max_buffer_position ) { aPosition = AudioEngine::min_buffer_position; } AudioEngine::bufferPosition = aPosition; AudioEngine::stepPosition = ( aPosition / AudioEngine::samples_per_bar ) * stepsPerBar; Notifier::broadcast( Notifications::SEQUENCER_POSITION_UPDATED ); } int SequencerController::getSamplesPerBeat() { return AudioEngine::samples_per_beat; } int SequencerController::getSamplesPerStep() { return ( int ) AudioEngine::samples_per_step; } int SequencerController::getSamplesPerBar() { return AudioEngine::samples_per_bar; } int SequencerController::getTimeSigBeatAmount() { return AudioEngine::time_sig_beat_amount; } int SequencerController::getTimeSigBeatUnit() { return AudioEngine::time_sig_beat_unit; } void SequencerController::updateStepsPerBar( int aStepsPerBar ) { stepsPerBar = aStepsPerBar; AudioEngine::max_step_position = ( stepsPerBar * AudioEngine::amount_of_bars ) - 1; AudioEngine::beat_subdivision = stepsPerBar / AudioEngine::time_sig_beat_amount; // keep current sequencer step within the new loop range if ( AudioEngine::stepPosition > AudioEngine::max_step_position ) AudioEngine::stepPosition = AudioEngine::min_step_position; } void SequencerController::updateMeasures( int aValue, int aStepsPerBar ) { AudioEngine::amount_of_bars = aValue; AudioEngine::max_buffer_position = ( AudioEngine::samples_per_bar * AudioEngine::amount_of_bars ) - 1; updateStepsPerBar( aStepsPerBar ); } void SequencerController::rewind() { setBufferPosition( AudioEngine::min_buffer_position ); } void SequencerController::setNotificationMarker( int aPosition ) { AudioEngine::marked_buffer_position = aPosition; } /** * used for intelligent pre-caching, get the BaseCacheableAudioEvents * belonging to a specific measure for on-demand caching * * @param aMeasure {int} the measure containing the events we'd like to precache */ void SequencerController::cacheAudioEventsForMeasure( int aMeasure ) { int startBufferPos = AudioEngine::samples_per_bar * aMeasure; int endBufferPos = ( startBufferPos + AudioEngine::samples_per_bar ) - 1; std::vector<BaseCacheableAudioEvent*>* list = Sequencer::collectCacheableSequencerEvents( startBufferPos, endBufferPos ); getBulkCacher()->addToQueue( list ); delete list; // free memory if ( getBulkCacher()->hasQueue()) getBulkCacher()->cacheQueue(); } BulkCacher* SequencerController::getBulkCacher() { return Sequencer::bulkCacher; } /** * when bouncing, the writing of buffers into the hardware is omitted * for an increase in bouncing speed (otherwise its real time) */ void SequencerController::setBounceState( bool aIsBouncing, int aMaxBuffers, char* aOutputFile ) { AudioEngine::bouncing = aIsBouncing; if ( AudioEngine::bouncing ) { AudioEngine::bufferPosition = 0; AudioEngine::stepPosition = 0; } setRecordingState( aIsBouncing, aMaxBuffers, aOutputFile ); } /** * Record the output of the sequencer onto storage * * aRecording {bool} toggles the recording state * aMaxBuffers {int} the total recorded buffer size to store in memory * before writing the recorded snippet as .WAV file into * the given output file's directory. * aOutputDirectory {char*} name of the output WAV file to generate when recording completes * (when recording state is disabled), this will concatenate all snippets. */ void SequencerController::setRecordingState( bool aRecording, int aMaxBuffers, char* aOutputFile ) { // in case Sequencer was recording input from the Android device, halt recording of input if ( AudioEngine::recordInputToDisk ) setRecordingFromDeviceState( false, 0, ( char* ) "\0" ); bool wasRecording = AudioEngine::recordOutputToDisk; AudioEngine::recordOutputToDisk = aRecording; if ( AudioEngine::recordOutputToDisk ) { DiskWriter::prepare( std::string( aOutputFile ), roundTo( aMaxBuffers, AudioEngineProps::BUFFER_SIZE ), AudioEngineProps::OUTPUT_CHANNELS ); } else if ( wasRecording ) { // recording halted, write currently recording snippet into file // and concatenate all recorded snippets into the requested output file name // we can do this synchronously as this method is called from outside the // rendering thread and thus won't lead to buffer under runs DiskWriter::writeBufferToFile( DiskWriter::currentBufferIndex, false ); if ( DiskWriter::finish()) Notifier::broadcast( Notifications::RECORDING_COMPLETED ); } } /** * record audio from the Androids input channel, this stores only the incoming audio * not the remaining audio processed / generated by the engine * * aRecording {bool} toggles the recording state * aMaxBuffers {int} the total recorded buffer size to store in memory * before writing the recorded contents as .WAV file into * the given output directory. * aOutputDirectory {char*} name of the folder to write each snippet into */ void SequencerController::setRecordingFromDeviceState( bool aRecording, int aMaxBuffers, char* aOutputFile ) { // in case Sequencer was recording its output, halt recording of output if ( AudioEngine::recordOutputToDisk ) setRecordingState( false, 0, ( char* ) "\0" ); bool wasRecording = AudioEngine::recordInputToDisk; AudioEngine::recordInputToDisk = aRecording; if ( AudioEngine::recordInputToDisk ) { DiskWriter::prepare( std::string( aOutputFile ), roundTo( aMaxBuffers, AudioEngineProps::BUFFER_SIZE ), AudioEngineProps::INPUT_CHANNELS ); } else if ( wasRecording ) { // recording halted, write currently recording snippet into file // and concatenate all recorded snippets into the requested output file name // we can do this synchronously as this method is called from outside the // rendering thread and thus won't lead to buffer under runs DiskWriter::writeBufferToFile( DiskWriter::currentBufferIndex, false ); if ( DiskWriter::finish()) Notifier::broadcast( Notifications::RECORDING_COMPLETED ); } } /** * Save the contents of the snippet at given buffer index * onto storage. This should be invoked from a thread separate to the * audio rendering thread to prevent buffer under runs from happening */ void SequencerController::saveRecordedSnippet( int snippetBufferIndex ) { DiskWriter::writeBufferToFile( snippetBufferIndex, true ); } } // E.O namespace MWEngine <commit_msg>Removed global play operation from SequencerController destructor<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2013-2019 Igor Zinken - http://www.igorski.nl * * 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 "sequencercontroller.h" #include "sequencer.h" #include "audioengine.h" #include <definitions/notifications.h> #include <messaging/notifier.h> #include <utilities/utils.h> #include <utilities/diskwriter.h> #include <utilities/volumeutil.h> namespace MWEngine { /* constructor / destructor */ SequencerController::SequencerController() { // by default, function as a sixteen step sequencer stepsPerBar = 16; AudioEngine::max_step_position = stepsPerBar - 1; }; SequencerController::~SequencerController() { // nothing allocated here... }; /* public methods */ void SequencerController::prepare( float aQueuedTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit ) { // calculate buffers and ranges if ( aQueuedTempo > 0 ) { setTempo( aQueuedTempo, aTimeSigBeatAmount, aTimeSigBeatUnit ); AudioEngine::handleTempoUpdate( aQueuedTempo, false ); // just to initialize all buffer sizes setLoopRange( 0, ( AudioEngine::amount_of_bars * AudioEngine::samples_per_bar ) - 1, stepsPerBar ); } }; float SequencerController::getTempo() { return AudioEngine::tempo; } void SequencerController::setTempo( float aTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit ) { AudioEngine::queuedTempo = aTempo; AudioEngine::queuedTime_sig_beat_amount = aTimeSigBeatAmount; AudioEngine::queuedTime_sig_beat_unit = aTimeSigBeatUnit; } void SequencerController::setTempoNow( float aTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit ) { setTempo( aTempo, aTimeSigBeatAmount, aTimeSigBeatUnit ); updateStepsPerBar( stepsPerBar ); AudioEngine::handleTempoUpdate( AudioEngine::queuedTempo, true ); } void SequencerController::setVolume( float aVolume ) { AudioEngine::volume = VolumeUtil::toLog( aVolume ); } void SequencerController::setPlaying( bool aIsPlaying ) { Sequencer::playing = aIsPlaying; } void SequencerController::setLoopRange( int aStartPosition, int aEndPosition ) { setLoopRange( aStartPosition, aEndPosition, stepsPerBar ); } /** * make the sequencer loop between two given points * * @param aStartPosition {int} buffer offset of the loops startpoint (starts at 0 !) * @param aEndPosition {int} buffer offset of the loops endpoint * @param aStepsPerBar {int} the amount of individual segments the sequencer subdivides a single bar into * this is used for periodic notifications when the sequencer switches step */ void SequencerController::setLoopRange( int aStartPosition, int aEndPosition, int aStepsPerBar ) { AudioEngine::min_buffer_position = aStartPosition; AudioEngine::max_buffer_position = aEndPosition; // keep current buffer read pointer within the new loop range if ( AudioEngine::bufferPosition < AudioEngine::min_buffer_position || AudioEngine::bufferPosition > AudioEngine::max_buffer_position ) { AudioEngine::bufferPosition = AudioEngine::min_buffer_position; } AudioEngine::min_step_position = ( int ) round(( aStartPosition / AudioEngine::samples_per_bar ) * aStepsPerBar ); AudioEngine::max_step_position = ( int ) round(((( float ) aEndPosition / ( float ) AudioEngine::samples_per_bar ) * aStepsPerBar ) - 1 ); // keep current sequencer step within the new loop range if ( AudioEngine::stepPosition < AudioEngine::min_step_position || AudioEngine::stepPosition > AudioEngine::max_step_position ) { AudioEngine::stepPosition = AudioEngine::min_step_position; } updateStepsPerBar( aStepsPerBar ); } int SequencerController::getStepPosition() { return AudioEngine::stepPosition; } int SequencerController::getBufferPosition() { return AudioEngine::bufferPosition; } void SequencerController::setBufferPosition( int aPosition ) { // keep position within the sequences range (see "setLoopRange") if ( aPosition < AudioEngine::min_buffer_position || aPosition > AudioEngine::max_buffer_position ) { aPosition = AudioEngine::min_buffer_position; } AudioEngine::bufferPosition = aPosition; AudioEngine::stepPosition = ( aPosition / AudioEngine::samples_per_bar ) * stepsPerBar; Notifier::broadcast( Notifications::SEQUENCER_POSITION_UPDATED ); } int SequencerController::getSamplesPerBeat() { return AudioEngine::samples_per_beat; } int SequencerController::getSamplesPerStep() { return ( int ) AudioEngine::samples_per_step; } int SequencerController::getSamplesPerBar() { return AudioEngine::samples_per_bar; } int SequencerController::getTimeSigBeatAmount() { return AudioEngine::time_sig_beat_amount; } int SequencerController::getTimeSigBeatUnit() { return AudioEngine::time_sig_beat_unit; } void SequencerController::updateStepsPerBar( int aStepsPerBar ) { stepsPerBar = aStepsPerBar; AudioEngine::max_step_position = ( stepsPerBar * AudioEngine::amount_of_bars ) - 1; AudioEngine::beat_subdivision = stepsPerBar / AudioEngine::time_sig_beat_amount; // keep current sequencer step within the new loop range if ( AudioEngine::stepPosition > AudioEngine::max_step_position ) AudioEngine::stepPosition = AudioEngine::min_step_position; } void SequencerController::updateMeasures( int aValue, int aStepsPerBar ) { AudioEngine::amount_of_bars = aValue; AudioEngine::max_buffer_position = ( AudioEngine::samples_per_bar * AudioEngine::amount_of_bars ) - 1; updateStepsPerBar( aStepsPerBar ); } void SequencerController::rewind() { setBufferPosition( AudioEngine::min_buffer_position ); } void SequencerController::setNotificationMarker( int aPosition ) { AudioEngine::marked_buffer_position = aPosition; } /** * used for intelligent pre-caching, get the BaseCacheableAudioEvents * belonging to a specific measure for on-demand caching * * @param aMeasure {int} the measure containing the events we'd like to precache */ void SequencerController::cacheAudioEventsForMeasure( int aMeasure ) { int startBufferPos = AudioEngine::samples_per_bar * aMeasure; int endBufferPos = ( startBufferPos + AudioEngine::samples_per_bar ) - 1; std::vector<BaseCacheableAudioEvent*>* list = Sequencer::collectCacheableSequencerEvents( startBufferPos, endBufferPos ); getBulkCacher()->addToQueue( list ); delete list; // free memory if ( getBulkCacher()->hasQueue()) getBulkCacher()->cacheQueue(); } BulkCacher* SequencerController::getBulkCacher() { return Sequencer::bulkCacher; } /** * when bouncing, the writing of buffers into the hardware is omitted * for an increase in bouncing speed (otherwise its real time) */ void SequencerController::setBounceState( bool aIsBouncing, int aMaxBuffers, char* aOutputFile ) { AudioEngine::bouncing = aIsBouncing; if ( AudioEngine::bouncing ) { AudioEngine::bufferPosition = 0; AudioEngine::stepPosition = 0; } setRecordingState( aIsBouncing, aMaxBuffers, aOutputFile ); } /** * Record the output of the sequencer onto storage * * aRecording {bool} toggles the recording state * aMaxBuffers {int} the total recorded buffer size to store in memory * before writing the recorded snippet as .WAV file into * the given output file's directory. * aOutputDirectory {char*} name of the output WAV file to generate when recording completes * (when recording state is disabled), this will concatenate all snippets. */ void SequencerController::setRecordingState( bool aRecording, int aMaxBuffers, char* aOutputFile ) { // in case Sequencer was recording input from the Android device, halt recording of input if ( AudioEngine::recordInputToDisk ) setRecordingFromDeviceState( false, 0, ( char* ) "\0" ); bool wasRecording = AudioEngine::recordOutputToDisk; AudioEngine::recordOutputToDisk = aRecording; if ( AudioEngine::recordOutputToDisk ) { DiskWriter::prepare( std::string( aOutputFile ), roundTo( aMaxBuffers, AudioEngineProps::BUFFER_SIZE ), AudioEngineProps::OUTPUT_CHANNELS ); } else if ( wasRecording ) { // recording halted, write currently recording snippet into file // and concatenate all recorded snippets into the requested output file name // we can do this synchronously as this method is called from outside the // rendering thread and thus won't lead to buffer under runs DiskWriter::writeBufferToFile( DiskWriter::currentBufferIndex, false ); if ( DiskWriter::finish()) Notifier::broadcast( Notifications::RECORDING_COMPLETED ); } } /** * record audio from the Androids input channel, this stores only the incoming audio * not the remaining audio processed / generated by the engine * * aRecording {bool} toggles the recording state * aMaxBuffers {int} the total recorded buffer size to store in memory * before writing the recorded contents as .WAV file into * the given output directory. * aOutputDirectory {char*} name of the folder to write each snippet into */ void SequencerController::setRecordingFromDeviceState( bool aRecording, int aMaxBuffers, char* aOutputFile ) { // in case Sequencer was recording its output, halt recording of output if ( AudioEngine::recordOutputToDisk ) setRecordingState( false, 0, ( char* ) "\0" ); bool wasRecording = AudioEngine::recordInputToDisk; AudioEngine::recordInputToDisk = aRecording; if ( AudioEngine::recordInputToDisk ) { DiskWriter::prepare( std::string( aOutputFile ), roundTo( aMaxBuffers, AudioEngineProps::BUFFER_SIZE ), AudioEngineProps::INPUT_CHANNELS ); } else if ( wasRecording ) { // recording halted, write currently recording snippet into file // and concatenate all recorded snippets into the requested output file name // we can do this synchronously as this method is called from outside the // rendering thread and thus won't lead to buffer under runs DiskWriter::writeBufferToFile( DiskWriter::currentBufferIndex, false ); if ( DiskWriter::finish()) Notifier::broadcast( Notifications::RECORDING_COMPLETED ); } } /** * Save the contents of the snippet at given buffer index * onto storage. This should be invoked from a thread separate to the * audio rendering thread to prevent buffer under runs from happening */ void SequencerController::saveRecordedSnippet( int snippetBufferIndex ) { DiskWriter::writeBufferToFile( snippetBufferIndex, true ); } } // E.O namespace MWEngine <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: vimacros.cpp // Purpose: Implementation of class wxExViMacros // Author: Anton van Wezenbeek // Copyright: (c) 2012 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/stdpaths.h> #include <wx/txtstrm.h> #include <wx/wfstream.h> #include <wx/utils.h> #include <wx/extension/vimacros.h> #include <wx/extension/ex.h> #include <wx/extension/stc.h> #if wxUSE_GUI bool wxExViMacros::m_IsExpand = false; bool wxExViMacros::m_IsModified = false; bool wxExViMacros::m_IsPlayback = false; std::map <wxString, std::vector< wxString > > wxExViMacros::m_Macros; std::map <wxString, wxExVariable > wxExViMacros::m_Variables; wxExViMacros::wxExViMacros() : m_IsRecording(false) { } void wxExViMacros::AskForInput() { for (std::map<wxString, wxExVariable >::iterator it = m_Variables.begin(); it != m_Variables.end(); ++it) { it->second.AskForInput(); } } const wxString wxExViMacros::Decode(const wxString& text) { long c; if (text.ToLong(&c)) { return char(c); } return text; } const wxString wxExViMacros::Encode(const wxString& text, bool& encoded) { if (text.length() == 1) { int c = text[0]; // Encode control characters, and whitespace. if (iscntrl(c) || isspace(c)) { encoded = true; return wxString::Format("%d", c); } } return text; } bool wxExViMacros::Expand(wxExEx* ex, const wxString& variable) { std::map<wxString, wxExVariable>::iterator it = m_Variables.find(variable); bool ok; if (it == m_Variables.end()) { std::pair<std::map<wxString, wxExVariable>::iterator, bool> ret = m_Variables.insert(std::make_pair(variable, wxExVariable(variable))); wxLogStatus(_("Added variable") + ": " + variable); ok = ret.first->second.Expand(ex); if (ret.first->second.IsModified()) { m_IsModified = true; } } else { ok = it->second.Expand(ex); if (it->second.IsModified()) { m_IsModified = true; } } if (!ok) { wxLogStatus(_("Could not expand variable") + ": " + variable); } return ok; } bool wxExViMacros::Expand(wxExEx* ex, const wxString& variable, wxString& value) { std::map<wxString, wxExVariable>::iterator it = m_Variables.find(variable); bool ok; if (it == m_Variables.end()) { std::pair<std::map<wxString, wxExVariable>::iterator, bool> ret = m_Variables.insert(std::make_pair(variable, wxExVariable(variable))); wxLogStatus(_("Added variable") + ": " + variable); ok = ret.first->second.Expand(ex, value); // If we are expanding, one input is enough. if (m_IsExpand) { ret.first->second.SkipInput(); } if (ret.first->second.IsModified()) { m_IsModified = true; } } else { ok = it->second.Expand(ex, value); // If we are expanding, one input is enough. if (m_IsExpand) { it->second.SkipInput(); } if (it->second.IsModified()) { m_IsModified = true; } } if (!ok) { wxLogStatus(_("Could not expand variable") + ": " + variable); } return ok; } bool wxExViMacros::ExpandTemplate( wxExEx* ex, const wxExVariable& v, wxString& expanded) { if (!m_IsExpand) { m_IsExpand = true; AskForInput(); } // Read the file (file name is in m_Value), expand // all macro variables in it, and set expanded. const wxFileName filename( #ifdef wxExUSE_PORTABLE wxPathOnly(wxStandardPaths::Get().GetExecutablePath()) #else wxStandardPaths::Get().GetUserDataDir() #endif + wxFileName::GetPathSeparator() + v.GetValue()); wxFileInputStream input(filename.GetFullPath()); if (!input.IsOk()) { wxLogError("Could not open template file: " + filename.GetFullPath()); return false; } wxTextInputStream text(input); while (input.IsOk() && !input.Eof()) { const wxChar c = text.GetChar(); if (c != '@') { expanded += c; } else { wxString variable; bool completed = false; while (input.IsOk() && !input.Eof() && !completed) { const wxChar c = text.GetChar(); if (c != '@') { variable += c; } else { completed = true; } } if (!completed) { return false; } // Prevent recursion. if (variable == v.GetName()) { return false; } wxString value; if (!Expand(ex, variable, value)) { return false; } expanded += value; } } m_IsExpand = false; // Set back to normal value. AskForInput(); return true; } const wxArrayString wxExViMacros::Get() const { wxArrayString as; for ( std::map<wxString, std::vector<wxString> >::const_iterator it = m_Macros.begin(); it != m_Macros.end(); ++it) { as.Add(it->first); } return as; } const std::vector< wxString > wxExViMacros::Get(const wxString& macro) const { std::map<wxString, std::vector< wxString > >::const_iterator it = m_Macros.find(macro); if (it != m_Macros.end()) { return it->second; } else { std::vector<wxString> empty; return empty; } } const wxFileName wxExViMacros::GetFileName() { return wxFileName( #ifdef wxExUSE_PORTABLE wxPathOnly(wxStandardPaths::Get().GetExecutablePath()) #else wxStandardPaths::Get().GetUserDataDir() #endif + wxFileName::GetPathSeparator() + "macros.xml"); } bool wxExViMacros::IsRecorded(const wxString& macro) const { if (macro.empty()) { return !m_Macros.empty(); } else { return !Get(macro).empty(); } } bool wxExViMacros::Load(wxXmlDocument& doc) { // This test is to prevent showing an error if the macro file does not exist, // as this is not required. if (!GetFileName().FileExists()) { return false; } if (!doc.Load(GetFileName().GetFullPath())) { return false; } return true; } bool wxExViMacros::LoadDocument() { wxXmlDocument doc; if (!Load(doc)) { return false; } // If modified is true, then you did not save previous // recordings. // We assume that this is your choice, so we reset the member. m_IsModified = false; m_Macros.clear(); m_Variables.clear(); wxXmlNode* root = doc.GetRoot(); wxXmlNode* child = root->GetChildren(); while (child) { if (child->GetName() == "macro") { std::vector<wxString> v; wxXmlNode* command = child->GetChildren(); while (command) { if (command->GetAttribute("encoded", "false") == "true") { v.push_back(Decode(command->GetNodeContent())); } else { v.push_back(command->GetNodeContent()); } command = command->GetNext(); } std::map<wxString, std::vector< wxString >>::const_iterator it = m_Macros.find(child->GetAttribute("name")); if (it != m_Macros.end()) { wxLogError("Duplicate macro: %s on line: %d", child->GetAttribute("name"), child->GetLineNumber()); } else { m_Macros.insert(std::make_pair(child->GetAttribute("name"), v)); } } else if (child->GetName() == "variable") { wxExVariable variable(child); std::map<wxString, wxExVariable>::const_iterator it = m_Variables.find(variable.GetName()); if (it != m_Variables.end()) { wxLogError("Duplicate variable: %s on line: %d", variable.GetName(), child->GetLineNumber()); } else { m_Variables.insert(std::make_pair(variable.GetName(), variable)); } } child = child->GetNext(); } return true; } bool wxExViMacros::Playback(wxExEx* ex, const wxString& macro, int repeat) { if (!IsRecorded(macro) || macro.empty()) { wxLogStatus(_("Unknown macro") + ": " + macro); return false; } if (m_IsPlayback && macro == m_Macro) { wxLogStatus(_("Already playing back")); return false; } if (repeat <= 0) { return false; } ex->GetSTC()->BeginUndoAction(); bool stop = false; m_IsPlayback = true; m_Macro = macro; wxBusyCursor; AskForInput(); for (int i = 0; i < repeat; i++) { for ( std::vector<wxString>::const_iterator it = m_Macros[macro].begin(); it != m_Macros[macro].end() && !stop; ++it) { stop = !ex->Command(*it); if (stop) { wxLogStatus(_("Macro aborted at '") + *it + "'"); } } } ex->GetSTC()->EndUndoAction(); if (!stop) { wxLogStatus(_("Macro played back")); } m_IsPlayback = false; return !stop; } void wxExViMacros::Record(const wxString& text, bool new_command) { if (!m_IsRecording) { return; } m_IsModified = true; if (new_command) { m_Macros[m_Macro].push_back(text); } else { if (m_Macros[m_Macro].empty()) { m_Macros[m_Macro].push_back(wxEmptyString); } m_Macros[m_Macro].back() += text; } } bool wxExViMacros::SaveDocument(bool only_if_modified) { if (!m_IsModified && only_if_modified) { return false; } wxXmlDocument doc; if (!Load(doc)) { return false; } wxXmlNode* root = doc.GetRoot(); wxXmlNode* child; while (child = root->GetChildren()) { root->RemoveChild(child); delete child; } for ( std::map<wxString, std::vector<wxString> >::reverse_iterator it = m_Macros.rbegin(); it != m_Macros.rend(); ++it) { wxXmlNode* element = new wxXmlNode(root, wxXML_ELEMENT_NODE, "macro"); element->AddAttribute("name", it->first); for ( std::vector<wxString>::reverse_iterator it2 = it->second.rbegin(); it2 != it->second.rend(); ++it2) { bool encoded = false; const wxString contents(Encode(*it2, encoded)); wxXmlNode* cmd = new wxXmlNode(element, wxXML_ELEMENT_NODE, "command"); new wxXmlNode(cmd, wxXML_TEXT_NODE, "", contents); if (encoded) { cmd->AddAttribute("encoded", "true"); } } } for ( std::map< wxString, wxExVariable >::reverse_iterator it2 = m_Variables.rbegin(); it2 != m_Variables.rend(); ++it2) { wxXmlNode* element = new wxXmlNode(root, wxXML_ELEMENT_NODE, "variable"); it2->second.Save(element); } const bool ok = doc.Save(GetFileName().GetFullPath()); if (ok) { m_IsModified = false; } return ok; } void wxExViMacros::StartRecording(const wxString& macro) { if (m_IsRecording || macro.empty()) { return; } m_IsRecording = true; if (macro.size() == 1) { // We only use lower case macro's, to be able to // append to them using qA. m_Macro = macro.Lower(); // Clear macro if it is lower case // (otherwise append to the macro). if (wxIslower(macro[0])) { m_Macros[m_Macro].clear(); } } else { m_Macro = macro; m_Macros[m_Macro].clear(); } wxLogStatus(_("Macro recording")); } void wxExViMacros::StopRecording() { if (!m_IsRecording) { return; } m_IsRecording = false; if (!Get(m_Macro).empty()) { wxLogStatus(wxString::Format(_("Macro '%s' is recorded"), m_Macro.c_str())); } else { wxLogStatus(_("Ready")); } } #endif // wxUSE_GUI <commit_msg>fixed compile error<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: vimacros.cpp // Purpose: Implementation of class wxExViMacros // Author: Anton van Wezenbeek // Copyright: (c) 2012 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/stdpaths.h> #include <wx/txtstrm.h> #include <wx/wfstream.h> #include <wx/utils.h> #include <wx/extension/vimacros.h> #include <wx/extension/ex.h> #include <wx/extension/stc.h> #if wxUSE_GUI bool wxExViMacros::m_IsExpand = false; bool wxExViMacros::m_IsModified = false; bool wxExViMacros::m_IsPlayback = false; std::map <wxString, std::vector< wxString > > wxExViMacros::m_Macros; std::map <wxString, wxExVariable > wxExViMacros::m_Variables; wxExViMacros::wxExViMacros() : m_IsRecording(false) { } void wxExViMacros::AskForInput() { for (std::map<wxString, wxExVariable >::iterator it = m_Variables.begin(); it != m_Variables.end(); ++it) { it->second.AskForInput(); } } const wxString wxExViMacros::Decode(const wxString& text) { long c; if (text.ToLong(&c)) { return char(c); } return text; } const wxString wxExViMacros::Encode(const wxString& text, bool& encoded) { if (text.length() == 1) { int c = text[0]; // Encode control characters, and whitespace. if (iscntrl(c) || isspace(c)) { encoded = true; return wxString::Format("%d", c); } } return text; } bool wxExViMacros::Expand(wxExEx* ex, const wxString& variable) { std::map<wxString, wxExVariable>::iterator it = m_Variables.find(variable); bool ok; if (it == m_Variables.end()) { std::pair<std::map<wxString, wxExVariable>::iterator, bool> ret = m_Variables.insert(std::make_pair(variable, wxExVariable(variable))); wxLogStatus(_("Added variable") + ": " + variable); ok = ret.first->second.Expand(ex); if (ret.first->second.IsModified()) { m_IsModified = true; } } else { ok = it->second.Expand(ex); if (it->second.IsModified()) { m_IsModified = true; } } if (!ok) { wxLogStatus(_("Could not expand variable") + ": " + variable); } return ok; } bool wxExViMacros::Expand(wxExEx* ex, const wxString& variable, wxString& value) { std::map<wxString, wxExVariable>::iterator it = m_Variables.find(variable); bool ok; if (it == m_Variables.end()) { std::pair<std::map<wxString, wxExVariable>::iterator, bool> ret = m_Variables.insert(std::make_pair(variable, wxExVariable(variable))); wxLogStatus(_("Added variable") + ": " + variable); ok = ret.first->second.Expand(ex, value); // If we are expanding, one input is enough. if (m_IsExpand) { ret.first->second.SkipInput(); } if (ret.first->second.IsModified()) { m_IsModified = true; } } else { ok = it->second.Expand(ex, value); // If we are expanding, one input is enough. if (m_IsExpand) { it->second.SkipInput(); } if (it->second.IsModified()) { m_IsModified = true; } } if (!ok) { wxLogStatus(_("Could not expand variable") + ": " + variable); } return ok; } bool wxExViMacros::ExpandTemplate( wxExEx* ex, const wxExVariable& v, wxString& expanded) { if (!m_IsExpand) { m_IsExpand = true; AskForInput(); } // Read the file (file name is in m_Value), expand // all macro variables in it, and set expanded. const wxFileName filename( #ifdef wxExUSE_PORTABLE wxPathOnly(wxStandardPaths::Get().GetExecutablePath()) #else wxStandardPaths::Get().GetUserDataDir() #endif + wxFileName::GetPathSeparator() + v.GetValue()); wxFileInputStream input(filename.GetFullPath()); if (!input.IsOk()) { wxLogError("Could not open template file: " + filename.GetFullPath()); return false; } wxTextInputStream text(input); while (input.IsOk() && !input.Eof()) { const wxChar c = text.GetChar(); if (c != '@') { expanded += c; } else { wxString variable; bool completed = false; while (input.IsOk() && !input.Eof() && !completed) { const wxChar c = text.GetChar(); if (c != '@') { variable += c; } else { completed = true; } } if (!completed) { return false; } // Prevent recursion. if (variable == v.GetName()) { return false; } wxString value; if (!Expand(ex, variable, value)) { return false; } expanded += value; } } m_IsExpand = false; // Set back to normal value. AskForInput(); return true; } const wxArrayString wxExViMacros::Get() const { wxArrayString as; for ( std::map<wxString, std::vector<wxString> >::const_iterator it = m_Macros.begin(); it != m_Macros.end(); ++it) { as.Add(it->first); } return as; } const std::vector< wxString > wxExViMacros::Get(const wxString& macro) const { std::map<wxString, std::vector< wxString > >::const_iterator it = m_Macros.find(macro); if (it != m_Macros.end()) { return it->second; } else { std::vector<wxString> empty; return empty; } } const wxFileName wxExViMacros::GetFileName() { return wxFileName( #ifdef wxExUSE_PORTABLE wxPathOnly(wxStandardPaths::Get().GetExecutablePath()) #else wxStandardPaths::Get().GetUserDataDir() #endif + wxFileName::GetPathSeparator() + "macros.xml"); } bool wxExViMacros::IsRecorded(const wxString& macro) const { if (macro.empty()) { return !m_Macros.empty(); } else { return !Get(macro).empty(); } } bool wxExViMacros::Load(wxXmlDocument& doc) { // This test is to prevent showing an error if the macro file does not exist, // as this is not required. if (!GetFileName().FileExists()) { return false; } if (!doc.Load(GetFileName().GetFullPath())) { return false; } return true; } bool wxExViMacros::LoadDocument() { wxXmlDocument doc; if (!Load(doc)) { return false; } // If modified is true, then you did not save previous // recordings. // We assume that this is your choice, so we reset the member. m_IsModified = false; m_Macros.clear(); m_Variables.clear(); wxXmlNode* root = doc.GetRoot(); wxXmlNode* child = root->GetChildren(); while (child) { if (child->GetName() == "macro") { std::vector<wxString> v; wxXmlNode* command = child->GetChildren(); while (command) { if (command->GetAttribute("encoded", "false") == "true") { v.push_back(Decode(command->GetNodeContent())); } else { v.push_back(command->GetNodeContent()); } command = command->GetNext(); } std::map<wxString, std::vector< wxString >>::const_iterator it = m_Macros.find(child->GetAttribute("name")); if (it != m_Macros.end()) { wxLogError("Duplicate macro: %s on line: %d", child->GetAttribute("name"), child->GetLineNumber()); } else { m_Macros.insert(std::make_pair(child->GetAttribute("name"), v)); } } else if (child->GetName() == "variable") { wxExVariable variable(child); std::map<wxString, wxExVariable>::const_iterator it = m_Variables.find(variable.GetName()); if (it != m_Variables.end()) { wxLogError("Duplicate variable: %s on line: %d", variable.GetName(), child->GetLineNumber()); } else { m_Variables.insert(std::make_pair(variable.GetName(), variable)); } } child = child->GetNext(); } return true; } bool wxExViMacros::Playback(wxExEx* ex, const wxString& macro, int repeat) { if (!IsRecorded(macro) || macro.empty()) { wxLogStatus(_("Unknown macro") + ": " + macro); return false; } if (m_IsPlayback && macro == m_Macro) { wxLogStatus(_("Already playing back")); return false; } if (repeat <= 0) { return false; } ex->GetSTC()->BeginUndoAction(); bool stop = false; m_IsPlayback = true; m_Macro = macro; wxBusyCursor wait; AskForInput(); for (int i = 0; i < repeat; i++) { for ( std::vector<wxString>::const_iterator it = m_Macros[macro].begin(); it != m_Macros[macro].end() && !stop; ++it) { stop = !ex->Command(*it); if (stop) { wxLogStatus(_("Macro aborted at '") + *it + "'"); } } } ex->GetSTC()->EndUndoAction(); if (!stop) { wxLogStatus(_("Macro played back")); } m_IsPlayback = false; return !stop; } void wxExViMacros::Record(const wxString& text, bool new_command) { if (!m_IsRecording) { return; } m_IsModified = true; if (new_command) { m_Macros[m_Macro].push_back(text); } else { if (m_Macros[m_Macro].empty()) { m_Macros[m_Macro].push_back(wxEmptyString); } m_Macros[m_Macro].back() += text; } } bool wxExViMacros::SaveDocument(bool only_if_modified) { if (!m_IsModified && only_if_modified) { return false; } wxXmlDocument doc; if (!Load(doc)) { return false; } wxXmlNode* root = doc.GetRoot(); wxXmlNode* child; while (child = root->GetChildren()) { root->RemoveChild(child); delete child; } for ( std::map<wxString, std::vector<wxString> >::reverse_iterator it = m_Macros.rbegin(); it != m_Macros.rend(); ++it) { wxXmlNode* element = new wxXmlNode(root, wxXML_ELEMENT_NODE, "macro"); element->AddAttribute("name", it->first); for ( std::vector<wxString>::reverse_iterator it2 = it->second.rbegin(); it2 != it->second.rend(); ++it2) { bool encoded = false; const wxString contents(Encode(*it2, encoded)); wxXmlNode* cmd = new wxXmlNode(element, wxXML_ELEMENT_NODE, "command"); new wxXmlNode(cmd, wxXML_TEXT_NODE, "", contents); if (encoded) { cmd->AddAttribute("encoded", "true"); } } } for ( std::map< wxString, wxExVariable >::reverse_iterator it2 = m_Variables.rbegin(); it2 != m_Variables.rend(); ++it2) { wxXmlNode* element = new wxXmlNode(root, wxXML_ELEMENT_NODE, "variable"); it2->second.Save(element); } const bool ok = doc.Save(GetFileName().GetFullPath()); if (ok) { m_IsModified = false; } return ok; } void wxExViMacros::StartRecording(const wxString& macro) { if (m_IsRecording || macro.empty()) { return; } m_IsRecording = true; if (macro.size() == 1) { // We only use lower case macro's, to be able to // append to them using qA. m_Macro = macro.Lower(); // Clear macro if it is lower case // (otherwise append to the macro). if (wxIslower(macro[0])) { m_Macros[m_Macro].clear(); } } else { m_Macro = macro; m_Macros[m_Macro].clear(); } wxLogStatus(_("Macro recording")); } void wxExViMacros::StopRecording() { if (!m_IsRecording) { return; } m_IsRecording = false; if (!Get(m_Macro).empty()) { wxLogStatus(wxString::Format(_("Macro '%s' is recorded"), m_Macro.c_str())); } else { wxLogStatus(_("Ready")); } } #endif // wxUSE_GUI <|endoftext|>
<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <common/Producer.h> #include <cstring> #include <dlfcn.h> #include <librdkafka/rdkafkacpp.h> #include <test/TestBase.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" int fail = -1; // Dont fail // Create pointers to the retuned objects typedef RdKafka::Conf *(*pcreate)(RdKafka::Conf::ConfType); typedef RdKafka::Producer *(*pcreateprod)(RdKafka::Conf *, std::string &); typedef RdKafka::Topic *(*pcreatetopic)(RdKafka::Handle *, std::string const &, RdKafka::Conf *, std::string &); /**Attmpt to load primary and alternatively secondary symbols using dlsym() * Created to cover different compilations of librdkafka (old and new abis) * Used for forcing external functions to fail for unit testing purposes * exit if none of the symbols can be loaded. **/ void * loadsyms(const char * primary, const char * secondary) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" void * vpsym = dlsym(RTLD_NEXT, primary); if (vpsym == NULL) { printf("Could not load primary symbol: %s\n", primary); printf("Trying secondary...\n"); dlerror(); vpsym = dlsym(RTLD_NEXT, secondary); if (vpsym == NULL) { printf("Could not load secondary symbol: %s\n", secondary); printf("Error stubbing kafka functions\n"); exit(1); } } #pragma GCC diagnostic pop return vpsym; } /** Intercept RdKafka::Conf::create() */ RdKafka::Conf *RdKafka::Conf::create(ConfType type) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" pcreate real_create = (pcreate)loadsyms( "_ZN7RdKafka4Conf6createENS0_8ConfTypeE", "_ZN7RdKafka4Conf6createENS0_8ConfTypeE"); // nm -C #pragma GCC diagnostic pop if (fail != -1 && type == fail) { printf("Forcing RdKafka::Conf::create() to fail\n"); return nullptr; } else { return real_create(type); } } /** Intercept RdKafka::Producer::create() */ RdKafka::Producer *RdKafka::Producer::create(RdKafka::Conf *type, std::string &str) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" pcreateprod real_create = (pcreateprod)loadsyms( "_ZN7RdKafka8Producer6createEPNS_4ConfERSs", "_ZN7RdKafka8Producer6createEPNS_4ConfERNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE"); // nm -C librdkafka.a #pragma GCC diagnostic pop if (fail == 777) { printf("Forcing RdKafka::Producer::create() to fail\n"); return nullptr; } else { return real_create(type, str); } } /** Intercept RdKafka::Topic::create() */ RdKafka::Topic *RdKafka::Topic::create(RdKafka::Handle *handle, std::string const &topic, RdKafka::Conf *conf, std::string &str) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" pcreatetopic real_create = (pcreatetopic)loadsyms( "_ZN7RdKafka5Topic6createEPNS_6HandleERKSsPNS_4ConfERSs", "_ZN7RdKafka5Topic6createEPNS_6HandleERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS_4ConfERS8_"); #pragma GCC diagnostic pop if (fail == 888) { printf("Forcing RdKafka::Topic::create() to fail\n"); return nullptr; } else { return real_create(handle, topic, conf, str); } } // // Google test code below // class ProducerTest : public TestBase { virtual void SetUp() { fail = -1; } virtual void TearDown() {} }; TEST_F(ProducerTest, ConstructorOK) { Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_NO_ERROR); ASSERT_EQ(prod.dr_errors, 0); ASSERT_EQ(prod.dr_noerrors, 0); ASSERT_EQ(prod.ev_errors, 0); ASSERT_EQ(prod.stats.ev_others, 0); } TEST_F(ProducerTest, CreateConfGlobalFail) { fail = RdKafka::Conf::CONF_GLOBAL; Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, CreateConfTopicFail) { fail = RdKafka::Conf::CONF_TOPIC; Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, CreateProducerFail) { fail = 777; Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, CreateTopicFail) { fail = 888; Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, ProducerFail) { Producer prod{"nobroker", "notopic"}; int ret = prod.produce((char *)10000, 100000000); ASSERT_EQ(ret, RdKafka::ERR_MSG_SIZE_TOO_LARGE); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #pragma GCC diagnostic pop <commit_msg>fixing unit test<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <common/Producer.h> #include <cstring> #include <dlfcn.h> #include <librdkafka/rdkafkacpp.h> #include <test/TestBase.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" int fail = -1; // Dont fail // Create pointers to the retuned objects typedef RdKafka::Conf *(*pcreate)(RdKafka::Conf::ConfType); typedef RdKafka::Producer *(*pcreateprod)(RdKafka::Conf *, std::string &); typedef RdKafka::Topic *(*pcreatetopic)(RdKafka::Handle *, std::string const &, RdKafka::Conf *, std::string &); /**Attmpt to load primary and alternatively secondary symbols using dlsym() * Created to cover different compilations of librdkafka (old and new abis) * Used for forcing external functions to fail for unit testing purposes * exit if none of the symbols can be loaded. **/ void * loadsyms(const char * primary, const char * secondary) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" void * vpsym = dlsym(RTLD_NEXT, primary); if (vpsym == NULL) { printf("Could not load primary symbol: %s\n", primary); printf("Trying secondary...\n"); dlerror(); vpsym = dlsym(RTLD_NEXT, secondary); if (vpsym == NULL) { printf("Could not load secondary symbol: %s\n", secondary); printf("Error stubbing kafka functions\n"); exit(1); } } #pragma GCC diagnostic pop return vpsym; } /** Intercept RdKafka::Conf::create() */ RdKafka::Conf *RdKafka::Conf::create(ConfType type) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" pcreate real_create = (pcreate)loadsyms( "_ZN7RdKafka4Conf6createENS0_8ConfTypeE", "_ZN7RdKafka4Conf6createENS0_8ConfTypeE"); // nm -C #pragma GCC diagnostic pop if (fail != -1 && type == fail) { printf("Forcing RdKafka::Conf::create() to fail\n"); return nullptr; } else { return real_create(type); } } /** Intercept RdKafka::Producer::create() */ RdKafka::Producer *RdKafka::Producer::create(RdKafka::Conf *type, std::string &str) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" pcreateprod real_create = (pcreateprod)loadsyms( "_ZN7RdKafka8Producer6createEPNS_4ConfERSs", "_ZN7RdKafka8Producer6createEPNS_4ConfERNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE"); // nm -C librdkafka.a #pragma GCC diagnostic pop if (fail == 777) { printf("Forcing RdKafka::Producer::create() to fail\n"); return nullptr; } else { return real_create(type, str); } } /** Intercept RdKafka::Topic::create() */ RdKafka::Topic *RdKafka::Topic::create(RdKafka::Handle *handle, std::string const &topic, RdKafka::Conf *conf, std::string &str) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" pcreatetopic real_create = (pcreatetopic)loadsyms( "_ZN7RdKafka5Topic6createEPNS_6HandleERKSsPNS_4ConfERSs", "_ZN7RdKafka5Topic6createEPNS_6HandleERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS_4ConfERS8_"); #pragma GCC diagnostic pop if (fail == 888) { printf("Forcing RdKafka::Topic::create() to fail\n"); return nullptr; } else { return real_create(handle, topic, conf, str); } } // // Google test code below // class ProducerTest : public TestBase { virtual void SetUp() { fail = -1; } virtual void TearDown() {} }; TEST_F(ProducerTest, ConstructorOK) { Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_NO_ERROR); ASSERT_EQ(prod.stats.dr_errors, 0); ASSERT_EQ(prod.stats.dr_noerrors, 0); ASSERT_EQ(prod.stats.ev_errors, 0); ASSERT_EQ(prod.stats.ev_others, 0); ASSERT_EQ(prod.stats.produce_fails, 0); } TEST_F(ProducerTest, CreateConfGlobalFail) { fail = RdKafka::Conf::CONF_GLOBAL; Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, CreateConfTopicFail) { fail = RdKafka::Conf::CONF_TOPIC; Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, CreateProducerFail) { fail = 777; Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, CreateTopicFail) { fail = 888; Producer prod{"nobroker", "notopic"}; int ret = prod.produce(0, 0); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, ProducerFail) { Producer prod{"nobroker", "notopic"}; int ret = prod.produce((char *)10000, 100000000); ASSERT_EQ(ret, RdKafka::ERR_MSG_SIZE_TOO_LARGE); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #pragma GCC diagnostic pop <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2015-2017. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "InstanceImpl.h" using namespace nt; std::atomic<int> InstanceImpl::s_default{-1}; std::atomic<InstanceImpl*> InstanceImpl::s_fast_instances[10]; wpi::UidVector<std::unique_ptr<InstanceImpl>, 10> InstanceImpl::s_instances; std::mutex InstanceImpl::s_mutex; using namespace std::placeholders; InstanceImpl::InstanceImpl(int inst) : logger_impl(inst), logger(std::bind(&LoggerImpl::Log, &logger_impl, _1, _2, _3, _4)), connection_notifier(inst), entry_notifier(inst, logger), rpc_server(inst, logger), storage(entry_notifier, rpc_server, logger), dispatcher(storage, connection_notifier, logger), ds_client(dispatcher, logger) {} InstanceImpl::~InstanceImpl() { logger.SetLogger(nullptr); } InstanceImpl* InstanceImpl::GetDefault() { return Get(GetDefaultIndex()); } InstanceImpl* InstanceImpl::Get(int inst) { if (inst < 0) return nullptr; // fast path, just an atomic read if (static_cast<unsigned int>(inst) < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { InstanceImpl* ptr = s_fast_instances[inst]; if (ptr) return ptr; } // slow path std::lock_guard<std::mutex> lock(s_mutex); // static fast-path block if (static_cast<unsigned int>(inst) < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { // double-check return s_fast_instances[inst]; } // vector if (static_cast<unsigned int>(inst) < s_instances.size()) { return s_instances[inst].get(); } // doesn't exist return nullptr; } int InstanceImpl::GetDefaultIndex() { int inst = s_default; if (inst >= 0) return inst; // slow path std::lock_guard<std::mutex> lock(s_mutex); // double-check inst = s_default; if (inst >= 0) return inst; // alloc and save inst = AllocImpl(); s_default = inst; return inst; } int InstanceImpl::Alloc() { std::lock_guard<std::mutex> lock(s_mutex); return AllocImpl(); } int InstanceImpl::AllocImpl() { unsigned int inst = s_instances.emplace_back(); InstanceImpl* ptr = new InstanceImpl(inst); s_instances[inst].reset(ptr); if (inst < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { s_fast_instances[inst] = ptr; } return static_cast<int>(inst); } void InstanceImpl::Destroy(int inst) { std::lock_guard<std::mutex> lock(s_mutex); if (inst < 0 || static_cast<unsigned int>(inst) >= s_instances.size()) return; if (static_cast<unsigned int>(inst) < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { s_fast_instances[inst] = nullptr; } s_instances.erase(inst); } <commit_msg>Initialize logger min level from logger_impl.<commit_after>/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2015-2017. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "InstanceImpl.h" using namespace nt; std::atomic<int> InstanceImpl::s_default{-1}; std::atomic<InstanceImpl*> InstanceImpl::s_fast_instances[10]; wpi::UidVector<std::unique_ptr<InstanceImpl>, 10> InstanceImpl::s_instances; std::mutex InstanceImpl::s_mutex; using namespace std::placeholders; InstanceImpl::InstanceImpl(int inst) : logger_impl(inst), logger(std::bind(&LoggerImpl::Log, &logger_impl, _1, _2, _3, _4)), connection_notifier(inst), entry_notifier(inst, logger), rpc_server(inst, logger), storage(entry_notifier, rpc_server, logger), dispatcher(storage, connection_notifier, logger), ds_client(dispatcher, logger) { logger.set_min_level(logger_impl.GetMinLevel()); } InstanceImpl::~InstanceImpl() { logger.SetLogger(nullptr); } InstanceImpl* InstanceImpl::GetDefault() { return Get(GetDefaultIndex()); } InstanceImpl* InstanceImpl::Get(int inst) { if (inst < 0) return nullptr; // fast path, just an atomic read if (static_cast<unsigned int>(inst) < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { InstanceImpl* ptr = s_fast_instances[inst]; if (ptr) return ptr; } // slow path std::lock_guard<std::mutex> lock(s_mutex); // static fast-path block if (static_cast<unsigned int>(inst) < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { // double-check return s_fast_instances[inst]; } // vector if (static_cast<unsigned int>(inst) < s_instances.size()) { return s_instances[inst].get(); } // doesn't exist return nullptr; } int InstanceImpl::GetDefaultIndex() { int inst = s_default; if (inst >= 0) return inst; // slow path std::lock_guard<std::mutex> lock(s_mutex); // double-check inst = s_default; if (inst >= 0) return inst; // alloc and save inst = AllocImpl(); s_default = inst; return inst; } int InstanceImpl::Alloc() { std::lock_guard<std::mutex> lock(s_mutex); return AllocImpl(); } int InstanceImpl::AllocImpl() { unsigned int inst = s_instances.emplace_back(); InstanceImpl* ptr = new InstanceImpl(inst); s_instances[inst].reset(ptr); if (inst < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { s_fast_instances[inst] = ptr; } return static_cast<int>(inst); } void InstanceImpl::Destroy(int inst) { std::lock_guard<std::mutex> lock(s_mutex); if (inst < 0 || static_cast<unsigned int>(inst) >= s_instances.size()) return; if (static_cast<unsigned int>(inst) < (sizeof(s_fast_instances) / sizeof(s_fast_instances[0]))) { s_fast_instances[inst] = nullptr; } s_instances.erase(inst); } <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/games/othello.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include <tuple> #include "open_spiel/spiel_utils.h" #include "open_spiel/utils/tensor_view.h" namespace open_spiel { namespace othello { namespace { // Facts about the game. const GameType kGameType{ /*short_name=*/"othello", /*long_name=*/"Othello", GameType::Dynamics::kSequential, GameType::ChanceMode::kDeterministic, GameType::Information::kPerfectInformation, GameType::Utility::kZeroSum, GameType::RewardModel::kTerminal, /*max_num_players=*/2, /*min_num_players=*/2, /*provides_information_state_string=*/true, /*provides_information_state_tensor=*/false, /*provides_observation_string=*/true, /*provides_observation_tensor=*/true, /*parameter_specification=*/{} // no parameters }; std::shared_ptr<const Game> Factory(const GameParameters& params) { return std::shared_ptr<const Game>(new OthelloGame(params)); } REGISTER_SPIEL_GAME(kGameType, Factory); } // namespace std::tuple<int, int> GetNext(int row, int col, Direction dir) { switch (dir) { case Direction::kUp: return std::make_tuple(row - 1, col); case Direction::kDown: return std::make_tuple(row + 1, col); case Direction::kLeft: return std::make_tuple(row, col - 1); case Direction::kRight: return std::make_tuple(row, col + 1); case Direction::kUpRight: return std::make_tuple(row - 1, col + 1); case Direction::kUpLeft: return std::make_tuple(row - 1, col - 1); case Direction::kDownRight: return std::make_tuple(row + 1, col + 1); case Direction::kDownLeft: return std::make_tuple(row + 1, col - 1); default: SpielFatalError(absl::StrCat("Found unmatched case in GetNext.")); } } inline bool OthelloState::OnBoard(int row, int col) const { return (0 <= row) && (row < kNumRows) && (0 <= col) && (col < kNumCols); } int OthelloState::CountSteps(Player player, int row, int col, Direction dir) const { std::tuple<int, int> rowcol = GetNext(row, col, dir); row = std::get<0>(rowcol); col = std::get<1>(rowcol); int count = 0; CellState cell = PlayerToState(player); while (OnBoard(row, col)) { if (BoardAt(row, col) == cell) { return count; } else if (BoardAt(row, col) == CellState::kEmpty) { return 0; } count++; rowcol = GetNext(row, col, dir); row = std::get<0>(rowcol); col = std::get<1>(rowcol); } return 0; } bool OthelloState::CanCapture(Player player, int move) const { if (board_[move] != CellState::kEmpty) return false; std::tuple<int, int> row_col = XYFromCode(move); int row = std::get<0>(row_col); int col = std::get<1>(row_col); // bool none_adjacent = true; // for (int i = -1; i < 2; i++) { // for (int j = -1; j < 2; j++) { // if (OnBoard(row + i, col + j) && (BoardAt(row + i, col + j) != CellState::kEmpty)) none_adjacent = false; // } // } // if (none_adjacent) return false; bool valid = false; for (int direction = Direction::kUp; direction < Direction::kLast; direction++) { if (CountSteps(player, row, col, static_cast<Direction>(direction)) != 0) { return true; } } return false; } void OthelloState::Capture(Player player, int row, int col, Direction dir, int steps) { std::tuple<int, int> rowcol = GetNext(row, col, dir); row = std::get<0>(rowcol); col = std::get<1>(rowcol); CellState cell = PlayerToState(player); for (int step = 0; step < steps; step++) { if (BoardAt(row, col) == CellState::kEmpty || BoardAt(row, col) == cell) { SpielFatalError(absl::StrCat("Cannot capture cell (", row, ", ", col, ")")); } board_[row * kNumCols + col] = cell; rowcol = GetNext(row, col, dir); row = std::get<0>(rowcol); col = std::get<1>(rowcol); } } int OthelloState::DiskCount(Player player) const { int count = 0; CellState cell = PlayerToState(player); for (int i = 0; i < kNumCells; i++) { if (board_[i] == cell) count++; } return count; } bool OthelloState::NoValidActions() const { return (LegalRegularActions(Player(0)).empty() & LegalRegularActions(Player(1)).empty()); } std::tuple<int, int> OthelloState::XYFromCode(int move) const { if (move >= kNumCells || move < 0) { SpielFatalError(absl::StrCat("Move too large: ", move)); } return std::make_tuple(move / kNumCols, move % kNumRows); } CellState PlayerToState(Player player) { switch (player) { case 0: return CellState::kBlack; case 1: return CellState::kWhite; default: SpielFatalError(absl::StrCat("Invalid player id ", player)); return CellState::kEmpty; } } std::string StateToString(CellState state) { switch (state) { case CellState::kEmpty: return "."; case CellState::kWhite: return "o"; case CellState::kBlack: return "x"; default: SpielFatalError("Unknown state."); } } bool OthelloState::ValidAction(Player player, int move) const { return (board_[move] == CellState::kEmpty && CanCapture(player, move)); } void OthelloState::DoApplyAction(Action move) { if (move == passMove) { // pass current_player_ = 1 - current_player_; num_moves_ += 1; return; } if (!ValidAction(current_player_, move)) { SpielFatalError(absl::StrCat("Invalid move ", move)); } std::tuple<int, int> rowcol = XYFromCode(move); CellState cell = PlayerToState(current_player_); int row = std::get<0>(rowcol); int col = std::get<1>(rowcol); board_[row * kNumCols + col] = cell; for (int direction = Direction::kUp; direction < Direction::kLast; direction++) { int steps = 0; if ((steps = CountSteps(current_player_, row, col, static_cast<Direction>(direction))) > 0) { Capture(current_player_, row, col, static_cast<Direction>(direction), steps); } } if (NoValidActions()) { int count_zero = DiskCount(Player(0)); int count_one = DiskCount(Player(1)); if (count_zero > count_one) { outcome_ = Player(0); } else if (count_zero < count_one) { outcome_ = Player(1); } } current_player_ = 1 - current_player_; num_moves_ += 1; } std::vector<Action> OthelloState::LegalRegularActions(Player p) const { // list std::vector<Action> moves; for (int cell = 0; cell < kNumCells; ++cell) { if (ValidAction(p, cell)) { moves.push_back(cell); } } return moves; } std::vector<Action> OthelloState::LegalActions() const { if (IsTerminal()) return {}; // can move in an empty cell that captures std::vector<Action> moves = LegalRegularActions(current_player_); if (moves.empty()) { moves.push_back(passMove); // pass } return moves; } std::string OthelloState::ActionToString(Player player, Action action_id) const { if (action_id == passMove) { return absl::StrCat(StateToString(PlayerToState(player)), "(pass)"); } else { return absl::StrCat(StateToString(PlayerToState(player)), "(", action_id / kNumCols, ",", action_id % kNumCols, ")"); } } bool OthelloState::IsFull() const { for (int i = 0; i < kNumCells; i++) { if (board_[i] == CellState::kEmpty) return false; } return true; } OthelloState::OthelloState(std::shared_ptr<const Game> game) : State(game) { std::fill(begin(board_), end(board_), CellState::kEmpty); board_[27] = CellState::kWhite; board_[28] = CellState::kBlack; board_[35] = CellState::kBlack; board_[36] = CellState::kWhite; } std::string OthelloState::ToString() const { std::string str; for (int r = 0; r < kNumRows; ++r) { for (int c = 0; c < kNumCols; ++c) { absl::StrAppend(&str, StateToString(BoardAt(r, c))); } if (r < (kNumRows - 1)) { absl::StrAppend(&str, "\n"); } } return str; } bool OthelloState::IsTerminal() const { return outcome_ != kInvalidPlayer || NoValidActions(); } std::vector<double> OthelloState::Returns() const { if (outcome_ == Player{0}) { return {1.0, -1.0}; } else if (outcome_ == Player{1}) { return {-1.0, 1.0}; } else { return {0.0, 0.0}; } } std::string OthelloState::InformationStateString(Player player) const { return HistoryString(); } std::string OthelloState::ObservationString(Player player) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); return ToString(); } void OthelloState::ObservationTensor(Player player, std::vector<double>* values) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); // Treat `values` as a 2-d tensor. TensorView<2> view(values, {kCellStates, kNumCells}, true); for (int cell = 0; cell < kNumCells; ++cell) { view[{static_cast<int>(board_[cell]), cell}] = 1.0; } } void OthelloState::UndoAction(Player player, Action move) { SpielFatalError("Undo not implemented for this game."); } std::unique_ptr<State> OthelloState::Clone() const { return std::unique_ptr<State>(new OthelloState(*this)); } OthelloGame::OthelloGame(const GameParameters& params) : Game(kGameType, params) {} } // namespace othello } // namespace open_spiel <commit_msg>removed commented code<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/games/othello.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include <tuple> #include "open_spiel/spiel_utils.h" #include "open_spiel/utils/tensor_view.h" namespace open_spiel { namespace othello { namespace { // Facts about the game. const GameType kGameType{ /*short_name=*/"othello", /*long_name=*/"Othello", GameType::Dynamics::kSequential, GameType::ChanceMode::kDeterministic, GameType::Information::kPerfectInformation, GameType::Utility::kZeroSum, GameType::RewardModel::kTerminal, /*max_num_players=*/2, /*min_num_players=*/2, /*provides_information_state_string=*/true, /*provides_information_state_tensor=*/false, /*provides_observation_string=*/true, /*provides_observation_tensor=*/true, /*parameter_specification=*/{} // no parameters }; std::shared_ptr<const Game> Factory(const GameParameters& params) { return std::shared_ptr<const Game>(new OthelloGame(params)); } REGISTER_SPIEL_GAME(kGameType, Factory); } // namespace std::tuple<int, int> GetNext(int row, int col, Direction dir) { switch (dir) { case Direction::kUp: return std::make_tuple(row - 1, col); case Direction::kDown: return std::make_tuple(row + 1, col); case Direction::kLeft: return std::make_tuple(row, col - 1); case Direction::kRight: return std::make_tuple(row, col + 1); case Direction::kUpRight: return std::make_tuple(row - 1, col + 1); case Direction::kUpLeft: return std::make_tuple(row - 1, col - 1); case Direction::kDownRight: return std::make_tuple(row + 1, col + 1); case Direction::kDownLeft: return std::make_tuple(row + 1, col - 1); default: SpielFatalError(absl::StrCat("Found unmatched case in GetNext.")); } } inline bool OthelloState::OnBoard(int row, int col) const { return (0 <= row) && (row < kNumRows) && (0 <= col) && (col < kNumCols); } int OthelloState::CountSteps(Player player, int row, int col, Direction dir) const { std::tuple<int, int> rowcol = GetNext(row, col, dir); row = std::get<0>(rowcol); col = std::get<1>(rowcol); int count = 0; CellState cell = PlayerToState(player); while (OnBoard(row, col)) { if (BoardAt(row, col) == cell) { return count; } else if (BoardAt(row, col) == CellState::kEmpty) { return 0; } count++; rowcol = GetNext(row, col, dir); row = std::get<0>(rowcol); col = std::get<1>(rowcol); } return 0; } bool OthelloState::CanCapture(Player player, int move) const { if (board_[move] != CellState::kEmpty) return false; std::tuple<int, int> row_col = XYFromCode(move); int row = std::get<0>(row_col); int col = std::get<1>(row_col); bool valid = false; for (int direction = Direction::kUp; direction < Direction::kLast; direction++) { if (CountSteps(player, row, col, static_cast<Direction>(direction)) != 0) { return true; } } return false; } void OthelloState::Capture(Player player, int row, int col, Direction dir, int steps) { std::tuple<int, int> rowcol = GetNext(row, col, dir); row = std::get<0>(rowcol); col = std::get<1>(rowcol); CellState cell = PlayerToState(player); for (int step = 0; step < steps; step++) { if (BoardAt(row, col) == CellState::kEmpty || BoardAt(row, col) == cell) { SpielFatalError(absl::StrCat("Cannot capture cell (", row, ", ", col, ")")); } board_[row * kNumCols + col] = cell; rowcol = GetNext(row, col, dir); row = std::get<0>(rowcol); col = std::get<1>(rowcol); } } int OthelloState::DiskCount(Player player) const { int count = 0; CellState cell = PlayerToState(player); for (int i = 0; i < kNumCells; i++) { if (board_[i] == cell) count++; } return count; } bool OthelloState::NoValidActions() const { return (LegalRegularActions(Player(0)).empty() & LegalRegularActions(Player(1)).empty()); } std::tuple<int, int> OthelloState::XYFromCode(int move) const { if (move >= kNumCells || move < 0) { SpielFatalError(absl::StrCat("Move too large: ", move)); } return std::make_tuple(move / kNumCols, move % kNumRows); } CellState PlayerToState(Player player) { switch (player) { case 0: return CellState::kBlack; case 1: return CellState::kWhite; default: SpielFatalError(absl::StrCat("Invalid player id ", player)); return CellState::kEmpty; } } std::string StateToString(CellState state) { switch (state) { case CellState::kEmpty: return "."; case CellState::kWhite: return "o"; case CellState::kBlack: return "x"; default: SpielFatalError("Unknown state."); } } bool OthelloState::ValidAction(Player player, int move) const { return (board_[move] == CellState::kEmpty && CanCapture(player, move)); } void OthelloState::DoApplyAction(Action move) { if (move == passMove) { // pass current_player_ = 1 - current_player_; num_moves_ += 1; return; } if (!ValidAction(current_player_, move)) { SpielFatalError(absl::StrCat("Invalid move ", move)); } std::tuple<int, int> rowcol = XYFromCode(move); CellState cell = PlayerToState(current_player_); int row = std::get<0>(rowcol); int col = std::get<1>(rowcol); board_[row * kNumCols + col] = cell; for (int direction = Direction::kUp; direction < Direction::kLast; direction++) { int steps = 0; if ((steps = CountSteps(current_player_, row, col, static_cast<Direction>(direction))) > 0) { Capture(current_player_, row, col, static_cast<Direction>(direction), steps); } } if (NoValidActions()) { int count_zero = DiskCount(Player(0)); int count_one = DiskCount(Player(1)); if (count_zero > count_one) { outcome_ = Player(0); } else if (count_zero < count_one) { outcome_ = Player(1); } } current_player_ = 1 - current_player_; num_moves_ += 1; } std::vector<Action> OthelloState::LegalRegularActions(Player p) const { // list std::vector<Action> moves; for (int cell = 0; cell < kNumCells; ++cell) { if (ValidAction(p, cell)) { moves.push_back(cell); } } return moves; } std::vector<Action> OthelloState::LegalActions() const { if (IsTerminal()) return {}; // can move in an empty cell that captures std::vector<Action> moves = LegalRegularActions(current_player_); if (moves.empty()) { moves.push_back(passMove); // pass } return moves; } std::string OthelloState::ActionToString(Player player, Action action_id) const { if (action_id == passMove) { return absl::StrCat(StateToString(PlayerToState(player)), "(pass)"); } else { return absl::StrCat(StateToString(PlayerToState(player)), "(", action_id / kNumCols, ",", action_id % kNumCols, ")"); } } bool OthelloState::IsFull() const { for (int i = 0; i < kNumCells; i++) { if (board_[i] == CellState::kEmpty) return false; } return true; } OthelloState::OthelloState(std::shared_ptr<const Game> game) : State(game) { std::fill(begin(board_), end(board_), CellState::kEmpty); board_[27] = CellState::kWhite; board_[28] = CellState::kBlack; board_[35] = CellState::kBlack; board_[36] = CellState::kWhite; } std::string OthelloState::ToString() const { std::string str; for (int r = 0; r < kNumRows; ++r) { for (int c = 0; c < kNumCols; ++c) { absl::StrAppend(&str, StateToString(BoardAt(r, c))); } if (r < (kNumRows - 1)) { absl::StrAppend(&str, "\n"); } } return str; } bool OthelloState::IsTerminal() const { return outcome_ != kInvalidPlayer || NoValidActions(); } std::vector<double> OthelloState::Returns() const { if (outcome_ == Player{0}) { return {1.0, -1.0}; } else if (outcome_ == Player{1}) { return {-1.0, 1.0}; } else { return {0.0, 0.0}; } } std::string OthelloState::InformationStateString(Player player) const { return HistoryString(); } std::string OthelloState::ObservationString(Player player) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); return ToString(); } void OthelloState::ObservationTensor(Player player, std::vector<double>* values) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); // Treat `values` as a 2-d tensor. TensorView<2> view(values, {kCellStates, kNumCells}, true); for (int cell = 0; cell < kNumCells; ++cell) { view[{static_cast<int>(board_[cell]), cell}] = 1.0; } } void OthelloState::UndoAction(Player player, Action move) { SpielFatalError("Undo not implemented for this game."); } std::unique_ptr<State> OthelloState::Clone() const { return std::unique_ptr<State>(new OthelloState(*this)); } OthelloGame::OthelloGame(const GameParameters& params) : Game(kGameType, params) {} } // namespace othello } // namespace open_spiel <|endoftext|>
<commit_before>/* * Copyright 2015 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * 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 "mapply_matrix_store.h" #include "local_matrix_store.h" namespace fm { namespace detail { namespace { class lmapply_col_matrix_store: public lvirtual_col_matrix_store { std::vector<local_matrix_store::const_ptr> ins; const portion_mapply_op &op; raw_data_array data; void materialize() const { local_buf_col_matrix_store res(get_global_start_row(), get_global_start_col(), get_num_rows(), get_num_cols(), get_type(), -1); op.run(ins, res); lmapply_col_matrix_store *mutable_this = const_cast<lmapply_col_matrix_store *>(this); mutable_this->data = res.get_data(); } public: lmapply_col_matrix_store( const std::vector<local_matrix_store::const_ptr> &ins, const portion_mapply_op &_op, off_t global_start_row, off_t global_start_col, size_t nrow, size_t ncol, const scalar_type &type, int node_id): lvirtual_col_matrix_store(global_start_row, global_start_col, nrow, ncol, type, node_id), op(_op) { this->ins = ins; } virtual const char *get_raw_arr() const { if (data.is_empty()) materialize(); return data.get_raw(); } virtual matrix_store::const_ptr transpose() const { // TODO assert(0); return matrix_store::const_ptr(); } virtual const char *get_col(size_t col) const { if (data.is_empty()) materialize(); return data.get_raw() + get_num_rows() * col * get_type().get_size(); } }; class lmapply_row_matrix_store: public lvirtual_row_matrix_store { std::vector<local_matrix_store::const_ptr> ins; const portion_mapply_op &op; raw_data_array data; void materialize() const { local_buf_row_matrix_store res(get_global_start_row(), get_global_start_col(), get_num_rows(), get_num_cols(), get_type(), -1); op.run(ins, res); lmapply_row_matrix_store *mutable_this = const_cast<lmapply_row_matrix_store *>(this); mutable_this->data = res.get_data(); } public: lmapply_row_matrix_store( const std::vector<local_matrix_store::const_ptr> &ins, const portion_mapply_op &_op, off_t global_start_row, off_t global_start_col, size_t nrow, size_t ncol, const scalar_type &type, int node_id): lvirtual_row_matrix_store(global_start_row, global_start_col, nrow, ncol, type, node_id), op(_op) { this->ins = ins; } virtual const char *get_raw_arr() const { if (data.is_empty()) materialize(); return data.get_raw(); } virtual matrix_store::const_ptr transpose() const { // TODO assert(0); return matrix_store::const_ptr(); } virtual const char *get_row(size_t row) const { if (data.is_empty()) materialize(); return data.get_raw() + get_num_cols() * row * get_type().get_size(); } virtual const char *get_rows(size_t row_start, size_t row_end) const { // TODO assert(0); return NULL; } }; } mapply_matrix_store::mapply_matrix_store( const std::vector<mem_dense_matrix::const_ptr> &in_mats, portion_mapply_op::const_ptr op, matrix_layout_t layout, size_t nrow, size_t ncol): virtual_matrix_store(nrow, ncol, op->get_output_type()) { this->layout = layout; this->in_mats = in_mats; this->op = op; } matrix_store::ptr mapply_matrix_store::materialize() const { return _mapply_portion(in_mats, op, layout); } matrix_store::const_ptr mapply_matrix_store::get_cols( const std::vector<off_t> &idxs) const { // TODO assert(0); return matrix_store::const_ptr(); } matrix_store::const_ptr mapply_matrix_store::get_rows( const std::vector<off_t> &idxs) const { // TODO assert(0); return matrix_store::const_ptr(); } local_matrix_store::const_ptr mapply_matrix_store::get_portion( size_t start_row, size_t start_col, size_t num_rows, size_t num_cols) const { std::vector<local_matrix_store::const_ptr> parts(in_mats.size()); if (is_wide()) { assert(start_row == 0); assert(num_rows == get_num_rows()); for (size_t i = 0; i < in_mats.size(); i++) parts[i] = static_cast<const mem_matrix_store &>( in_mats[i]->get_data()).get_portion(start_row, start_col, in_mats[i]->get_num_rows(), num_cols); } else { assert(start_col == 0); assert(num_cols == get_num_cols()); for (size_t i = 0; i < in_mats.size(); i++) parts[i] = static_cast<const mem_matrix_store &>( in_mats[i]->get_data()).get_portion(start_row, start_col, num_rows, in_mats[i]->get_num_cols()); } if (store_layout() == matrix_layout_t::L_ROW) return local_matrix_store::const_ptr(new lmapply_row_matrix_store( parts, *op, start_row, start_col, num_rows, num_cols, get_type(), parts.front()->get_node_id())); else return local_matrix_store::const_ptr(new lmapply_col_matrix_store( parts, *op, start_row, start_col, num_rows, num_cols, get_type(), parts.front()->get_node_id())); } local_matrix_store::const_ptr mapply_matrix_store::get_portion( size_t id) const { size_t start_row; size_t start_col; size_t num_rows; size_t num_cols; std::pair<size_t, size_t> chunk_size = get_portion_size(); if (is_wide()) { start_row = 0; start_col = chunk_size.second * id; num_rows = get_num_rows(); num_cols = std::min(chunk_size.second, get_num_cols() - start_col); } else { start_row = chunk_size.first * id; start_col = 0; num_rows = std::min(chunk_size.first, get_num_rows() - start_row); num_cols = get_num_cols(); } return get_portion(start_row, start_col, num_rows, num_cols); } matrix_store::const_ptr mapply_matrix_store::transpose() const { // TODO assert(0); return matrix_store::const_ptr(); } } } <commit_msg>[Matrix]: optimize mapply_matrix_store for CPU cache.<commit_after>/* * Copyright 2015 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * 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 "mapply_matrix_store.h" #include "local_matrix_store.h" namespace fm { namespace detail { namespace { size_t SUB_CHUNK_SIZE = 4 * 1024; class mapply_store { std::vector<local_matrix_store::const_ptr> ins; const portion_mapply_op &op; raw_data_array buf; bool materialized; local_matrix_store *lstore; public: mapply_store(const std::vector<local_matrix_store::const_ptr> &ins, const portion_mapply_op &_op, local_matrix_store *lstore): op(_op) { this->lstore = lstore; this->ins = ins; materialized = false; } const char *get_raw_arr() const { return buf.get_raw(); } bool is_materialized() const { return materialized; } void materialize() const; void materialize_whole(); void resize(off_t local_start_row, off_t local_start_col, size_t local_num_rows, size_t local_num_cols); void reset_size(); }; void mapply_store::reset_size() { // When the matrix store is resized, we should drop the materialized data. materialized = false; buf = raw_data_array(); for (size_t i = 0; i < ins.size(); i++) const_cast<local_matrix_store *>(ins[i].get())->reset_size(); } void mapply_store::resize(off_t local_start_row, off_t local_start_col, size_t local_num_rows, size_t local_num_cols) { // When the matrix store is resized, we should drop the materialized data. materialized = false; // To avoid unnecessary memory allocation, if the new exposed part isn't // larger than the buffer size, we can keep the buffer. if (local_num_rows * local_num_cols * lstore->get_entry_size() > buf.get_num_bytes()) buf = raw_data_array(); if (lstore->is_wide()) { assert(local_start_row == 0 && local_num_rows == lstore->get_num_rows()); for (size_t i = 0; i < ins.size(); i++) const_cast<local_matrix_store *>(ins[i].get())->resize(0, local_start_col, ins[i]->get_num_rows(), local_num_cols); } else { assert(local_start_col == 0 && local_num_cols == lstore->get_num_cols()); for (size_t i = 0; i < ins.size(); i++) const_cast<local_matrix_store *>(ins[i].get())->resize( local_start_row, 0, local_num_rows, ins[i]->get_num_cols()); } } void mapply_store::materialize_whole() { local_matrix_store::ptr res; if (lstore->store_layout() == matrix_layout_t::L_COL) { local_buf_col_matrix_store *tmp = new local_buf_col_matrix_store( lstore->get_global_start_row(), lstore->get_global_start_col(), lstore->get_num_rows(), lstore->get_num_cols(), lstore->get_type(), -1); res = local_matrix_store::ptr(tmp); this->buf = tmp->get_data(); } else { local_buf_row_matrix_store *tmp = new local_buf_row_matrix_store( lstore->get_global_start_row(), lstore->get_global_start_col(), lstore->get_num_rows(), lstore->get_num_cols(), lstore->get_type(), -1); res = local_matrix_store::ptr(tmp); this->buf = tmp->get_data(); } std::vector<local_matrix_store *> mutable_ins(ins.size()); for (size_t i = 0; i < ins.size(); i++) mutable_ins[i] = const_cast<local_matrix_store *>(ins[i].get()); if (lstore->is_wide()) { for (size_t local_start_col = 0; local_start_col < lstore->get_num_cols(); local_start_col += SUB_CHUNK_SIZE) { size_t local_num_cols = std::min(SUB_CHUNK_SIZE, lstore->get_num_cols() - local_start_col); for (size_t i = 0; i < mutable_ins.size(); i++) { mutable_ins[i]->resize(0, local_start_col, mutable_ins[i]->get_num_rows(), local_num_cols); } res->resize(0, local_start_col, res->get_num_rows(), local_num_cols); op.run(ins, *res); } } else { // If this is a tall matrix. for (size_t local_start_row = 0; local_start_row < lstore->get_num_rows(); local_start_row += SUB_CHUNK_SIZE) { size_t local_num_rows = std::min(SUB_CHUNK_SIZE, lstore->get_num_rows() - local_start_row); for (size_t i = 0; i < mutable_ins.size(); i++) { mutable_ins[i]->resize(local_start_row, 0, local_num_rows, mutable_ins[i]->get_num_cols()); } res->resize(local_start_row, 0, local_num_rows, res->get_num_cols()); op.run(ins, *res); } } for (size_t i = 0; i < mutable_ins.size(); i++) mutable_ins[i]->reset_size(); } void mapply_store::materialize() const { mapply_store *mutable_this = const_cast<mapply_store *>(this); if (lstore->is_whole()) mutable_this->materialize_whole(); else if (lstore->store_layout() == matrix_layout_t::L_COL && this->buf.is_empty()) { local_buf_col_matrix_store res(lstore->get_global_start_row(), lstore->get_global_start_col(), lstore->get_num_rows(), lstore->get_num_cols(), lstore->get_type(), -1); op.run(ins, res); mutable_this->buf = res.get_data(); } else if (lstore->store_layout() == matrix_layout_t::L_COL) { local_ref_contig_col_matrix_store res(mutable_this->buf.get_raw(), lstore->get_global_start_row(), lstore->get_global_start_col(), lstore->get_num_rows(), lstore->get_num_cols(), lstore->get_type(), -1); op.run(ins, res); } else if (this->buf.is_empty()) { local_buf_row_matrix_store res(lstore->get_global_start_row(), lstore->get_global_start_col(), lstore->get_num_rows(), lstore->get_num_cols(), lstore->get_type(), -1); op.run(ins, res); mutable_this->buf = res.get_data(); } else { local_ref_contig_row_matrix_store res(mutable_this->buf.get_raw(), lstore->get_global_start_row(), lstore->get_global_start_col(), lstore->get_num_rows(), lstore->get_num_cols(), lstore->get_type(), -1); op.run(ins, res); } mutable_this->materialized = true; } class lmapply_col_matrix_store: public lvirtual_col_matrix_store { mapply_store store; public: lmapply_col_matrix_store( const std::vector<local_matrix_store::const_ptr> &ins, const portion_mapply_op &op, off_t global_start_row, off_t global_start_col, size_t nrow, size_t ncol, const scalar_type &type, int node_id): lvirtual_col_matrix_store(global_start_row, global_start_col, nrow, ncol, type, node_id), store(ins, op, this) { } virtual bool resize(off_t local_start_row, off_t local_start_col, size_t local_num_rows, size_t local_num_cols) { store.resize(local_start_row, local_start_col, local_num_rows, local_num_cols); return local_matrix_store::resize(local_start_row, local_start_col, local_num_rows, local_num_cols); } virtual void reset_size() { store.reset_size(); local_matrix_store::reset_size(); } virtual const char *get_raw_arr() const { if (!store.is_materialized()) store.materialize(); return store.get_raw_arr(); } virtual matrix_store::const_ptr transpose() const { // TODO assert(0); return matrix_store::const_ptr(); } virtual const char *get_col(size_t col) const { if (!store.is_materialized()) store.materialize(); return store.get_raw_arr() + get_num_rows() * col * get_type().get_size(); } }; class lmapply_row_matrix_store: public lvirtual_row_matrix_store { mapply_store store; public: lmapply_row_matrix_store( const std::vector<local_matrix_store::const_ptr> &ins, const portion_mapply_op &op, off_t global_start_row, off_t global_start_col, size_t nrow, size_t ncol, const scalar_type &type, int node_id): lvirtual_row_matrix_store(global_start_row, global_start_col, nrow, ncol, type, node_id), store(ins, op, this) { } virtual bool resize(off_t local_start_row, off_t local_start_col, size_t local_num_rows, size_t local_num_cols) { store.resize(local_start_row, local_start_col, local_num_rows, local_num_cols); return local_matrix_store::resize(local_start_row, local_start_col, local_num_rows, local_num_cols); } virtual void reset_size() { store.reset_size(); local_matrix_store::reset_size(); } virtual const char *get_raw_arr() const { if (!store.is_materialized()) store.materialize(); return store.get_raw_arr(); } virtual matrix_store::const_ptr transpose() const { // TODO assert(0); return matrix_store::const_ptr(); } virtual const char *get_row(size_t row) const { if (!store.is_materialized()) store.materialize(); return store.get_raw_arr() + get_num_cols() * row * get_type().get_size(); } virtual const char *get_rows(size_t row_start, size_t row_end) const { // TODO assert(0); return NULL; } }; } mapply_matrix_store::mapply_matrix_store( const std::vector<mem_dense_matrix::const_ptr> &in_mats, portion_mapply_op::const_ptr op, matrix_layout_t layout, size_t nrow, size_t ncol): virtual_matrix_store(nrow, ncol, op->get_output_type()) { this->layout = layout; this->in_mats = in_mats; this->op = op; } matrix_store::ptr mapply_matrix_store::materialize() const { return _mapply_portion(in_mats, op, layout); } matrix_store::const_ptr mapply_matrix_store::get_cols( const std::vector<off_t> &idxs) const { // TODO assert(0); return matrix_store::const_ptr(); } matrix_store::const_ptr mapply_matrix_store::get_rows( const std::vector<off_t> &idxs) const { // TODO assert(0); return matrix_store::const_ptr(); } local_matrix_store::const_ptr mapply_matrix_store::get_portion( size_t start_row, size_t start_col, size_t num_rows, size_t num_cols) const { std::vector<local_matrix_store::const_ptr> parts(in_mats.size()); if (is_wide()) { assert(start_row == 0); assert(num_rows == get_num_rows()); for (size_t i = 0; i < in_mats.size(); i++) parts[i] = static_cast<const mem_matrix_store &>( in_mats[i]->get_data()).get_portion(start_row, start_col, in_mats[i]->get_num_rows(), num_cols); } else { assert(start_col == 0); assert(num_cols == get_num_cols()); for (size_t i = 0; i < in_mats.size(); i++) parts[i] = static_cast<const mem_matrix_store &>( in_mats[i]->get_data()).get_portion(start_row, start_col, num_rows, in_mats[i]->get_num_cols()); } if (store_layout() == matrix_layout_t::L_ROW) return local_matrix_store::const_ptr(new lmapply_row_matrix_store( parts, *op, start_row, start_col, num_rows, num_cols, get_type(), parts.front()->get_node_id())); else return local_matrix_store::const_ptr(new lmapply_col_matrix_store( parts, *op, start_row, start_col, num_rows, num_cols, get_type(), parts.front()->get_node_id())); } local_matrix_store::const_ptr mapply_matrix_store::get_portion( size_t id) const { size_t start_row; size_t start_col; size_t num_rows; size_t num_cols; std::pair<size_t, size_t> chunk_size = get_portion_size(); if (is_wide()) { start_row = 0; start_col = chunk_size.second * id; num_rows = get_num_rows(); num_cols = std::min(chunk_size.second, get_num_cols() - start_col); } else { start_row = chunk_size.first * id; start_col = 0; num_rows = std::min(chunk_size.first, get_num_rows() - start_row); num_cols = get_num_cols(); } return get_portion(start_row, start_col, num_rows, num_cols); } matrix_store::const_ptr mapply_matrix_store::transpose() const { // TODO assert(0); return matrix_store::const_ptr(); } } } <|endoftext|>
<commit_before>#pragma once #include <memory> #include <iostream> #include "error.hpp" #include <boost/serialization/access.hpp> #include <boost/serialization/vector.hpp> // clangでshared_ptrが定義されない問題への一時的な対処 #include <boost/serialization/singleton.hpp> #include <boost/serialization/extended_type_info.hpp> #undef BOOST_NO_CXX11_SMART_PTR #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/weak_ptr.hpp> namespace spn { DEF_HASMETHOD(clone) // cloneメソッドを持っていればそれを呼ぶ template <class T> auto CopyAsSP(T& t, std::true_type) { return t.clone(); } // cloneメソッドを持っていない時はコピーコンストラクタで対処 template <class T> auto CopyAsSP(T& t, std::false_type) { using Tc = typename std::remove_const<T>::type; return std::shared_ptr<Tc>(new Tc(t)); } //! iterateDepthFirstの戻り値 enum class Iterate { ReturnFromChild, //!< 内部用 StepIn, //!< 子を巡回 Next, //!< 子を巡回せず兄弟ノードへ進む Quit //!< 直ちに巡回を終える }; //! 汎用ツリー構造 /*! Tは必ずTreeNode<T>を継承する前提 */ template <class T> class TreeNode : public std::enable_shared_from_this<T> { private: friend class boost::serialization::access; template <class Ar> void serialize(Ar& ar, const unsigned int) { ar & BOOST_SERIALIZATION_NVP(_spChild) & BOOST_SERIALIZATION_NVP(_wpParent) & BOOST_SERIALIZATION_NVP(_spSibling); } // 巡回参照を避けるために親ノードはweak_ptrで格納 public: using this_t = TreeNode<T>; using pointer = this_t*; using SP = std::shared_ptr<T>; using SPC = std::shared_ptr<const T>; using WP = std::weak_ptr<T>; using SPVector = std::vector<SP>; using SPCVector = std::vector<SPC>; SP _spChild, _spSibling; WP _wpParent; // --- ノードつなぎ変え時に呼ばれる関数. 継承先クラスが適時オーバーライドする --- void onParentChange(const SP& /*from*/, const SP& /*to*/) {} void onChildRemove(const SP& /*node*/) {} void onChildAdded(const SP& /*node*/) {} static void _PrintIndent(std::ostream& os, int n) { while(--n >= 0) os << '\t'; } template <class CB> void _iterateAll(CB&& cb) const { auto* self = const_cast<this_t*>(this); self->template iterateDepthFirst<true>([&cb](auto& nd, int){ cb(nd); return Iterate::StepIn; }); } template <class T_SP> std::vector<T_SP> _plain() const { std::vector<T_SP> spv; _iterateAll([&spv](auto& nd){ spv.emplace_back(nd.shared_from_this()); }); return spv; } template <class T_PTR> std::vector<T_PTR> _plainPtr() const { std::vector<T_PTR> pv; _iterateAll([&pv](auto& nd){ pv.emplace_back(&nd); }); return pv; } public: TreeNode() = default; explicit TreeNode(TreeNode&& t) = default; //! copy-ctorに置いてはリンク情報をコピーしない explicit TreeNode(const TreeNode&) {} // コピー禁止 TreeNode& operator = (const TreeNode&) = delete; // ムーブは可 TreeNode& operator = (TreeNode&& t) = default; void setParent(const SP& s) { setParent(WP(s)); } void setParent(const WP& w) { SP sp = w.lock(), spP = getParent(); AssertP(Trap, sp.get() != this, "self-reference detected") if(sp.get() != spP.get()) { onParentChange(spP, sp); _wpParent = w; } } SP getParent() const { return SP(_wpParent.lock()); } const SP& getChild() const { return _spChild; } const SP& getSibling() const { return _spSibling; } SP getPrevSibling(const bool bLoop=false) const { const SP p = getParent(); if(p) { auto cur = p->getChild(); if(!cur->getSibling()) { // 項目が1つしかない return nullptr; } // カーソルがリストの最初 if(cur.get() == this) { if(bLoop) { // カーソルを末尾にループ while(const auto& tmp = cur->getSibling()) cur = tmp; return cur; } return nullptr; } // 直前の項目を探す while(const auto& cur2 = cur->getSibling()) { if(cur2.get() == this) return cur; cur = cur2; } } return nullptr; } void removeChild(const SP& target) { AssertP(Trap, _spChild) if(_spChild == target) { onChildRemove(target); // 最初の子ノードが削除対象 target->setParent(WP()); _spChild = target->getSibling(); target->_spSibling = nullptr; } else { // 兄弟ノードのどれかが削除対象 _spChild->removeSibling(nullptr, target); } } void removeSibling(pointer prev, const SP& target) { if(target.get() == this) { if(auto sp = getParent()) sp->onChildRemove(this->shared_from_this()); // このノードが削除対象 AssertP(Trap, prev) prev->_spSibling = _spSibling; setParent(WP()); _spSibling = nullptr; return; } AssertP(Trap, _spSibling) _spSibling->removeSibling(this, target); } void addChild(const SP& s) { AssertP(Trap, s.get() != this, "self-reference detected") if(_spChild) _spChild->addSibling(s); else { _spChild = s; s->setParent(this->shared_from_this()); onChildAdded(s); } } void addSibling(const SP& s) { AssertP(Trap, s.get() != this, "self-reference detected") if(_spSibling) _spSibling->addSibling(s); else { _spSibling = s; s->setParent(_wpParent); if(auto sp = getParent()) sp->onChildAdded(s); } } //! 深さ優先で巡回 /*! \tparam Sib 兄弟ノードを巡回対象に加えるか \tparam BConst trueならconst巡回 */ template <bool Sib, class Callback, bool BConst=false> Iterate iterateDepthFirst(Callback&& cb, int depth=0) { using thistc = std::conditional_t<BConst, const T, T>; Iterate t = cb(static_cast<thistc&>(*this), depth); if(t == Iterate::Quit) return Iterate::Quit; if(t == Iterate::StepIn) { if(_spChild) { if(_spChild->template iterateDepthFirst<true>(std::forward<Callback>(cb), depth+1) == Iterate::Quit) return Iterate::Quit; } } if(Sib && _spSibling) return _spSibling->template iterateDepthFirst<true>(std::forward<Callback>(cb), depth); return Iterate::ReturnFromChild; } template <bool Sib, class Callback> Iterate iterateDepthFirst(Callback&& cb, int depth=0) const { return const_cast<this_t*>(this)->template iterateDepthFirst<Sib, Callback, true>(std::forward<Callback>(cb), depth); } template <class Callback> SP find(Callback&& cb) const { SP ret; iterateDepthFirst<false>([&cb, &ret](auto& nd, int){ if(cb(nd)) { ret = nd.shared_from_this(); return Iterate::Quit; } return Iterate::StepIn; }); return ret; } //! このノード以下を全て複製 SP cloneTree(const WP& parent=WP()) const { SP sp = CopyAsSP(static_cast<const T&>(*this), HasMethod_clone<T>(nullptr)); if(_spChild) sp->_spChild = _spChild->cloneTree(sp); if(_spSibling) sp->_spSibling = _spSibling->cloneTree(parent); sp->_wpParent = parent; return sp; } //! 主にデバッグ用 void print(std::ostream& os, int indent) const { _PrintIndent(os, indent); // 明示的なダウンキャスト os << *static_cast<const T*>(this); } //! ツリー構造を配列化 SPVector plain() { return _plain<SP>(); } //! ツリー構造を配列化 (const) SPCVector plain() const { return _plain<SPC>(); } //! ツリー構造を配列化 (pointer) std::vector<T*> plainPtr() { return _plainPtr<T*>(); } //! ツリー構造を配列化 (const pointer) std::vector<const T*> plainPtr() const { return _plainPtr<const T*>(); } //! 最大ツリー深度を取得 int getDepth() const { int depth = 0; if(_spChild) depth = _spChild->getDepth() + 1; if(_spSibling) depth = std::max(depth, _spSibling->getDepth()); return depth; } }; template <class T0, class T1, class CMP> bool _CompareTree(const TreeNode<T0>& t0, const TreeNode<T1>& t1, CMP&& cmp) { auto fnParentIndex = [](const auto& ar, const auto& p){ if(!p) return ar.end() - ar.begin(); auto itr = std::find_if(ar.begin(), ar.end(), [&p](auto& r){ return r == p.get(); }); return itr - ar.begin(); }; // 配列化して親ノード番号をチェック auto ar0 = t0.plainPtr(); auto ar1 = t1.plainPtr(); if(ar0.size() != ar1.size()) return false; auto sz = ar0.size(); for(size_t i=0 ; i<sz ; i++) { // 親ノード番号 int idx0 = fnParentIndex(ar0, ar0[i]->getParent()), idx1 = fnParentIndex(ar1, ar1[i]->getParent()); if(idx0!=idx1 || !cmp(ar0[i], ar1[i])) return false; } return true; } // ツリー構造のみを比較する template <class T0, class T1> bool CompareTreeStructure(const TreeNode<T0>& t0, const TreeNode<T1>& t1) { return _CompareTree(t0, t1, [](auto&,auto&){ return true; }); } //! データも含めて比較 template <class T0, class T1> bool CompareTree(const TreeNode<T0>& t0, const TreeNode<T1>& t1) { auto cmp = [](auto& sp0, auto& sp1){ return *sp0 == *sp1; }; return _CompareTree(t0, t1, cmp); } template <class T> inline std::ostream& operator << (std::ostream& os, const TreeNode<T>& t) { auto& self = const_cast<TreeNode<T>&>(t); self.iterateDepthFirst<false>([&os](auto& s, int indent){ s.print(os, indent); os << std::endl; return TreeNode<T>::Iterate::StepIn; }); return os; } } <commit_msg>TreeNode: 子ノードのソート関数<commit_after>#pragma once #include <memory> #include <iostream> #include "error.hpp" #include <boost/serialization/access.hpp> #include <boost/serialization/vector.hpp> // clangでshared_ptrが定義されない問題への一時的な対処 #include <boost/serialization/singleton.hpp> #include <boost/serialization/extended_type_info.hpp> #undef BOOST_NO_CXX11_SMART_PTR #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/weak_ptr.hpp> namespace spn { DEF_HASMETHOD(clone) // cloneメソッドを持っていればそれを呼ぶ template <class T> auto CopyAsSP(T& t, std::true_type) { return t.clone(); } // cloneメソッドを持っていない時はコピーコンストラクタで対処 template <class T> auto CopyAsSP(T& t, std::false_type) { using Tc = typename std::remove_const<T>::type; return std::shared_ptr<Tc>(new Tc(t)); } //! iterateDepthFirstの戻り値 enum class Iterate { ReturnFromChild, //!< 内部用 StepIn, //!< 子を巡回 Next, //!< 子を巡回せず兄弟ノードへ進む Quit //!< 直ちに巡回を終える }; //! 汎用ツリー構造 /*! Tは必ずTreeNode<T>を継承する前提 */ template <class T> class TreeNode : public std::enable_shared_from_this<T> { private: friend class boost::serialization::access; template <class Ar> void serialize(Ar& ar, const unsigned int) { ar & BOOST_SERIALIZATION_NVP(_spChild) & BOOST_SERIALIZATION_NVP(_wpParent) & BOOST_SERIALIZATION_NVP(_spSibling); } // 巡回参照を避けるために親ノードはweak_ptrで格納 public: using Iterate = ::spn::Iterate; using this_t = TreeNode<T>; using pointer = this_t*; using element_type = T; using SP = std::shared_ptr<T>; using SPC = std::shared_ptr<const T>; using WP = std::weak_ptr<T>; using SPVector = std::vector<SP>; using SPCVector = std::vector<SPC>; SP _spChild, _spSibling; WP _wpParent; // --- ノードつなぎ変え時に呼ばれる関数. 継承先クラスが適時オーバーライドする --- void onParentChange(const SP& /*from*/, const SP& /*to*/) {} void onChildRemove(const SP& /*node*/) {} void onChildAdded(const SP& /*node*/) {} static void _PrintIndent(std::ostream& os, int n) { while(--n >= 0) os << '\t'; } template <class CB> void _iterateAll(CB&& cb) const { auto* self = const_cast<this_t*>(this); self->template iterateDepthFirst<true>([&cb](auto& nd, int){ cb(nd); return Iterate::StepIn; }); } template <class T_SP> std::vector<T_SP> _plain() const { std::vector<T_SP> spv; _iterateAll([&spv](auto& nd){ spv.emplace_back(nd.shared_from_this()); }); return spv; } template <class T_PTR> std::vector<T_PTR> _plainPtr() const { std::vector<T_PTR> pv; _iterateAll([&pv](auto& nd){ pv.emplace_back(&nd); }); return pv; } template <class CB> void _iterateChild(CB&& cb) const { if(SP sp = getChild()) { do { cb(sp); sp = sp->getSibling(); } while(sp); } } public: TreeNode() = default; explicit TreeNode(TreeNode&& t) = default; //! copy-ctorに置いてはリンク情報をコピーしない explicit TreeNode(const TreeNode&) {} // コピー禁止 TreeNode& operator = (const TreeNode&) = delete; // ムーブは可 TreeNode& operator = (TreeNode&& t) = default; //! 任意の基準で子ノードをソート template <class CMP> void sortChild(CMP&& cmp, const bool recursive) { if(auto c = getChild()) { SPVector spv; _iterateChild([&spv](auto& nd){ spv.emplace_back(nd); }); std::sort(spv.begin(), spv.end(), cmp); SP cur = spv.front(), pcur; _spChild = cur; auto itr = spv.begin(); do { cur = *itr; if(pcur) pcur->_spSibling = cur; pcur = cur; } while(++itr != spv.end()); cur->_spSibling.reset(); if(recursive) { for(auto& s : spv) s->sortChild(cmp, recursive); } } } void setParent(const SP& s) { setParent(WP(s)); } void setParent(const WP& w) { SP sp = w.lock(), spP = getParent(); AssertP(Trap, sp.get() != this, "self-reference detected") if(sp.get() != spP.get()) { onParentChange(spP, sp); _wpParent = w; } } SP getParent() const { return SP(_wpParent.lock()); } const SP& getChild() const { return _spChild; } const SP& getSibling() const { return _spSibling; } SP getPrevSibling(const bool bLoop=false) const { const SP p = getParent(); if(p) { auto cur = p->getChild(); if(!cur->getSibling()) { // 項目が1つしかない return nullptr; } // カーソルがリストの最初 if(cur.get() == this) { if(bLoop) { // カーソルを末尾にループ while(const auto& tmp = cur->getSibling()) cur = tmp; return cur; } return nullptr; } // 直前の項目を探す while(const auto& cur2 = cur->getSibling()) { if(cur2.get() == this) return cur; cur = cur2; } } return nullptr; } void removeChild(const SP& target) { AssertP(Trap, _spChild) if(_spChild == target) { onChildRemove(target); // 最初の子ノードが削除対象 target->setParent(WP()); _spChild = target->getSibling(); target->_spSibling = nullptr; } else { // 兄弟ノードのどれかが削除対象 _spChild->removeSibling(nullptr, target); } } void removeSibling(pointer prev, const SP& target) { if(target.get() == this) { if(auto sp = getParent()) sp->onChildRemove(this->shared_from_this()); // このノードが削除対象 AssertP(Trap, prev) prev->_spSibling = _spSibling; setParent(WP()); _spSibling = nullptr; return; } AssertP(Trap, _spSibling) _spSibling->removeSibling(this, target); } void addChild(const SP& s) { AssertP(Trap, s.get() != this, "self-reference detected") if(_spChild) _spChild->addSibling(s); else { _spChild = s; s->setParent(this->shared_from_this()); onChildAdded(s); } } void addSibling(const SP& s) { AssertP(Trap, s.get() != this, "self-reference detected") if(_spSibling) _spSibling->addSibling(s); else { _spSibling = s; s->setParent(_wpParent); if(auto sp = getParent()) sp->onChildAdded(s); } } //! 深さ優先で巡回 /*! \tparam Sib 兄弟ノードを巡回対象に加えるか \tparam BConst trueならconst巡回 */ template <bool Sib, class Callback, bool BConst=false> Iterate iterateDepthFirst(Callback&& cb, int depth=0) { using thistc = std::conditional_t<BConst, const T, T>; Iterate t = cb(static_cast<thistc&>(*this), depth); if(t == Iterate::Quit) return Iterate::Quit; if(t == Iterate::StepIn) { if(_spChild) { if(_spChild->template iterateDepthFirst<true>(std::forward<Callback>(cb), depth+1) == Iterate::Quit) return Iterate::Quit; } } if(Sib && _spSibling) return _spSibling->template iterateDepthFirst<true>(std::forward<Callback>(cb), depth); return Iterate::ReturnFromChild; } template <bool Sib, class Callback> Iterate iterateDepthFirst(Callback&& cb, int depth=0) const { return const_cast<this_t*>(this)->template iterateDepthFirst<Sib, Callback, true>(std::forward<Callback>(cb), depth); } template <class Callback> SP find(Callback&& cb) const { SP ret; iterateDepthFirst<false>([&cb, &ret](auto& nd, int){ if(cb(nd)) { ret = nd.shared_from_this(); return Iterate::Quit; } return Iterate::StepIn; }); return ret; } //! このノード以下を全て複製 SP cloneTree(const WP& parent=WP()) const { SP sp = CopyAsSP(static_cast<const T&>(*this), HasMethod_clone<T>(nullptr)); if(_spChild) sp->_spChild = _spChild->cloneTree(sp); if(_spSibling) sp->_spSibling = _spSibling->cloneTree(parent); sp->_wpParent = parent; return sp; } //! 主にデバッグ用 void print(std::ostream& os, int indent) const { _PrintIndent(os, indent); // 明示的なダウンキャスト os << *static_cast<const T*>(this); } //! ツリー構造を配列化 SPVector plain() { return _plain<SP>(); } //! ツリー構造を配列化 (const) SPCVector plain() const { return _plain<SPC>(); } //! ツリー構造を配列化 (pointer) std::vector<T*> plainPtr() { return _plainPtr<T*>(); } //! ツリー構造を配列化 (const pointer) std::vector<const T*> plainPtr() const { return _plainPtr<const T*>(); } //! 最大ツリー深度を取得 int getDepth() const { int depth = 0; if(_spChild) depth = _spChild->getDepth() + 1; if(_spSibling) depth = std::max(depth, _spSibling->getDepth()); return depth; } }; template <class T0, class T1, class CMP> bool _CompareTree(const TreeNode<T0>& t0, const TreeNode<T1>& t1, CMP&& cmp) { auto fnParentIndex = [](const auto& ar, const auto& p){ if(!p) return ar.end() - ar.begin(); auto itr = std::find_if(ar.begin(), ar.end(), [&p](auto& r){ return r == p.get(); }); return itr - ar.begin(); }; // 配列化して親ノード番号をチェック auto ar0 = t0.plainPtr(); auto ar1 = t1.plainPtr(); if(ar0.size() != ar1.size()) return false; auto sz = ar0.size(); for(size_t i=0 ; i<sz ; i++) { // 親ノード番号 int idx0 = fnParentIndex(ar0, ar0[i]->getParent()), idx1 = fnParentIndex(ar1, ar1[i]->getParent()); if(idx0!=idx1 || !cmp(ar0[i], ar1[i])) return false; } return true; } // ツリー構造のみを比較する template <class T0, class T1> bool CompareTreeStructure(const TreeNode<T0>& t0, const TreeNode<T1>& t1) { return _CompareTree(t0, t1, [](auto&,auto&){ return true; }); } //! データも含めて比較 template <class T0, class T1> bool CompareTree(const TreeNode<T0>& t0, const TreeNode<T1>& t1) { auto cmp = [](auto& sp0, auto& sp1){ return *sp0 == *sp1; }; return _CompareTree(t0, t1, cmp); } template <class T> inline std::ostream& operator << (std::ostream& os, const TreeNode<T>& t) { auto& self = const_cast<TreeNode<T>&>(t); self.iterateDepthFirst<false>([&os](auto& s, int indent){ s.print(os, indent); os << std::endl; return TreeNode<T>::Iterate::StepIn; }); return os; } } <|endoftext|>
<commit_before>#include "../stdafx.h" #include "list_view.h" namespace uih { void ListView::destroy_header() { if (m_wnd_header) { DestroyWindow(m_wnd_header); m_wnd_header = nullptr; m_header_font.reset(); } } void ListView::create_header() { // if (m_show_header) { if (!m_wnd_header) { m_header_font.reset(m_lf_header_valid ? CreateFontIndirect(&m_lf_header) : uih::create_icon_font()); m_wnd_header = CreateWindowEx(0, WC_HEADER, _T("NGLVH"), WS_CHILD | (0) | /*(m_autosize ? 0x0800 : NULL) |*/ HDS_HOTTRACK | (m_allow_header_rearrange ? HDS_DRAGDROP : NULL) | HDS_HORZ | HDS_FULLDRAG | (m_sorting_enabled ? HDS_BUTTONS : 0) | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, 0, 0, get_wnd(), HMENU(IDC_HEADER), mmh::get_current_instance(), nullptr); SetWindowTheme(m_wnd_header, m_use_dark_mode ? L"DarkMode_ItemsView" : L"ItemsView", nullptr); SendMessage(m_wnd_header, WM_SETFONT, (WPARAM)m_header_font.get(), MAKELPARAM(FALSE, 0)); if (m_initialised) { build_header(); ShowWindow(m_wnd_header, SW_SHOWNORMAL); } } } } void ListView::set_show_header(bool b_val) { if (b_val != m_show_header) { m_show_header = b_val; if (m_initialised) { if (m_show_header) create_header(); else destroy_header(); on_size(); } } } void ListView::reposition_header() { RECT rc; GetClientRect(get_wnd(), &rc); int cx = RECT_CX(rc); RECT rc_header; get_header_rect(&rc_header); SetWindowPos(m_wnd_header, nullptr, -m_horizontal_scroll_position, 0, cx + m_horizontal_scroll_position, RECT_CY(rc_header), SWP_NOZORDER); } void ListView::build_header() { if (m_wnd_header) { pfc::vartoggle_t<bool> toggle(m_ignore_column_size_change_notification, true); t_size header_count = Header_GetItemCount(m_wnd_header); for (; header_count; header_count--) Header_DeleteItem(m_wnd_header, header_count - 1); HDITEM hdi; memset(&hdi, 0, sizeof(HDITEM)); hdi.mask = HDI_TEXT | HDI_FORMAT | HDI_WIDTH; hdi.fmt = HDF_LEFT | HDF_STRING; pfc::string8 name; pfc::stringcvt::string_wide_from_utf8 wstr; { int n; int t = m_columns.size(); int i = 0; const auto indentation = get_total_indentation(); if (indentation /*m_group_count*/) { hdi.fmt = HDF_STRING | HDF_LEFT; hdi.cchTextMax = 0; hdi.pszText = const_cast<wchar_t*>(L""); hdi.cxy = indentation; Header_InsertItem(m_wnd_header, i++, &hdi); m_have_indent_column = true; } else m_have_indent_column = false; for (n = 0; n < t; n++) { hdi.fmt = HDF_STRING | HDF_LEFT; if (m_columns[n].m_alignment == uih::ALIGN_CENTRE) hdi.fmt |= HDF_CENTER; else if (m_columns[n].m_alignment == uih::ALIGN_RIGHT) hdi.fmt |= HDF_RIGHT; hdi.cchTextMax = m_columns[n].m_title.length(); wstr.convert(m_columns[n].m_title); hdi.pszText = const_cast<wchar_t*>(wstr.get_ptr()); hdi.cxy = m_columns[n].m_display_size; if (m_sort_column_index == n && m_show_sort_indicators) { hdi.fmt |= (m_sort_direction ? HDF_SORTDOWN : HDF_SORTUP); } Header_InsertItem(m_wnd_header, i++, &hdi); } } } } bool ListView::on_wm_notify_header(LPNMHDR lpnm, LRESULT& ret) { switch (lpnm->code) { case NM_CUSTOMDRAW: { LPNMCUSTOMDRAW lpcd = (LPNMCUSTOMDRAW)lpnm; switch (lpcd->dwDrawStage) { case CDDS_PREPAINT: ret = CDRF_NOTIFYITEMDRAW; return true; case CDDS_ITEMPREPAINT: { auto cr{RGB(255, 0, 0)}; if (!SUCCEEDED(GetThemeColor(m_header_theme.get(), HP_HEADERITEM, 0, TMT_TEXTCOLOR, &cr))) return false; SetTextColor(lpcd->hdc, cr); ret = CDRF_NEWFONT; return true; } default: return false; } } case HDN_BEGINTRACKA: case HDN_BEGINTRACKW: { auto lpnmh = (LPNMHEADER)lpnm; if (m_autosize && (!get_show_group_info_area() || lpnmh->iItem)) { ret = TRUE; return true; } } break; case HDN_DIVIDERDBLCLICK: { auto lpnmh = (LPNMHEADER)lpnm; if (!m_autosize) { if (lpnmh->iItem != -1 && (!m_have_indent_column || lpnmh->iItem)) { t_size realIndex = lpnmh->iItem; if (m_have_indent_column) realIndex--; if (realIndex < m_columns.size()) { HDC dc; dc = GetDC(get_wnd()); int size; HFONT fnt_old = SelectFont(dc, m_items_font.get()); int w = 0; int n; int t = get_item_count(); for (n = 0; n < t; n++) { const char* str = get_item_text(n, realIndex); size = uih::get_text_width_colour(dc, str, strlen(str)); if (size > w) w = size; } w += uih::scale_dpi_value(3) * 2 + scale_dpi_value(1); SelectFont(dc, fnt_old); ReleaseDC(get_wnd(), dc); m_columns[realIndex].m_size = w; m_columns[realIndex].m_display_size = w; update_header(); invalidate_all(); notify_on_column_size_change(realIndex, m_columns[realIndex].m_size); update_scroll_info(); } } } } break; case HDN_ITEMCHANGING: { if (!m_ignore_column_size_change_notification) { auto lpnmh = (LPNMHEADER)lpnm; if (lpnmh->pitem->mask & HDI_WIDTH) { if (m_have_indent_column && lpnmh->iItem == 0) { int min_indent = get_item_indentation(); if (get_show_group_info_area()) min_indent += get_default_indentation_step(); if (lpnmh->pitem->cxy < min_indent) { ret = TRUE; return true; } } } } } break; case HDN_ITEMCHANGED: { if (!m_ignore_column_size_change_notification) { auto lpnmh = (LPNMHEADER)lpnm; if (lpnmh->pitem->mask & HDI_WIDTH) { if (lpnmh->iItem != -1) { if (m_have_indent_column && lpnmh->iItem == 0) { int new_size = lpnmh->pitem->cxy - get_item_indentation() - get_default_indentation_step(); if (new_size >= 0 && new_size != get_group_info_area_width()) { /*set_group_info_area_size(new_size); if (m_autosize) { update_column_sizes(); update_header(); }*/ notify_on_group_info_area_size_change(new_size); /*invalidate_all(); update_scroll_info();*/ } } else if (!m_autosize) { t_size realIndex = lpnmh->iItem; if (m_have_indent_column) realIndex--; if (realIndex < m_columns.size() && m_columns[realIndex].m_display_size != lpnmh->pitem->cxy) { m_columns[realIndex].m_size = lpnmh->pitem->cxy; m_columns[realIndex].m_display_size = lpnmh->pitem->cxy; invalidate_all(); notify_on_column_size_change(realIndex, m_columns[realIndex].m_size); on_size(); } } } } } } break; case HDN_ITEMCLICK: { auto lpnmh = (LPNMHEADER)lpnm; if (lpnmh->iItem != -1 && (!m_have_indent_column || lpnmh->iItem)) { t_size realIndex = lpnmh->iItem; if (m_have_indent_column) realIndex--; if (realIndex < m_columns.size()) { bool des = (realIndex == m_sort_column_index ? !m_sort_direction : false); sort_by_column(realIndex, des); } } } break; /*case HDN_BEGINDRAG: { LPNMHEADER lpnmh = (LPNMHEADER)lpnm; if (lpnmh->iItem == 0 && m_have_indent_column) { ret = TRUE; return true; } } break;*/ case HDN_ENDDRAG: { auto lpnmh = (LPNMHEADER)lpnm; if (lpnmh->iButton == 0) { if (lpnmh->pitem && (lpnmh->pitem->mask & HDI_ORDER)) { int from = lpnmh->iItem; int to = lpnmh->pitem->iOrder; if (m_have_indent_column) { from--; to--; } if (to >= 0 && from >= 0 && from != to) { notify_on_header_rearrange(from, to); } } } } ret = TRUE; return true; } return false; } void ListView::get_header_rect(LPRECT rc) const { if (m_wnd_header) *rc = uih::get_relative_rect(m_wnd_header, get_wnd()); else { GetClientRect(get_wnd(), rc); rc->bottom = rc->top; } } unsigned ListView::get_header_height() const { unsigned ret = 0; if (m_wnd_header) { RECT rc; get_header_rect(&rc); ret = RECT_CY(rc); } return ret; } unsigned ListView::calculate_header_height() { unsigned rv = 0; if (m_wnd_header) { auto font = (HFONT)SendMessage(m_wnd_header, WM_GETFONT, 0, 0); rv = uih::get_font_height(font) + m_vertical_item_padding + scale_dpi_value(2); } return rv; } void ListView::update_header() { if (m_wnd_header) { pfc::vartoggle_t<bool> toggle(m_ignore_column_size_change_notification, true); // SendMessage(m_wnd_header, WM_SETREDRAW, FALSE, NULL); t_size i; t_size count = m_columns.size(); t_size j = 0; if (m_have_indent_column) { uih::header_set_item_width(m_wnd_header, j, get_total_indentation()); j++; } for (i = 0; i < count; i++) { uih::header_set_item_width(m_wnd_header, i + j, m_columns[i].m_display_size); } // SendMessage(m_wnd_header, WM_SETREDRAW, TRUE, NULL); // RedrawWindow(m_wnd_header, NULL, NULL, RDW_INVALIDATE|(b_update?RDW_UPDATENOW:0)); } } } // namespace uih <commit_msg>Don't set list view header window theme in non-dark mode<commit_after>#include "../stdafx.h" #include "list_view.h" namespace uih { void ListView::destroy_header() { if (m_wnd_header) { DestroyWindow(m_wnd_header); m_wnd_header = nullptr; m_header_font.reset(); } } void ListView::create_header() { // if (m_show_header) { if (!m_wnd_header) { m_header_font.reset(m_lf_header_valid ? CreateFontIndirect(&m_lf_header) : uih::create_icon_font()); m_wnd_header = CreateWindowEx(0, WC_HEADER, _T("NGLVH"), WS_CHILD | (0) | /*(m_autosize ? 0x0800 : NULL) |*/ HDS_HOTTRACK | (m_allow_header_rearrange ? HDS_DRAGDROP : NULL) | HDS_HORZ | HDS_FULLDRAG | (m_sorting_enabled ? HDS_BUTTONS : 0) | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, 0, 0, get_wnd(), HMENU(IDC_HEADER), mmh::get_current_instance(), nullptr); SetWindowTheme(m_wnd_header, m_use_dark_mode ? L"DarkMode_ItemsView" : nullptr, nullptr); SendMessage(m_wnd_header, WM_SETFONT, (WPARAM)m_header_font.get(), MAKELPARAM(FALSE, 0)); if (m_initialised) { build_header(); ShowWindow(m_wnd_header, SW_SHOWNORMAL); } } } } void ListView::set_show_header(bool b_val) { if (b_val != m_show_header) { m_show_header = b_val; if (m_initialised) { if (m_show_header) create_header(); else destroy_header(); on_size(); } } } void ListView::reposition_header() { RECT rc; GetClientRect(get_wnd(), &rc); int cx = RECT_CX(rc); RECT rc_header; get_header_rect(&rc_header); SetWindowPos(m_wnd_header, nullptr, -m_horizontal_scroll_position, 0, cx + m_horizontal_scroll_position, RECT_CY(rc_header), SWP_NOZORDER); } void ListView::build_header() { if (m_wnd_header) { pfc::vartoggle_t<bool> toggle(m_ignore_column_size_change_notification, true); t_size header_count = Header_GetItemCount(m_wnd_header); for (; header_count; header_count--) Header_DeleteItem(m_wnd_header, header_count - 1); HDITEM hdi; memset(&hdi, 0, sizeof(HDITEM)); hdi.mask = HDI_TEXT | HDI_FORMAT | HDI_WIDTH; hdi.fmt = HDF_LEFT | HDF_STRING; pfc::string8 name; pfc::stringcvt::string_wide_from_utf8 wstr; { int n; int t = m_columns.size(); int i = 0; const auto indentation = get_total_indentation(); if (indentation /*m_group_count*/) { hdi.fmt = HDF_STRING | HDF_LEFT; hdi.cchTextMax = 0; hdi.pszText = const_cast<wchar_t*>(L""); hdi.cxy = indentation; Header_InsertItem(m_wnd_header, i++, &hdi); m_have_indent_column = true; } else m_have_indent_column = false; for (n = 0; n < t; n++) { hdi.fmt = HDF_STRING | HDF_LEFT; if (m_columns[n].m_alignment == uih::ALIGN_CENTRE) hdi.fmt |= HDF_CENTER; else if (m_columns[n].m_alignment == uih::ALIGN_RIGHT) hdi.fmt |= HDF_RIGHT; hdi.cchTextMax = m_columns[n].m_title.length(); wstr.convert(m_columns[n].m_title); hdi.pszText = const_cast<wchar_t*>(wstr.get_ptr()); hdi.cxy = m_columns[n].m_display_size; if (m_sort_column_index == n && m_show_sort_indicators) { hdi.fmt |= (m_sort_direction ? HDF_SORTDOWN : HDF_SORTUP); } Header_InsertItem(m_wnd_header, i++, &hdi); } } } } bool ListView::on_wm_notify_header(LPNMHDR lpnm, LRESULT& ret) { switch (lpnm->code) { case NM_CUSTOMDRAW: { LPNMCUSTOMDRAW lpcd = (LPNMCUSTOMDRAW)lpnm; switch (lpcd->dwDrawStage) { case CDDS_PREPAINT: ret = CDRF_NOTIFYITEMDRAW; return true; case CDDS_ITEMPREPAINT: { auto cr{RGB(255, 0, 0)}; if (!SUCCEEDED(GetThemeColor(m_header_theme.get(), HP_HEADERITEM, 0, TMT_TEXTCOLOR, &cr))) return false; SetTextColor(lpcd->hdc, cr); ret = CDRF_NEWFONT; return true; } default: return false; } } case HDN_BEGINTRACKA: case HDN_BEGINTRACKW: { auto lpnmh = (LPNMHEADER)lpnm; if (m_autosize && (!get_show_group_info_area() || lpnmh->iItem)) { ret = TRUE; return true; } } break; case HDN_DIVIDERDBLCLICK: { auto lpnmh = (LPNMHEADER)lpnm; if (!m_autosize) { if (lpnmh->iItem != -1 && (!m_have_indent_column || lpnmh->iItem)) { t_size realIndex = lpnmh->iItem; if (m_have_indent_column) realIndex--; if (realIndex < m_columns.size()) { HDC dc; dc = GetDC(get_wnd()); int size; HFONT fnt_old = SelectFont(dc, m_items_font.get()); int w = 0; int n; int t = get_item_count(); for (n = 0; n < t; n++) { const char* str = get_item_text(n, realIndex); size = uih::get_text_width_colour(dc, str, strlen(str)); if (size > w) w = size; } w += uih::scale_dpi_value(3) * 2 + scale_dpi_value(1); SelectFont(dc, fnt_old); ReleaseDC(get_wnd(), dc); m_columns[realIndex].m_size = w; m_columns[realIndex].m_display_size = w; update_header(); invalidate_all(); notify_on_column_size_change(realIndex, m_columns[realIndex].m_size); update_scroll_info(); } } } } break; case HDN_ITEMCHANGING: { if (!m_ignore_column_size_change_notification) { auto lpnmh = (LPNMHEADER)lpnm; if (lpnmh->pitem->mask & HDI_WIDTH) { if (m_have_indent_column && lpnmh->iItem == 0) { int min_indent = get_item_indentation(); if (get_show_group_info_area()) min_indent += get_default_indentation_step(); if (lpnmh->pitem->cxy < min_indent) { ret = TRUE; return true; } } } } } break; case HDN_ITEMCHANGED: { if (!m_ignore_column_size_change_notification) { auto lpnmh = (LPNMHEADER)lpnm; if (lpnmh->pitem->mask & HDI_WIDTH) { if (lpnmh->iItem != -1) { if (m_have_indent_column && lpnmh->iItem == 0) { int new_size = lpnmh->pitem->cxy - get_item_indentation() - get_default_indentation_step(); if (new_size >= 0 && new_size != get_group_info_area_width()) { /*set_group_info_area_size(new_size); if (m_autosize) { update_column_sizes(); update_header(); }*/ notify_on_group_info_area_size_change(new_size); /*invalidate_all(); update_scroll_info();*/ } } else if (!m_autosize) { t_size realIndex = lpnmh->iItem; if (m_have_indent_column) realIndex--; if (realIndex < m_columns.size() && m_columns[realIndex].m_display_size != lpnmh->pitem->cxy) { m_columns[realIndex].m_size = lpnmh->pitem->cxy; m_columns[realIndex].m_display_size = lpnmh->pitem->cxy; invalidate_all(); notify_on_column_size_change(realIndex, m_columns[realIndex].m_size); on_size(); } } } } } } break; case HDN_ITEMCLICK: { auto lpnmh = (LPNMHEADER)lpnm; if (lpnmh->iItem != -1 && (!m_have_indent_column || lpnmh->iItem)) { t_size realIndex = lpnmh->iItem; if (m_have_indent_column) realIndex--; if (realIndex < m_columns.size()) { bool des = (realIndex == m_sort_column_index ? !m_sort_direction : false); sort_by_column(realIndex, des); } } } break; /*case HDN_BEGINDRAG: { LPNMHEADER lpnmh = (LPNMHEADER)lpnm; if (lpnmh->iItem == 0 && m_have_indent_column) { ret = TRUE; return true; } } break;*/ case HDN_ENDDRAG: { auto lpnmh = (LPNMHEADER)lpnm; if (lpnmh->iButton == 0) { if (lpnmh->pitem && (lpnmh->pitem->mask & HDI_ORDER)) { int from = lpnmh->iItem; int to = lpnmh->pitem->iOrder; if (m_have_indent_column) { from--; to--; } if (to >= 0 && from >= 0 && from != to) { notify_on_header_rearrange(from, to); } } } } ret = TRUE; return true; } return false; } void ListView::get_header_rect(LPRECT rc) const { if (m_wnd_header) *rc = uih::get_relative_rect(m_wnd_header, get_wnd()); else { GetClientRect(get_wnd(), rc); rc->bottom = rc->top; } } unsigned ListView::get_header_height() const { unsigned ret = 0; if (m_wnd_header) { RECT rc; get_header_rect(&rc); ret = RECT_CY(rc); } return ret; } unsigned ListView::calculate_header_height() { unsigned rv = 0; if (m_wnd_header) { auto font = (HFONT)SendMessage(m_wnd_header, WM_GETFONT, 0, 0); rv = uih::get_font_height(font) + m_vertical_item_padding + scale_dpi_value(2); } return rv; } void ListView::update_header() { if (m_wnd_header) { pfc::vartoggle_t<bool> toggle(m_ignore_column_size_change_notification, true); // SendMessage(m_wnd_header, WM_SETREDRAW, FALSE, NULL); t_size i; t_size count = m_columns.size(); t_size j = 0; if (m_have_indent_column) { uih::header_set_item_width(m_wnd_header, j, get_total_indentation()); j++; } for (i = 0; i < count; i++) { uih::header_set_item_width(m_wnd_header, i + j, m_columns[i].m_display_size); } // SendMessage(m_wnd_header, WM_SETREDRAW, TRUE, NULL); // RedrawWindow(m_wnd_header, NULL, NULL, RDW_INVALIDATE|(b_update?RDW_UPDATENOW:0)); } } } // namespace uih <|endoftext|>
<commit_before>#ifndef TEST_HELPER_H_ #define TEST_HELPER_H_ #include <internal/iterbase.hpp> #include <sstream> #include <stdexcept> #include <type_traits> #include <utility> #include <vector> namespace itertest { // non-copyable. non-movable. non-default-constructible class SolidInt { private: const int i; public: constexpr SolidInt(int n) : i{n} {} constexpr int getint() const { return this->i; } SolidInt() = delete; SolidInt(const SolidInt&) = delete; SolidInt& operator=(const SolidInt&) = delete; SolidInt& operator=(SolidInt&&) = delete; SolidInt(SolidInt&&) = delete; }; namespace { struct DoubleDereferenceError : std::exception { const char* what() const noexcept override { return "Iterator dereferenced twice without increment"; } }; // this class's iterator will throw if it's dereference twice without // an increment in between class InputIterable { public: class Iterator { private: int i; bool was_incremented = true; public: Iterator(int n) : i{n} {} Iterator& operator++() { ++this->i; this->was_incremented = true; return *this; } int operator*() { if (!this->was_incremented) { throw DoubleDereferenceError{}; } this->was_incremented = false; return this->i; } bool operator!=(const Iterator& other) const { return this->i != other.i; } }; Iterator begin() { return {0}; } Iterator end() { return {5}; } }; } // BasicIterable provides a minimal forward iterator // operator++(), operator!=(const BasicIterable&), operator*() // move constructible only // not copy constructible, move assignable, or copy assignable template <typename T> class BasicIterable { private: T* data; std::size_t size; bool was_moved_from_ = false; mutable bool was_copied_from_ = false; public: BasicIterable(std::initializer_list<T> il) : data{new T[il.size()]}, size{il.size()} { // would like to use enumerate, can't because it's for unit // testing enumerate std::size_t i = 0; for (auto&& e : il) { data[i] = e; ++i; } } BasicIterable& operator=(BasicIterable&&) = delete; BasicIterable& operator=(const BasicIterable&) = delete; #ifndef DEFINE_BASIC_ITERABLE_COPY_CTOR BasicIterable(const BasicIterable&) = delete; #else BasicIterable(const BasicIterable& other) : data{new T[other.size]}, size{other.size} { other.was_copied_from_ = true; auto o_it = begin(other); for (auto it = begin(*this); o_it != end(other); ++it, ++o_it) { *it = *o_it; } } #endif BasicIterable(BasicIterable&& other) : data{other.data}, size{other.size} { other.data = nullptr; other.was_moved_from_ = true; } bool was_moved_from() const { return this->was_moved_from_; } bool was_copied_from() const { return this->was_copied_from_; } ~BasicIterable() { delete[] this->data; } template <typename U> class Iterator { private: U* p; public: #ifdef DEFINE_DEFAULT_ITERATOR_CTOR Iterator() = default; #endif Iterator(U* b) : p{b} {} bool operator!=(const Iterator& other) const { return this->p != other.p; } Iterator& operator++() { ++this->p; return *this; } U& operator*() { return *this->p; } }; friend BasicIterable::Iterator<T> begin(BasicIterable& b) { return {b.data}; } friend BasicIterable::Iterator<T> end(BasicIterable& b) { return {b.data + b.size}; } #ifdef DEFINE_BASIC_ITERABLE_CONST_BEGIN_AND_END friend BasicIterable::Iterator<const T> begin(const BasicIterable& b) { return {b.data}; } friend BasicIterable::Iterator<const T> end(const BasicIterable& b) { return {b.data + b.size}; } #endif #ifdef DECLARE_REVERSE_ITERATOR Iterator<T> rbegin(); Iterator<T> rend(); #endif // ifdef DECLARE_REVERSE_ITERATOR }; template <typename, typename = void> struct IsIterator : std::false_type {}; template <typename T> struct IsIterator<T, std::void_t<decltype(T(std::declval<const T&>())), // copyctor decltype(std::declval<T&>() = std::declval<const T&>()), // copy = decltype(*std::declval<T&>()), // operator* decltype(std::declval<T&>().operator->()), // operator-> decltype(++std::declval<T&>()), // prefix ++ decltype(std::declval<T&>()++), // postfix ++ decltype( std::declval<const T&>() != std::declval<const T&>()), // != decltype(std::declval<const T&>() == std::declval<const T&>()) // == >> : std::true_type {}; template <typename T> struct IsForwardIterator : std::integral_constant<bool, IsIterator<T>::value && std::is_default_constructible<T>::value> {}; template <typename T> struct IsMoveConstructibleOnly : std::integral_constant<bool, !std::is_copy_constructible<T>::value && !std::is_copy_assignable<T>::value && !std::is_move_assignable<T>::value && std::is_move_constructible<T>::value> {}; struct Point { int x; int y; int get_x() const { return x; } int get_y() const { return y; } std::string prefix(const std::string& str) { std::ostringstream ss; ss << str << "(" << x << ", " << y << ")"; return ss.str(); } }; } template <typename T, typename Inc> class DiffEndRange { private: T start_; T stop_; std::vector<T> all_results_; public: constexpr DiffEndRange(T start, T stop) : start_{start}, stop_{stop} { while (start < stop_) { all_results_.push_back(start); Inc{}(start); } } class Iterator; class EndIterator; class Iterator { using SubIter = typename std::vector<T>::iterator; private: SubIter it_; SubIter end_; public: #ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE Iterator() = default; #endif Iterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {} T& operator*() const { return *it_; } T* operator->() const { return &*it_; } Iterator& operator++() { ++it_; return *this; } bool operator!=(const Iterator& other) const { return it_ != other.it_; } bool operator!=(const EndIterator&) const { return it_ != end_; } friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) { return rhs != lhs; } }; class ReverseIterator { using SubIter = typename std::vector<T>::reverse_iterator; private: SubIter it_; SubIter end_; public: #ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE ReverseIterator() = default; #endif ReverseIterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {} T& operator*() const { return *it_; } T* operator->() const { return &*it_; } Iterator& operator++() { ++it_; return *this; } bool operator!=(const Iterator& other) const { return it_ != other.it_; } bool operator!=(const EndIterator&) const { return it_ != end_; } friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) { return rhs != lhs; } }; class EndIterator {}; class ReverseEndIterator {}; Iterator begin() { return {std::begin(all_results_), std::end(all_results_)}; } EndIterator end() { return {}; } ReverseIterator rbegin() { return {std::rbegin(all_results_), std::rend(all_results_)}; } ReverseEndIterator rend() { return {}; } }; struct CharInc { void operator()(char& c) { ++c; } }; // A range from 'a' to stop, begin() and end() are different class CharRange : public DiffEndRange<char, CharInc> { public: constexpr CharRange(char stop) : DiffEndRange<char, CharInc>('a', stop) {} }; struct IncIntCharPair { void operator()(std::pair<int, char>& p) { ++p.first; ++p.second; } }; class IntCharPairRange : public DiffEndRange<std::pair<int, char>, IncIntCharPair> { public: IntCharPairRange(std::pair<int, char> stop) : DiffEndRange<std::pair<int, char>, IncIntCharPair>({0, 'a'}, stop) {} }; #endif <commit_msg>Adds == and != operators to Point<commit_after>#ifndef TEST_HELPER_H_ #define TEST_HELPER_H_ #include <internal/iterbase.hpp> #include <sstream> #include <stdexcept> #include <type_traits> #include <utility> #include <vector> namespace itertest { // non-copyable. non-movable. non-default-constructible class SolidInt { private: const int i; public: constexpr SolidInt(int n) : i{n} {} constexpr int getint() const { return this->i; } SolidInt() = delete; SolidInt(const SolidInt&) = delete; SolidInt& operator=(const SolidInt&) = delete; SolidInt& operator=(SolidInt&&) = delete; SolidInt(SolidInt&&) = delete; }; namespace { struct DoubleDereferenceError : std::exception { const char* what() const noexcept override { return "Iterator dereferenced twice without increment"; } }; // this class's iterator will throw if it's dereference twice without // an increment in between class InputIterable { public: class Iterator { private: int i; bool was_incremented = true; public: Iterator(int n) : i{n} {} Iterator& operator++() { ++this->i; this->was_incremented = true; return *this; } int operator*() { if (!this->was_incremented) { throw DoubleDereferenceError{}; } this->was_incremented = false; return this->i; } bool operator!=(const Iterator& other) const { return this->i != other.i; } }; Iterator begin() { return {0}; } Iterator end() { return {5}; } }; } // BasicIterable provides a minimal forward iterator // operator++(), operator!=(const BasicIterable&), operator*() // move constructible only // not copy constructible, move assignable, or copy assignable template <typename T> class BasicIterable { private: T* data; std::size_t size; bool was_moved_from_ = false; mutable bool was_copied_from_ = false; public: BasicIterable(std::initializer_list<T> il) : data{new T[il.size()]}, size{il.size()} { // would like to use enumerate, can't because it's for unit // testing enumerate std::size_t i = 0; for (auto&& e : il) { data[i] = e; ++i; } } BasicIterable& operator=(BasicIterable&&) = delete; BasicIterable& operator=(const BasicIterable&) = delete; #ifndef DEFINE_BASIC_ITERABLE_COPY_CTOR BasicIterable(const BasicIterable&) = delete; #else BasicIterable(const BasicIterable& other) : data{new T[other.size]}, size{other.size} { other.was_copied_from_ = true; auto o_it = begin(other); for (auto it = begin(*this); o_it != end(other); ++it, ++o_it) { *it = *o_it; } } #endif BasicIterable(BasicIterable&& other) : data{other.data}, size{other.size} { other.data = nullptr; other.was_moved_from_ = true; } bool was_moved_from() const { return this->was_moved_from_; } bool was_copied_from() const { return this->was_copied_from_; } ~BasicIterable() { delete[] this->data; } template <typename U> class Iterator { private: U* p; public: #ifdef DEFINE_DEFAULT_ITERATOR_CTOR Iterator() = default; #endif Iterator(U* b) : p{b} {} bool operator!=(const Iterator& other) const { return this->p != other.p; } Iterator& operator++() { ++this->p; return *this; } U& operator*() { return *this->p; } }; friend BasicIterable::Iterator<T> begin(BasicIterable& b) { return {b.data}; } friend BasicIterable::Iterator<T> end(BasicIterable& b) { return {b.data + b.size}; } #ifdef DEFINE_BASIC_ITERABLE_CONST_BEGIN_AND_END friend BasicIterable::Iterator<const T> begin(const BasicIterable& b) { return {b.data}; } friend BasicIterable::Iterator<const T> end(const BasicIterable& b) { return {b.data + b.size}; } #endif #ifdef DECLARE_REVERSE_ITERATOR Iterator<T> rbegin(); Iterator<T> rend(); #endif // ifdef DECLARE_REVERSE_ITERATOR }; template <typename, typename = void> struct IsIterator : std::false_type {}; template <typename T> struct IsIterator<T, std::void_t<decltype(T(std::declval<const T&>())), // copyctor decltype(std::declval<T&>() = std::declval<const T&>()), // copy = decltype(*std::declval<T&>()), // operator* decltype(std::declval<T&>().operator->()), // operator-> decltype(++std::declval<T&>()), // prefix ++ decltype(std::declval<T&>()++), // postfix ++ decltype( std::declval<const T&>() != std::declval<const T&>()), // != decltype(std::declval<const T&>() == std::declval<const T&>()) // == >> : std::true_type {}; template <typename T> struct IsForwardIterator : std::integral_constant<bool, IsIterator<T>::value && std::is_default_constructible<T>::value> {}; template <typename T> struct IsMoveConstructibleOnly : std::integral_constant<bool, !std::is_copy_constructible<T>::value && !std::is_copy_assignable<T>::value && !std::is_move_assignable<T>::value && std::is_move_constructible<T>::value> {}; struct Point { int x; int y; int get_x() const { return x; } int get_y() const { return y; } std::string prefix(const std::string& str) { std::ostringstream ss; ss << str << "(" << x << ", " << y << ")"; return ss.str(); } bool operator==(Point other) const { return x == other.x && y == other.y; } bool operator!=(Point other) const { return !(*this == other); } }; } template <typename T, typename Inc> class DiffEndRange { private: T start_; T stop_; std::vector<T> all_results_; public: constexpr DiffEndRange(T start, T stop) : start_{start}, stop_{stop} { while (start < stop_) { all_results_.push_back(start); Inc{}(start); } } class Iterator; class EndIterator; class Iterator { using SubIter = typename std::vector<T>::iterator; private: SubIter it_; SubIter end_; public: #ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE Iterator() = default; #endif Iterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {} T& operator*() const { return *it_; } T* operator->() const { return &*it_; } Iterator& operator++() { ++it_; return *this; } bool operator!=(const Iterator& other) const { return it_ != other.it_; } bool operator!=(const EndIterator&) const { return it_ != end_; } friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) { return rhs != lhs; } }; class ReverseIterator { using SubIter = typename std::vector<T>::reverse_iterator; private: SubIter it_; SubIter end_; public: #ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE ReverseIterator() = default; #endif ReverseIterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {} T& operator*() const { return *it_; } T* operator->() const { return &*it_; } Iterator& operator++() { ++it_; return *this; } bool operator!=(const Iterator& other) const { return it_ != other.it_; } bool operator!=(const EndIterator&) const { return it_ != end_; } friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) { return rhs != lhs; } }; class EndIterator {}; class ReverseEndIterator {}; Iterator begin() { return {std::begin(all_results_), std::end(all_results_)}; } EndIterator end() { return {}; } ReverseIterator rbegin() { return {std::rbegin(all_results_), std::rend(all_results_)}; } ReverseEndIterator rend() { return {}; } }; struct CharInc { void operator()(char& c) { ++c; } }; // A range from 'a' to stop, begin() and end() are different class CharRange : public DiffEndRange<char, CharInc> { public: constexpr CharRange(char stop) : DiffEndRange<char, CharInc>('a', stop) {} }; struct IncIntCharPair { void operator()(std::pair<int, char>& p) { ++p.first; ++p.second; } }; class IntCharPairRange : public DiffEndRange<std::pair<int, char>, IncIntCharPair> { public: IntCharPairRange(std::pair<int, char> stop) : DiffEndRange<std::pair<int, char>, IncIntCharPair>({0, 'a'}, stop) {} }; #endif <|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * 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 HitFinderTools.h */ #include "HitFinderTools.h" using namespace std; vector<JPetHit> HitFinderTools::createHits(const SignalsContainer& allSignalsInTimeWindow, const double timeDifferenceWindow){ // This method takes signal from side A on a scintilator and compares it with signals on side B - if they are within time window then it creates hit vector<JPetHit> hits; for (auto scintillator : allSignalsInTimeWindow) { auto sideA = scintillator.second.first; auto sideB = scintillator.second.second; if(sideA.size() > 0 and sideB.size() > 0){ for(auto signalA : sideA){ for(auto signalB : sideB){ if(abs(signalA.getTime() - signalB.getTime()) < timeDifferenceWindow /*ps*/){ JPetHit hit; hit.setSignalA(signalA); hit.setSignalB(signalB); hit.setTime( (signalA.getTime() + signalB.getTime())/2.0 ); hit.setScintillator(signalA.getRecoSignal().getRawSignal().getPM().getScin()); hit.setBarrelSlot(signalA.getRecoSignal().getRawSignal().getPM().getScin().getBarrelSlot()); hits.push_back(hit); } } } } } return hits; } <commit_msg>Sort signals<commit_after>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * 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 HitFinderTools.h */ #include "HitFinderTools.h" using namespace std; vector<JPetHit> HitFinderTools::createHits(const SignalsContainer& allSignalsInTimeWindow, const double timeDifferenceWindow){ // This method takes signal from side A on a scintilator and compares it with signals on side B - if they are within time window then it creates hit vector<JPetHit> hits; for (auto scintillator : allSignalsInTimeWindow) { auto sideA = scintillator.second.first; auto sideB = scintillator.second.second; if(sideA.size() > 0 and sideB.size() > 0){ std::sort(sideA.begin(), sideA.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) {return h1.getTime() < h2.getTime();}); std::sort(sideB.begin(), sideB.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) {return h1.getTime() < h2.getTime();}); for(auto signalA : sideA){ for(auto signalB : sideB){ if(abs(signalA.getTime() - signalB.getTime()) < timeDifferenceWindow && (signalA.getTime() - signalB.getTime()) < timeDifferenceWindow/*ps*/){ JPetHit hit; hit.setSignalA(signalA); hit.setSignalB(signalB); hit.setTime( (signalA.getTime() + signalB.getTime())/2.0 ); hit.setScintillator(signalA.getRecoSignal().getRawSignal().getPM().getScin()); hit.setBarrelSlot(signalA.getRecoSignal().getRawSignal().getPM().getScin().getBarrelSlot()); hits.push_back(hit); } } } } } return hits; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.2 2000/02/06 07:47:24 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:09:29 twl * Initial checkin * * Revision 1.11 1999/11/08 20:43:42 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/XMLUni.hpp> #include <sax/AttributeList.hpp> #include "SAXPrint.hpp" // --------------------------------------------------------------------------- // SAXPrintHandlers: Constructors and Destructor // --------------------------------------------------------------------------- SAXPrintHandlers::SAXPrintHandlers(const bool doEscapes) : fDoEscapes(doEscapes) { } SAXPrintHandlers::~SAXPrintHandlers() { } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX ErrorHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::error(const SAXParseException& e) { cerr << "\nError at (file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "): " << StrX(e.getMessage()) << endl; } void SAXPrintHandlers::fatalError(const SAXParseException& e) { cerr << "\nFatal Error at (file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "): " << StrX(e.getMessage()) << endl; } void SAXPrintHandlers::warning(const SAXParseException& e) { cerr << "\nWarning at (file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "): " << StrX(e.getMessage()) << endl; } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX DTDHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::unparsedEntityDecl(const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId , const XMLCh* const notationName) { // Not used at this time } void SAXPrintHandlers::notationDecl( const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId) { // Not used at this time } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX DocumentHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::characters(const XMLCh* const chars , const unsigned int length) { // Transcode to UTF-8 for portable display StrX tmpXCode(chars, length); const char* tmpText = tmpXCode.localForm(); // // If we were asked to escape special chars, then do that. Else just // display it as normal text. // if (fDoEscapes) { for (unsigned int index = 0; index < length; index++) { switch (tmpText[index]) { case chAmpersand : cout << "&amp;"; break; case chOpenAngle : cout << "&lt;"; break; case chCloseAngle: cout << "&gt;"; break; case chDoubleQuote : cout << "&quot;"; break; default: cout << tmpText[index]; break; } } } else { cout << tmpText; } } void SAXPrintHandlers::endDocument() { } void SAXPrintHandlers::endElement(const XMLCh* const name) { cout << "</" << StrX(name) << ">"; } void SAXPrintHandlers::ignorableWhitespace( const XMLCh* const chars ,const unsigned int length) { cout << StrX(chars, length); } void SAXPrintHandlers::processingInstruction(const XMLCh* const target , const XMLCh* const data) { cout << "<?" << StrX(target); if (data) cout << " " << StrX(data); cout << "?>\n"; } void SAXPrintHandlers::startDocument() { } void SAXPrintHandlers::startElement(const XMLCh* const name , AttributeList& attributes) { cout << "<" << StrX(name); unsigned int len = attributes.getLength(); for (unsigned int index = 0; index < len; index++) { cout << " " << StrX(attributes.getName(index)) << "=\""; cout << StrX(attributes.getValue(index)) << "\""; } cout << ">"; } <commit_msg>Removed second parameter from call to StrX constructor<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.3 2000/02/11 03:05:35 abagchi * Removed second parameter from call to StrX constructor * * Revision 1.2 2000/02/06 07:47:24 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:09:29 twl * Initial checkin * * Revision 1.11 1999/11/08 20:43:42 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/XMLUni.hpp> #include <sax/AttributeList.hpp> #include "SAXPrint.hpp" // --------------------------------------------------------------------------- // SAXPrintHandlers: Constructors and Destructor // --------------------------------------------------------------------------- SAXPrintHandlers::SAXPrintHandlers(const bool doEscapes) : fDoEscapes(doEscapes) { } SAXPrintHandlers::~SAXPrintHandlers() { } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX ErrorHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::error(const SAXParseException& e) { cerr << "\nError at (file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "): " << StrX(e.getMessage()) << endl; } void SAXPrintHandlers::fatalError(const SAXParseException& e) { cerr << "\nFatal Error at (file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "): " << StrX(e.getMessage()) << endl; } void SAXPrintHandlers::warning(const SAXParseException& e) { cerr << "\nWarning at (file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "): " << StrX(e.getMessage()) << endl; } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX DTDHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::unparsedEntityDecl(const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId , const XMLCh* const notationName) { // Not used at this time } void SAXPrintHandlers::notationDecl( const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId) { // Not used at this time } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX DocumentHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::characters(const XMLCh* const chars , const unsigned int length) { // Transcode to UTF-8 for portable display StrX tmpXCode(chars); const char* tmpText = tmpXCode.localForm(); // // If we were asked to escape special chars, then do that. Else just // display it as normal text. // if (fDoEscapes) { for (unsigned int index = 0; index < length; index++) { switch (tmpText[index]) { case chAmpersand : cout << "&amp;"; break; case chOpenAngle : cout << "&lt;"; break; case chCloseAngle: cout << "&gt;"; break; case chDoubleQuote : cout << "&quot;"; break; default: cout << tmpText[index]; break; } } } else { cout << tmpText; } } void SAXPrintHandlers::endDocument() { } void SAXPrintHandlers::endElement(const XMLCh* const name) { cout << "</" << StrX(name) << ">"; } void SAXPrintHandlers::ignorableWhitespace( const XMLCh* const chars ,const unsigned int length) { cout << StrX(chars); } void SAXPrintHandlers::processingInstruction(const XMLCh* const target , const XMLCh* const data) { cout << "<?" << StrX(target); if (data) cout << " " << StrX(data); cout << "?>\n"; } void SAXPrintHandlers::startDocument() { } void SAXPrintHandlers::startElement(const XMLCh* const name , AttributeList& attributes) { cout << "<" << StrX(name); unsigned int len = attributes.getLength(); for (unsigned int index = 0; index < len; index++) { cout << " " << StrX(attributes.getName(index)) << "=\""; cout << StrX(attributes.getValue(index)) << "\""; } cout << ">"; } <|endoftext|>
<commit_before>// // Exponent.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Exponential.h" Exponential::Exponential(Expression* base, Rational* exponent){ this->type = "exponential"; this->base = base; this->exponent = exponent; this->exde = new Integer(exponent->getDenominator()); if (exde->getValue() != 1) { //if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1 Integer* baseAsInteger = (Integer *) base; base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1); Integer* one = new Integer(1); exponent->setDenominator(one); } this->exnu = new Integer(exponent->getNumerator()); if (canExponentiate()) { exponentiate(); } } Exponential::~Exponential(){ } bool Exponential::canExponentiate() { if(base->type == "euler"){ return false; }else if(base->type == "exponential"){ Exponential* ex = (Exponential *) base; this->exponent->multiply(ex->getExponent()); Integer* numSum = new Integer (1); ex->getExponent()->setNumerator(numSum); return false; // false is returned because the base itself would have already been exponentiated if it were possible }else if(base->type == "integer"){ return true; }else if(base->type == "logarithm"){ return false; }else if(base->type == "nthRoot"){ nthRoot* nr = (nthRoot *) base; Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator()); //makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one this->exponent = r; nr->setRoot(1); return false; }else if(base->type == "pi"){ return false; }else if(base->type == "rational"){ Rational* r = (Rational *) base; if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") { Exponential* nu = new Exponential(r->geteNumerator(), this->exponent); r->setNumerator(nu); Exponential* de = new Exponential(r->geteDenominator(), this->exponent); r->setDenominator(de); } }else{ cout << "type not recognized" << endl; } return false; } void Exponential::exponentiate(){ Integer* one = new Integer(1); Rational* oneRat = new Rational(1, 1); if (this->base->type == "rational") { Rational* ratBase = (Rational *) this->base; Exponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); //no matching constructor for exponential Exponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); //same error Rational* newRatBase = new Rational(numAsExponential, denAsExponential); this->base = newRatBase; this->exponent = oneRat; } else { if (this->exponent->getNumerator()==0) { this->exponent=oneRat; this->base=one; } bool toFlip = false; if (exnu->getValue()<0) { exnu->setValue(exnu->getValue()*-1); toFlip = true; //handles negative exponents } Expression* constantBase = 0; if (base->type == "integer") { //fixed the problem for integers but nothing else Integer *a = (Integer *)base; constantBase = new Integer(a->getValue()); } while (exponent->getNumerator()>1) { base->multiply(constantBase); exponent->setNumerator(exponent->geteNumerator()->subtract(one)); } if (toFlip) { Integer* one = new Integer(1); Rational* mouse = new Rational(one, base); base = mouse; } } } Expression* Exponential::add(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* two = new Integer(2); this->multiply(two); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::subtract(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* zero = new Integer(0); this->multiply(zero); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::multiply(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (this->base == ex->getBase()) { this->exponent->add(ex->getExponent()); } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* numToSet = r->geteNumerator(); numToSet->multiply(this); r->setNumerator(numToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::divide(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (this->base == ex->getBase()) { this->exponent->subtract(ex->getExponent()); } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* denToSet = r->geteDenominator(); denToSet->multiply(this); r->setDenominator(denToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Rational* Exponential::getExponent() { return exponent; } Expression* Exponential::getBase() { return base; } Integer* Exponential::getExnu() { return exnu; } Integer* Exponential::getExde() { return exde; } void Exponential::setExnu(Integer* n) { exnu = n; } void Exponential::setExde(Integer* n) { exde = n; } void Exponential::setExponent(Rational* e) { exponent = e; } void Exponential::setBase(Expression* e) { base = e; } string Exponential::toString() { stringstream str; if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){ str << *base; } else if(exponent->getDenominator() == 1){ str << *base << "^" << *exponent->geteNumerator(); }else{ str << *base << "^" << *exponent; } return str.str(); } ostream& Exponential::print(std::ostream& output) const{ Exponential *a = (Exponential *)this; output << a->toString(); return output; } bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } <commit_msg>Fixed canMultiply and canDivide<commit_after>// // Exponent.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Exponential.h" Exponential::Exponential(Expression* base, Rational* exponent){ this->type = "exponential"; this->base = base; this->exponent = exponent; this->exde = new Integer(exponent->getDenominator()); if (exde->getValue() != 1) { //if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1 Integer* baseAsInteger = (Integer *) base; base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1); Integer* one = new Integer(1); exponent->setDenominator(one); } this->exnu = new Integer(exponent->getNumerator()); if (canExponentiate()) { exponentiate(); } } Exponential::~Exponential(){ } bool Exponential::canExponentiate() { if(base->type == "euler"){ return false; }else if(base->type == "exponential"){ Exponential* ex = (Exponential *) base; this->exponent->multiply(ex->getExponent()); Integer* numSum = new Integer (1); ex->getExponent()->setNumerator(numSum); return false; // false is returned because the base itself would have already been exponentiated if it were possible }else if(base->type == "integer"){ return true; }else if(base->type == "logarithm"){ return false; }else if(base->type == "nthRoot"){ nthRoot* nr = (nthRoot *) base; Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator()); //makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one this->exponent = r; nr->setRoot(1); return false; }else if(base->type == "pi"){ return false; }else if(base->type == "rational"){ Rational* r = (Rational *) base; if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") { Exponential* nu = new Exponential(r->geteNumerator(), this->exponent); r->setNumerator(nu); Exponential* de = new Exponential(r->geteDenominator(), this->exponent); r->setDenominator(de); } }else{ cout << "type not recognized" << endl; } return false; } void Exponential::exponentiate(){ Integer* one = new Integer(1); Rational* oneRat = new Rational(1, 1); if (this->base->type == "rational") { Rational* ratBase = (Rational *) this->base; Exponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); //no matching constructor for exponential Exponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); //same error Rational* newRatBase = new Rational(numAsExponential, denAsExponential); this->base = newRatBase; this->exponent = oneRat; } else { if (this->exponent->getNumerator()==0) { this->exponent=oneRat; this->base=one; } bool toFlip = false; if (exnu->getValue()<0) { exnu->setValue(exnu->getValue()*-1); toFlip = true; //handles negative exponents } Expression* constantBase = 0; if (base->type == "integer") { //fixed the problem for integers but nothing else Integer *a = (Integer *)base; constantBase = new Integer(a->getValue()); } while (exponent->getNumerator()>1) { base->multiply(constantBase); exponent->setNumerator(exponent->geteNumerator()->subtract(one)); } if (toFlip) { Integer* one = new Integer(1); Rational* mouse = new Rational(one, base); base = mouse; } } } Expression* Exponential::add(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* two = new Integer(2); this->multiply(two); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::subtract(Expression* a){ if(a->type == "euler"){ }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (ex->getBase()==this->base) { if (ex->getExponent()==this->exponent) { Integer* zero = new Integer(0); this->multiply(zero); } } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ }else if(a->type == "rational"){ }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::multiply(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (this->base == ex->getBase()) { this->exponent->add(ex->getExponent()); } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->add(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* numToSet = r->geteNumerator(); numToSet->multiply(this); r->setNumerator(numToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Expression* Exponential::divide(Expression* a){ if(a->type == "euler"){ if (this->base->type == "euler") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "exponential"){ Exponential* ex = (Exponential *) a; if (this->base == ex->getBase()) { this->exponent->subtract(ex->getExponent()); } }else if(a->type == "integer"){ }else if(a->type == "logarithm"){ }else if(a->type == "nthRoot"){ }else if(a->type == "pi"){ if (this->base->type == "pi") { Rational* oneRat = new Rational(1, 1); this->exponent->subtract(oneRat); } }else if(a->type == "rational"){ Rational* r = (Rational *) a; Expression* denToSet = r->geteDenominator(); denToSet->multiply(this); r->setDenominator(denToSet); return r; }else{ cout << "type not recognized" << endl; } return this; } Rational* Exponential::getExponent() { return exponent; } Expression* Exponential::getBase() { return base; } Integer* Exponential::getExnu() { return exnu; } Integer* Exponential::getExde() { return exde; } void Exponential::setExnu(Integer* n) { exnu = n; } void Exponential::setExde(Integer* n) { exde = n; } void Exponential::setExponent(Rational* e) { exponent = e; } void Exponential::setBase(Expression* e) { base = e; } string Exponential::toString() { stringstream str; if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){ str << *base; } else if(exponent->getDenominator() == 1){ str << *base << "^" << *exponent->geteNumerator(); }else{ str << *base << "^" << *exponent; } return str.str(); } ostream& Exponential::print(std::ostream& output) const{ Exponential *a = (Exponential *)this; output << a->toString(); return output; } bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression) if (this->type == b->type && this->type != "logarithm") { if (this->type == "nthRoot") { } return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canSubtract(Expression* b){ if (this->type == b->type) { return true; }else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){ return true; }else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canMultiply(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer" && b->type == "rational") return true; else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } bool Exponential::canDivide(Expression* b){ if (this->type == b->type) { return true; } else if (this->base->type == b->type) { return true; } else if(this->type == "integer"){ if( b->type == "rational") return true; } else if(this->type == "rational" && b->type == "integer") return true; else if(this->type == "multiple" && b->type == "multiple"){ MultipleExpressions *t = (MultipleExpressions *)this; MultipleExpressions *m = (MultipleExpressions *)b; if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) { return true; } }else if(this->type == "multiple" || b->type == "multiple") return true; return false; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fprogressbar.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-05-21 08:02:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // ============================================================================ #ifndef SC_FPROGRESSBAR_HXX #define SC_FPROGRESSBAR_HXX #include "globstr.hrc" #ifndef SC_FTOOLS_HXX #include "ftools.hxx" #endif class SfxObjectShell; class ScProgress; // ============================================================================ const sal_Int32 SCF_INV_SEGMENT = -1; // ============================================================================ /** Progress bar for complex progress representation. @descr The progress bar contains one or more segments, each with customable size. Each segment is represented by a unique identifier. While showing the progress bar, several segments can be started simultaneously. The progress bar displays the sum of all started segments on screen. It is possible to create a full featured ScfProgressBar object from any segment. This sub progress bar works only on that parent segment, with the effect, that if the sub progress bar reaches 100%, the parent segment is filled completely. After adding segments, the progress bar has to be activated. In this step the total size of all segments is calculated. Therefore it is not possible to add more segments from here. If a sub progress bar is created from a segment, and the main progress bar has been started (but not the sub progress bar), it is still possible to add segments to the sub progress bar. It is not allowed to get the sub progress bar of a started segment. And it is not allowed to modify the segment containing a sub progress bar directly. Following a few code examples, how to use the progress bar. Example 1: Simple progress bar (see also ScfSimpleProgressBar below). ScfProgressBar aProgress( ... ); sal_Int32 nSeg = aProgress.AddSegment( 50 ); // segment with 50 steps (1 step = 2%) aProgress.ActivateSegment( nSeg ); // start segment nSeg aProgress.Progress(); // 0->1; display: 2% aProgress.Progress( 9 ); // 1->9; display: 18% Example 2: Progress bar with 2 segments. ScfProgressBar aProgress( ... ); sal_Int32 nSeg1 = aProgress.AddSegment( 70 ); // segment with 70 steps sal_Int32 nSeg2 = aProgress.AddSegment( 30 ); // segment with 30 steps // both segments: 100 steps (1 step = 1%) aProgress.ActivateSegment( nSeg1 ); // start first segment aProgress.Progress(); // 0->1, display: 1% aProgress.Progress( 3 ); // 1->3, display: 3% aProgress.ActivateSegment( nSeg2 ); // start second segment aProgress.Progress( 5 ); // 0->5, display: 8% (5+3 steps) aProgress.ActivateSegment( nSeg1 ); // continue with first segment aProgress.Progress(); // 3->4, display: 9% (5+4 steps) Example 3: Progress bar with 2 segments, one contains a sub progress bar. ScfProgressBar aProgress( ... ); sal_Int32 nSeg1 = aProgress.AddSegment( 75 ); // segment with 75 steps sal_Int32 nSeg2 = aProgress.AddSegment( 25 ); // segment with 25 steps // both segments: 100 steps (1 step = 1%) aProgress.ActivateSegment( nSeg1 ); // start first segment aProgress.Progress(); // 0->1, display: 1% ScfProgressBar& rSubProgress = aProgress.GetSegmentProgressBar( nSeg2 ); // sub progress bar from second segment sal_Int32 nSubSeg = rSubProgress.AddSegment( 5 ); // 5 steps, mapped to second segment // => 1 step = 5 steps in parent = 5% rSubProgress.ActivateSegment( nSubSeg ); // start the segment (auto activate parent segment) rSubProgress.Progress(); // 0->1 (0->5 in parent); display: 6% (1+5) // not allowed (second segment active): aProgress.Progress(); // not allowed (first segment not empty): aProgress.GetSegmentProgressBar( nSeg1 ); */ class ScfProgressBar : ScfNoCopy { private: /** Contains all data of a segment of the progress bar. */ struct ScfProgressSegment { typedef ::std::auto_ptr< ScfProgressBar > ScfProgressBarPtr; ScfProgressBarPtr mpProgress; /// Pointer to sub progress bar for this segment. sal_uInt32 mnSize; /// Size of this segment. sal_uInt32 mnPos; /// Current position of this segment. explicit ScfProgressSegment( sal_uInt32 nSize ); ~ScfProgressSegment(); }; typedef ::std::auto_ptr< ScProgress > ScProgressPtr; typedef ScfDelList< ScfProgressSegment > ScfSegmentList; ScfSegmentList maSegments; /// List of progress segments. String maText; /// UI string for system progress. ScProgressPtr mpSysProgress; /// System progress bar. SfxObjectShell* mpDocShell; /// The document shell for the progress bar. ScfProgressBar* mpParentProgress; /// Parent progress bar, if this is a segment progress bar. ScfProgressSegment* mpParentSegment; /// Parent segment, if this is a segment progress bar. ScfProgressSegment* mpCurrSegment; /// Current segment for progress. sal_uInt32 mnTotalSize; /// Total size of all segments. sal_uInt32 mnTotalPos; /// Sum of positions of all segments. sal_uInt32 mnUnitSize; /// Size between two calls of system progress. sal_uInt32 mnNextUnitPos; /// Limit for next system progress call. bool mbInProgress; /// true = progress bar started. public: explicit ScfProgressBar( SfxObjectShell* pDocShell, const String& rText ); explicit ScfProgressBar( SfxObjectShell* pDocShell, sal_uInt16 nResId ); virtual ~ScfProgressBar(); /** Adds a new segment to the progress bar. @return the identifier of the segment. */ sal_Int32 AddSegment( sal_uInt32 nSize ); /** Returns a complete progress bar for the specified segment. @descr The progress bar can be used to create sub segments inside of the segment. Do not delete it (done by root progress bar)! @return A reference to an ScfProgressBar connected to the segment. */ ScfProgressBar& GetSegmentProgressBar( sal_Int32 nSegment ); /** Returns true, if any progress segment has been started. */ inline bool IsStarted() const { return mbInProgress; } /** Starts the progress bar or activates another segment. */ void ActivateSegment( sal_Int32 nSegment ); /** Starts the progress bar (with first segment). */ inline void Activate() { ActivateSegment( 0 ); } /** Set current segment to the specified position. */ void Progress( sal_uInt32 nPos ); /** Increase current segment by 1. */ void Progress(); private: /** Used to create sub progress bars. */ explicit ScfProgressBar( ScfProgressBar& rParProgress, ScfProgressSegment* pParSegment ); /** Initializes all members on construction. */ void Init( SfxObjectShell* pDocShell ); /** Returns the segment specified by list index. */ ScfProgressSegment* GetSegment( sal_Int32 nSegment ) const; /** Activates progress bar and sets current segment. */ void SetCurrSegment( ScfProgressSegment* pSegment ); /** Increases mnTotalPos and calls the system progress bar. */ void IncreaseProgressBar( sal_uInt32 nDelta ); }; // ============================================================================ /** A simplified progress bar with only one segment. */ class ScfSimpleProgressBar { private: ScfProgressBar maProgress; /// The used progress bar. public: explicit ScfSimpleProgressBar( sal_uInt32 nSize, SfxObjectShell* pDocShell, const String& rText ); explicit ScfSimpleProgressBar( sal_uInt32 nSize, SfxObjectShell* pDocShell, sal_uInt16 nResId ); /** Set progress bar to the specified position. */ inline void Progress( sal_uInt32 nPos ) { maProgress.Progress( nPos ); } /** Increase progress bar by 1. */ inline void Progress() { maProgress.Progress(); } private: /** Initializes and starts the progress bar. */ void Init( sal_uInt32 nSize ); }; // ============================================================================ /** A simplified progress bar based on the stream position of an existing stream. */ class ScfStreamProgressBar { private: typedef ::std::auto_ptr< ScfSimpleProgressBar > ScfSimpleProgressBarPtr; ScfSimpleProgressBarPtr mpProgress; /// The used progress bar. SvStream& mrStrm; /// The used stream. public: explicit ScfStreamProgressBar( SvStream& rStrm, SfxObjectShell* pDocShell, const String& rText ); explicit ScfStreamProgressBar( SvStream& rStrm, SfxObjectShell* pDocShell, sal_uInt16 nResId = STR_LOAD_DOC ); /** Sets the progress bar to the current stream position. */ void Progress(); private: /** Initializes and starts the progress bar. */ void Init( SfxObjectShell* pDocShell, const String& rText ); }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS dr20 (1.3.320); FILE MERGED 2004/08/11 10:43:50 dr 1.3.320.3: #i12577# #i16277# #i24129# #i31482# #i24672# #i27407# #i30411# rework of cell table export - default row/column formats and shared formulas 2004/06/17 14:58:10 dr 1.3.320.2: #i27407# handle limit of SfxProgress (ULONG_MAX/100) 2004/06/15 16:40:26 dr 1.3.320.1: #i30205# Excel filter code cleanup - rowlimit changes: SCCOL/SCROW/SCTAB usage - type correctness: USHORT vs. sal_uInt16, ULONG/size_t vs. sal_uInt32 - removed compiler warnings<commit_after>/************************************************************************* * * $RCSfile: fprogressbar.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-09-08 15:43:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_FPROGRESSBAR_HXX #define SC_FPROGRESSBAR_HXX #include "globstr.hrc" #ifndef SC_FTOOLS_HXX #include "ftools.hxx" #endif class SfxObjectShell; class ScProgress; // ============================================================================ const sal_Int32 SCF_INV_SEGMENT = -1; // ============================================================================ /** Progress bar for complex progress representation. The progress bar contains one or more segments, each with customable size. Each segment is represented by a unique identifier. While showing the progress bar, several segments can be started simultaneously. The progress bar displays the sum of all started segments on screen. It is possible to create a full featured ScfProgressBar object from any segment. This sub progress bar works only on that parent segment, with the effect, that if the sub progress bar reaches 100%, the parent segment is filled completely. After adding segments, the progress bar has to be activated. In this step the total size of all segments is calculated. Therefore it is not possible to add more segments from here. If a sub progress bar is created from a segment, and the main progress bar has been started (but not the sub progress bar), it is still possible to add segments to the sub progress bar. It is not allowed to get the sub progress bar of a started segment. And it is not allowed to modify the segment containing a sub progress bar directly. Following a few code examples, how to use the progress bar. Example 1: Simple progress bar (see also ScfSimpleProgressBar below). ScfProgressBar aProgress( ... ); sal_Int32 nSeg = aProgress.AddSegment( 50 ); // segment with 50 steps (1 step = 2%) aProgress.ActivateSegment( nSeg ); // start segment nSeg aProgress.Progress(); // 0->1; display: 2% aProgress.Progress( 9 ); // 1->9; display: 18% Example 2: Progress bar with 2 segments. ScfProgressBar aProgress( ... ); sal_Int32 nSeg1 = aProgress.AddSegment( 70 ); // segment with 70 steps sal_Int32 nSeg2 = aProgress.AddSegment( 30 ); // segment with 30 steps // both segments: 100 steps (1 step = 1%) aProgress.ActivateSegment( nSeg1 ); // start first segment aProgress.Progress(); // 0->1, display: 1% aProgress.Progress( 3 ); // 1->3, display: 3% aProgress.ActivateSegment( nSeg2 ); // start second segment aProgress.Progress( 5 ); // 0->5, display: 8% (5+3 steps) aProgress.ActivateSegment( nSeg1 ); // continue with first segment aProgress.Progress(); // 3->4, display: 9% (5+4 steps) Example 3: Progress bar with 2 segments, one contains a sub progress bar. ScfProgressBar aProgress( ... ); sal_Int32 nSeg1 = aProgress.AddSegment( 75 ); // segment with 75 steps sal_Int32 nSeg2 = aProgress.AddSegment( 25 ); // segment with 25 steps // both segments: 100 steps (1 step = 1%) aProgress.ActivateSegment( nSeg1 ); // start first segment aProgress.Progress(); // 0->1, display: 1% ScfProgressBar& rSubProgress = aProgress.GetSegmentProgressBar( nSeg2 ); // sub progress bar from second segment sal_Int32 nSubSeg = rSubProgress.AddSegment( 5 ); // 5 steps, mapped to second segment // => 1 step = 5 steps in parent = 5% rSubProgress.ActivateSegment( nSubSeg ); // start the segment (auto activate parent segment) rSubProgress.Progress(); // 0->1 (0->5 in parent); display: 6% (1+5) // not allowed (second segment active): aProgress.Progress(); // not allowed (first segment not empty): aProgress.GetSegmentProgressBar( nSeg1 ); */ class ScfProgressBar : ScfNoCopy { public: explicit ScfProgressBar( SfxObjectShell* pDocShell, const String& rText ); explicit ScfProgressBar( SfxObjectShell* pDocShell, USHORT nResId ); virtual ~ScfProgressBar(); /** Adds a new segment to the progress bar. @return the identifier of the segment. */ sal_Int32 AddSegment( sal_uInt32 nSize ); /** Returns a complete progress bar for the specified segment. @descr The progress bar can be used to create sub segments inside of the segment. Do not delete it (done by root progress bar)! @return A reference to an ScfProgressBar connected to the segment. */ ScfProgressBar& GetSegmentProgressBar( sal_Int32 nSegment ); /** Returns true, if any progress segment has been started. */ inline bool IsStarted() const { return mbInProgress; } /** Returns true, if the current progress segment is already full. */ bool IsFull() const; /** Starts the progress bar or activates another segment. */ void ActivateSegment( sal_Int32 nSegment ); /** Starts the progress bar (with first segment). */ inline void Activate() { ActivateSegment( 0 ); } /** Set current segment to the specified position. */ void Progress( sal_uInt32 nPos ); /** Increase current segment by 1. */ void Progress(); private: struct ScfProgressSegment; /** Used to create sub progress bars. */ explicit ScfProgressBar( ScfProgressBar& rParProgress, ScfProgressSegment* pParSegment ); /** Initializes all members on construction. */ void Init( SfxObjectShell* pDocShell ); /** Returns the segment specified by list index. */ ScfProgressSegment* GetSegment( sal_Int32 nSegment ) const; /** Activates progress bar and sets current segment. */ void SetCurrSegment( ScfProgressSegment* pSegment ); /** Increases mnTotalPos and calls the system progress bar. */ void IncreaseProgressBar( sal_uInt32 nDelta ); private: /** Contains all data of a segment of the progress bar. */ struct ScfProgressSegment { typedef ::std::auto_ptr< ScfProgressBar > ScfProgressBarPtr; ScfProgressBarPtr mxProgress; /// Pointer to sub progress bar for this segment. sal_uInt32 mnSize; /// Size of this segment. sal_uInt32 mnPos; /// Current position of this segment. explicit ScfProgressSegment( sal_uInt32 nSize ); ~ScfProgressSegment(); }; typedef ::std::auto_ptr< ScProgress > ScProgressPtr; typedef ScfDelList< ScfProgressSegment > ScfSegmentList; ScfSegmentList maSegments; /// List of progress segments. String maText; /// UI string for system progress. ScProgressPtr mxSysProgress; /// System progress bar. SfxObjectShell* mpDocShell; /// The document shell for the progress bar. ScfProgressBar* mpParentProgress; /// Parent progress bar, if this is a segment progress bar. ScfProgressSegment* mpParentSegment; /// Parent segment, if this is a segment progress bar. ScfProgressSegment* mpCurrSegment; /// Current segment for progress. sal_uInt32 mnTotalSize; /// Total size of all segments. sal_uInt32 mnTotalPos; /// Sum of positions of all segments. sal_uInt32 mnUnitSize; /// Size between two calls of system progress. sal_uInt32 mnNextUnitPos; /// Limit for next system progress call. sal_uInt32 mnSysProgressScale; /// Additionally scaling factor for system progress. bool mbInProgress; /// true = progress bar started. }; // ============================================================================ /** A simplified progress bar with only one segment. */ class ScfSimpleProgressBar { public: explicit ScfSimpleProgressBar( sal_uInt32 nSize, SfxObjectShell* pDocShell, const String& rText ); explicit ScfSimpleProgressBar( sal_uInt32 nSize, SfxObjectShell* pDocShell, USHORT nResId ); /** Set progress bar to the specified position. */ inline void Progress( sal_uInt32 nPos ) { maProgress.Progress( nPos ); } /** Increase progress bar by 1. */ inline void Progress() { maProgress.Progress(); } private: /** Initializes and starts the progress bar. */ void Init( sal_uInt32 nSize ); private: ScfProgressBar maProgress; /// The used progress bar. }; // ============================================================================ /** A simplified progress bar based on the stream position of an existing stream. */ class ScfStreamProgressBar { public: explicit ScfStreamProgressBar( SvStream& rStrm, SfxObjectShell* pDocShell, const String& rText ); explicit ScfStreamProgressBar( SvStream& rStrm, SfxObjectShell* pDocShell, USHORT nResId = STR_LOAD_DOC ); /** Sets the progress bar to the current stream position. */ void Progress(); private: /** Initializes and starts the progress bar. */ void Init( SfxObjectShell* pDocShell, const String& rText ); private: typedef ::std::auto_ptr< ScfSimpleProgressBar > ScfSimpleProgressBarPtr; ScfSimpleProgressBarPtr mxProgress; /// The used progress bar. SvStream& mrStrm; /// The used stream. }; // ============================================================================ #endif <|endoftext|>
<commit_before>#ifndef _LIBYAML_HPP_ #define _LIBYAML_HPP_ #include <yaml.h> #include <c4/yml/yml.hpp> #include <stdexcept> //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- namespace c4 { namespace yml { namespace detail { class Event; } // detail class detail::Event { public: yaml_event_t m_event; public: Event() {} ~Event() { yaml_event_delete(&m_event); } }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- class LibyamlParser { public: yaml_parser_t m_parser; const char * m_input; size_t m_length; NodeData * m_load_root; private: cspan get_scalar_val(detail::Event const &ev) const { // the memory in data.scalar is allocated anew, so don't do this //auto const& scalar = e.m_event.data.scalar; //cspan val((const char*)scalar.value, scalar.length); //return val; // ... but the event tells us where in the string the value is auto const& e = ev.m_event; size_t len = e.end_mark.index - e.start_mark.index; cspan val(m_input + e.start_mark.index, len); return val; } public: LibyamlParser() { memset(this, 0, sizeof(*this)); yaml_parser_initialize(&m_parser); } ~LibyamlParser() { yaml_parser_delete(&m_parser); memset(&m_parser, 0, sizeof(decltype(m_parser))); } template< size_t N > void parse(/*Tree *s, */const char (&input)[N]) { parse(/*s, */&input[0], N-1); } void parse(/*Tree *s, */const cspan sp) { parse(/*s, */sp.str, sp.len); } void parse(/*Tree *s, */const char* input, size_t length) { m_input = input; m_length = length; yaml_parser_set_input_string(&m_parser, (const unsigned char*)input, length); _do_parse(/*s*/); } void _do_parse(/*Tree *s*/) { bool done = false; //bool doc_had_scalars = false; //cspan prev_scalar; while( ! done) { detail::Event ev; if( ! yaml_parser_parse(&m_parser, &ev.m_event)) { _handle_error(); break; } #define _c4_handle_case(_ev) \ case YAML_ ## _ev ## _EVENT: \ printf(#_ev " val=%.*s\n", \ /*(int)prev_scalar.len, prev_scalar.str,*/ \ (int)val.len, val.str); cspan val = get_scalar_val(ev); switch(ev.m_event.type) { _c4_handle_case(MAPPING_START) /*if(( ! s->stack_top_is_type(DOC) || doc_had_scalars) && ( ! m_load_root)) { C4_ASSERT( ! prev_scalar.empty()); s->begin_map(prev_scalar, s->top_last()); prev_scalar.clear(); } */ break; _c4_handle_case(MAPPING_END) /*if( ! s->stack_top_is_type(DOC) && ! m_load_root) { s->end_map(); }*/ break; _c4_handle_case(SEQUENCE_START) //s->begin_seq(prev_scalar, s->top_last()); break; _c4_handle_case(SEQUENCE_END) //s->end_seq(); break; _c4_handle_case(SCALAR) /*if(s->stack_top_is_type(SEQ)) { s->add_val({}, val, s->top_last()); prev_scalar.clear(); } else { if( ! prev_scalar.empty()) { s->add_val(prev_scalar, val, s->top_last()); prev_scalar.clear(); } else { prev_scalar = val; } } doc_had_scalars = true; */ break; _c4_handle_case(DOCUMENT_START) /*if( ! m_load_root) { s->begin_doc(s->top_last()); doc_had_scalars = false; }*/ break; _c4_handle_case(DOCUMENT_END) /*if( ! m_load_root) { s->end_doc(); }*/ break; _c4_handle_case(STREAM_START) //s->begin_stream(); break; _c4_handle_case(STREAM_END) //s->end_stream(); done = true; break; _c4_handle_case(ALIAS) //C4_ASSERT(false && "YAML_ALIAS_EVENT not implemented"); break; #undef _c4_handle_case default: break; }; } } void _handle_error() { Location problem_loc, context_loc; if(m_parser.problem) { auto const& m = m_parser.problem_mark; problem_loc = Location(m_parser.problem, m.index, m.line+1, m.column+1); } if(m_parser.context) { auto const& m = m_parser.context_mark; context_loc = Location(m_parser.context, m.index, m.line+1, m.column+1); } switch(m_parser.error) { case YAML_MEMORY_ERROR: error("Memory error: Not enough memory for parsing"); break; case YAML_READER_ERROR: if (m_parser.problem_value != -1) { char buf[32]; int ret = snprintf(buf, sizeof(buf), "Reader error: #%X", m_parser.problem_value); error(buf, ret, &problem_loc); } else { error("Reader error", &problem_loc); } break; case YAML_SCANNER_ERROR: error("Scanner error", &context_loc, &problem_loc); break; case YAML_PARSER_ERROR: error("Parser error", &context_loc, &problem_loc); break; default: /* Couldn't happen. */ error("Internal error"); break; }; } static void error(const char* msg, size_t length, Location *loc1 = nullptr, Location *loc2 = nullptr) { fprintf(stderr, "%.*s\n", (int)length, msg); if(loc1 && *loc1) { fprintf(stderr, " : %s at %zd:%zd (offset %zd)\n", loc1->name, loc1->line, loc1->col, loc1->offset); } if(loc2 && *loc2) { fprintf(stderr, " : %s at %zd:%zd (offset %zd)\n", loc2->name, loc1->line, loc2->col, loc2->offset); } throw std::runtime_error({msg, length}); } template< size_t N > static void error(char const (&msg)[N], Location *loc1 = nullptr, Location *loc2 = nullptr) { error(&msg[0], N-1, loc1, loc2); } }; } // namespace yml } // namespace c4 #endif // _LIBYAML_HPP_ <commit_msg>reduce test verbosity<commit_after>#ifndef _LIBYAML_HPP_ #define _LIBYAML_HPP_ #include <yaml.h> #include <c4/yml/yml.hpp> #include <stdexcept> //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- namespace c4 { namespace yml { namespace detail { class Event; } // detail class detail::Event { public: yaml_event_t m_event; public: Event() {} ~Event() { yaml_event_delete(&m_event); } }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- class LibyamlParser { public: yaml_parser_t m_parser; const char * m_input; size_t m_length; NodeData * m_load_root; private: cspan get_scalar_val(detail::Event const &ev) const { // the memory in data.scalar is allocated anew, so don't do this //auto const& scalar = e.m_event.data.scalar; //cspan val((const char*)scalar.value, scalar.length); //return val; // ... but the event tells us where in the string the value is auto const& e = ev.m_event; size_t len = e.end_mark.index - e.start_mark.index; cspan val(m_input + e.start_mark.index, len); return val; } public: LibyamlParser() { memset(this, 0, sizeof(*this)); yaml_parser_initialize(&m_parser); } ~LibyamlParser() { yaml_parser_delete(&m_parser); memset(&m_parser, 0, sizeof(decltype(m_parser))); } template< size_t N > void parse(/*Tree *s, */const char (&input)[N]) { parse(/*s, */&input[0], N-1); } void parse(/*Tree *s, */const cspan sp) { parse(/*s, */sp.str, sp.len); } void parse(/*Tree *s, */const char* input, size_t length) { m_input = input; m_length = length; yaml_parser_set_input_string(&m_parser, (const unsigned char*)input, length); _do_parse(/*s*/); } void _do_parse(/*Tree *s*/) { bool done = false; //bool doc_had_scalars = false; //cspan prev_scalar; while( ! done) { detail::Event ev; if( ! yaml_parser_parse(&m_parser, &ev.m_event)) { _handle_error(); break; } #ifdef RYML_DBG #define _c4_handle_case(_ev) \ case YAML_ ## _ev ## _EVENT: \ printf(#_ev " val=%.*s\n", \ /*(int)prev_scalar.len, prev_scalar.str,*/ \ (int)val.len, val.str); #else #define _c4_handle_case(_ev) \ case YAML_ ## _ev ## _EVENT: \ (void)val; #endif cspan val = get_scalar_val(ev); switch(ev.m_event.type) { _c4_handle_case(MAPPING_START) /*if(( ! s->stack_top_is_type(DOC) || doc_had_scalars) && ( ! m_load_root)) { C4_ASSERT( ! prev_scalar.empty()); s->begin_map(prev_scalar, s->top_last()); prev_scalar.clear(); } */ break; _c4_handle_case(MAPPING_END) /*if( ! s->stack_top_is_type(DOC) && ! m_load_root) { s->end_map(); }*/ break; _c4_handle_case(SEQUENCE_START) //s->begin_seq(prev_scalar, s->top_last()); break; _c4_handle_case(SEQUENCE_END) //s->end_seq(); break; _c4_handle_case(SCALAR) /*if(s->stack_top_is_type(SEQ)) { s->add_val({}, val, s->top_last()); prev_scalar.clear(); } else { if( ! prev_scalar.empty()) { s->add_val(prev_scalar, val, s->top_last()); prev_scalar.clear(); } else { prev_scalar = val; } } doc_had_scalars = true; */ break; _c4_handle_case(DOCUMENT_START) /*if( ! m_load_root) { s->begin_doc(s->top_last()); doc_had_scalars = false; }*/ break; _c4_handle_case(DOCUMENT_END) /*if( ! m_load_root) { s->end_doc(); }*/ break; _c4_handle_case(STREAM_START) //s->begin_stream(); break; _c4_handle_case(STREAM_END) //s->end_stream(); done = true; break; _c4_handle_case(ALIAS) //C4_ASSERT(false && "YAML_ALIAS_EVENT not implemented"); break; #undef _c4_handle_case default: break; }; } } void _handle_error() { Location problem_loc, context_loc; if(m_parser.problem) { auto const& m = m_parser.problem_mark; problem_loc = Location(m_parser.problem, m.index, m.line+1, m.column+1); } if(m_parser.context) { auto const& m = m_parser.context_mark; context_loc = Location(m_parser.context, m.index, m.line+1, m.column+1); } switch(m_parser.error) { case YAML_MEMORY_ERROR: error("Memory error: Not enough memory for parsing"); break; case YAML_READER_ERROR: if (m_parser.problem_value != -1) { char buf[32]; int ret = snprintf(buf, sizeof(buf), "Reader error: #%X", m_parser.problem_value); error(buf, ret, &problem_loc); } else { error("Reader error", &problem_loc); } break; case YAML_SCANNER_ERROR: error("Scanner error", &context_loc, &problem_loc); break; case YAML_PARSER_ERROR: error("Parser error", &context_loc, &problem_loc); break; default: /* Couldn't happen. */ error("Internal error"); break; }; } static void error(const char* msg, size_t length, Location *loc1 = nullptr, Location *loc2 = nullptr) { fprintf(stderr, "%.*s\n", (int)length, msg); if(loc1 && *loc1) { fprintf(stderr, " : %s at %zd:%zd (offset %zd)\n", loc1->name, loc1->line, loc1->col, loc1->offset); } if(loc2 && *loc2) { fprintf(stderr, " : %s at %zd:%zd (offset %zd)\n", loc2->name, loc1->line, loc2->col, loc2->offset); } throw std::runtime_error({msg, length}); } template< size_t N > static void error(char const (&msg)[N], Location *loc1 = nullptr, Location *loc2 = nullptr) { error(&msg[0], N-1, loc1, loc2); } }; } // namespace yml } // namespace c4 #endif // _LIBYAML_HPP_ <|endoftext|>
<commit_before>/* * mf_test.cpp * * Created on: Aug 7, 2011 * Author: gmueller */ #include "gadget/MagneticField.hpp" #include "gadget/SmoothParticle.hpp" #include <memory> #include <limits> #include <stdexcept> class AbstractTest { protected: std::vector<SmoothParticle> particles; std::auto_ptr<DirectMagneticField> dmf; std::auto_ptr<SampledMagneticField> smf; std::vector<std::pair<Vector3f, float> > positions; public: virtual void setup() = 0; void run() { for (size_t i = 0; i < positions.size(); i++) testPosition(positions[i].first, positions[i].second); } void testPosition(const Vector3f &position, float expected_error = std::numeric_limits<float>::epsilon()) { Vector3f df = dmf->getField(position); Vector3f sf = smf->getField(position); float error = (df - sf).length(); std::cout << "Direct: " << df << ", Sampled: " << sf << ", Error: " << error << std::endl; if (error > expected_error) throw std::runtime_error("unexpected deviation!"); } void addPosition(const Vector3f &position, float expected_error = std::numeric_limits<float>::epsilon()) { positions.push_back(std::make_pair(position, expected_error)); } }; class SimpleTest: public AbstractTest { public: void setup() { particles.resize(1); particles[0].bfield = Vector3f(0, 1, 0); particles[0].position = Vector3f(120000, 120000, 120000); particles[0].smoothingLength = 10000; particles[0].mass = 1; SmoothParticleHelper::updateRho(particles); Vector3f origin(100000, 100000, 100000); float size(40000); dmf.reset(new DirectMagneticField(origin, size)); dmf->init(100); dmf->load(particles); smf.reset(new SampledMagneticField(origin, size)); smf->init(500); smf->load(particles); addPosition(Vector3f(120000, 120000, 120000)); addPosition(Vector3f(120500, 120500, 120500)); addPosition(Vector3f(120550, 120550, 120550), 0.01); } }; int main() { SimpleTest stest; stest.setup(); stest.run(); } <commit_msg>improve mf_test, use coma radial profile<commit_after>/* * mf_test.cpp * * Created on: Aug 7, 2011 * Author: gmueller */ #include "gadget/MagneticField.hpp" #include "gadget/SmoothParticle.hpp" #include <memory> #include <limits> #include <stdexcept> class AbstractTest { public: struct TestPoint { TestPoint() : position(Vector3f(0, 0, 0)), value(Vector3f(0, 0, 0)), error( std::numeric_limits<float>::epsilon()) { } TestPoint(Vector3f position, Vector3f value, float error = std::numeric_limits<float>::epsilon()) : position(position), value(value), error(error) { } Vector3f position; Vector3f value; float error; }; protected: std::vector<SmoothParticle> particles; std::auto_ptr<DirectMagneticField> dmf; std::auto_ptr<SampledMagneticField> smf; std::vector<TestPoint> testPoints; public: virtual void setup() = 0; void runTestPoints() { std::cout << ">> test points: " << testPoints.size() << std::endl; for (size_t i = 0; i < testPoints.size(); i++) test(testPoints[i]); std::cout << ">> done" << std::endl; } void runSweep(const Vector3f &from, const Vector3f &to, float stepSize, float allowedError) { std::cout << ">> Sweep from " << from << " to " << to << ", Step: " << stepSize << std::endl; float length = (from - to).length(); size_t steps = length / stepSize; Vector3f step = (to - from) * stepSize / length; Vector3f position = from; float minError = std::numeric_limits<float>::max(); float maxError = std::numeric_limits<float>::min(); for (size_t i = 0; i < steps; i++) { position += step; Vector3f df = dmf->getField(position); Vector3f sf = smf->getField(position); std::cout << " -> " << df.length() << std::endl; float error = (df - sf).length(); minError = std::min(error, minError); maxError = std::max(error, maxError); if (error > allowedError) throw std::runtime_error("unexpected deviation!"); } std::cout << " min error: " << minError << std::endl; std::cout << " max error: " << maxError << std::endl; std::cout << " average total: " << dmf->getStatistics().getAverageTotal() << std::endl; std::cout << " average actual: " << dmf->getStatistics().getAverageActual() << std::endl; std::cout << ">> done" << std::endl; } void test(const TestPoint &testPoint) { std::cout << " TestPoint: " << testPoint.position << " -> " << testPoint.value << ", +- " << testPoint.error << std::endl; Vector3f df = dmf->getField(testPoint.position); float dfError = (df - testPoint.value).length(); std::cout << " - Direct: " << df << ", Error: " << dfError << std::endl; Vector3f sf = smf->getField(testPoint.position); float sfError = (sf - testPoint.value).length(); std::cout << " - Samples: " << sf << ", Error: " << sfError << std::endl; if (dfError > testPoint.error || sfError > testPoint.error) throw std::runtime_error("unexpected deviation!"); } void getAverageFieldOnSphere(const Vector3f &center, float radius, float &avgDirect, float &avgSampled) { avgDirect = 0; avgSampled = 0; size_t count = 0; float phi = 0; while (phi < 360) { float theta = -90; while (theta <= 90) { theta += 10; Vector3f position = center; try { position.x += radius * sin(phi) * cos(theta); position.y += radius * cos(phi) * cos(theta); position.z += radius * sin(theta); avgDirect += dmf->getField(position).length(); avgSampled += smf->getField(position).length(); count++; } catch (...) { } } phi += 10; } avgDirect /= count; avgSampled /= count; } void runHaloTest(const Vector3f &center, float radius) { std::cout << ">> Halo Test around " << center << ", R_v: " << radius << std::endl; std::cout << " - direct sampled" << std::endl; for (size_t i = 0; i < 51; i++) { float r = (radius / 50) * i; float avgDirect, avgSampled; getAverageFieldOnSphere(center, r, avgDirect, avgSampled); std::cout << r/radius << " " << avgDirect << " " << avgSampled << std::endl; } } }; class SimpleTest: public AbstractTest { public: void setup() { particles.resize(1); particles[0].bfield = Vector3f(0, 1, 0); particles[0].position = Vector3f(120000, 120000, 120000); particles[0].smoothingLength = 10000; particles[0].mass = 1; SmoothParticleHelper::updateRho(particles); Vector3f origin(100000, 100000, 100000); float size(40000); dmf.reset(new DirectMagneticField(origin, size)); dmf->init(100); dmf->load(particles); smf.reset(new SampledMagneticField(origin, size)); smf->init(500); smf->load(particles); testPoints.push_back( TestPoint(Vector3f(120000, 120000, 120000), Vector3f(0, 1, 0))); testPoints.push_back( TestPoint(Vector3f(120500, 120500, 120500), Vector3f(0, 0.958897, 0))); testPoints.push_back( TestPoint(Vector3f(120550, 120550, 120550), Vector3f(0, 0.950737, 0), 0.01)); } }; // Coma // 11 411121 214459 7.570E+14 6.634E+14 1885.23 119.8023 190.8159 129.1431 -361.72 566.41 -315.91 949.39 Vector3f ComaPosition(119717, 221164, 133061); class HaloTest: public AbstractTest { public: void setup() { SmoothParticleHelper::read("test/mhd_z-5-11-6.raw", particles); Vector3f origin(99000, 219000, 119000); float size(22000); dmf.reset(new DirectMagneticField(origin, size)); dmf->init(50); dmf->load(particles); smf.reset(new SampledMagneticField(origin, size)); smf->init(100); smf->load(particles); testPoints.push_back( TestPoint(ComaPosition, Vector3f(-1.60984e-09, -3.48952e-10, 1.00858e-09), 1)); } }; int main() { SimpleTest stest; stest.setup(); stest.runTestPoints(); stest.runSweep(Vector3f(120000, 120000, 120000), Vector3f(120000, 110000, 120000), 10, 0.01); HaloTest htest; htest.setup(); htest.runTestPoints(); htest.runSweep(ComaPosition, ComaPosition + Vector3f(-1000, 1000, 500), 10, 0.01); htest.runHaloTest(ComaPosition, 2700); } <|endoftext|>
<commit_before>// Copyright 2015 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 "mandoline/tab/web_view_impl.h" #include "components/view_manager/public/cpp/view.h" #include "components/view_manager/public/cpp/view_manager.h" #include "mandoline/tab/frame.h" #include "mandoline/tab/frame_connection.h" #include "mandoline/tab/frame_tree.h" #include "mojo/application/public/cpp/application_impl.h" #include "mojo/converters/geometry/geometry_type_converters.h" // TODO(beng): remove once these classes are in the web_view namespace. using mandoline::FrameTreeClient; using mandoline::FrameConnection; namespace web_view { //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, public: WebViewImpl::WebViewImpl(mojo::ApplicationImpl* app, mojom::WebViewClientPtr client, mojo::InterfaceRequest<mojom::WebView> request) : app_(app), client_(client.Pass()), binding_(this, request.Pass()), content_(nullptr), view_manager_client_factory_(app->shell(), this) { } WebViewImpl::~WebViewImpl() {} //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, WebView implementation: void WebViewImpl::LoadRequest(mojo::URLRequestPtr request) { if (!content_) { // We haven't been embedded yet, store the request for when we are. pending_request_ = request.Pass(); return; } scoped_ptr<FrameConnection> frame_connection(new FrameConnection); mojo::ViewManagerClientPtr view_manager_client; frame_connection->Init(app_, request.Pass(), &view_manager_client); FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client(); frame_tree_.reset(new FrameTree(content_, this, frame_tree_client, frame_connection.Pass())); content_->Embed(view_manager_client.Pass()); } void WebViewImpl::GetViewManagerClient( mojo::InterfaceRequest<mojo::ViewManagerClient> view_manager_client) { view_manager_client_factory_.Create(nullptr, view_manager_client.Pass()); } //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, mojo::ViewManagerDelegate implementation: void WebViewImpl::OnEmbed(mojo::View* root) { root->view_manager()->SetEmbedRoot(); root->AddObserver(this); content_ = root->view_manager()->CreateView(); root->AddChild(content_); content_->SetVisible(true); content_->AddObserver(this); if (!pending_request_.is_null()) LoadRequest(pending_request_.Pass()); } void WebViewImpl::OnEmbedForDescendant(mojo::View* view, mojo::URLRequestPtr request, mojo::ViewManagerClientPtr* client) { // TODO(sky): move this to Frame/FrameTree. Frame* frame = Frame::FindFirstFrameAncestor(view); if (!frame || !frame->HasAncestor(frame_tree_->root())) { // TODO(sky): add requestor url so that we can return false if it's not // an app we expect. scoped_ptr<mojo::ApplicationConnection> connection = app_->ConnectToApplication(request.Pass()); connection->ConnectToService(client); return; } scoped_ptr<FrameConnection> frame_connection(new FrameConnection); frame_connection->Init(app_, request.Pass(), client); FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client(); frame_tree_->CreateOrReplaceFrame(frame, view, frame_tree_client, frame_connection.Pass()); } void WebViewImpl::OnViewManagerDestroyed(mojo::ViewManager* view_manager) { } //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, mojo::ViewObserver implementation: void WebViewImpl::OnViewBoundsChanged(mojo::View* view, const mojo::Rect& old_bounds, const mojo::Rect& new_bounds) { if (view != content_) { mojo::Rect rect; rect.width = new_bounds.width; rect.height = new_bounds.height; content_->SetBounds(rect); } } void WebViewImpl::OnViewDestroyed(mojo::View* view) { // |FrameTree| cannot outlive the content view. if (view == content_) frame_tree_.reset(); } //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, mandoline::FrameTreeDelegate implementation: bool WebViewImpl::CanPostMessageEventToFrame(const Frame* source, const Frame* target, HTMLMessageEvent* event) { return true; } void WebViewImpl::LoadingStateChanged(bool loading) { client_->LoadingStateChanged(loading); } void WebViewImpl::ProgressChanged(double progress) { client_->ProgressChanged(progress); } void WebViewImpl::RequestNavigate(Frame* source, mandoline::NavigationTargetType target_type, Frame* target_frame, mojo::URLRequestPtr request) { // TODO: this needs security checks. if (target_type == mandoline::NAVIGATION_TARGET_TYPE_EXISTING_FRAME) { if (target_frame && target_frame != frame_tree_->root() && target_frame->view()) { NavigateExistingFrame(target_frame, request.Pass()); return; } DVLOG(1) << "RequestNavigate() targeted existing frame that doesn't exist."; return; } client_->TopLevelNavigate(request.Pass()); } //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, private: void WebViewImpl::NavigateExistingFrame(Frame* frame, mojo::URLRequestPtr request) { scoped_ptr<FrameConnection> frame_connection(new FrameConnection); mojo::ViewManagerClientPtr view_manager_client; frame_connection->Init(app_, request.Pass(), &view_manager_client); frame->view()->Embed(view_manager_client.Pass()); FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client(); frame_tree_->CreateOrReplaceFrame(frame, frame->view(), frame_tree_client, frame_connection.Pass()); } } // namespace web_view <commit_msg>Honors requests to navigate in existing frame for the root<commit_after>// Copyright 2015 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 "mandoline/tab/web_view_impl.h" #include "components/view_manager/public/cpp/view.h" #include "components/view_manager/public/cpp/view_manager.h" #include "mandoline/tab/frame.h" #include "mandoline/tab/frame_connection.h" #include "mandoline/tab/frame_tree.h" #include "mojo/application/public/cpp/application_impl.h" #include "mojo/converters/geometry/geometry_type_converters.h" // TODO(beng): remove once these classes are in the web_view namespace. using mandoline::FrameTreeClient; using mandoline::FrameConnection; namespace web_view { //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, public: WebViewImpl::WebViewImpl(mojo::ApplicationImpl* app, mojom::WebViewClientPtr client, mojo::InterfaceRequest<mojom::WebView> request) : app_(app), client_(client.Pass()), binding_(this, request.Pass()), content_(nullptr), view_manager_client_factory_(app->shell(), this) { } WebViewImpl::~WebViewImpl() {} //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, WebView implementation: void WebViewImpl::LoadRequest(mojo::URLRequestPtr request) { if (!content_) { // We haven't been embedded yet, store the request for when we are. pending_request_ = request.Pass(); return; } scoped_ptr<FrameConnection> frame_connection(new FrameConnection); mojo::ViewManagerClientPtr view_manager_client; frame_connection->Init(app_, request.Pass(), &view_manager_client); FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client(); frame_tree_.reset(new FrameTree(content_, this, frame_tree_client, frame_connection.Pass())); content_->Embed(view_manager_client.Pass()); } void WebViewImpl::GetViewManagerClient( mojo::InterfaceRequest<mojo::ViewManagerClient> view_manager_client) { view_manager_client_factory_.Create(nullptr, view_manager_client.Pass()); } //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, mojo::ViewManagerDelegate implementation: void WebViewImpl::OnEmbed(mojo::View* root) { root->view_manager()->SetEmbedRoot(); root->AddObserver(this); content_ = root->view_manager()->CreateView(); root->AddChild(content_); content_->SetVisible(true); content_->AddObserver(this); if (!pending_request_.is_null()) LoadRequest(pending_request_.Pass()); } void WebViewImpl::OnEmbedForDescendant(mojo::View* view, mojo::URLRequestPtr request, mojo::ViewManagerClientPtr* client) { // TODO(sky): move this to Frame/FrameTree. Frame* frame = Frame::FindFirstFrameAncestor(view); if (!frame || !frame->HasAncestor(frame_tree_->root())) { // TODO(sky): add requestor url so that we can return false if it's not // an app we expect. scoped_ptr<mojo::ApplicationConnection> connection = app_->ConnectToApplication(request.Pass()); connection->ConnectToService(client); return; } scoped_ptr<FrameConnection> frame_connection(new FrameConnection); frame_connection->Init(app_, request.Pass(), client); FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client(); frame_tree_->CreateOrReplaceFrame(frame, view, frame_tree_client, frame_connection.Pass()); } void WebViewImpl::OnViewManagerDestroyed(mojo::ViewManager* view_manager) { } //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, mojo::ViewObserver implementation: void WebViewImpl::OnViewBoundsChanged(mojo::View* view, const mojo::Rect& old_bounds, const mojo::Rect& new_bounds) { if (view != content_) { mojo::Rect rect; rect.width = new_bounds.width; rect.height = new_bounds.height; content_->SetBounds(rect); } } void WebViewImpl::OnViewDestroyed(mojo::View* view) { // |FrameTree| cannot outlive the content view. if (view == content_) frame_tree_.reset(); } //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, mandoline::FrameTreeDelegate implementation: bool WebViewImpl::CanPostMessageEventToFrame(const Frame* source, const Frame* target, HTMLMessageEvent* event) { return true; } void WebViewImpl::LoadingStateChanged(bool loading) { client_->LoadingStateChanged(loading); } void WebViewImpl::ProgressChanged(double progress) { client_->ProgressChanged(progress); } void WebViewImpl::RequestNavigate(Frame* source, mandoline::NavigationTargetType target_type, Frame* target_frame, mojo::URLRequestPtr request) { // TODO: this needs security checks. if (target_type == mandoline::NAVIGATION_TARGET_TYPE_EXISTING_FRAME && target_frame != frame_tree_->root()) { if (target_frame && target_frame->view()) { NavigateExistingFrame(target_frame, request.Pass()); return; } DVLOG(1) << "RequestNavigate() targeted existing frame that doesn't exist."; return; } client_->TopLevelNavigate(request.Pass()); } //////////////////////////////////////////////////////////////////////////////// // WebViewImpl, private: void WebViewImpl::NavigateExistingFrame(Frame* frame, mojo::URLRequestPtr request) { scoped_ptr<FrameConnection> frame_connection(new FrameConnection); mojo::ViewManagerClientPtr view_manager_client; frame_connection->Init(app_, request.Pass(), &view_manager_client); frame->view()->Embed(view_manager_client.Pass()); FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client(); frame_tree_->CreateOrReplaceFrame(frame, frame->view(), frame_tree_client, frame_connection.Pass()); } } // namespace web_view <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include "core/posix.hh" #include "core/vla.hh" #include "core/reactor.hh" #include "core/future-util.hh" #include "core/stream.hh" #include "core/circular_buffer.hh" #include "core/align.hh" #include <atomic> #include <list> #include <queue> #include <fcntl.h> #include <linux/if_tun.h> #include "ip.hh" #include <xen/xen.h> #include <xen/memory.h> #include <xen/sys/gntalloc.h> #include "core/xen/xenstore.hh" #include "core/xen/evtchn.hh" #include "xenfront.hh" #include <unordered_set> using namespace net; using phys = uint64_t; class xenfront_net_device : public net::device { private: bool _userspace; stream<packet> _rx_stream; net::hw_features _hw_features; std::string _device_str; xenstore* _xenstore = xenstore::instance(); unsigned _otherend; std::string _backend; gntalloc *_gntalloc; evtchn *_evtchn; port *_tx_evtchn; port *_rx_evtchn; front_ring<tx> _tx_ring; front_ring<rx> _rx_ring; grant_head *_tx_refs; grant_head *_rx_refs; std::list<std::pair<std::string, std::string>> _features; static std::unordered_set<std::string> _supported_features; ethernet_address _hw_address; port *bind_tx_evtchn(); port *bind_rx_evtchn(); future<> alloc_rx_references(); future<> handle_tx_completions(); future<> queue_rx_packet(); void alloc_one_rx_reference(unsigned id); std::string path(std::string s) { return _device_str + "/" + s; } public: explicit xenfront_net_device(boost::program_options::variables_map opts, bool userspace); ~xenfront_net_device(); virtual subscription<packet> receive(std::function<future<> (packet)> next) override; virtual future<> send(packet p) override; ethernet_address hw_address(); net::hw_features hw_features(); }; std::unordered_set<std::string> xenfront_net_device::_supported_features = { "feature-split-event-channels", "feature-rx-copy", }; subscription<packet> xenfront_net_device::receive(std::function<future<> (packet)> next) { auto sub = _rx_stream.listen(std::move(next)); keep_doing([this] { return _rx_evtchn->pending().then([this] { return queue_rx_packet(); }); }); return std::move(sub); } future<> xenfront_net_device::send(packet _p) { uint32_t frag = 0; // There doesn't seem to be a way to tell xen, when using the userspace // drivers, to map a particular page. Therefore, the only alternative // here is to copy. All pages shared must come from the gntalloc mmap. // // A better solution could be to change the packet allocation path to // use a pre-determined page for data. // // In-kernel should be fine // FIXME: negotiate and use scatter/gather _p.linearize(); return _tx_ring.entries.get_index().then([this, p = std::move(_p), frag] (unsigned idx) mutable { auto req_prod = _tx_ring._sring->req_prod; auto f = p.frag(frag); auto ref = _tx_refs->new_ref(f.base, f.size); assert(!_tx_ring.entries[idx]); _tx_ring.entries[idx] = ref; auto req = &_tx_ring._sring->_ring[idx].req; req->gref = ref.xen_id; req->offset = 0; req->flags = {}; if (p.offload_info().protocol != ip_protocol_num::unused) { req->flags.csum_blank = true; req->flags.data_validated = true; } else { req->flags.data_validated = true; } req->id = idx; req->size = f.size; _tx_ring.req_prod_pvt = idx; _tx_ring._sring->req_prod = req_prod + 1; _tx_ring._sring->req_event++; if ((frag + 1) == p.nr_frags()) { _tx_evtchn->notify(); return make_ready_future<>(); } else { return make_ready_future<>(); } }); // FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic? } #define rmb() asm volatile("lfence":::"memory"); #define wmb() asm volatile("":::"memory"); template <typename T> future<unsigned> front_ring<T>::entries::get_index() { return _available.wait().then([this] { auto ret = _ids.front(); _ids.pop(); return make_ready_future<unsigned>(ret); }); } template <typename T> void front_ring<T>::entries::free_index(unsigned id) { _ids.push(id); _available.signal(); } future<> xenfront_net_device::queue_rx_packet() { auto rsp_cons = _rx_ring.rsp_cons; rmb(); auto rsp_prod = _rx_ring._sring->rsp_prod; while (rsp_cons < rsp_prod) { auto rsp = _rx_ring[rsp_cons].rsp; auto& entry = _rx_ring.entries[rsp.id]; rsp_cons++; _rx_ring.rsp_cons = rsp_cons; if (rsp.status < 0) { printf("Packet error: Handle it\n"); continue; } auto rsp_size = rsp.status; packet p(static_cast<char *>(entry.page) + rsp.offset, rsp_size); _rx_stream.produce(std::move(p)); _rx_ring._sring->rsp_event = rsp_cons + 1; rsp_prod = _rx_ring._sring->rsp_prod; _rx_refs->free_ref(entry); _rx_ring.entries.free_index(rsp.id); } // FIXME: Queue_rx maybe should not be a future then return make_ready_future<>(); } void xenfront_net_device::alloc_one_rx_reference(unsigned index) { _rx_ring.entries[index] = _rx_refs->new_ref(); // This is how the backend knows where to put data. auto req = &_rx_ring._sring->_ring[index].req; req->id = index; req->gref = _rx_ring.entries[index].xen_id; } future<> xenfront_net_device::alloc_rx_references() { return _rx_ring.entries.get_index().then([this] (unsigned i) { auto req_prod = _rx_ring.req_prod_pvt; alloc_one_rx_reference(i); ++req_prod; _rx_ring.req_prod_pvt = req_prod; wmb(); _rx_ring._sring->req_prod = req_prod; /* ready */ _rx_evtchn->notify(); }); } future<> xenfront_net_device::handle_tx_completions() { auto prod = _tx_ring._sring->rsp_prod; rmb(); for (unsigned i = _tx_ring.rsp_cons; i != prod; i++) { auto rsp = _tx_ring[i].rsp; if (rsp.status == 1) { continue; } if (rsp.status != 0) { printf("Packet error: Handle it\n"); continue; } auto& entry = _tx_ring.entries[rsp.id]; _tx_refs->free_ref(entry); _tx_ring.entries.free_index(rsp.id); } _tx_ring.rsp_cons = prod; _tx_ring._sring->rsp_event = prod + 1; return make_ready_future<>(); } ethernet_address xenfront_net_device::hw_address() { return _hw_address; } net::hw_features xenfront_net_device::hw_features() { return _hw_features; } port *xenfront_net_device::bind_tx_evtchn() { return _evtchn->bind(); } port *xenfront_net_device::bind_rx_evtchn() { auto split = _xenstore->read(_backend + "/feature-split-event-channels"); if (split != "") { return _evtchn->bind(); } return _evtchn->bind(*_tx_evtchn); } xenfront_net_device::xenfront_net_device(boost::program_options::variables_map opts, bool userspace) : _userspace(userspace) , _rx_stream() , _device_str("device/vif/" + std::to_string(opts["vif"].as<unsigned>())) , _otherend(_xenstore->read<int>(path("backend-id"))) , _backend(_xenstore->read(path("backend"))) , _gntalloc(gntalloc::instance(_userspace, _otherend)) , _evtchn(evtchn::instance(_userspace, _otherend)) , _tx_evtchn(bind_tx_evtchn()) , _rx_evtchn(bind_rx_evtchn()) , _tx_ring(_gntalloc->alloc_ref()) , _rx_ring(_gntalloc->alloc_ref()) , _tx_refs(_gntalloc->alloc_ref(front_ring<tx>::nr_ents)) , _rx_refs(_gntalloc->alloc_ref(front_ring<rx>::nr_ents)) , _hw_address(net::parse_ethernet_address(_xenstore->read(path("mac")))) { _rx_stream.started(); auto all_features = _xenstore->ls(_backend); std::unordered_map<std::string, int> features_nack; for (auto&& feat : all_features) { if (feat.compare(0, 8, "feature-") == 0 && !_supported_features.count(feat)) { features_nack[feat] = 0; } } _hw_features.rx_csum_offload = true; _hw_features.tx_csum_offload = true; for (auto&s : all_features) { auto value = _xenstore->read(_backend + "/" + s); _features.push_back(std::make_pair(s, value)); } { auto t = xenstore::xenstore_transaction(); for (auto&& f: features_nack) { _xenstore->write(path(f.first), f.second, t); } _xenstore->write<int>(path("event-channel-tx"), *_tx_evtchn, t); _xenstore->write<int>(path("event-channel-rx"), *_rx_evtchn, t); _xenstore->write<int>(path("tx-ring-ref"), _tx_ring.ref, t); _xenstore->write<int>(path("rx-ring-ref"), _rx_ring.ref, t); _xenstore->write<int>(path("state"), 4, t); } keep_doing([this] { return alloc_rx_references(); }); keep_doing([this] () { return _tx_evtchn->pending().then([this] { handle_tx_completions(); }); }); } xenfront_net_device::~xenfront_net_device() { { auto t = xenstore::xenstore_transaction(); for (auto& f: _features) { _xenstore->remove(path(f.first), t); } _xenstore->remove(path("event-channel-tx"), t); _xenstore->remove(path("event-channel-rx"), t); _xenstore->remove(path("tx-ring-ref"), t); _xenstore->remove(path("rx-ring-ref"), t); _xenstore->write<int>(path("state"), 6, t); } _xenstore->write<int>(path("state"), 1); } boost::program_options::options_description get_xenfront_net_options_description() { boost::program_options::options_description opts( "xenfront net options"); opts.add_options() ("vif", boost::program_options::value<unsigned>()->default_value(0), "vif number to hijack") ; return opts; } std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) { auto ptr = std::make_unique<xenfront_net_device>(opts, userspace); // This assumes only one device per cpu. Will need to be fixed when // this assumption will no longer hold. dev = ptr.get(); return std::move(ptr); } <commit_msg>xen: fix explicitly-disabled split event channel feature<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include "core/posix.hh" #include "core/vla.hh" #include "core/reactor.hh" #include "core/future-util.hh" #include "core/stream.hh" #include "core/circular_buffer.hh" #include "core/align.hh" #include <atomic> #include <list> #include <queue> #include <fcntl.h> #include <linux/if_tun.h> #include "ip.hh" #include <xen/xen.h> #include <xen/memory.h> #include <xen/sys/gntalloc.h> #include "core/xen/xenstore.hh" #include "core/xen/evtchn.hh" #include "xenfront.hh" #include <unordered_set> using namespace net; using phys = uint64_t; class xenfront_net_device : public net::device { private: bool _userspace; stream<packet> _rx_stream; net::hw_features _hw_features; std::string _device_str; xenstore* _xenstore = xenstore::instance(); unsigned _otherend; std::string _backend; gntalloc *_gntalloc; evtchn *_evtchn; port *_tx_evtchn; port *_rx_evtchn; front_ring<tx> _tx_ring; front_ring<rx> _rx_ring; grant_head *_tx_refs; grant_head *_rx_refs; std::list<std::pair<std::string, std::string>> _features; static std::unordered_set<std::string> _supported_features; ethernet_address _hw_address; port *bind_tx_evtchn(); port *bind_rx_evtchn(); future<> alloc_rx_references(); future<> handle_tx_completions(); future<> queue_rx_packet(); void alloc_one_rx_reference(unsigned id); std::string path(std::string s) { return _device_str + "/" + s; } public: explicit xenfront_net_device(boost::program_options::variables_map opts, bool userspace); ~xenfront_net_device(); virtual subscription<packet> receive(std::function<future<> (packet)> next) override; virtual future<> send(packet p) override; ethernet_address hw_address(); net::hw_features hw_features(); }; std::unordered_set<std::string> xenfront_net_device::_supported_features = { "feature-split-event-channels", "feature-rx-copy", }; subscription<packet> xenfront_net_device::receive(std::function<future<> (packet)> next) { auto sub = _rx_stream.listen(std::move(next)); keep_doing([this] { return _rx_evtchn->pending().then([this] { return queue_rx_packet(); }); }); return std::move(sub); } future<> xenfront_net_device::send(packet _p) { uint32_t frag = 0; // There doesn't seem to be a way to tell xen, when using the userspace // drivers, to map a particular page. Therefore, the only alternative // here is to copy. All pages shared must come from the gntalloc mmap. // // A better solution could be to change the packet allocation path to // use a pre-determined page for data. // // In-kernel should be fine // FIXME: negotiate and use scatter/gather _p.linearize(); return _tx_ring.entries.get_index().then([this, p = std::move(_p), frag] (unsigned idx) mutable { auto req_prod = _tx_ring._sring->req_prod; auto f = p.frag(frag); auto ref = _tx_refs->new_ref(f.base, f.size); assert(!_tx_ring.entries[idx]); _tx_ring.entries[idx] = ref; auto req = &_tx_ring._sring->_ring[idx].req; req->gref = ref.xen_id; req->offset = 0; req->flags = {}; if (p.offload_info().protocol != ip_protocol_num::unused) { req->flags.csum_blank = true; req->flags.data_validated = true; } else { req->flags.data_validated = true; } req->id = idx; req->size = f.size; _tx_ring.req_prod_pvt = idx; _tx_ring._sring->req_prod = req_prod + 1; _tx_ring._sring->req_event++; if ((frag + 1) == p.nr_frags()) { _tx_evtchn->notify(); return make_ready_future<>(); } else { return make_ready_future<>(); } }); // FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic? } #define rmb() asm volatile("lfence":::"memory"); #define wmb() asm volatile("":::"memory"); template <typename T> future<unsigned> front_ring<T>::entries::get_index() { return _available.wait().then([this] { auto ret = _ids.front(); _ids.pop(); return make_ready_future<unsigned>(ret); }); } template <typename T> void front_ring<T>::entries::free_index(unsigned id) { _ids.push(id); _available.signal(); } future<> xenfront_net_device::queue_rx_packet() { auto rsp_cons = _rx_ring.rsp_cons; rmb(); auto rsp_prod = _rx_ring._sring->rsp_prod; while (rsp_cons < rsp_prod) { auto rsp = _rx_ring[rsp_cons].rsp; auto& entry = _rx_ring.entries[rsp.id]; rsp_cons++; _rx_ring.rsp_cons = rsp_cons; if (rsp.status < 0) { printf("Packet error: Handle it\n"); continue; } auto rsp_size = rsp.status; packet p(static_cast<char *>(entry.page) + rsp.offset, rsp_size); _rx_stream.produce(std::move(p)); _rx_ring._sring->rsp_event = rsp_cons + 1; rsp_prod = _rx_ring._sring->rsp_prod; _rx_refs->free_ref(entry); _rx_ring.entries.free_index(rsp.id); } // FIXME: Queue_rx maybe should not be a future then return make_ready_future<>(); } void xenfront_net_device::alloc_one_rx_reference(unsigned index) { _rx_ring.entries[index] = _rx_refs->new_ref(); // This is how the backend knows where to put data. auto req = &_rx_ring._sring->_ring[index].req; req->id = index; req->gref = _rx_ring.entries[index].xen_id; } future<> xenfront_net_device::alloc_rx_references() { return _rx_ring.entries.get_index().then([this] (unsigned i) { auto req_prod = _rx_ring.req_prod_pvt; alloc_one_rx_reference(i); ++req_prod; _rx_ring.req_prod_pvt = req_prod; wmb(); _rx_ring._sring->req_prod = req_prod; /* ready */ _rx_evtchn->notify(); }); } future<> xenfront_net_device::handle_tx_completions() { auto prod = _tx_ring._sring->rsp_prod; rmb(); for (unsigned i = _tx_ring.rsp_cons; i != prod; i++) { auto rsp = _tx_ring[i].rsp; if (rsp.status == 1) { continue; } if (rsp.status != 0) { printf("Packet error: Handle it\n"); continue; } auto& entry = _tx_ring.entries[rsp.id]; _tx_refs->free_ref(entry); _tx_ring.entries.free_index(rsp.id); } _tx_ring.rsp_cons = prod; _tx_ring._sring->rsp_event = prod + 1; return make_ready_future<>(); } ethernet_address xenfront_net_device::hw_address() { return _hw_address; } net::hw_features xenfront_net_device::hw_features() { return _hw_features; } port *xenfront_net_device::bind_tx_evtchn() { return _evtchn->bind(); } port *xenfront_net_device::bind_rx_evtchn() { auto split = _xenstore->read_or_default<int>(_backend + "/feature-split-event-channels"); if (split) { return _evtchn->bind(); } return _evtchn->bind(*_tx_evtchn); } xenfront_net_device::xenfront_net_device(boost::program_options::variables_map opts, bool userspace) : _userspace(userspace) , _rx_stream() , _device_str("device/vif/" + std::to_string(opts["vif"].as<unsigned>())) , _otherend(_xenstore->read<int>(path("backend-id"))) , _backend(_xenstore->read(path("backend"))) , _gntalloc(gntalloc::instance(_userspace, _otherend)) , _evtchn(evtchn::instance(_userspace, _otherend)) , _tx_evtchn(bind_tx_evtchn()) , _rx_evtchn(bind_rx_evtchn()) , _tx_ring(_gntalloc->alloc_ref()) , _rx_ring(_gntalloc->alloc_ref()) , _tx_refs(_gntalloc->alloc_ref(front_ring<tx>::nr_ents)) , _rx_refs(_gntalloc->alloc_ref(front_ring<rx>::nr_ents)) , _hw_address(net::parse_ethernet_address(_xenstore->read(path("mac")))) { _rx_stream.started(); auto all_features = _xenstore->ls(_backend); std::unordered_map<std::string, int> features_nack; for (auto&& feat : all_features) { if (feat.compare(0, 8, "feature-") == 0 && !_supported_features.count(feat)) { features_nack[feat] = 0; } } _hw_features.rx_csum_offload = true; _hw_features.tx_csum_offload = true; for (auto&s : all_features) { auto value = _xenstore->read(_backend + "/" + s); _features.push_back(std::make_pair(s, value)); } { auto t = xenstore::xenstore_transaction(); for (auto&& f: features_nack) { _xenstore->write(path(f.first), f.second, t); } _xenstore->write<int>(path("event-channel-tx"), *_tx_evtchn, t); _xenstore->write<int>(path("event-channel-rx"), *_rx_evtchn, t); _xenstore->write<int>(path("tx-ring-ref"), _tx_ring.ref, t); _xenstore->write<int>(path("rx-ring-ref"), _rx_ring.ref, t); _xenstore->write<int>(path("state"), 4, t); } keep_doing([this] { return alloc_rx_references(); }); keep_doing([this] () { return _tx_evtchn->pending().then([this] { handle_tx_completions(); }); }); } xenfront_net_device::~xenfront_net_device() { { auto t = xenstore::xenstore_transaction(); for (auto& f: _features) { _xenstore->remove(path(f.first), t); } _xenstore->remove(path("event-channel-tx"), t); _xenstore->remove(path("event-channel-rx"), t); _xenstore->remove(path("tx-ring-ref"), t); _xenstore->remove(path("rx-ring-ref"), t); _xenstore->write<int>(path("state"), 6, t); } _xenstore->write<int>(path("state"), 1); } boost::program_options::options_description get_xenfront_net_options_description() { boost::program_options::options_description opts( "xenfront net options"); opts.add_options() ("vif", boost::program_options::value<unsigned>()->default_value(0), "vif number to hijack") ; return opts; } std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) { auto ptr = std::make_unique<xenfront_net_device>(opts, userspace); // This assumes only one device per cpu. Will need to be fixed when // this assumption will no longer hold. dev = ptr.get(); return std::move(ptr); } <|endoftext|>
<commit_before>/*-------------netlist_gen.cpp------------------------------------------------// * * netlist generator * * Purpose: The BIAS project intends to re-implement the TrueNorth architechture * in analog electronics. For this purpose, we will need to create a * simple script that will create a netlist to be read into a SPICE * simulator (or similar software that is compatable with the netlist * format. * * Notes: This could be written a little cleaner in another language, but... * We need to determine the appropriate analog inputs for this file * * To compile, use the following command: * g++ netlist_gen.cpp -std=c++11 -o genet * * PEMDAS: We will place everything on a grid. The components we need are: * 1. inverting amp * 2. summing amp * 3. differential amp * 4. sample and hold * * The grid will then be enumerated appropriately by filling the grid * points with integers and counting. * * Finally, this will be written out to a file. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; /*----------------------------------------------------------------------------// * STRUCTURES AND FUNCTIONS *-----------------------------------------------------------------------------*/ struct resistor{ double value; int forw, back; }; struct capacitor{ double value; int forw, back; }; // opamps are weird in spice. They have 4 extremities: // out, ground, in+, in- struct opamp{ int inp, inn, out; }; // struct to pass output and index between functions struct netlist{ string str; int index; }; // These functions will all take the current netlist and count and append the // appropriate variables to it. These will be used in the larger f(x)'s below netlist inv_amp(netlist net); netlist sum_amp(netlist net, vector<resistor> connections); netlist diff_amp(netlist net, int inp, int inn); netlist samhold(netlist net); // These functions will take care of connections and such within the core netlist neuron(netlist net); netlist junction(netlist net); netlist connectome(netlist net); // Quick function to write the netlist to a file void write_netlist(netlist net, ofstream &output); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(void){ return 0; } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // These functions will all take the current netlist and count and append the // appropriate variables to it. These will be used in the larger f(x)'s below netlist inv_amp(netlist net){ resistor res, res_2; opamp oa; // Setting initial values res.value = res_2.value = 1000; // Setting resistors in place res.back = net.index; res.forw = net.index + 1; res_2.back = net.index + 1; res_2.forw = net.index + 2; // Setting opamp up oa.inp = 0; oa.inn = net.index + 1; oa.out = net.index + 2; // appending to netlist // opamp net.str.append(" e" + to_string(net.index) + " " + to_string(oa.out) + " 0 " + to_string(oa.inp) + " " + to_string(oa.inn) + " 999k"); // R1 net.str.append(" r" + to_string(res.back) + " " + to_string(res.forw) + " " + to_string(res.value) + "k"); // R2 net.str.append(" r" + to_string(res_2.back) + " " + to_string(res_2.forw) + " " + to_string(res.value) + "k"); return net; } // Write out summing amp, including preceding resistors here. // This function is simple because we are assuming we are reading in the R vals netlist sum_amp(netlist net, vector<resistor> connections){ opamp oa; resistor res; // For this function, it is assumed that all the incoming resistors are // of the same value for (auto &r : connections){ r.forw = net.index; net.str.append(" r" + to_string(r.back) + " " + to_string(r.forw) + " " + to_string(res.value) + "k"); } //Setting up op amp oa.inp = 0; oa.inn = net.index; oa.out = net.index + 1; // setting up resistor res.back = net.index; res.forw = net.index + 1; res.value = connections[0].value; // appending to netlist // opamp net.str.append(" e" + to_string(net.index) + " " + to_string(oa.out) + " 0 " + to_string(oa.inp) + " " + to_string(oa.inn) + " 999k"); // Resistor net.str.append(" r" + to_string(res.back) + " " + to_string(res.forw) + " " + to_string(res.value) + "k"); return net; } netlist diff_amp(netlist net, int inp, int inn){ return net; } netlist samhold(netlist net){ return net; } // These functions will take care of connections and such within the core netlist neuron(netlist net){ return net; } netlist junction(netlist net){ return net; } netlist connectome(netlist net){ return net; } // Quick function to write the netlist to a file void write_netlist(netlist net, ofstream &output){ } <commit_msg>added the sample and hold and differential amplifier<commit_after>/*-------------netlist_gen.cpp------------------------------------------------// * * netlist generator * * Purpose: The BIAS project intends to re-implement the TrueNorth architechture * in analog electronics. For this purpose, we will need to create a * simple script that will create a netlist to be read into a SPICE * simulator (or similar software that is compatable with the netlist * format. * * Notes: This could be written a little cleaner in another language, but... * We need to determine the appropriate analog inputs for this file * * To compile, use the following command: * g++ netlist_gen.cpp -std=c++11 -o genet * * PEMDAS: We will place everything on a grid. The components we need are: * 1. inverting amp * 2. summing amp * 3. differential amp * 4. sample and hold * * The grid will then be enumerated appropriately by filling the grid * points with integers and counting. * * Finally, this will be written out to a file. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; /*----------------------------------------------------------------------------// * STRUCTURES AND FUNCTIONS *-----------------------------------------------------------------------------*/ struct resistor{ double value; int forw, back; }; struct capacitor{ double value; int forw, back; }; // opamps are weird in spice. They have 4 extremities: // out, ground, in+, in- struct opamp{ int inp, inn, out; }; // struct to pass output and index between functions struct netlist{ string str; int index; }; // These functions will all take the current netlist and count and append the // appropriate variables to it. These will be used in the larger f(x)'s below netlist inv_amp(netlist net); netlist sum_amp(netlist net, vector<resistor> connections); netlist diff_amp(netlist net, resistor inrp, resistor inrn); netlist samhold(netlist net); // These functions will take care of connections and such within the core netlist neuron(netlist net); netlist junction(netlist net); netlist connectome(netlist net); // Quick function to write the netlist to a file void write_netlist(netlist net, ofstream &output); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(void){ return 0; } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // These functions will all take the current netlist and count and append the // appropriate variables to it. These will be used in the larger f(x)'s below netlist inv_amp(netlist net){ resistor res, res_2; opamp oa; // Setting initial values res.value = res_2.value = 1000; // Setting resistors in place res.back = net.index; res.forw = net.index + 1; res_2.back = net.index + 1; res_2.forw = net.index + 2; // Setting opamp up oa.inp = 0; oa.inn = net.index + 1; oa.out = net.index + 2; // appending to netlist // opamp net.str.append(" e" + to_string(net.index) + " " + to_string(oa.out) + " 0 " + to_string(oa.inp) + " " + to_string(oa.inn) + " 999k"); // R1 net.str.append(" r" + to_string(res.back) + " " + to_string(res.forw) + " " + to_string(res.value) + "k"); // R2 net.str.append(" r" + to_string(res_2.back) + " " + to_string(res_2.forw) + " " + to_string(res.value) + "k"); net.index++; return net; } // Write out summing amp, including preceding resistors here. // This function is simple because we are assuming we are reading in the R vals netlist sum_amp(netlist net, vector<resistor> connections){ opamp oa; resistor res; // For this function, it is assumed that all the incoming resistors are // of the same value for (auto &r : connections){ r.forw = net.index; net.str.append(" r" + to_string(r.back) + " " + to_string(r.forw) + " " + to_string(res.value) + "k"); } //Setting up op amp oa.inp = 0; oa.inn = net.index; oa.out = net.index + 1; // setting up resistor res.back = net.index; res.forw = net.index + 1; res.value = connections[0].value; // appending to netlist // opamp net.str.append(" e" + to_string(net.index) + " " + to_string(oa.out) + " 0 " + to_string(oa.inp) + " " + to_string(oa.inn) + " 999k"); // Resistor net.str.append(" r" + to_string(res.back) + " " + to_string(res.forw) + " " + to_string(res.value) + "k"); net.index++; return net; } // Because we only want the differences between the voltages, we do not need // to worry about different resistor values. // Like the summing amplifier, its easier to read in resistors than ints and // write them here. netlist diff_amp(netlist net, resistor inrp, resistor inrn){ opamp oa; // Note: No resistor def necessary since all resistor values are the same // First, let's write out the resistors we have coming in inrp.forw = net.index + 1; inrn.forw = net.index; net.str.append(" r" + to_string(inrp.back) + " " + to_string(inrp.forw) +" " + to_string(inrp.value) + "k"); net.str.append(" r" + to_string(inrn.back) + " " + to_string(inrn.forw) +" " + to_string(inrn.value) + "k"); // Now we need to create the rest of the differential amplifier circuit // r2 clone to ground net.str.append(" r" + to_string(inrp.forw) + " " + to_string(0) +" " + to_string(inrp.value) + "k"); // r1 clone to out net.str.append(" r" + to_string(inrn.forw) + " " + to_string(net.index + 2) + " " + to_string(inrn.value) + "k"); // opamp definitions and writing oa.inp = inrp.forw; oa.inn = inrn.forw; // Note +2 instead of +1 due to two inputs oa.out = net.index + 2; net.str.append(" e" + to_string(net.index) + " " + to_string(oa.out) + " 0 " + to_string(oa.inp) + " " + to_string(oa.inn) + " 999k"); net.index += 2; return net; } // This iteration of a sample and hold circuit will not have FET switches. // To implement FET switches, just put on the output of oa1 for charging, and // another parallel to the capacitor for discarging netlist samhold(netlist net){ opamp oa1, oa2; capacitor cap; // opamp1 oa1.inp = 0; oa1.inn = net.index; oa1.out = net.index + 1; // opamp2 oa2.inp = 0; oa2.inn = net.index + 1; oa2.out = net.index + 2; // capacitor cap.back = net.index + 1; cap.forw = 0; //appending to netlist // opamp net.str.append(" e"+to_string(net.index)+" "+to_string(oa1.out)+" 0 " + to_string(oa1.inp) + " " + to_string(oa1.inn) + " 999k"); net.str.append(" e"+to_string(net.index+1)+" "+to_string(oa2.out)+" 0 " + to_string(oa2.inp) + " " + to_string(oa2.inn) + " 999k"); // Resistor net.str.append(" c" + to_string(cap.back) + " " + to_string(cap.forw) + " " + to_string(cap.value) + "k"); net.index += 2; return net; } // These functions will take care of connections and such within the core netlist neuron(netlist net){ return net; } netlist junction(netlist net){ return net; } netlist connectome(netlist net){ return net; } // Quick function to write the netlist to a file void write_netlist(netlist net, ofstream &output){ } <|endoftext|>