text
stringlengths 54
60.6k
|
|---|
<commit_before>/**************************************************************************
**
** Copyright (C) 2012 - 2014 BlackBerry Limited. All rights reserved
**
** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qnxutils.h"
#include "qnxabstractqtversion.h"
#include <utils/hostosinfo.h>
#include <utils/synchronousprocess.h>
#include <QDir>
#include <QDomDocument>
#include <QProcess>
#include <QStandardPaths>
#include <QTemporaryFile>
#include <QApplication>
using namespace Qnx;
using namespace Qnx::Internal;
namespace {
const char *EVAL_ENV_VARS[] = {
"QNX_TARGET", "QNX_HOST", "QNX_CONFIGURATION", "MAKEFLAGS", "LD_LIBRARY_PATH",
"PATH", "QDE", "CPUVARDIR", "PYTHONPATH"
};
}
QString QnxUtils::addQuotes(const QString &string)
{
return QLatin1Char('"') + string + QLatin1Char('"');
}
Qnx::QnxArchitecture QnxUtils::cpudirToArch(const QString &cpuDir)
{
if (cpuDir == QLatin1String("x86"))
return Qnx::X86;
else if (cpuDir == QLatin1String("armle-v7"))
return Qnx::ArmLeV7;
else
return Qnx::UnknownArch;
}
QStringList QnxUtils::searchPaths(QnxAbstractQtVersion *qtVersion)
{
const QDir pluginDir(qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS")));
const QStringList pluginSubDirs = pluginDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
QStringList searchPaths;
Q_FOREACH (const QString &dir, pluginSubDirs) {
searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS"))
+ QLatin1Char('/') + dir;
}
searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_LIBS"));
searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower()
+ QLatin1String("/lib");
searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower()
+ QLatin1String("/usr/lib");
return searchPaths;
}
QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironmentFromEnvFile(const QString &fileName)
{
QList <Utils::EnvironmentItem> items;
if (!QFileInfo(fileName).exists())
return items;
const bool isWindows = Utils::HostOsInfo::isWindowsHost();
// locking creating bbndk-env file wrapper script
QTemporaryFile tmpFile(
QDir::tempPath() + QDir::separator()
+ QLatin1String("bbndk-env-eval-XXXXXX") + QLatin1String(isWindows ? ".bat" : ".sh"));
if (!tmpFile.open())
return items;
tmpFile.setTextModeEnabled(true);
// writing content to wrapper script
QTextStream fileContent(&tmpFile);
if (isWindows)
fileContent << QLatin1String("@echo off\n")
<< QLatin1String("call ") << fileName << QLatin1Char('\n');
else
fileContent << QLatin1String("#!/bin/bash\n")
<< QLatin1String(". ") << fileName << QLatin1Char('\n');
QString linePattern = QString::fromLatin1(isWindows ? "echo %1=%%1%" : "echo %1=$%1");
for (int i = 0, len = sizeof(EVAL_ENV_VARS) / sizeof(const char *); i < len; ++i)
fileContent << linePattern.arg(QLatin1String(EVAL_ENV_VARS[i])) << QLatin1Char('\n');
tmpFile.close();
// running wrapper script
QProcess process;
if (isWindows)
process.start(QLatin1String("cmd.exe"),
QStringList() << QLatin1String("/C") << tmpFile.fileName());
else
process.start(QLatin1String("/bin/bash"),
QStringList() << tmpFile.fileName());
// waiting for finish
QApplication::setOverrideCursor(Qt::BusyCursor);
bool waitResult = process.waitForFinished(10000);
QApplication::restoreOverrideCursor();
if (!waitResult) {
Utils::SynchronousProcess::stopProcess(process);
return items;
}
if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0)
return items;
// parsing process output
QTextStream str(&process);
while (!str.atEnd()) {
QString line = str.readLine();
int equalIndex = line.indexOf(QLatin1Char('='));
if (equalIndex < 0)
continue;
QString var = line.left(equalIndex);
QString value = line.mid(equalIndex + 1);
items.append(Utils::EnvironmentItem(var, value));
}
return items;
}
bool QnxUtils::isValidNdkPath(const QString &ndkPath)
{
return (QFileInfo(envFilePath(ndkPath)).exists());
}
QString QnxUtils::envFilePath(const QString &ndkPath, const QString &targetVersion)
{
QString envFile;
if (Utils::HostOsInfo::isWindowsHost())
envFile = ndkPath + QLatin1String("/bbndk-env.bat");
else if (Utils::HostOsInfo::isAnyUnixHost())
envFile = ndkPath + QLatin1String("/bbndk-env.sh");
if (!QFileInfo(envFile).exists()) {
QString version = targetVersion.isEmpty() ? defaultTargetVersion(ndkPath) : targetVersion;
version = version.replace(QLatin1Char('.'), QLatin1Char('_'));
if (Utils::HostOsInfo::isWindowsHost())
envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".bat");
else if (Utils::HostOsInfo::isAnyUnixHost())
envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".sh");
}
return envFile;
}
QString QnxUtils::bbDataDirPath()
{
const QString homeDir = QDir::homePath();
if (Utils::HostOsInfo::isMacHost())
return homeDir + QLatin1String("/Library/Research in Motion");
if (Utils::HostOsInfo::isAnyUnixHost())
return homeDir + QLatin1String("/.rim");
if (Utils::HostOsInfo::isWindowsHost()) {
// Get the proper storage location on Windows using QDesktopServices,
// to not hardcode "AppData/Local", as it might refer to "AppData/Roaming".
QString dataDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)
+ QLatin1String("/data");
dataDir = dataDir.left(dataDir.indexOf(QCoreApplication::organizationName()));
dataDir.append(QLatin1String("Research in Motion"));
qDebug("qnx: Full data dir is '%s'", qPrintable(dataDir));
return dataDir;
}
return QString();
}
QString QnxUtils::bbqConfigPath()
{
if (Utils::HostOsInfo::isMacHost() || Utils::HostOsInfo::isWindowsHost())
return bbDataDirPath() + QLatin1String("/BlackBerry Native SDK/qconfig");
else
return bbDataDirPath() + QLatin1String("/bbndk/qconfig");
}
QString QnxUtils::defaultTargetVersion(const QString &ndkPath)
{
foreach (const ConfigInstallInformation &ndkInfo, installedConfigs()) {
if (!ndkInfo.path.compare(ndkPath, Utils::HostOsInfo::fileNameCaseSensitivity()))
return ndkInfo.version;
}
return QString();
}
QList<ConfigInstallInformation> QnxUtils::installedConfigs(const QString &configPath)
{
QList<ConfigInstallInformation> ndkList;
QString ndkConfigPath = configPath;
if (ndkConfigPath.isEmpty())
ndkConfigPath = bbqConfigPath();
if (!QDir(ndkConfigPath).exists())
return ndkList;
QFileInfoList ndkfileList = QDir(ndkConfigPath).entryInfoList(QStringList() << QLatin1String("*.xml"),
QDir::Files, QDir::Time);
foreach (const QFileInfo &ndkFile, ndkfileList) {
QFile xmlFile(ndkFile.absoluteFilePath());
if (!xmlFile.open(QIODevice::ReadOnly))
continue;
QDomDocument doc;
if (!doc.setContent(&xmlFile)) // Skip error message
continue;
QDomElement docElt = doc.documentElement();
if (docElt.tagName() != QLatin1String("qnxSystemDefinition"))
continue;
QDomElement childElt = docElt.firstChildElement(QLatin1String("installation"));
// The file contains only one installation node
if (!childElt.isNull()) {
// The file contains only one base node
ConfigInstallInformation ndkInfo;
ndkInfo.path = childElt.firstChildElement(QLatin1String("base")).text();
ndkInfo.name = childElt.firstChildElement(QLatin1String("name")).text();
ndkInfo.host = childElt.firstChildElement(QLatin1String("host")).text();
ndkInfo.target = childElt.firstChildElement(QLatin1String("target")).text();
ndkInfo.version = childElt.firstChildElement(QLatin1String("version")).text();
ndkInfo.installationXmlFilePath = ndkFile.absoluteFilePath();
ndkList.append(ndkInfo);
}
}
return ndkList;
}
QString QnxUtils::sdkInstallerPath(const QString &ndkPath)
{
QString sdkinstallPath = Utils::HostOsInfo::withExecutableSuffix(ndkPath + QLatin1String("/qde"));
if (QFileInfo(sdkinstallPath).exists())
return sdkinstallPath;
return QString();
}
// The resulting process when launching sdkinstall
QString QnxUtils::qdeInstallProcess(const QString &ndkPath, const QString &target,
const QString &option, const QString &version)
{
QString installerPath = sdkInstallerPath(ndkPath);
if (installerPath.isEmpty())
return QString();
const QDir pluginDir(ndkPath + QLatin1String("/plugins"));
const QStringList installerPlugins = pluginDir.entryList(QStringList() << QLatin1String("com.qnx.tools.ide.sdk.installer.app_*.jar"));
const QString installerApplication = installerPlugins.size() >= 1 ? QLatin1String("com.qnx.tools.ide.sdk.installer.app.SDKInstallerApplication")
: QLatin1String("com.qnx.tools.ide.sdk.manager.core.SDKInstallerApplication");
return QString::fromLatin1("%1 -nosplash -application %2 "
"%3 %4 %5 -vmargs -Dosgi.console=:none").arg(installerPath, installerApplication, target, option, version);
}
QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironment(const QString &sdkPath)
{
// Mimic what the SDP installer puts into the system environment
QList<Utils::EnvironmentItem> environmentItems;
if (Utils::HostOsInfo::isWindowsHost()) {
// TODO:
//environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"));
environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/win32/x86")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/win32/x86/usr/bin;%PATH%")));
// TODO:
//environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin"));
} else if (Utils::HostOsInfo::isAnyUnixHost()) {
environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/linux/x86")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/bin:/etc/qnx/bin:${PATH}")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String("LD_LIBRARY_PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/lib:${LD_LIBRARY_PATH}")));
}
environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_JAVAHOME"), sdkPath + QLatin1String("/_jvm")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String("MAKEFLAGS"), QLatin1String("-I") + sdkPath + QLatin1String("/target/qnx6/usr/include")));
return environmentItems;
}
<commit_msg>Qnx: remove left-over qDebug call<commit_after>/**************************************************************************
**
** Copyright (C) 2012 - 2014 BlackBerry Limited. All rights reserved
**
** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qnxutils.h"
#include "qnxabstractqtversion.h"
#include <utils/hostosinfo.h>
#include <utils/synchronousprocess.h>
#include <QDir>
#include <QDomDocument>
#include <QProcess>
#include <QStandardPaths>
#include <QTemporaryFile>
#include <QApplication>
using namespace Qnx;
using namespace Qnx::Internal;
namespace {
const char *EVAL_ENV_VARS[] = {
"QNX_TARGET", "QNX_HOST", "QNX_CONFIGURATION", "MAKEFLAGS", "LD_LIBRARY_PATH",
"PATH", "QDE", "CPUVARDIR", "PYTHONPATH"
};
}
QString QnxUtils::addQuotes(const QString &string)
{
return QLatin1Char('"') + string + QLatin1Char('"');
}
Qnx::QnxArchitecture QnxUtils::cpudirToArch(const QString &cpuDir)
{
if (cpuDir == QLatin1String("x86"))
return Qnx::X86;
else if (cpuDir == QLatin1String("armle-v7"))
return Qnx::ArmLeV7;
else
return Qnx::UnknownArch;
}
QStringList QnxUtils::searchPaths(QnxAbstractQtVersion *qtVersion)
{
const QDir pluginDir(qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS")));
const QStringList pluginSubDirs = pluginDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
QStringList searchPaths;
Q_FOREACH (const QString &dir, pluginSubDirs) {
searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_PLUGINS"))
+ QLatin1Char('/') + dir;
}
searchPaths << qtVersion->versionInfo().value(QLatin1String("QT_INSTALL_LIBS"));
searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower()
+ QLatin1String("/lib");
searchPaths << qtVersion->qnxTarget() + QLatin1Char('/') + qtVersion->archString().toLower()
+ QLatin1String("/usr/lib");
return searchPaths;
}
QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironmentFromEnvFile(const QString &fileName)
{
QList <Utils::EnvironmentItem> items;
if (!QFileInfo(fileName).exists())
return items;
const bool isWindows = Utils::HostOsInfo::isWindowsHost();
// locking creating bbndk-env file wrapper script
QTemporaryFile tmpFile(
QDir::tempPath() + QDir::separator()
+ QLatin1String("bbndk-env-eval-XXXXXX") + QLatin1String(isWindows ? ".bat" : ".sh"));
if (!tmpFile.open())
return items;
tmpFile.setTextModeEnabled(true);
// writing content to wrapper script
QTextStream fileContent(&tmpFile);
if (isWindows)
fileContent << QLatin1String("@echo off\n")
<< QLatin1String("call ") << fileName << QLatin1Char('\n');
else
fileContent << QLatin1String("#!/bin/bash\n")
<< QLatin1String(". ") << fileName << QLatin1Char('\n');
QString linePattern = QString::fromLatin1(isWindows ? "echo %1=%%1%" : "echo %1=$%1");
for (int i = 0, len = sizeof(EVAL_ENV_VARS) / sizeof(const char *); i < len; ++i)
fileContent << linePattern.arg(QLatin1String(EVAL_ENV_VARS[i])) << QLatin1Char('\n');
tmpFile.close();
// running wrapper script
QProcess process;
if (isWindows)
process.start(QLatin1String("cmd.exe"),
QStringList() << QLatin1String("/C") << tmpFile.fileName());
else
process.start(QLatin1String("/bin/bash"),
QStringList() << tmpFile.fileName());
// waiting for finish
QApplication::setOverrideCursor(Qt::BusyCursor);
bool waitResult = process.waitForFinished(10000);
QApplication::restoreOverrideCursor();
if (!waitResult) {
Utils::SynchronousProcess::stopProcess(process);
return items;
}
if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0)
return items;
// parsing process output
QTextStream str(&process);
while (!str.atEnd()) {
QString line = str.readLine();
int equalIndex = line.indexOf(QLatin1Char('='));
if (equalIndex < 0)
continue;
QString var = line.left(equalIndex);
QString value = line.mid(equalIndex + 1);
items.append(Utils::EnvironmentItem(var, value));
}
return items;
}
bool QnxUtils::isValidNdkPath(const QString &ndkPath)
{
return (QFileInfo(envFilePath(ndkPath)).exists());
}
QString QnxUtils::envFilePath(const QString &ndkPath, const QString &targetVersion)
{
QString envFile;
if (Utils::HostOsInfo::isWindowsHost())
envFile = ndkPath + QLatin1String("/bbndk-env.bat");
else if (Utils::HostOsInfo::isAnyUnixHost())
envFile = ndkPath + QLatin1String("/bbndk-env.sh");
if (!QFileInfo(envFile).exists()) {
QString version = targetVersion.isEmpty() ? defaultTargetVersion(ndkPath) : targetVersion;
version = version.replace(QLatin1Char('.'), QLatin1Char('_'));
if (Utils::HostOsInfo::isWindowsHost())
envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".bat");
else if (Utils::HostOsInfo::isAnyUnixHost())
envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".sh");
}
return envFile;
}
QString QnxUtils::bbDataDirPath()
{
const QString homeDir = QDir::homePath();
if (Utils::HostOsInfo::isMacHost())
return homeDir + QLatin1String("/Library/Research in Motion");
if (Utils::HostOsInfo::isAnyUnixHost())
return homeDir + QLatin1String("/.rim");
if (Utils::HostOsInfo::isWindowsHost()) {
// Get the proper storage location on Windows using QDesktopServices,
// to not hardcode "AppData/Local", as it might refer to "AppData/Roaming".
QString dataDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)
+ QLatin1String("/data");
dataDir = dataDir.left(dataDir.indexOf(QCoreApplication::organizationName()));
dataDir.append(QLatin1String("Research in Motion"));
return dataDir;
}
return QString();
}
QString QnxUtils::bbqConfigPath()
{
if (Utils::HostOsInfo::isMacHost() || Utils::HostOsInfo::isWindowsHost())
return bbDataDirPath() + QLatin1String("/BlackBerry Native SDK/qconfig");
else
return bbDataDirPath() + QLatin1String("/bbndk/qconfig");
}
QString QnxUtils::defaultTargetVersion(const QString &ndkPath)
{
foreach (const ConfigInstallInformation &ndkInfo, installedConfigs()) {
if (!ndkInfo.path.compare(ndkPath, Utils::HostOsInfo::fileNameCaseSensitivity()))
return ndkInfo.version;
}
return QString();
}
QList<ConfigInstallInformation> QnxUtils::installedConfigs(const QString &configPath)
{
QList<ConfigInstallInformation> ndkList;
QString ndkConfigPath = configPath;
if (ndkConfigPath.isEmpty())
ndkConfigPath = bbqConfigPath();
if (!QDir(ndkConfigPath).exists())
return ndkList;
QFileInfoList ndkfileList = QDir(ndkConfigPath).entryInfoList(QStringList() << QLatin1String("*.xml"),
QDir::Files, QDir::Time);
foreach (const QFileInfo &ndkFile, ndkfileList) {
QFile xmlFile(ndkFile.absoluteFilePath());
if (!xmlFile.open(QIODevice::ReadOnly))
continue;
QDomDocument doc;
if (!doc.setContent(&xmlFile)) // Skip error message
continue;
QDomElement docElt = doc.documentElement();
if (docElt.tagName() != QLatin1String("qnxSystemDefinition"))
continue;
QDomElement childElt = docElt.firstChildElement(QLatin1String("installation"));
// The file contains only one installation node
if (!childElt.isNull()) {
// The file contains only one base node
ConfigInstallInformation ndkInfo;
ndkInfo.path = childElt.firstChildElement(QLatin1String("base")).text();
ndkInfo.name = childElt.firstChildElement(QLatin1String("name")).text();
ndkInfo.host = childElt.firstChildElement(QLatin1String("host")).text();
ndkInfo.target = childElt.firstChildElement(QLatin1String("target")).text();
ndkInfo.version = childElt.firstChildElement(QLatin1String("version")).text();
ndkInfo.installationXmlFilePath = ndkFile.absoluteFilePath();
ndkList.append(ndkInfo);
}
}
return ndkList;
}
QString QnxUtils::sdkInstallerPath(const QString &ndkPath)
{
QString sdkinstallPath = Utils::HostOsInfo::withExecutableSuffix(ndkPath + QLatin1String("/qde"));
if (QFileInfo(sdkinstallPath).exists())
return sdkinstallPath;
return QString();
}
// The resulting process when launching sdkinstall
QString QnxUtils::qdeInstallProcess(const QString &ndkPath, const QString &target,
const QString &option, const QString &version)
{
QString installerPath = sdkInstallerPath(ndkPath);
if (installerPath.isEmpty())
return QString();
const QDir pluginDir(ndkPath + QLatin1String("/plugins"));
const QStringList installerPlugins = pluginDir.entryList(QStringList() << QLatin1String("com.qnx.tools.ide.sdk.installer.app_*.jar"));
const QString installerApplication = installerPlugins.size() >= 1 ? QLatin1String("com.qnx.tools.ide.sdk.installer.app.SDKInstallerApplication")
: QLatin1String("com.qnx.tools.ide.sdk.manager.core.SDKInstallerApplication");
return QString::fromLatin1("%1 -nosplash -application %2 "
"%3 %4 %5 -vmargs -Dosgi.console=:none").arg(installerPath, installerApplication, target, option, version);
}
QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironment(const QString &sdkPath)
{
// Mimic what the SDP installer puts into the system environment
QList<Utils::EnvironmentItem> environmentItems;
if (Utils::HostOsInfo::isWindowsHost()) {
// TODO:
//environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"));
environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/win32/x86")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/win32/x86/usr/bin;%PATH%")));
// TODO:
//environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin"));
} else if (Utils::HostOsInfo::isAnyUnixHost()) {
environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath + QLatin1String("/target/qnx6")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String(Constants::QNX_HOST_KEY), sdkPath + QLatin1String("/host/linux/x86")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String("PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/bin:/etc/qnx/bin:${PATH}")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String("LD_LIBRARY_PATH"), sdkPath + QLatin1String("/host/linux/x86/usr/lib:${LD_LIBRARY_PATH}")));
}
environmentItems.append(Utils::EnvironmentItem(QLatin1String("QNX_JAVAHOME"), sdkPath + QLatin1String("/_jvm")));
environmentItems.append(Utils::EnvironmentItem(QLatin1String("MAKEFLAGS"), QLatin1String("-I") + sdkPath + QLatin1String("/target/qnx6/usr/include")));
return environmentItems;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grammar.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_GRAMMAR_HXX
#define SC_GRAMMAR_HXX
#include "com/sun/star/sheet/FormulaLanguage.hpp"
#include "address.hxx"
/** Grammars digested by ScCompiler.
*/
class ScGrammar
{
public:
//! ScAddress::CONV_UNSPECIFIED is a negative value!
static const int kConventionOffset = - ScAddress::CONV_UNSPECIFIED + 1;
// Room for 32k hypothetical languages plus EXTERNAL.
static const int kConventionShift = 16;
// Room for 256 reference conventions.
static const int kEnglishBit = (1 << (kConventionShift + 8));
// Mask off all non-language bits.
static const int kFlagMask = ~((~int(0)) << kConventionShift);
/** Values encoding the formula language plus address reference convention
plus English parsing/formatting
*/
//! When adding new values adapt isSupported() below as well.
enum Grammar
{
/// Used only in ScCompiler ctor and in some XML import API context.
GRAM_UNSPECIFIED = -1,
/// ODFF with default ODF A1 bracketed references.
GRAM_ODFF = ::com::sun::star::sheet::FormulaLanguage::ODFF |
((ScAddress::CONV_ODF +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// ODF 1.1 with default ODF A1 bracketed references.
GRAM_PODF = ::com::sun::star::sheet::FormulaLanguage::ODF_11 |
((ScAddress::CONV_ODF +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// English with default A1 reference style.
GRAM_ENGLISH = ::com::sun::star::sheet::FormulaLanguage::ENGLISH |
((ScAddress::CONV_OOO +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// Native with default A1 reference style.
GRAM_NATIVE = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_OOO +
kConventionOffset) << kConventionShift),
/// ODFF with reference style as set in UI, may be A1 or R1C1.
GRAM_ODFF_UI = ::com::sun::star::sheet::FormulaLanguage::ODFF |
((ScAddress::CONV_UNSPECIFIED +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// ODFF with A1 reference style, unbracketed.
GRAM_ODFF_A1 = ::com::sun::star::sheet::FormulaLanguage::ODFF |
((ScAddress::CONV_OOO +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// ODF 1.1 with reference style as set in UI, may be A1 or R1C1.
GRAM_PODF_UI = ::com::sun::star::sheet::FormulaLanguage::ODF_11 |
((ScAddress::CONV_UNSPECIFIED +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// ODF 1.1 with A1 reference style, unbracketed.
GRAM_PODF_A1 = ::com::sun::star::sheet::FormulaLanguage::ODF_11 |
((ScAddress::CONV_OOO +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// Native with reference style as set in UI, may be A1 or R1C1.
GRAM_NATIVE_UI = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_UNSPECIFIED +
kConventionOffset) << kConventionShift),
/// Native with ODF A1 bracketed references. Not very useful but supported.
GRAM_NATIVE_ODF = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_ODF +
kConventionOffset) << kConventionShift),
/// Native with Excel A1 reference style.
GRAM_NATIVE_XL_A1 = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_XL_A1 +
kConventionOffset) << kConventionShift),
/// Native with Excel R1C1 reference style.
GRAM_NATIVE_XL_R1C1 = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_XL_R1C1 +
kConventionOffset) << kConventionShift),
/// Central definition of the default grammar to be used.
GRAM_DEFAULT = GRAM_NATIVE_UI,
/** Central definition of the default storage grammar to be used.
If GRAM_PODF switch this to GRAM_ODFF when we're ready. */
GRAM_STORAGE_DEFAULT = GRAM_PODF,
/** OpCodeMap set by external filter and merged with reference
convention plus English bit on top. Plain value acts as
FormulaLanguage. */
GRAM_EXTERNAL = (1 << (kConventionShift - 1))
};
/// If English parsing/formatting is associated with a grammar.
static inline bool isEnglish( const Grammar eGrammar )
{
return (eGrammar & kEnglishBit) != 0;
}
/** Compatibility helper for old "bCompileEnglish, bCompileXML" API calls
to obtain the new grammar. */
static Grammar mapAPItoGrammar( const bool bEnglish, const bool bXML )
{
Grammar eGrammar;
if (bEnglish && bXML)
eGrammar = GRAM_PODF;
else if (bEnglish && !bXML)
eGrammar = GRAM_PODF_A1;
else if (!bEnglish && bXML)
eGrammar = GRAM_NATIVE_ODF;
else // (!bEnglish && !bXML)
eGrammar = GRAM_NATIVE;
return eGrammar;
}
static bool isSupported( const Grammar eGrammar )
{
switch (eGrammar)
{
case GRAM_ODFF :
case GRAM_PODF :
case GRAM_ENGLISH :
case GRAM_NATIVE :
case GRAM_ODFF_UI :
case GRAM_ODFF_A1 :
case GRAM_PODF_UI :
case GRAM_PODF_A1 :
case GRAM_NATIVE_UI :
case GRAM_NATIVE_ODF :
case GRAM_NATIVE_XL_A1 :
case GRAM_NATIVE_XL_R1C1 :
return true;
default:
return extractFormulaLanguage( eGrammar) == GRAM_EXTERNAL;
}
}
static inline sal_Int32 extractFormulaLanguage( const Grammar eGrammar )
{
return eGrammar & kFlagMask;
}
static inline ScAddress::Convention extractRefConvention( const Grammar eGrammar )
{
return static_cast<ScAddress::Convention>(
((eGrammar & ~kEnglishBit) >> kConventionShift) -
kConventionOffset);
}
static inline Grammar setEnglishBit( const Grammar eGrammar, const bool bEnglish )
{
if (bEnglish)
return static_cast<Grammar>( eGrammar | kEnglishBit);
else
return static_cast<Grammar>( eGrammar & ~kEnglishBit);
}
static inline Grammar mergeToGrammar( const Grammar eGrammar, const ScAddress::Convention eConv )
{
bool bEnglish = isEnglish( eGrammar);
Grammar eGram = static_cast<Grammar>(
extractFormulaLanguage( eGrammar) |
((eConv + kConventionOffset) << kConventionShift));
eGram = setEnglishBit( eGram, bEnglish);
DBG_ASSERT( isSupported( eGram), "ScCompilerGrammarMap::mergeToGrammar: unsupported grammar");
return eGram;
}
/// If grammar is of ODF 1.1
static inline bool isPODF( const Grammar eGrammar )
{
return extractFormulaLanguage( eGrammar) ==
::com::sun::star::sheet::FormulaLanguage::ODF_11;
}
/// If grammar is of ODFF
static inline bool isODFF( const Grammar eGrammar )
{
return extractFormulaLanguage( eGrammar) ==
::com::sun::star::sheet::FormulaLanguage::ODFF;
}
};
#endif // SC_GRAMMAR_HXX
<commit_msg>INTEGRATION: CWS calcodfversion (1.3.6); FILE MERGED 2008/04/28 20:44:36 er 1.3.6.1: #i88113# switch GRAM_STORAGE_DEFAULT to GRAM_ODFF<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grammar.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_GRAMMAR_HXX
#define SC_GRAMMAR_HXX
#include "com/sun/star/sheet/FormulaLanguage.hpp"
#include "address.hxx"
/** Grammars digested by ScCompiler.
*/
class ScGrammar
{
public:
//! ScAddress::CONV_UNSPECIFIED is a negative value!
static const int kConventionOffset = - ScAddress::CONV_UNSPECIFIED + 1;
// Room for 32k hypothetical languages plus EXTERNAL.
static const int kConventionShift = 16;
// Room for 256 reference conventions.
static const int kEnglishBit = (1 << (kConventionShift + 8));
// Mask off all non-language bits.
static const int kFlagMask = ~((~int(0)) << kConventionShift);
/** Values encoding the formula language plus address reference convention
plus English parsing/formatting
*/
//! When adding new values adapt isSupported() below as well.
enum Grammar
{
/// Used only in ScCompiler ctor and in some XML import API context.
GRAM_UNSPECIFIED = -1,
/// ODFF with default ODF A1 bracketed references.
GRAM_ODFF = ::com::sun::star::sheet::FormulaLanguage::ODFF |
((ScAddress::CONV_ODF +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// ODF 1.1 with default ODF A1 bracketed references.
GRAM_PODF = ::com::sun::star::sheet::FormulaLanguage::ODF_11 |
((ScAddress::CONV_ODF +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// English with default A1 reference style.
GRAM_ENGLISH = ::com::sun::star::sheet::FormulaLanguage::ENGLISH |
((ScAddress::CONV_OOO +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// Native with default A1 reference style.
GRAM_NATIVE = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_OOO +
kConventionOffset) << kConventionShift),
/// ODFF with reference style as set in UI, may be A1 or R1C1.
GRAM_ODFF_UI = ::com::sun::star::sheet::FormulaLanguage::ODFF |
((ScAddress::CONV_UNSPECIFIED +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// ODFF with A1 reference style, unbracketed.
GRAM_ODFF_A1 = ::com::sun::star::sheet::FormulaLanguage::ODFF |
((ScAddress::CONV_OOO +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// ODF 1.1 with reference style as set in UI, may be A1 or R1C1.
GRAM_PODF_UI = ::com::sun::star::sheet::FormulaLanguage::ODF_11 |
((ScAddress::CONV_UNSPECIFIED +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// ODF 1.1 with A1 reference style, unbracketed.
GRAM_PODF_A1 = ::com::sun::star::sheet::FormulaLanguage::ODF_11 |
((ScAddress::CONV_OOO +
kConventionOffset) << kConventionShift) |
kEnglishBit,
/// Native with reference style as set in UI, may be A1 or R1C1.
GRAM_NATIVE_UI = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_UNSPECIFIED +
kConventionOffset) << kConventionShift),
/// Native with ODF A1 bracketed references. Not very useful but supported.
GRAM_NATIVE_ODF = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_ODF +
kConventionOffset) << kConventionShift),
/// Native with Excel A1 reference style.
GRAM_NATIVE_XL_A1 = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_XL_A1 +
kConventionOffset) << kConventionShift),
/// Native with Excel R1C1 reference style.
GRAM_NATIVE_XL_R1C1 = ::com::sun::star::sheet::FormulaLanguage::NATIVE |
((ScAddress::CONV_XL_R1C1 +
kConventionOffset) << kConventionShift),
/// Central definition of the default grammar to be used.
GRAM_DEFAULT = GRAM_NATIVE_UI,
/// Central definition of the default storage grammar to be used.
GRAM_STORAGE_DEFAULT = GRAM_ODFF,
/** OpCodeMap set by external filter and merged with reference
convention plus English bit on top. Plain value acts as
FormulaLanguage. */
GRAM_EXTERNAL = (1 << (kConventionShift - 1))
};
/// If English parsing/formatting is associated with a grammar.
static inline bool isEnglish( const Grammar eGrammar )
{
return (eGrammar & kEnglishBit) != 0;
}
/** Compatibility helper for old "bCompileEnglish, bCompileXML" API calls
to obtain the new grammar. */
static Grammar mapAPItoGrammar( const bool bEnglish, const bool bXML )
{
Grammar eGrammar;
if (bEnglish && bXML)
eGrammar = GRAM_PODF;
else if (bEnglish && !bXML)
eGrammar = GRAM_PODF_A1;
else if (!bEnglish && bXML)
eGrammar = GRAM_NATIVE_ODF;
else // (!bEnglish && !bXML)
eGrammar = GRAM_NATIVE;
return eGrammar;
}
static bool isSupported( const Grammar eGrammar )
{
switch (eGrammar)
{
case GRAM_ODFF :
case GRAM_PODF :
case GRAM_ENGLISH :
case GRAM_NATIVE :
case GRAM_ODFF_UI :
case GRAM_ODFF_A1 :
case GRAM_PODF_UI :
case GRAM_PODF_A1 :
case GRAM_NATIVE_UI :
case GRAM_NATIVE_ODF :
case GRAM_NATIVE_XL_A1 :
case GRAM_NATIVE_XL_R1C1 :
return true;
default:
return extractFormulaLanguage( eGrammar) == GRAM_EXTERNAL;
}
}
static inline sal_Int32 extractFormulaLanguage( const Grammar eGrammar )
{
return eGrammar & kFlagMask;
}
static inline ScAddress::Convention extractRefConvention( const Grammar eGrammar )
{
return static_cast<ScAddress::Convention>(
((eGrammar & ~kEnglishBit) >> kConventionShift) -
kConventionOffset);
}
static inline Grammar setEnglishBit( const Grammar eGrammar, const bool bEnglish )
{
if (bEnglish)
return static_cast<Grammar>( eGrammar | kEnglishBit);
else
return static_cast<Grammar>( eGrammar & ~kEnglishBit);
}
static inline Grammar mergeToGrammar( const Grammar eGrammar, const ScAddress::Convention eConv )
{
bool bEnglish = isEnglish( eGrammar);
Grammar eGram = static_cast<Grammar>(
extractFormulaLanguage( eGrammar) |
((eConv + kConventionOffset) << kConventionShift));
eGram = setEnglishBit( eGram, bEnglish);
DBG_ASSERT( isSupported( eGram), "ScCompilerGrammarMap::mergeToGrammar: unsupported grammar");
return eGram;
}
/// If grammar is of ODF 1.1
static inline bool isPODF( const Grammar eGrammar )
{
return extractFormulaLanguage( eGrammar) ==
::com::sun::star::sheet::FormulaLanguage::ODF_11;
}
/// If grammar is of ODFF
static inline bool isODFF( const Grammar eGrammar )
{
return extractFormulaLanguage( eGrammar) ==
::com::sun::star::sheet::FormulaLanguage::ODFF;
}
};
#endif // SC_GRAMMAR_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unowids.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:02:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_UNOWIDS_HXX
#define SC_UNOWIDS_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif
// WIDs for uno property maps,
// never stored in files
#define SC_WID_UNO_START 1200
#define SC_WID_UNO_CELLSTYL ( SC_WID_UNO_START + 0 )
#define SC_WID_UNO_CHCOLHDR ( SC_WID_UNO_START + 1 )
#define SC_WID_UNO_CHROWHDR ( SC_WID_UNO_START + 2 )
#define SC_WID_UNO_CONDFMT ( SC_WID_UNO_START + 3 )
#define SC_WID_UNO_CONDLOC ( SC_WID_UNO_START + 4 )
#define SC_WID_UNO_CONDXML ( SC_WID_UNO_START + 5 )
#define SC_WID_UNO_TBLBORD ( SC_WID_UNO_START + 6 )
#define SC_WID_UNO_VALIDAT ( SC_WID_UNO_START + 7 )
#define SC_WID_UNO_VALILOC ( SC_WID_UNO_START + 8 )
#define SC_WID_UNO_VALIXML ( SC_WID_UNO_START + 9 )
#define SC_WID_UNO_POS ( SC_WID_UNO_START + 10 )
#define SC_WID_UNO_SIZE ( SC_WID_UNO_START + 11 )
#define SC_WID_UNO_FORMLOC ( SC_WID_UNO_START + 12 )
#define SC_WID_UNO_FORMRT ( SC_WID_UNO_START + 13 )
#define SC_WID_UNO_PAGESTL ( SC_WID_UNO_START + 14 )
#define SC_WID_UNO_CELLVIS ( SC_WID_UNO_START + 15 )
#define SC_WID_UNO_LINKDISPBIT ( SC_WID_UNO_START + 16 )
#define SC_WID_UNO_LINKDISPNAME ( SC_WID_UNO_START + 17 )
#define SC_WID_UNO_CELLWID ( SC_WID_UNO_START + 18 )
#define SC_WID_UNO_OWIDTH ( SC_WID_UNO_START + 19 )
#define SC_WID_UNO_NEWPAGE ( SC_WID_UNO_START + 20 )
#define SC_WID_UNO_MANPAGE ( SC_WID_UNO_START + 21 )
#define SC_WID_UNO_CELLHGT ( SC_WID_UNO_START + 22 )
#define SC_WID_UNO_CELLFILT ( SC_WID_UNO_START + 23 )
#define SC_WID_UNO_OHEIGHT ( SC_WID_UNO_START + 24 )
#define SC_WID_UNO_DISPNAME ( SC_WID_UNO_START + 25 )
#define SC_WID_UNO_HEADERSET ( SC_WID_UNO_START + 26 )
#define SC_WID_UNO_FOOTERSET ( SC_WID_UNO_START + 27 )
#define SC_WID_UNO_NUMRULES ( SC_WID_UNO_START + 28 )
#define SC_WID_UNO_ISACTIVE ( SC_WID_UNO_START + 29 )
#define SC_WID_UNO_BORDCOL ( SC_WID_UNO_START + 30 )
#define SC_WID_UNO_PROTECT ( SC_WID_UNO_START + 31 )
#define SC_WID_UNO_SHOWBORD ( SC_WID_UNO_START + 32 )
#define SC_WID_UNO_PRINTBORD ( SC_WID_UNO_START + 33 )
#define SC_WID_UNO_COPYBACK ( SC_WID_UNO_START + 34 )
#define SC_WID_UNO_COPYSTYL ( SC_WID_UNO_START + 35 )
#define SC_WID_UNO_COPYFORM ( SC_WID_UNO_START + 36 )
#define SC_WID_UNO_TABLAYOUT ( SC_WID_UNO_START + 37 )
#define SC_WID_UNO_AUTOPRINT ( SC_WID_UNO_START + 38 )
#define SC_WID_UNO_END ( SC_WID_UNO_START + 38 )
inline BOOL IsScUnoWid( USHORT nWid )
{
return nWid >= SC_WID_UNO_START && nWid <= SC_WID_UNO_END;
}
inline BOOL IsScItemWid( USHORT nWid )
{
return nWid >= ATTR_STARTINDEX && nWid <= ATTR_ENDINDEX; // incl. page
}
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.6.10); FILE MERGED 2005/10/08 06:50:28 bm 1.6.10.2: RESYNC: (1.6-1.7); FILE MERGED 2004/05/05 14:47:36 sab 1.6.10.1: #i10734#; have access to the absolut name of every cellrange<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unowids.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2007-05-22 19:40:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_UNOWIDS_HXX
#define SC_UNOWIDS_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif
// WIDs for uno property maps,
// never stored in files
#define SC_WID_UNO_START 1200
#define SC_WID_UNO_CELLSTYL ( SC_WID_UNO_START + 0 )
#define SC_WID_UNO_CHCOLHDR ( SC_WID_UNO_START + 1 )
#define SC_WID_UNO_CHROWHDR ( SC_WID_UNO_START + 2 )
#define SC_WID_UNO_CONDFMT ( SC_WID_UNO_START + 3 )
#define SC_WID_UNO_CONDLOC ( SC_WID_UNO_START + 4 )
#define SC_WID_UNO_CONDXML ( SC_WID_UNO_START + 5 )
#define SC_WID_UNO_TBLBORD ( SC_WID_UNO_START + 6 )
#define SC_WID_UNO_VALIDAT ( SC_WID_UNO_START + 7 )
#define SC_WID_UNO_VALILOC ( SC_WID_UNO_START + 8 )
#define SC_WID_UNO_VALIXML ( SC_WID_UNO_START + 9 )
#define SC_WID_UNO_POS ( SC_WID_UNO_START + 10 )
#define SC_WID_UNO_SIZE ( SC_WID_UNO_START + 11 )
#define SC_WID_UNO_FORMLOC ( SC_WID_UNO_START + 12 )
#define SC_WID_UNO_FORMRT ( SC_WID_UNO_START + 13 )
#define SC_WID_UNO_PAGESTL ( SC_WID_UNO_START + 14 )
#define SC_WID_UNO_CELLVIS ( SC_WID_UNO_START + 15 )
#define SC_WID_UNO_LINKDISPBIT ( SC_WID_UNO_START + 16 )
#define SC_WID_UNO_LINKDISPNAME ( SC_WID_UNO_START + 17 )
#define SC_WID_UNO_CELLWID ( SC_WID_UNO_START + 18 )
#define SC_WID_UNO_OWIDTH ( SC_WID_UNO_START + 19 )
#define SC_WID_UNO_NEWPAGE ( SC_WID_UNO_START + 20 )
#define SC_WID_UNO_MANPAGE ( SC_WID_UNO_START + 21 )
#define SC_WID_UNO_CELLHGT ( SC_WID_UNO_START + 22 )
#define SC_WID_UNO_CELLFILT ( SC_WID_UNO_START + 23 )
#define SC_WID_UNO_OHEIGHT ( SC_WID_UNO_START + 24 )
#define SC_WID_UNO_DISPNAME ( SC_WID_UNO_START + 25 )
#define SC_WID_UNO_HEADERSET ( SC_WID_UNO_START + 26 )
#define SC_WID_UNO_FOOTERSET ( SC_WID_UNO_START + 27 )
#define SC_WID_UNO_NUMRULES ( SC_WID_UNO_START + 28 )
#define SC_WID_UNO_ISACTIVE ( SC_WID_UNO_START + 29 )
#define SC_WID_UNO_BORDCOL ( SC_WID_UNO_START + 30 )
#define SC_WID_UNO_PROTECT ( SC_WID_UNO_START + 31 )
#define SC_WID_UNO_SHOWBORD ( SC_WID_UNO_START + 32 )
#define SC_WID_UNO_PRINTBORD ( SC_WID_UNO_START + 33 )
#define SC_WID_UNO_COPYBACK ( SC_WID_UNO_START + 34 )
#define SC_WID_UNO_COPYSTYL ( SC_WID_UNO_START + 35 )
#define SC_WID_UNO_COPYFORM ( SC_WID_UNO_START + 36 )
#define SC_WID_UNO_TABLAYOUT ( SC_WID_UNO_START + 37 )
#define SC_WID_UNO_AUTOPRINT ( SC_WID_UNO_START + 38 )
#define SC_WID_UNO_ABSNAME ( SC_WID_UNO_START + 39 )
#define SC_WID_UNO_END ( SC_WID_UNO_START + 39 )
inline BOOL IsScUnoWid( USHORT nWid )
{
return nWid >= SC_WID_UNO_START && nWid <= SC_WID_UNO_END;
}
inline BOOL IsScItemWid( USHORT nWid )
{
return nWid >= ATTR_STARTINDEX && nWid <= ATTR_ENDINDEX; // incl. page
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015,2017-2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __BASE_CIRCLEBUF_HH__
#define __BASE_CIRCLEBUF_HH__
#include <algorithm>
#include <cassert>
#include <vector>
#include "base/circular_queue.hh"
#include "base/logging.hh"
#include "sim/serialize.hh"
/**
* Circular buffer backed by a vector though a CircularQueue.
*
* The data in the cricular buffer is stored in a standard
* vector.
*
*/
template<typename T>
class CircleBuf : public CircularQueue<T>
{
public:
explicit CircleBuf(size_t size)
: CircularQueue<T>(size) {}
using CircularQueue<T>::empty;
using CircularQueue<T>::size;
using CircularQueue<T>::capacity;
using CircularQueue<T>::begin;
using CircularQueue<T>::end;
using CircularQueue<T>::pop_front;
using CircularQueue<T>::advance_tail;
/**
* Copy buffer contents without advancing the read pointer
*
* @param out Output iterator/pointer
* @param len Number of elements to copy
*/
template <class OutputIterator>
void
peek(OutputIterator out, size_t len) const
{
peek(out, 0, len);
}
/**
* Copy buffer contents without advancing the read pointer
*
* @param out Output iterator/pointer
* @param offset Offset into the ring buffer
* @param len Number of elements to copy
*/
template <class OutputIterator>
void
peek(OutputIterator out, off_t offset, size_t len) const
{
panic_if(offset + len > size(),
"Trying to read past end of circular buffer.");
std::copy(begin() + offset, begin() + offset + len, out);
}
/**
* Copy buffer contents and advance the read pointer
*
* @param out Output iterator/pointer
* @param len Number of elements to read
*/
template <class OutputIterator>
void
read(OutputIterator out, size_t len)
{
peek(out, len);
pop_front(len);
}
/**
* Add elements to the end of the ring buffers and advance.
*
* @param in Input iterator/pointer
* @param len Number of elements to read
*/
template <class InputIterator>
void
write(InputIterator in, size_t len)
{
// Writes that are larger than the backing store are allowed,
// but only the last part of the buffer will be written.
if (len > capacity()) {
in += len - capacity();
len = capacity();
}
std::copy(in, in + len, end());
advance_tail(len);
}
};
/**
* Simple FIFO implementation backed by a circular buffer.
*
* This class provides the same basic functionallity as the circular
* buffer with the folling differences:
* <ul>
* <li>Writes are checked to ensure that overflows can't happen.
* <li>Unserialization ensures that the data in the checkpoint fits
* in the buffer.
* </ul>
*/
template<typename T>
class Fifo
{
public:
typedef T value_type;
public:
Fifo(size_t size) : buf(size) {}
bool empty() const { return buf.empty(); }
size_t size() const { return buf.size(); }
size_t capacity() const { return buf.capacity(); }
void flush() { buf.flush(); }
template <class OutputIterator>
void peek(OutputIterator out, size_t len) const { buf.peek(out, len); }
template <class OutputIterator>
void read(OutputIterator out, size_t len) { buf.read(out, len); }
template <class InputIterator>
void
write(InputIterator in, size_t len)
{
panic_if(size() + len > capacity(), "Trying to overfill FIFO buffer.");
buf.write(in, len);
}
private:
CircleBuf<value_type> buf;
};
template <typename T>
void
arrayParamOut(CheckpointOut &cp, const std::string &name,
const CircleBuf<T> ¶m)
{
std::vector<T> temp(param.size());
param.peek(temp.begin(), temp.size());
arrayParamOut(cp, name, temp);
}
template <typename T>
void
arrayParamIn(CheckpointIn &cp, const std::string &name, CircleBuf<T> ¶m)
{
std::vector<T> temp;
arrayParamIn(cp, name, temp);
param.flush();
param.write(temp.cbegin(), temp.size());
}
template <typename T>
void
arrayParamOut(CheckpointOut &cp, const std::string &name, const Fifo<T> ¶m)
{
std::vector<T> temp(param.size());
param.peek(temp.begin(), temp.size());
arrayParamOut(cp, name, temp);
}
template <typename T>
void
arrayParamIn(CheckpointIn &cp, const std::string &name, Fifo<T> ¶m)
{
std::vector<T> temp;
arrayParamIn(cp, name, temp);
fatal_if(param.capacity() < temp.size(),
"Trying to unserialize data into too small FIFO");
param.flush();
param.write(temp.cbegin(), temp.size());
}
#endif // __BASE_CIRCLEBUF_HH__
<commit_msg>base: Re-implement CircleBuf without using CircularQueue.<commit_after>/*
* Copyright (c) 2015,2017-2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __BASE_CIRCLEBUF_HH__
#define __BASE_CIRCLEBUF_HH__
#include <algorithm>
#include <cassert>
#include <iterator>
#include <vector>
#include "base/logging.hh"
#include "sim/serialize.hh"
/**
* Circular buffer backed by a vector.
*
* The data in the cricular buffer is stored in a standard vector.
*/
template<typename T>
class CircleBuf
{
private:
std::vector<T> buffer;
size_t start = 0;
size_t used = 0;
size_t maxSize;
public:
using value_type = T;
using iterator = typename std::vector<T>::iterator;
using const_iterator = typename std::vector<T>::const_iterator;
explicit CircleBuf(size_t size) : buffer(size), maxSize(size) {}
bool empty() const { return used == 0; }
size_t size() const { return used; }
size_t capacity() const { return maxSize; }
iterator begin() { return buffer.begin() + start % maxSize; }
const_iterator begin() const { return buffer.begin() + start % maxSize; }
iterator end() { return buffer.begin() + (start + used) % maxSize; }
const_iterator
end() const
{
return buffer.begin() + (start + used) % maxSize;
}
/**
* Throw away any data in the buffer.
*/
void
flush()
{
start = 0;
used = 0;
}
/**
* Copy buffer contents without advancing the read pointer
*
* @param out Output iterator/pointer
* @param len Number of elements to copy
*/
template <class OutputIterator>
void
peek(OutputIterator out, size_t len) const
{
peek(out, 0, len);
}
/**
* Copy buffer contents without advancing the read pointer
*
* @param out Output iterator/pointer
* @param offset Offset into the ring buffer
* @param len Number of elements to copy
*/
template <class OutputIterator>
void
peek(OutputIterator out, off_t offset, size_t len) const
{
panic_if(offset + len > used,
"Trying to read past end of circular buffer.");
if (!len)
return;
// The iterator for the next byte to copy out.
auto next_it = buffer.begin() + (start + offset) % maxSize;
// How much there is to copy from until the end of the buffer.
const size_t to_end = buffer.end() - next_it;
// If the data to be copied wraps, take care of the first part.
if (to_end < len) {
// Copy it.
out = std::copy_n(next_it, to_end, out);
// Start copying again at the start of buffer.
next_it = buffer.begin();
len -= to_end;
}
// Copy the remaining (or only) chunk of data.
std::copy_n(next_it, len, out);
}
/**
* Copy buffer contents and advance the read pointer
*
* @param out Output iterator/pointer
* @param len Number of elements to read
*/
template <class OutputIterator>
void
read(OutputIterator out, size_t len)
{
peek(out, len);
used -= len;
start += len;
}
/**
* Add elements to the end of the ring buffers and advance. Writes which
* would exceed the capacity of the queue fill the avaialble space, and
* then continue overwriting the head of the queue. The head advances as
* if that data had been read out.
*
* @param in Input iterator/pointer
* @param len Number of elements to read
*/
template <class InputIterator>
void
write(InputIterator in, size_t len)
{
if (!len)
return;
// Writes that are larger than the buffer size are allowed, but only
// the last part of the date will be written since the rest will be
// overwritten and not remain in the buffer.
if (len > maxSize) {
in += len - maxSize;
flush();
len = maxSize;
}
// How much existing data will be overwritten?
const size_t overflow = std::max<size_t>(0, used + len - maxSize);
// The iterator of the next byte to add.
auto next_it = buffer.begin() + (start + used) % maxSize;
// How much there is to copy to the end of the buffer.
const size_t to_end = buffer.end() - next_it;
// If this addition wraps, take care of the first part here.
if (to_end < len) {
// Copy it.
std::copy_n(in, to_end, next_it);
// Update state to reflect what's left.
next_it = buffer.begin();
std::advance(in, to_end);
len -= to_end;
used += to_end;
}
// Copy the remaining (or only) chunk of data.
std::copy_n(in, len, next_it);
used += len;
// Don't count data that was overwritten.
used -= overflow;
start += overflow;
}
};
/**
* Simple FIFO implementation backed by a circular buffer.
*
* This class provides the same basic functionallity as the circular
* buffer with the folling differences:
* <ul>
* <li>Writes are checked to ensure that overflows can't happen.
* <li>Unserialization ensures that the data in the checkpoint fits
* in the buffer.
* </ul>
*/
template<typename T>
class Fifo
{
public:
typedef T value_type;
public:
Fifo(size_t size) : buf(size) {}
bool empty() const { return buf.empty(); }
size_t size() const { return buf.size(); }
size_t capacity() const { return buf.capacity(); }
void flush() { buf.flush(); }
template <class OutputIterator>
void peek(OutputIterator out, size_t len) const { buf.peek(out, len); }
template <class OutputIterator>
void read(OutputIterator out, size_t len) { buf.read(out, len); }
template <class InputIterator>
void
write(InputIterator in, size_t len)
{
panic_if(size() + len > capacity(), "Trying to overfill FIFO buffer.");
buf.write(in, len);
}
private:
CircleBuf<value_type> buf;
};
template <typename T>
void
arrayParamOut(CheckpointOut &cp, const std::string &name,
const CircleBuf<T> ¶m)
{
std::vector<T> temp(param.size());
param.peek(temp.begin(), temp.size());
arrayParamOut(cp, name, temp);
}
template <typename T>
void
arrayParamIn(CheckpointIn &cp, const std::string &name, CircleBuf<T> ¶m)
{
std::vector<T> temp;
arrayParamIn(cp, name, temp);
param.flush();
param.write(temp.cbegin(), temp.size());
}
template <typename T>
void
arrayParamOut(CheckpointOut &cp, const std::string &name, const Fifo<T> ¶m)
{
std::vector<T> temp(param.size());
param.peek(temp.begin(), temp.size());
arrayParamOut(cp, name, temp);
}
template <typename T>
void
arrayParamIn(CheckpointIn &cp, const std::string &name, Fifo<T> ¶m)
{
std::vector<T> temp;
arrayParamIn(cp, name, temp);
fatal_if(param.capacity() < temp.size(),
"Trying to unserialize data into too small FIFO");
param.flush();
param.write(temp.cbegin(), temp.size());
}
#endif // __BASE_CIRCLEBUF_HH__
<|endoftext|>
|
<commit_before>/*
This file is part of qNotesManager.
qNotesManager 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.
qNotesManager 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 qNotesManager. If not, see <http://www.gnu.org/licenses/>.
*/
#include "basemodelitem.h"
#include "basemodel.h"
#ifdef DEBUG
#include <QDebug>
#endif
using namespace qNotesManager;
BaseModelItem::BaseModelItem(ItemType type)
: itemType(type)
{
parentItem = 0;
sorted = false;
sortOrder = Qt::AscendingOrder;
}
BaseModelItem::~BaseModelItem() {
Clear();
}
// Return item parent or 0 if there is none.
BaseModelItem* BaseModelItem::parent() const {
return parentItem;
}
/* virtual */
// Returns item flags
Qt::ItemFlags BaseModelItem::flags () const {
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
// Adds item 'item' into the end children list.
// It is supposed that 'item' is a valid pointer.
void BaseModelItem::AddChild(BaseModelItem* item) {
Q_ASSERT(item != 0);
Q_ASSERT(!childrenList.contains(item));
Q_ASSERT(item->parentItem == 0);
AddChildTo(item, childrenList.size());
}
// Adds item 'item' into children list in specified position.
// It is supposed that 'item' is a valid pointer.
// NOTE: 'position' parameter is ignored when sorting is enabled
void BaseModelItem::AddChildTo(BaseModelItem* item, int position) {
Q_ASSERT(item != 0);
Q_ASSERT(!childrenList.contains(item));
Q_ASSERT(item->parentItem == 0);
Q_ASSERT(position >= 0 && position <= childrenList.size());
childrenList.insert(position, item);
item->parentItem = this;
insertIndexCache.Clear();
}
// Removes child item
// It is supposed that 'item' is a valid pointer.
void BaseModelItem::RemoveChild(BaseModelItem* item) {
Q_ASSERT(item != 0);
Q_ASSERT(childrenList.contains(item));
childrenList.removeAll(item);
item->parentItem = 0;
insertIndexCache.Clear();
}
// Returns index of child item. It is supposed that 'item' is actually child item.
// It is supposed that 'item' is a valid pointer.
int BaseModelItem::IndexOfChild(BaseModelItem* item) const {
Q_ASSERT(item != 0);
Q_ASSERT(childrenList.contains(item));
return childrenList.indexOf(item);
}
// Returns children count
int BaseModelItem::ChildrenCount() const {
return childrenList.count();
}
// Returns child item at position 'index'. It is supposed that 'index' is valid index
BaseModelItem* BaseModelItem::ChildAt(int index) const {
Q_ASSERT(index >= 0 && index < childrenList.count());
return childrenList.at(index);
}
void BaseModelItem::Clear() {
for (int i = 0; i < childrenList.count(); ++i) {
delete childrenList.at(i);
childrenList[i] = 0;
}
childrenList.clear();
insertIndexCache.Clear();
}
// Returns true if object is a child or a grandchild of item 'parent', otherwise returns false.
// It is supposed that 'parent' is a valid pointer.
bool BaseModelItem::IsOffspringOf(const BaseModelItem* parent) const {
Q_ASSERT(parent != 0);
if (parent == this) {return false;}
const BaseModelItem* f = parent;
while (f != 0) {
if (f == parent) {return true;}
f = f->parent();
}
return false;
}
BaseModelItem::ItemType BaseModelItem::DataType() const {
return itemType;
}
QVariant BaseModelItem::data(int role) const {
return QVariant();
}
// Returns index where a new item will be inserted with AddChild()
// It is supposed that 'item' is a valid pointer.
int BaseModelItem::FindInsertIndex(const BaseModelItem* item) const {
Q_ASSERT(item != 0);
int newIndex = -1;
// Cached index. Mechanism not finished
//if (insertIndexCache.IsValid() && insertIndexCache.prt == item) {
//return insertIndexCache.cachedIndex;
//}
if (sorted) {
newIndex = findInsertIndex_Sorted(item);
} else {
newIndex = findInsertIndex_Simple(item);
}
//insertIndexCache.Set(item, newIndex);
return newIndex;
}
//int BaseModelItem::FindInsertIndex(const BaseModelItem* item, const int suggestedIndex) const {}
// virtual
// Compares internal item data for sorting purpose. Returns true by default.
// It is supposed that 'item' is a valid pointer.
bool BaseModelItem::LessThan(const BaseModelItem*) const {
return true;
}
// Returns index for a new item when list is sorted
// It is supposed that 'item' is a valid pointer.
int BaseModelItem::findInsertIndex_Sorted(const BaseModelItem* item) const {
// TODO: add anchors handling
// TODO: handle Qt::DescendingOrder
Q_ASSERT(item != 0);
const int size = ChildrenCount();
if (size == 0) {return 0;}
if (item->LessThan(ChildAt(0))) {return 0;}
if (ChildAt(size - 1)->LessThan(item)) {return size;}
int index = 0;
int left = 1;
int right = size - 1;
while (true) {
index = (left + right) / 2;
BaseModelItem* leftItem = ChildAt(index - 1);
BaseModelItem* rightItem = ChildAt(index);
if (leftItem->LessThan(item) && item->LessThan(rightItem)) {
break;
} else if (rightItem->LessThan(item)) {
left = index + 1;
} else if (item->LessThan(leftItem)) {
right = index - 1;
} else {
break;
}
}
return index;
}
// Returns index for a new item when list is not sorted
// It is supposed that 'item' is a valid pointer.
int BaseModelItem::findInsertIndex_Simple(const BaseModelItem* item) const {
// TODO: add anchors handling
return ChildrenCount();
}
// Returns true if children list is sorted, otherwise returns false
bool BaseModelItem::IsSorted() const {
return sorted;
}
// Sets children list sorting
// NOTE: Sorting may be changed only when children list is empty
void BaseModelItem::SetSorted(const bool s) {
if (ChildrenCount() == 0) {
sorted = s;
}
}
// Returns children list sorting order
Qt::SortOrder BaseModelItem::GetSortOrder() const {
return sortOrder;
}
// Sets children list sorting order
// NOTE: Sort order may be changed only when children list is empty
void BaseModelItem::SetSortOrder(const Qt::SortOrder order) {
if (ChildrenCount() == 0) {
sortOrder = order;
}
}
<commit_msg>Fixed 'index out of range' bug<commit_after>/*
This file is part of qNotesManager.
qNotesManager 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.
qNotesManager 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 qNotesManager. If not, see <http://www.gnu.org/licenses/>.
*/
#include "basemodelitem.h"
#include "basemodel.h"
#ifdef DEBUG
#include <QDebug>
#endif
using namespace qNotesManager;
BaseModelItem::BaseModelItem(ItemType type)
: itemType(type)
{
parentItem = 0;
sorted = false;
sortOrder = Qt::AscendingOrder;
}
BaseModelItem::~BaseModelItem() {
Clear();
}
// Return item parent or 0 if there is none.
BaseModelItem* BaseModelItem::parent() const {
return parentItem;
}
/* virtual */
// Returns item flags
Qt::ItemFlags BaseModelItem::flags () const {
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
// Adds item 'item' into the end children list.
// It is supposed that 'item' is a valid pointer.
void BaseModelItem::AddChild(BaseModelItem* item) {
Q_ASSERT(item != 0);
Q_ASSERT(!childrenList.contains(item));
Q_ASSERT(item->parentItem == 0);
AddChildTo(item, childrenList.size());
}
// Adds item 'item' into children list in specified position.
// It is supposed that 'item' is a valid pointer.
// NOTE: 'position' parameter is ignored when sorting is enabled
void BaseModelItem::AddChildTo(BaseModelItem* item, int position) {
Q_ASSERT(item != 0);
Q_ASSERT(!childrenList.contains(item));
Q_ASSERT(item->parentItem == 0);
Q_ASSERT(position >= 0 && position <= childrenList.size());
childrenList.insert(position, item);
item->parentItem = this;
insertIndexCache.Clear();
}
// Removes child item
// It is supposed that 'item' is a valid pointer.
void BaseModelItem::RemoveChild(BaseModelItem* item) {
Q_ASSERT(item != 0);
Q_ASSERT(childrenList.contains(item));
childrenList.removeAll(item);
item->parentItem = 0;
insertIndexCache.Clear();
}
// Returns index of child item. It is supposed that 'item' is actually child item.
// It is supposed that 'item' is a valid pointer.
int BaseModelItem::IndexOfChild(BaseModelItem* item) const {
Q_ASSERT(item != 0);
Q_ASSERT(childrenList.contains(item));
return childrenList.indexOf(item);
}
// Returns children count
int BaseModelItem::ChildrenCount() const {
return childrenList.count();
}
// Returns child item at position 'index'. It is supposed that 'index' is valid index
BaseModelItem* BaseModelItem::ChildAt(int index) const {
if (!(index >= 0 && index < childrenList.count())) {
qWarning("Item at non-existent index requested");
return 0;
}
return childrenList.at(index);
}
void BaseModelItem::Clear() {
for (int i = 0; i < childrenList.count(); ++i) {
delete childrenList.at(i);
childrenList[i] = 0;
}
childrenList.clear();
insertIndexCache.Clear();
}
// Returns true if object is a child or a grandchild of item 'parent', otherwise returns false.
// It is supposed that 'parent' is a valid pointer.
bool BaseModelItem::IsOffspringOf(const BaseModelItem* parent) const {
Q_ASSERT(parent != 0);
if (parent == this) {return false;}
const BaseModelItem* f = parent;
while (f != 0) {
if (f == parent) {return true;}
f = f->parent();
}
return false;
}
BaseModelItem::ItemType BaseModelItem::DataType() const {
return itemType;
}
QVariant BaseModelItem::data(int role) const {
return QVariant();
}
// Returns index where a new item will be inserted with AddChild()
// It is supposed that 'item' is a valid pointer.
int BaseModelItem::FindInsertIndex(const BaseModelItem* item) const {
Q_ASSERT(item != 0);
int newIndex = -1;
// Cached index. Mechanism not finished
//if (insertIndexCache.IsValid() && insertIndexCache.prt == item) {
//return insertIndexCache.cachedIndex;
//}
if (sorted) {
newIndex = findInsertIndex_Sorted(item);
} else {
newIndex = findInsertIndex_Simple(item);
}
//insertIndexCache.Set(item, newIndex);
return newIndex;
}
//int BaseModelItem::FindInsertIndex(const BaseModelItem* item, const int suggestedIndex) const {}
// virtual
// Compares internal item data for sorting purpose. Returns true by default.
// It is supposed that 'item' is a valid pointer.
bool BaseModelItem::LessThan(const BaseModelItem*) const {
return true;
}
// Returns index for a new item when list is sorted
// It is supposed that 'item' is a valid pointer.
int BaseModelItem::findInsertIndex_Sorted(const BaseModelItem* item) const {
// TODO: add anchors handling
// TODO: handle Qt::DescendingOrder
Q_ASSERT(item != 0);
const int size = ChildrenCount();
if (size == 0) {return 0;}
if (item->LessThan(ChildAt(0))) {return 0;}
if (ChildAt(size - 1)->LessThan(item)) {return size;}
int index = 0;
int left = 1;
int right = size - 1;
while (true) {
index = (left + right) / 2;
if (index == 0 || index == size) {
break;
}
BaseModelItem* leftItem = ChildAt(index - 1);
BaseModelItem* rightItem = ChildAt(index);
if (leftItem->LessThan(item) && item->LessThan(rightItem)) {
break;
} else if (rightItem->LessThan(item)) {
left = index + 1;
} else if (item->LessThan(leftItem)) {
right = index - 1;
} else {
break;
}
}
return index;
}
// Returns index for a new item when list is not sorted
// It is supposed that 'item' is a valid pointer.
int BaseModelItem::findInsertIndex_Simple(const BaseModelItem* item) const {
// TODO: add anchors handling
return ChildrenCount();
}
// Returns true if children list is sorted, otherwise returns false
bool BaseModelItem::IsSorted() const {
return sorted;
}
// Sets children list sorting
// NOTE: Sorting may be changed only when children list is empty
void BaseModelItem::SetSorted(const bool s) {
if (ChildrenCount() == 0) {
sorted = s;
}
}
// Returns children list sorting order
Qt::SortOrder BaseModelItem::GetSortOrder() const {
return sortOrder;
}
// Sets children list sorting order
// NOTE: Sort order may be changed only when children list is empty
void BaseModelItem::SetSortOrder(const Qt::SortOrder order) {
if (ChildrenCount() == 0) {
sortOrder = order;
}
}
<|endoftext|>
|
<commit_before>/*-
* Copyright (c) 2015 Masayoshi Mizutani <mizutani@sfc.wide.ad.jp>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sstream>
#include <sys/time.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include "./fluent/logger.hpp"
#include "./fluent/message.hpp"
#include "./fluent/emitter.hpp"
#include "./debug.h"
namespace fluent {
Logger::Logger() {
#ifdef _WIN32
#ifndef FLUENTSKIPSTARTWINSOCK
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 2);
WSAStartup(wVersionRequested, &wsaData);
#endif // FLUENTSKIPSTARTWINSOCK
#endif // _WIN32
}
Logger::~Logger() {
// delete not used messages.
for (auto it = this->msg_set_.begin(); it != this->msg_set_.end(); it++) {
delete *it;
}
for (size_t i = 0; i < this->emitter_.size(); i++) {
delete this->emitter_[i];
}
std::for_each(this->queue_.begin(), this->queue_.end(),
[](MsgQueue* const &x) { delete x; });
#ifdef _WIN32
#ifndef FLUENTSKIPSTARTWINSOCK
WSACleanup();
#endif // FLUENTSKIPSTARTWINSOCK
#endif // _WIN32
}
void Logger::new_forward(const std::string &host, int port) {
Emitter *e = new InetEmitter(host, port);
this->emitter_.push_back(e);
}
void Logger::new_forward(const std::string &host, const std::string &port) {
Emitter *e = new InetEmitter(host, port);
this->emitter_.push_back(e);
}
void Logger::new_dumpfile(const std::string &fname) {
Emitter *e = new FileEmitter(fname, FileEmitter::MsgPack);
this->emitter_.push_back(e);
}
void Logger::new_dumpfile(int fd) {
Emitter *e = new FileEmitter(fd, FileEmitter::MsgPack);
this->emitter_.push_back(e);
}
void Logger::new_textfile(const std::string &fname) {
Emitter *e = new FileEmitter(fname, FileEmitter::Text);
this->emitter_.push_back(e);
}
void Logger::new_textfile(int fd) {
Emitter *e = new FileEmitter(fd, FileEmitter::Text);
this->emitter_.push_back(e);
}
MsgQueue* Logger::new_msgqueue() {
MsgQueue *q = new MsgQueue();
this->queue_.push_back(q);
Emitter *e = new QueueEmitter(q);
this->emitter_.push_back(e);
return q;
}
Message* Logger::retain_message(const std::string &tag) {
Message *msg;
if (this->tag_prefix_.empty()) {
msg = new Message(tag);
} else {
std::string cattag = this->tag_prefix_ + "." + tag;
msg = new Message(cattag);
}
this->msg_set_.insert(msg);
return msg;
}
bool Logger::emit(Message *msg) {
if (this->msg_set_.find(msg) == this->msg_set_.end()) {
this->errmsg_ = "invalid Message instance, "
"should be got by Logger::retain_message()";
return false;
}
this->msg_set_.erase(msg);
bool rc = true;
if (this->emitter_.size() == 1) {
rc = this->emitter_[0]->emit(msg);
} else if (this->emitter_.size() > 1) {
for (size_t i = 0; i < this->emitter_.size() - 1; i++) {
Message *cloned_msg = msg->clone();
rc &= this->emitter_[i]->emit(cloned_msg);
}
rc &= this->emitter_[this->emitter_.size() - 1]->emit(msg);
}
return rc;
}
void Logger::set_queue_limit(size_t limit) {
for (size_t i = 0; i < this->emitter_.size(); i++) {
this->emitter_[i]->set_queue_limit(limit);
}
}
void Logger::set_tag_prefix(const std::string &tag_prefix) {
this->tag_prefix_ = tag_prefix;
}
}
<commit_msg>Fix memory leak when logger has no output<commit_after>/*-
* Copyright (c) 2015 Masayoshi Mizutani <mizutani@sfc.wide.ad.jp>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sstream>
#include <sys/time.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include "./fluent/logger.hpp"
#include "./fluent/message.hpp"
#include "./fluent/emitter.hpp"
#include "./debug.h"
namespace fluent {
Logger::Logger() {
#ifdef _WIN32
#ifndef FLUENTSKIPSTARTWINSOCK
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 2);
WSAStartup(wVersionRequested, &wsaData);
#endif // FLUENTSKIPSTARTWINSOCK
#endif // _WIN32
}
Logger::~Logger() {
// delete not used messages.
for (auto it = this->msg_set_.begin(); it != this->msg_set_.end(); it++) {
delete *it;
}
for (size_t i = 0; i < this->emitter_.size(); i++) {
delete this->emitter_[i];
}
std::for_each(this->queue_.begin(), this->queue_.end(),
[](MsgQueue* const &x) { delete x; });
#ifdef _WIN32
#ifndef FLUENTSKIPSTARTWINSOCK
WSACleanup();
#endif // FLUENTSKIPSTARTWINSOCK
#endif // _WIN32
}
void Logger::new_forward(const std::string &host, int port) {
Emitter *e = new InetEmitter(host, port);
this->emitter_.push_back(e);
}
void Logger::new_forward(const std::string &host, const std::string &port) {
Emitter *e = new InetEmitter(host, port);
this->emitter_.push_back(e);
}
void Logger::new_dumpfile(const std::string &fname) {
Emitter *e = new FileEmitter(fname, FileEmitter::MsgPack);
this->emitter_.push_back(e);
}
void Logger::new_dumpfile(int fd) {
Emitter *e = new FileEmitter(fd, FileEmitter::MsgPack);
this->emitter_.push_back(e);
}
void Logger::new_textfile(const std::string &fname) {
Emitter *e = new FileEmitter(fname, FileEmitter::Text);
this->emitter_.push_back(e);
}
void Logger::new_textfile(int fd) {
Emitter *e = new FileEmitter(fd, FileEmitter::Text);
this->emitter_.push_back(e);
}
MsgQueue* Logger::new_msgqueue() {
MsgQueue *q = new MsgQueue();
this->queue_.push_back(q);
Emitter *e = new QueueEmitter(q);
this->emitter_.push_back(e);
return q;
}
Message* Logger::retain_message(const std::string &tag) {
Message *msg;
if (this->tag_prefix_.empty()) {
msg = new Message(tag);
} else {
std::string cattag = this->tag_prefix_ + "." + tag;
msg = new Message(cattag);
}
this->msg_set_.insert(msg);
return msg;
}
bool Logger::emit(Message *msg) {
if (this->msg_set_.find(msg) == this->msg_set_.end()) {
this->errmsg_ = "invalid Message instance, "
"should be got by Logger::retain_message()";
return false;
}
this->msg_set_.erase(msg);
bool rc = true;
if (this->emitter_.size() == 1) {
rc = this->emitter_[0]->emit(msg);
} else if (this->emitter_.size() > 1) {
for (size_t i = 0; i < this->emitter_.size() - 1; i++) {
Message *cloned_msg = msg->clone();
rc &= this->emitter_[i]->emit(cloned_msg);
}
rc &= this->emitter_[this->emitter_.size() - 1]->emit(msg);
} else {
// no output
delete msg;
}
return rc;
}
void Logger::set_queue_limit(size_t limit) {
for (size_t i = 0; i < this->emitter_.size(); i++) {
this->emitter_[i]->set_queue_limit(limit);
}
}
void Logger::set_tag_prefix(const std::string &tag_prefix) {
this->tag_prefix_ = tag_prefix;
}
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_COMMON_EXCEPTIONS_HH
#define DUNE_STUFF_COMMON_EXCEPTIONS_HH
#include <dune/common/exceptions.hh>
#include <dune/common/parallel/mpihelper.hh>
#include <dune/common/deprecated.hh>
#ifdef DUNE_THROW
# undef DUNE_THROW
#endif
/**
* \brief Macro to throw a colorfull exception.
*
* Example:
\code
#include <dune/stuff/common/exceptions.hh>
if (a.size() != b.size())
DUNE_THROW(Exceptions::shapes_do_not_match,
"size of a (" << a.size() << ") does not match the size of b (" << b.size() << ")!");
\endcode
* This macro is essentially copied from dune-common with added color functionality and rank information.
* \param E Exception class, derived from Dune::Exception.
* \param m Message in ostream notation.
* \see Dune::Exception
*/
#define DUNE_THROW(E, m) \
do { \
const std::string th__red = "\033[31m"; \
const std::string th__brown = "\033[33m"; \
const std::string th__clear = "\033[0m"; \
E th__ex; \
std::ostringstream th__msg; \
th__msg << m; \
std::ostringstream th__out; \
th__out << th__red << # E << th__clear; \
if (Dune::MPIHelper::getCollectiveCommunication().size() > 1) \
th__out << " (on rank " << Dune::MPIHelper::getCollectiveCommunication().rank() << ")"; \
th__out << "\n"; \
th__out << th__brown << "[" << th__clear; \
th__out << th__red << __func__ << th__clear; \
th__out << th__brown << "|" << th__clear; \
th__out << __FILE__ << th__brown << ":" << th__clear << th__red << __LINE__ << th__clear << th__brown << "]" << th__clear; \
if (!th__msg.str().empty()) th__out << "\n" << th__brown << "=>" << th__clear << " " << th__msg.str(); \
th__ex.message(th__out.str()); \
throw th__ex; \
} while (0)
// DUNE_THROW
#define DUNE_THROW_COLORFULLY(E, m) \
do { \
const std::string th__red __attribute__((deprecated)) /* use DUNE_THROW instead! */ = "\033[31m"; \
const std::string th__brown = "\033[33m"; \
const std::string th__clear = "\033[0m"; \
E th__ex; \
std::ostringstream th__msg; \
th__msg << m; \
std::ostringstream th__out; \
th__out << th__red << # E << th__clear; \
if (Dune::MPIHelper::getCollectiveCommunication().size() > 1) \
th__out << " (on rank " << Dune::MPIHelper::getCollectiveCommunication().rank() << ")"; \
th__out << "\n"; \
th__out << th__brown << "[" << th__clear; \
th__out << th__red << __func__ << th__clear; \
th__out << th__brown << "|" << th__clear; \
th__out << __FILE__ << th__brown << ":" << th__clear << th__red << __LINE__ << th__clear << th__brown << "]" << th__clear; \
if (!th__msg.str().empty()) th__out << "\n" << th__brown << "=>" << th__clear << " " << th__msg.str(); \
th__ex.message(th__out.str()); \
throw th__ex; \
} while (0)
// DUNE_THROW_COLORFULLY
namespace Dune {
namespace Stuff {
namespace Exceptions {
class CRTP_check_failed : public Dune::Exception {};
class shapes_do_not_match : public Dune::Exception {};
class index_out_of_range : public Dune::Exception {};
class you_are_using_this_wrong : public Dune::Exception {};
class wrong_input_given : public you_are_using_this_wrong {};
class requirements_not_met: public you_are_using_this_wrong {};
class configuration_error : public Dune::Exception {};
class results_are_not_as_expected : public Dune::Exception {};
class internal_error : public Dune::Exception {};
class external_error : public Dune::Exception {};
class linear_solver_failed : public Dune::Exception {};
class you_have_to_implement_this : public Dune::NotImplemented {};
class
DUNE_DEPRECATED_MSG("Use something like 'EXPECT_TRUE(false) << \"test results missing for type: \" << type;' (08.09.2014)!")
test_results_missing : public Dune::NotImplemented {};
} // namespace Exceptions
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_EXCEPTIONS_HH
<commit_msg>[common.exceptions] add conversion_error<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_COMMON_EXCEPTIONS_HH
#define DUNE_STUFF_COMMON_EXCEPTIONS_HH
#include <dune/common/exceptions.hh>
#include <dune/common/parallel/mpihelper.hh>
#include <dune/common/deprecated.hh>
#ifdef DUNE_THROW
# undef DUNE_THROW
#endif
/**
* \brief Macro to throw a colorfull exception.
*
* Example:
\code
#include <dune/stuff/common/exceptions.hh>
if (a.size() != b.size())
DUNE_THROW(Exceptions::shapes_do_not_match,
"size of a (" << a.size() << ") does not match the size of b (" << b.size() << ")!");
\endcode
* This macro is essentially copied from dune-common with added color functionality and rank information.
* \param E Exception class, derived from Dune::Exception.
* \param m Message in ostream notation.
* \see Dune::Exception
*/
#define DUNE_THROW(E, m) \
do { \
const std::string th__red = "\033[31m"; \
const std::string th__brown = "\033[33m"; \
const std::string th__clear = "\033[0m"; \
E th__ex; \
std::ostringstream th__msg; \
th__msg << m; \
std::ostringstream th__out; \
th__out << th__red << # E << th__clear; \
if (Dune::MPIHelper::getCollectiveCommunication().size() > 1) \
th__out << " (on rank " << Dune::MPIHelper::getCollectiveCommunication().rank() << ")"; \
th__out << "\n"; \
th__out << th__brown << "[" << th__clear; \
th__out << th__red << __func__ << th__clear; \
th__out << th__brown << "|" << th__clear; \
th__out << __FILE__ << th__brown << ":" << th__clear << th__red << __LINE__ << th__clear << th__brown << "]" << th__clear; \
if (!th__msg.str().empty()) th__out << "\n" << th__brown << "=>" << th__clear << " " << th__msg.str(); \
th__ex.message(th__out.str()); \
throw th__ex; \
} while (0)
// DUNE_THROW
#define DUNE_THROW_COLORFULLY(E, m) \
do { \
const std::string th__red __attribute__((deprecated)) /* use DUNE_THROW instead! */ = "\033[31m"; \
const std::string th__brown = "\033[33m"; \
const std::string th__clear = "\033[0m"; \
E th__ex; \
std::ostringstream th__msg; \
th__msg << m; \
std::ostringstream th__out; \
th__out << th__red << # E << th__clear; \
if (Dune::MPIHelper::getCollectiveCommunication().size() > 1) \
th__out << " (on rank " << Dune::MPIHelper::getCollectiveCommunication().rank() << ")"; \
th__out << "\n"; \
th__out << th__brown << "[" << th__clear; \
th__out << th__red << __func__ << th__clear; \
th__out << th__brown << "|" << th__clear; \
th__out << __FILE__ << th__brown << ":" << th__clear << th__red << __LINE__ << th__clear << th__brown << "]" << th__clear; \
if (!th__msg.str().empty()) th__out << "\n" << th__brown << "=>" << th__clear << " " << th__msg.str(); \
th__ex.message(th__out.str()); \
throw th__ex; \
} while (0)
// DUNE_THROW_COLORFULLY
namespace Dune {
namespace Stuff {
namespace Exceptions {
class CRTP_check_failed : public Dune::Exception {};
class shapes_do_not_match : public Dune::Exception {};
class index_out_of_range : public Dune::Exception {};
class you_are_using_this_wrong : public Dune::Exception {};
class wrong_input_given : public you_are_using_this_wrong {};
class requirements_not_met: public you_are_using_this_wrong {};
class configuration_error : public Dune::Exception {};
class conversion_error : public Dune::Exception {};
class results_are_not_as_expected : public Dune::Exception {};
class internal_error : public Dune::Exception {};
class external_error : public Dune::Exception {};
class linear_solver_failed : public Dune::Exception {};
class you_have_to_implement_this : public Dune::NotImplemented {};
class
DUNE_DEPRECATED_MSG("Use something like 'EXPECT_TRUE(false) << \"test results missing for type: \" << type;' (08.09.2014)!")
test_results_missing : public Dune::NotImplemented {};
} // namespace Exceptions
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_EXCEPTIONS_HH
<|endoftext|>
|
<commit_before>#include <BST.hpp>
#include <catch.hpp>
#include <fstream>
SCENARIO ("init", "[init]")
{
BST<int> test;
REQUIRE(test.getroot() == nullptr);
REQUIRE(test.getcount() == 0);
}
SCENARIO("insert", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.search(10, test.getroot()) != 0);
}
SCENARIO("find_node", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.search(10, test.getroot()) != 0);
REQUIRE(test.search(10, test.getroot()) != 0);
}
SCENARIO("get root", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.getcount() == 1);
REQUIRE(test.getroot() != 0);
}
SCENARIO ("test1", "[init]")
{
BST<int> test;
ofstream testfile("testfile.txt");
testfile << "2 1 9 5";
testfile.close();
test.input("testfile.txt");
REQUIRE(test.getcount() == 3);
}
/*
SCENARIO("del", "[init]")
{
BST<int> test;
test.add(1);
test.add(2);
test.add(3);
test.del(test.getroot(), 1);
test.del(test.getroot(), 2);
REQUIRE(test.search(1, test.getroot()) != 0);
REQUIRE(test.search(2, test.getroot()) == 0);
REQUIRE(test.search(3, test.getroot())!= 0);
}
*/
<commit_msg>Create init.cpp<commit_after>#include <BST.hpp>
#include <catch.hpp>
#include <fstream>
SCENARIO ("init", "[init]")
{
BST<int> test;
REQUIRE(test.getroot() == nullptr);
REQUIRE(test.getcount() == 0);
}
SCENARIO("insert", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.search(10, test.getroot()) != 0);
}
SCENARIO("find_node", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.search(10, test.getroot()) != 0);
REQUIRE(test.search(10, test.getroot()) != 0);
}
SCENARIO("get root", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.getcount() == 1);
REQUIRE(test.getroot() != 0);
}
SCENARIO ("test1", "[init]")
{
BST<int> test;
ofstream testfile("testfile.txt");
testfile << "2 1 9";
testfile.close();
test.input("testfile.txt");
REQUIRE(test.getcount() == 3);
}
/*
SCENARIO("del", "[init]")
{
BST<int> test;
test.add(1);
test.add(2);
test.add(3);
test.del(test.getroot(), 1);
test.del(test.getroot(), 2);
REQUIRE(test.search(1, test.getroot()) != 0);
REQUIRE(test.search(2, test.getroot()) == 0);
REQUIRE(test.search(3, test.getroot())!= 0);
}
*/
<|endoftext|>
|
<commit_before>#ifndef MANIFOLDS_FUNCTIONS_DERIVATIVES_HH
#define MANIFOLDS_FUNCTIONS_DERIVATIVES_HH
#include "addition.hh"
#include "multiplication.hh"
#include "variables.hh"
#include "division.hh"
#include "polynomial.hh"
#include "trig.hh"
#include "operators.hh"
#include "function_matrix.hh"
#ifdef PRINT_SIMPLIFIES
# define PRINT_DERIV(object, variable, name) \
std::cout << "Taking derivative of " << name \
<< " (" << object << ") with respect to " << variable <<'\n'
#else
# define PRINT_DERIV(o, v, n)
#endif
namespace manifolds {
template <int iter>
struct DerivativeWrapper
{
template <class ... Funcs, int i,
std::size_t ... indices>
static auto Derivative(const Addition<Funcs...> & a,
Variable<i> v,
std::integer_sequence<std::size_t, indices...>)
{
return
Add(DerivativeWrapper<iter+1>::
Derivative(get<indices>(a.GetFunctions())..., v));
}
template <class ... Funcs, int i>
static auto Derivative(const Addition<Funcs...> & a,
Variable<i> v)
{
PRINT_DERIV(a, v, "addition");
return DerivativeWrapper<iter+1>::
Derivative(a, v, std::index_sequence_for<Funcs...>());
}
template <class F, int i>
static auto Derivative(UnaryMinus<F> f, Variable<i> v)
{
PRINT_DERIV(f, v, "negative of function");
return -DerivativeWrapper<iter+1>::
Derivative(f.GetFunction(), v);
}
template <class Func, int i>
static auto Derivative(const Composition<Func> & c,
Variable<i> v)
{
PRINT_DERIV(c, v, "last composition");
return DerivativeWrapper<iter+1>::
Derivative(get<0>(c.GetFunctions()),v);
}
template <class Func, class ... Funcs, int i,
class = typename std::enable_if<
(sizeof...(Funcs)>0)>::type>
static auto Derivative(const Composition<Func,Funcs...> & c,
Variable<i> v)
{
PRINT_DERIV(c, v, "composition");
auto funcs = remove_element<0>(c.GetFunctions());
auto d = FullDeriv(get<0>(c.GetFunctions()));
auto next =
tuple_cat(make_my_tuple(d), funcs);
return Composition<decltype(d), Funcs...>(next) *
DerivativeWrapper<iter+1>::
Derivative(Composition<Funcs...>(funcs), v);
}
template <class F1, class F2, int i>
static auto Derivative(const Division<F1,F2>& d,
Variable<i> v)
{
PRINT_DERIV(d, v, "division");
auto n = d.GetNumerator();
auto de = d.GetDenominator();
return (DerivativeWrapper<iter+1>::Derivative(n, v) * de -
n * DerivativeWrapper<iter+1>::Derivative(de, v)) /
(de * de);
}
template <int i, class ... Funcs, int d_i,
std::size_t ... lefts, std::size_t ... rights>
static auto TimesDerivHelper(const Multiplication<Funcs...> & a,
Variable<d_i> v,
std::integer_sequence<
std::size_t, lefts...>,
std::integer_sequence<
std::size_t, rights...>)
{
auto t = a.GetFunctions();
return Multiply(get<lefts>(t)...,
DerivativeWrapper<iter+1>::
Derivative(get<i>(t),v),
get<rights+i+1>(t)...);
}
template <int i, class ... Funcs, int d_i>
static auto TimesDerivHelper(const Multiplication<Funcs...> & a,
Variable<d_i> v)
{
return TimesDerivHelper<i>
(a, v, std::make_index_sequence<i>(),
std::make_index_sequence<
sizeof...(Funcs)-i-1>());
}
template <class ... Funcs, int i,
std::size_t ... indices>
static auto Derivative(const Multiplication<Funcs...> & a,
Variable<i> v,
std::integer_sequence<std::size_t, indices...>)
{
return
Add(TimesDerivHelper<indices>(a, v)...);
}
template <class ... Funcs, int i>
static auto Derivative(const Multiplication<Funcs...> & a,
Variable<i> v)
{
PRINT_DERIV(a, v, "multiplication");
return DerivativeWrapper<iter+1>::
Derivative(a, v, std::index_sequence_for<Funcs...>());
}
template <class CoeffType, class Order, int i>
static auto Derivative(const Polynomial<CoeffType, Order> & p,
Variable<i> v)
{
PRINT_DERIV(p, v, "non-constant polynomial");
return zero;
}
template <class CoeffType, int i>
static auto Derivative(Polynomial<CoeffType, int_<1>> p,
Variable<i> v)
{
PRINT_DERIV(p, v, "constant polynomial");
return zero;
}
template <class CoeffType, class Order,
class = typename std::enable_if<
Order::value != 1
>::type>
static auto Derivative(const Polynomial<CoeffType, Order> & p,
Variable<0> v)
{
PRINT_DERIV(p, v, "non-constant polynomial");
std::array<CoeffType, Order::value-1> d;
for(unsigned i = 0; i < Order::value-1; i++)
d[i] = (i+1)*p.GetCoeffs()[i+1];
return Polynomial<CoeffType,int_<Order::value-1>>{d};
}
#define TRIG_DERIV(func, deriv) \
static auto Derivative(func f,Variable<0> v){ \
PRINT_DERIV(f,v,#func); return deriv;} \
template <int i> \
static auto Derivative(func f,Variable<i> v){ \
PRINT_DERIV(f,v,#func); return zero;}
TRIG_DERIV(Sin, Cos())
TRIG_DERIV(Cos, -Sin())
TRIG_DERIV(Tan, 1_c / (Cos()*Cos()))
TRIG_DERIV(Log, 1_c / x)
TRIG_DERIV(Sinh, Cosh())
TRIG_DERIV(Cosh, Sinh())
TRIG_DERIV(Tanh, 1_c / (Cosh()*Cosh()))
TRIG_DERIV(ASin, 1_c / Sqrt()(1_c-x*x))
TRIG_DERIV(ACos, -1_c / Sqrt()(1_c-x*x))
TRIG_DERIV(ATan, 1_c / (1_c+x*x))
TRIG_DERIV(ASinh, 1_c / Sqrt()(1_c+x*x))
TRIG_DERIV(ACosh, 1_c / Sqrt()(-1_c+x*x))
TRIG_DERIV(ATanh, 1_c / (1_c-x*x))
TRIG_DERIV(Exp, Exp())
TRIG_DERIV(Sqrt, 0.5_c / Sqrt())
TRIG_DERIV(Zero, zero)
#undef TRIG_DERIV
template <int i>
static auto Derivative(Pow p, Variable<i> v)
{
PRINT_DERIV(p, v, "Pow");
return zero;
}
static auto Derivative(Pow p, Variable<0> v)
{
PRINT_DERIV(p, v, "Pow");
return y * Pow()(x, y-1_c);
}
static auto Derivative(Pow p, Variable<1> v)
{
PRINT_DERIV(p, v, "Pow");
return (Log()(x)) * Pow()(x, y);
}
template <int i>
static auto Derivative(Variable<i> v1, Variable<i> v2)
{
PRINT_DERIV(v1, v2, "variable");
return 1_c;
}
template <int i, int j>
static auto Derivative(Variable<i> v1, Variable<j> v2)
{
PRINT_DERIV(v1, v2, "variable");
return zero;
}
template <class ... Functions, int i,
std::size_t ... indices>
static auto Derivative(FunctionMatrix<Functions...> m,
Variable<i> v,
std::integer_sequence<
std::size_t,indices...>)
{
typedef FunctionMatrix<Functions...> M;
return GetFunctionMatrix<
M::num_rows,M::num_cols>
(make_my_tuple(Derivative
(get<indices>(m.GetFunctions()),
v)...));
}
template <class ... Functions, int i>
static auto Derivative(FunctionMatrix<Functions...> m,
Variable<i> v)
{
PRINT_DERIV(m, v, "function matrix");
static const int size =
tuple_size<decltype(m.GetFunctions())>::type::value;
return Derivative
(m, v, std::make_index_sequence<size>());
}
template <class T, std::size_t ... ins>
static auto FullDerivHelper(T t, int_<T::output_dim>,
std::integer_sequence<std::size_t, ins...>)
{
return tuple<>();
}
template <class T>
static auto GetOutputs(T t, int_<1>)
{
return make_my_tuple(t);
}
template <class T, int i>
static auto GetOutputs(T t, int_<i>)
{
return t.GetOutputs();
}
template <class T>
static auto GetOutputs(T t)
{
return GetOutputs(t, int_<T::output_dim>());
}
template <int col, class T, std::size_t ... ins,
class = typename std::enable_if<
col != T::output_dim>::type>
static auto FullDerivHelper(T t, int_<col>,
std::integer_sequence<std::size_t, ins...> b)
{
auto r =
make_my_tuple(Derivative(get<col>(GetOutputs(t)),
Variable<ins>())...);
return tuple_cat(r, DerivativeWrapper<iter+1>::
FullDerivHelper(t, int_<col+1>(), b));
}
template <class T>
static auto FullDerivOutput(tuple<T> t,
int_<1>, int_<1>)
{
return get<0>(t);
}
template <class ... Ts, int rows, int cols>
static auto FullDerivOutput(tuple<Ts...> t,
int_<rows>, int_<cols>)
{
return GetFunctionMatrix<rows,cols>(t);
}
template <class T>
static auto FullDeriv(T t)
{
#ifdef PRINT_SIMPLIFIES
std::cout << "Taking full derivative of " << t << '\n';
#endif
return FullDerivOutput
(DerivativeWrapper<iter+1>::
FullDerivHelper(t, int_<0>(),
std::make_index_sequence<
T::input_dim>()),
int_<T::output_dim>(), int_<T::input_dim>());
}
};
template <class T, int i>
auto Derivative(T t, Variable<i> v)
{
return DerivativeWrapper<0>::Derivative(t, v);
}
template <class T>
auto Derivative(T t)
{
return DerivativeWrapper<0>::Derivative(t, x);
}
template <class T>
auto FullDerivative(T t)
{
return DerivativeWrapper<0>::FullDeriv(t);
}
template <int order, int i = 0>
struct D
{
template <class F>
auto operator()(F f) const
{
return D<order-1,i>()(Derivative(f, Variable<i>()));
}
};
template <int i>
struct D<0,i>
{
template <class F>
auto operator()(F f) const
{
return f;
}
};
}
#endif
<commit_msg>Changing D to be a Function, but don't try too much with it just yet<commit_after>#ifndef MANIFOLDS_FUNCTIONS_DERIVATIVES_HH
#define MANIFOLDS_FUNCTIONS_DERIVATIVES_HH
#include "addition.hh"
#include "multiplication.hh"
#include "variables.hh"
#include "division.hh"
#include "polynomial.hh"
#include "trig.hh"
#include "operators.hh"
#include "function_matrix.hh"
#ifdef PRINT_SIMPLIFIES
# define PRINT_DERIV(object, variable, name) \
std::cout << "Taking derivative of " << name \
<< " (" << object << ") with respect to " << variable <<'\n'
#else
# define PRINT_DERIV(o, v, n)
#endif
namespace manifolds {
template <int iter>
struct DerivativeWrapper
{
template <class ... Funcs, int i,
std::size_t ... indices>
static auto Derivative(const Addition<Funcs...> & a,
Variable<i> v,
std::integer_sequence<std::size_t, indices...>)
{
return
Add(DerivativeWrapper<iter+1>::
Derivative(get<indices>(a.GetFunctions())..., v));
}
template <class ... Funcs, int i>
static auto Derivative(const Addition<Funcs...> & a,
Variable<i> v)
{
PRINT_DERIV(a, v, "addition");
return DerivativeWrapper<iter+1>::
Derivative(a, v, std::index_sequence_for<Funcs...>());
}
template <class F, int i>
static auto Derivative(UnaryMinus<F> f, Variable<i> v)
{
PRINT_DERIV(f, v, "negative of function");
return -DerivativeWrapper<iter+1>::
Derivative(f.GetFunction(), v);
}
template <class Func, int i>
static auto Derivative(const Composition<Func> & c,
Variable<i> v)
{
PRINT_DERIV(c, v, "last composition");
return DerivativeWrapper<iter+1>::
Derivative(get<0>(c.GetFunctions()),v);
}
template <class Func, class ... Funcs, int i,
class = typename std::enable_if<
(sizeof...(Funcs)>0)>::type>
static auto Derivative(const Composition<Func,Funcs...> & c,
Variable<i> v)
{
PRINT_DERIV(c, v, "composition");
auto funcs = remove_element<0>(c.GetFunctions());
auto d = FullDeriv(get<0>(c.GetFunctions()));
auto next =
tuple_cat(make_my_tuple(d), funcs);
return Composition<decltype(d), Funcs...>(next) *
DerivativeWrapper<iter+1>::
Derivative(Composition<Funcs...>(funcs), v);
}
template <class F1, class F2, int i>
static auto Derivative(const Division<F1,F2>& d,
Variable<i> v)
{
PRINT_DERIV(d, v, "division");
auto n = d.GetNumerator();
auto de = d.GetDenominator();
return (DerivativeWrapper<iter+1>::Derivative(n, v) * de -
n * DerivativeWrapper<iter+1>::Derivative(de, v)) /
(de * de);
}
template <int i, class ... Funcs, int d_i,
std::size_t ... lefts, std::size_t ... rights>
static auto TimesDerivHelper(const Multiplication<Funcs...> & a,
Variable<d_i> v,
std::integer_sequence<
std::size_t, lefts...>,
std::integer_sequence<
std::size_t, rights...>)
{
auto t = a.GetFunctions();
return Multiply(get<lefts>(t)...,
DerivativeWrapper<iter+1>::
Derivative(get<i>(t),v),
get<rights+i+1>(t)...);
}
template <int i, class ... Funcs, int d_i>
static auto TimesDerivHelper(const Multiplication<Funcs...> & a,
Variable<d_i> v)
{
return TimesDerivHelper<i>
(a, v, std::make_index_sequence<i>(),
std::make_index_sequence<
sizeof...(Funcs)-i-1>());
}
template <class ... Funcs, int i,
std::size_t ... indices>
static auto Derivative(const Multiplication<Funcs...> & a,
Variable<i> v,
std::integer_sequence<std::size_t, indices...>)
{
return
Add(TimesDerivHelper<indices>(a, v)...);
}
template <class ... Funcs, int i>
static auto Derivative(const Multiplication<Funcs...> & a,
Variable<i> v)
{
PRINT_DERIV(a, v, "multiplication");
return DerivativeWrapper<iter+1>::
Derivative(a, v, std::index_sequence_for<Funcs...>());
}
template <class CoeffType, class Order, int i>
static auto Derivative(const Polynomial<CoeffType, Order> & p,
Variable<i> v)
{
PRINT_DERIV(p, v, "non-constant polynomial");
return zero;
}
template <class CoeffType, int i>
static auto Derivative(Polynomial<CoeffType, int_<1>> p,
Variable<i> v)
{
PRINT_DERIV(p, v, "constant polynomial");
return zero;
}
template <class CoeffType, class Order,
class = typename std::enable_if<
Order::value != 1
>::type>
static auto Derivative(const Polynomial<CoeffType, Order> & p,
Variable<0> v)
{
PRINT_DERIV(p, v, "non-constant polynomial");
std::array<CoeffType, Order::value-1> d;
for(unsigned i = 0; i < Order::value-1; i++)
d[i] = (i+1)*p.GetCoeffs()[i+1];
return Polynomial<CoeffType,int_<Order::value-1>>{d};
}
#define TRIG_DERIV(func, deriv) \
static auto Derivative(func f,Variable<0> v){ \
PRINT_DERIV(f,v,#func); return deriv;} \
template <int i> \
static auto Derivative(func f,Variable<i> v){ \
PRINT_DERIV(f,v,#func); return zero;}
TRIG_DERIV(Sin, Cos())
TRIG_DERIV(Cos, -Sin())
TRIG_DERIV(Tan, 1_c / (Cos()*Cos()))
TRIG_DERIV(Log, 1_c / x)
TRIG_DERIV(Sinh, Cosh())
TRIG_DERIV(Cosh, Sinh())
TRIG_DERIV(Tanh, 1_c / (Cosh()*Cosh()))
TRIG_DERIV(ASin, 1_c / Sqrt()(1_c-x*x))
TRIG_DERIV(ACos, -1_c / Sqrt()(1_c-x*x))
TRIG_DERIV(ATan, 1_c / (1_c+x*x))
TRIG_DERIV(ASinh, 1_c / Sqrt()(1_c+x*x))
TRIG_DERIV(ACosh, 1_c / Sqrt()(-1_c+x*x))
TRIG_DERIV(ATanh, 1_c / (1_c-x*x))
TRIG_DERIV(Exp, Exp())
TRIG_DERIV(Sqrt, 0.5_c / Sqrt())
TRIG_DERIV(Zero, zero)
#undef TRIG_DERIV
template <int i>
static auto Derivative(Pow p, Variable<i> v)
{
PRINT_DERIV(p, v, "Pow");
return zero;
}
static auto Derivative(Pow p, Variable<0> v)
{
PRINT_DERIV(p, v, "Pow");
return y * Pow()(x, y-1_c);
}
static auto Derivative(Pow p, Variable<1> v)
{
PRINT_DERIV(p, v, "Pow");
return (Log()(x)) * Pow()(x, y);
}
template <int i>
static auto Derivative(Variable<i> v1, Variable<i> v2)
{
PRINT_DERIV(v1, v2, "variable");
return 1_c;
}
template <int i, int j>
static auto Derivative(Variable<i> v1, Variable<j> v2)
{
PRINT_DERIV(v1, v2, "variable");
return zero;
}
template <class ... Functions, int i,
std::size_t ... indices>
static auto Derivative(FunctionMatrix<Functions...> m,
Variable<i> v,
std::integer_sequence<
std::size_t,indices...>)
{
typedef FunctionMatrix<Functions...> M;
return GetFunctionMatrix<
M::num_rows,M::num_cols>
(make_my_tuple(Derivative
(get<indices>(m.GetFunctions()),
v)...));
}
template <class ... Functions, int i>
static auto Derivative(FunctionMatrix<Functions...> m,
Variable<i> v)
{
PRINT_DERIV(m, v, "function matrix");
static const int size =
tuple_size<decltype(m.GetFunctions())>::type::value;
return Derivative
(m, v, std::make_index_sequence<size>());
}
template <class T, std::size_t ... ins>
static auto FullDerivHelper(T t, int_<T::output_dim>,
std::integer_sequence<std::size_t, ins...>)
{
return tuple<>();
}
template <class T>
static auto GetOutputs(T t, int_<1>)
{
return make_my_tuple(t);
}
template <class T, int i>
static auto GetOutputs(T t, int_<i>)
{
return t.GetOutputs();
}
template <class T>
static auto GetOutputs(T t)
{
return GetOutputs(t, int_<T::output_dim>());
}
template <int col, class T, std::size_t ... ins,
class = typename std::enable_if<
col != T::output_dim>::type>
static auto FullDerivHelper(T t, int_<col>,
std::integer_sequence<std::size_t, ins...> b)
{
auto r =
make_my_tuple(Derivative(get<col>(GetOutputs(t)),
Variable<ins>())...);
return tuple_cat(r, DerivativeWrapper<iter+1>::
FullDerivHelper(t, int_<col+1>(), b));
}
template <class T>
static auto FullDerivOutput(tuple<T> t,
int_<1>, int_<1>)
{
return get<0>(t);
}
template <class ... Ts, int rows, int cols>
static auto FullDerivOutput(tuple<Ts...> t,
int_<rows>, int_<cols>)
{
return GetFunctionMatrix<rows,cols>(t);
}
template <class T>
static auto FullDeriv(T t)
{
#ifdef PRINT_SIMPLIFIES
std::cout << "Taking full derivative of " << t << '\n';
#endif
return FullDerivOutput
(DerivativeWrapper<iter+1>::
FullDerivHelper(t, int_<0>(),
std::make_index_sequence<
T::input_dim>()),
int_<T::output_dim>(), int_<T::input_dim>());
}
};
template <class T, int i>
auto Derivative(T t, Variable<i> v)
{
return DerivativeWrapper<0>::Derivative(t, v);
}
template <class T>
auto Derivative(T t)
{
return DerivativeWrapper<0>::Derivative(t, x);
}
template <class T>
auto FullDerivative(T t)
{
return DerivativeWrapper<0>::FullDeriv(t);
}
template <int order, int i = 0, bool ABELIAN = true>
struct D : Function<int_<26>, 1, 1>
{
typedef std::tuple<FTag<FunctionType::Function>> input_types;
typedef std::tuple<FTag<FunctionType::Function>> output_types;
static const bool stateless = true;
static const bool abelian = ABELIAN;
template <class F>
auto operator()(F f) const
{
return D<order-1,i>()(Derivative(f, Variable<i>()));
}
};
template <int i>
struct D<0,i>
{
template <class F>
auto operator()(F f) const
{
return f;
}
};
}
#endif
<|endoftext|>
|
<commit_before>#include "OpenVINOEngine.hpp"
#include <inference_engine.hpp>
#include <FAST/Utility.hpp>
namespace fast {
using namespace InferenceEngine;
void OpenVINOEngine::run() {
// --------------------------- 6. Prepare input --------------------------------------------------------
auto inputTensor = mInputNodes.begin()->second.data;
auto access = inputTensor->getAccess(ACCESS_READ);
auto data = access->getData<4>();
Blob::Ptr input = m_inferRequest->GetBlob(mInputNodes.begin()->first);
auto input_data = input->buffer().as<PrecisionTrait<Precision::FP32>::value_type *>();
std::memcpy(input_data, data.data(), input->byteSize());
reportInfo() << "OpenVINO: Ready to execute." << reportEnd();
m_inferRequest->Infer();
reportInfo() << "OpenVINO: Network executed." << reportEnd();
// --------------------------- 8. Process output ------------------------------------------------------
Blob::Ptr output = m_inferRequest->GetBlob(mOutputNodes.begin()->first);
auto outputData = (output->buffer().as<::InferenceEngine::PrecisionTrait<Precision::FP32>::value_type*>());
auto copied_data = make_uninitialized_unique<float[]>(output->byteSize());
std::memcpy(copied_data.get(), outputData, output->byteSize());
auto tensor = Tensor::New();
tensor->create(std::move(copied_data), mOutputNodes.begin()->second.shape);
mOutputNodes.begin()->second.data = tensor;
}
void OpenVINOEngine::load() {
PluginDispatcher dispatcher({""});
InferencePlugin plugin(dispatcher.getSuitablePlugin(TargetDevice::eCPU));
reportInfo() << "OpenVINO: Inference plugin setup complete." << reportEnd();
// --------------------------- 2. Read IR Generated by ModelOptimizer (.xml and .bin files) ------------
auto input_model = getFilename();
if(!fileExists(input_model))
throw FileNotFoundException(input_model);
CNNNetReader network_reader;
network_reader.ReadNetwork(fileNameToString(input_model));
network_reader.ReadWeights(fileNameToString(input_model).substr(0, input_model.size() - 4) + ".bin");
CNNNetwork network = network_reader.getNetwork();
//network.setBatchSize(1);
reportInfo() << "OpenVINO: Network loaded." << reportEnd();
// -----------------------------------------------------------------------------------------------------
// --------------------------- 3. Configure input & output ---------------------------------------------
// --------------------------- Prepare input blobs -----------------------------------------------------
InputInfo::Ptr input_info = network.getInputsInfo().begin()->second;
std::string input_name = network.getInputsInfo().begin()->first;
input_info->setPrecision(Precision::FP32);
// TODO shape is reverse direction here for some reason..
TensorShape shape;
auto dims = input_info->getDims();
for(int i = dims.size()-1; i >= 0; --i) // TODO why reverse??
shape.addDimension(dims[i]);
if(shape.getDimensions() > 3) {
input_info->setLayout(Layout::NCHW);
addInputNode(0, input_name, NodeType::IMAGE, shape);
} else {
addInputNode(0, input_name, NodeType::TENSOR, shape);
}
reportInfo() << "Input node is: " << input_name << " with shape " << shape.toString() << reportEnd();
// --------------------------- Prepare output blobs ----------------------------------------------------
DataPtr output_info = network.getOutputsInfo().begin()->second;
std::string output_name = network.getOutputsInfo().begin()->first;
TensorShape outputShape;
for(auto dim : output_info->getDims())
outputShape.addDimension(dim);
addOutputNode(0, output_name, NodeType::TENSOR, outputShape);
reportInfo() << "Output node is: " << output_name << " with shape " << outputShape.toString() << reportEnd();
output_info->setPrecision(Precision::FP32);
reportInfo() << "OpenVINO: Node setup complete." << reportEnd();
ExecutableNetwork executable_network = plugin.LoadNetwork(network, {});
m_inferRequest = executable_network.CreateInferRequestPtr();
setIsLoaded(true);
reportInfo() << "OpenVINO: Network fully loaded." << reportEnd();
}
ImageOrdering OpenVINOEngine::getPreferredImageOrdering() const {
return ImageOrdering::CHW;
}
std::string OpenVINOEngine::getName() const {
return "OpenVINO";
}
}
<commit_msg>multi input and output support in OpenVINO engine<commit_after>#include "OpenVINOEngine.hpp"
#include <inference_engine.hpp>
#include <FAST/Utility.hpp>
namespace fast {
using namespace InferenceEngine;
void OpenVINOEngine::run() {
// Copy input data
for(const auto& node : mInputNodes) {
auto tensor = node.second.data;
auto access = tensor->getAccess(ACCESS_READ);
float* tensorData;
switch(tensor->getShape().getDimensions()) {
case 2:
tensorData = access->getData<2>().data();
break;
case 3:
tensorData = access->getData<3>().data();
break;
case 4:
tensorData = access->getData<4>().data();
break;
case 5:
tensorData = access->getData<5>().data();
break;
case 6:
tensorData = access->getData<6>().data();
break;
default:
throw Exception("Invalid tensor dimension size");
}
Blob::Ptr input = m_inferRequest->GetBlob(node.first);
auto input_data = input->buffer().as<PrecisionTrait<Precision::FP32>::value_type * >();
std::memcpy(input_data, tensorData, input->byteSize());
}
// Execute network
m_inferRequest->Infer();
reportInfo() << "OpenVINO: Network executed." << reportEnd();
// Copy output data
for(auto& node : mOutputNodes) {
Blob::Ptr output = m_inferRequest->GetBlob(node.first);
auto outputData = (output->buffer().as<::InferenceEngine::PrecisionTrait<Precision::FP32>::value_type *>());
auto copied_data = make_uninitialized_unique<float[]>(output->byteSize());
std::memcpy(copied_data.get(), outputData, output->byteSize());
auto tensor = Tensor::New();
tensor->create(std::move(copied_data), node.second.shape);
node.second.data = tensor;
}
}
void OpenVINOEngine::load() {
PluginDispatcher dispatcher({""});
InferencePlugin plugin(dispatcher.getSuitablePlugin(TargetDevice::eCPU));
reportInfo() << "OpenVINO: Inference plugin setup complete." << reportEnd();
// --------------------------- 2. Read IR Generated by ModelOptimizer (.xml and .bin files) ------------
auto input_model = getFilename();
if(!fileExists(input_model))
throw FileNotFoundException(input_model);
CNNNetReader network_reader;
network_reader.ReadNetwork(fileNameToString(input_model));
network_reader.ReadWeights(fileNameToString(input_model).substr(0, input_model.size() - 4) + ".bin");
CNNNetwork network = network_reader.getNetwork();
//network.setBatchSize(1);
reportInfo() << "OpenVINO: Network loaded." << reportEnd();
// --------------------------- Prepare input blobs -----------------------------------------------------
int counter = 0;
for(auto& input : network.getInputsInfo()) {
auto input_info = input.second;
auto input_name = input.first;
input_info->setPrecision(Precision::FP32);
// TODO shape is reverse direction here for some reason..
TensorShape shape;
auto dims = input_info->getDims();
for(int i = dims.size() - 1; i >= 0; --i) // TODO why reverse??
shape.addDimension(dims[i]);
if(shape.getDimensions() > 3) {
input_info->setLayout(Layout::NCHW);
addInputNode(counter, input_name, NodeType::IMAGE, shape);
} else {
addInputNode(counter, input_name, NodeType::TENSOR, shape);
}
reportInfo() << "Found input node: " << input_name << " with shape " << shape.toString() << reportEnd();
counter++;
}
// --------------------------- Prepare output blobs ----------------------------------------------------
counter = 0;
for(auto& output : network.getOutputsInfo()) {
auto info = output.second;
auto name = output.first;
info->setPrecision(Precision::FP32);
TensorShape shape;
for(auto dim : info->getDims())
shape.addDimension(dim);
addOutputNode(counter, name, NodeType::TENSOR, shape);
reportInfo() << "Found output node: " << name << " with shape " << shape.toString() << reportEnd();
counter++;
}
reportInfo() << "OpenVINO: Node setup complete." << reportEnd();
ExecutableNetwork executable_network = plugin.LoadNetwork(network, {});
m_inferRequest = executable_network.CreateInferRequestPtr();
setIsLoaded(true);
reportInfo() << "OpenVINO: Network fully loaded." << reportEnd();
}
ImageOrdering OpenVINOEngine::getPreferredImageOrdering() const {
return ImageOrdering::CHW;
}
std::string OpenVINOEngine::getName() const {
return "OpenVINO";
}
}
<|endoftext|>
|
<commit_before>//!@todo: files_t: Rotation condition.
//! Sample config:
/*!
Rotate by datetime:
"rotate": {
"backups" 5,
"pattern": "%(filename)s.log.%Y%M%d",
"every": "d" [m, H, a, d, w, M, y]
}
Rotate both:
"rotate": {
"backups" 5,
"pattern": "%(filename)s.log.%N.%Y%M%d",
"size": 1000000,
"every": "d" [m, H, a, d, w, M, y]
}
*/
//!@todo: api: Renaming repository methods.
//!@todo: stream_t: Implement stream sink.
//!@todo: example: Make stdout/string example with demonstration of formatting other attribute.
//!@todo: api: More verbose error messages.
//!@todo: feature: Verbosity filter from file.
//!@todo: api: Ability to set global attribute mapper (?)
//!@todo: api: Microseconds support in timestamps.
//!@todo: benchmark: File logging comparing with boost::log.
//!@todo: benchmark: Socket logging with json.
//!@todo: files_t: Make file naming by pattern.
//!@todo: files_t: logrotate support - ability to handle signals to reopen current file (SIGHUP) (?).
//!@todo: performance: Experiment with std::ostringstream or format library for performance check.
//!@todo: performance: Current naive implementation of timestamp formatter is suck and have large performance troubles. Fix it.
//!@todo: api: Make fallback logger. Make it configurable.
//!@todo: aux: Make internal exception class with attribute keeping, e.g. line, file or path.
//!@todo: api: Maybe squish repository_t::init and ::configure methods?
//!@todo: msgpack_t: Attribute mappings.
//!@todo: socket_t: Make asynchronous TCP backend.
<commit_msg>Subtask is done.<commit_after>//!@todo: files_t: Rotation condition.
//! Sample config:
/*!
Rotate both:
"rotate": {
"backups" 5,
"pattern": "%(filename)s.log.%N.%Y%M%d",
"size": 1000000,
"every": "d" [m, H, a, d, w, M, y]
}
*/
//!@todo: api: Renaming repository methods.
//!@todo: stream_t: Implement stream sink.
//!@todo: example: Make stdout/string example with demonstration of formatting other attribute.
//!@todo: api: More verbose error messages.
//!@todo: feature: Verbosity filter from file.
//!@todo: api: Ability to set global attribute mapper (?)
//!@todo: api: Microseconds support in timestamps.
//!@todo: benchmark: File logging comparing with boost::log.
//!@todo: benchmark: Socket logging with json.
//!@todo: files_t: Make file naming by pattern.
//!@todo: files_t: logrotate support - ability to handle signals to reopen current file (SIGHUP) (?).
//!@todo: performance: Experiment with std::ostringstream or format library for performance check.
//!@todo: performance: Current naive implementation of timestamp formatter is suck and have large performance troubles. Fix it.
//!@todo: api: Make fallback logger. Make it configurable.
//!@todo: aux: Make internal exception class with attribute keeping, e.g. line, file or path.
//!@todo: api: Maybe squish repository_t::init and ::configure methods?
//!@todo: msgpack_t: Attribute mappings.
//!@todo: socket_t: Make asynchronous TCP backend.
<|endoftext|>
|
<commit_before>#include "XPlayer.h"
#include "XEngine.h"
//************************************
// Method: Init
// FullName: XPlayer::Init
// Access: public
// Returns: void
// Qualifier:
// Parameter: sf::Vector2f pos
//************************************
//
void XPlayer::Init(sf::Vector2f pos, sf::View pView) {
m_pPlayerView = pView;
m_pPlayerView.zoom(0.5);
if (!texture.loadFromFile("data/player_male.png")) {
throw "Could not load player sprite!";
}
for (int i = 0; i < 4; ++i) {
walkingAnimation[i].setSpriteSheet(texture);
walkingAnimation[i].addFrame(sf::IntRect(16, i * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(0, i * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(16, i * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(32, i * 20, 16, 20));
}
for (int i = 4, y = 0; i < 8; ++i, ++y) {
walkingAnimation[i].setSpriteSheet(texture);
walkingAnimation[i].addFrame(sf::IntRect(64, y * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(48, y * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(64, y * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(80, y * 20, 16, 20));
}
currentAnimation = &walkingAnimation[DOWN];
animatedSprite = AnimatedSprite(sf::seconds(fWalkSpeed), true, false);
animatedSprite.setPosition(pos);
vPosition = vStartPos = vCurrentPos = pos;
vPosition.y += 4;
vCurrentPos.y += 4;
}
sf::Vector2f XPlayer::GetAbsolutePosition() {
return {vStartPos.x - vCurrentPos.x, vStartPos.y - vCurrentPos.y + 4};
}
//************************************
// Method: Render
// FullName: XPlayer::Render
// Access: public
// Returns: void
// Qualifier:
// Parameter: sf::RenderWindow * window
// Parameter: float dt
//************************************
void XPlayer::Render(sf::RenderWindow *renderWindow, float deltaTime) {
renderWindow->setView(m_pPlayerView);
XEngine::GetInstance().GetXMap()->Render(renderWindow, vPosition);
renderWindow->draw(animatedSprite);
animatedSprite.play(*currentAnimation);
animatedSprite.update(sf::seconds(deltaTime));
}
//************************************
// Method: Move
// FullName: XPlayer::Input
// Access: public
// Returns: void
// Qualifier:
// Parameter: float dt
//************************************
void XPlayer::Input(float deltaTime) {
// Check for all the buttons pressed
if (sf::Keyboard::isKeyPressed(sf::Keyboard::B)) {
isRunning = true;
animatedSprite.setFrameTime(sf::seconds(fRunSpeed / 2));
} else {
isRunning = false;
animatedSprite.setFrameTime(sf::seconds(fWalkSpeed));
}
if (!isMoving) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
fNextSpot = vPosition.y + TILESIZE;
nDirection = UP;
currentAnimation = &walkingAnimation[isRunning ? UP + 4 : UP];
if (XEngine::GetInstance().GetXMap()->isCollision(
{vStartPos.x - vPosition.x, vStartPos.y + 4 - fNextSpot})) {
return;
}
isMoving = true;
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
fNextSpot = vPosition.y - TILESIZE;
nDirection = DOWN;
currentAnimation = &walkingAnimation[isRunning ? DOWN + 4 : DOWN];
if (XEngine::GetInstance().GetXMap()->isCollision(
{vStartPos.x - vPosition.x, vStartPos.y + 4 - fNextSpot})) {
return;
}
isMoving = true;
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
fNextSpot = vPosition.x + TILESIZE;
nDirection = LEFT;
currentAnimation = &walkingAnimation[isRunning ? LEFT + 4 : LEFT];
if (XEngine::GetInstance().GetXMap()->isCollision(
{vStartPos.x - fNextSpot, vStartPos.y + 4 - vPosition.y})) {
return;
}
isMoving = true;
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
fNextSpot = vPosition.x - TILESIZE;
nDirection = RIGHT;
currentAnimation = &walkingAnimation[isRunning ? RIGHT + 4 : RIGHT];
if (XEngine::GetInstance().GetXMap()->isCollision(
{vStartPos.x - fNextSpot, vStartPos.y + 4 - vPosition.y})) {
return;
}
isMoving = true;
}
}
// Do the actual movement
if (isMoving) {
switch (nDirection) {
case UP: {
vPosition.y += nMoveSpeed * (isRunning ? 2 : 1) * deltaTime;
if (vPosition.y >= fNextSpot) {
vPosition.y = fNextSpot;
vCurrentPos = vPosition;
isMoving = false;
isRunning = false;
}
}
break;
case DOWN:
vPosition.y -= nMoveSpeed * (isRunning ? 2 : 1) * deltaTime;
if (vPosition.y <= fNextSpot) {
vPosition.y = fNextSpot;
vCurrentPos = vPosition;
isMoving = false;
isRunning = false;
}
break;
case LEFT:
vPosition.x += nMoveSpeed * (isRunning ? 2 : 1) * deltaTime;
if (vPosition.x >= fNextSpot) {
vPosition.x = fNextSpot;
vCurrentPos = vPosition;
isMoving = false;
isRunning = false;
}
break;
case RIGHT:
vPosition.x -= nMoveSpeed * (isRunning ? 2 : 1) * deltaTime;
if (vPosition.x <= fNextSpot) {
vPosition.x = fNextSpot;
vCurrentPos = vPosition;
isMoving = false;
isRunning = false;
}
break;
default:
break;
}
} else {
isRunning = false;
currentAnimation = &walkingAnimation[nDirection];
animatedSprite.stop();
}
}
void XPlayer::Update(float deltaTime) {
}<commit_msg>(XPlayer): Made use of a macro, added XMap->Update() to the update function and renamed GetAbsolutePosition to GetRelativePosition<commit_after>#include "XPlayer.h"
#include "XEngine.h"
//************************************
// Method: Init
// FullName: XPlayer::Init
// Access: public
// Returns: void
// Qualifier:
// Parameter: sf::Vector2f pos
//************************************
//
void XPlayer::Init(sf::Vector2f pos, sf::View pView) {
m_pPlayerView = pView;
m_pPlayerView.zoom(0.5);
if (!texture.loadFromFile("data/player_male.png")) {
throw "Could not load player tileSprite!";
}
for (int i = 0; i < 4; ++i) {
walkingAnimation[i].setSpriteSheet(texture);
walkingAnimation[i].addFrame(sf::IntRect(16, i * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(0, i * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(16, i * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(32, i * 20, 16, 20));
}
for (int i = 4, y = 0; i < 8; ++i, ++y) {
walkingAnimation[i].setSpriteSheet(texture);
walkingAnimation[i].addFrame(sf::IntRect(64, y * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(48, y * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(64, y * 20, 16, 20));
walkingAnimation[i].addFrame(sf::IntRect(80, y * 20, 16, 20));
}
currentAnimation = &walkingAnimation[DOWN];
animatedSprite = AnimatedSprite(sf::seconds(fWalkSpeed), true, false);
animatedSprite.setPosition(pos);
vPosition = vStartPos = vCurrentPos = pos;
vPosition.y += 4;
vCurrentPos.y += 4;
}
sf::Vector2f XPlayer::GetRelativePosition() {
return {vStartPos.x - vCurrentPos.x, vStartPos.y - vCurrentPos.y + 4};
}
//************************************
// Method: Render
// FullName: XPlayer::Render
// Access: public
// Returns: void
// Qualifier:
// Parameter: sf::RenderWindow * window
// Parameter: float dt
//************************************
void XPlayer::Render(sf::RenderWindow *renderWindow, float deltaTime) {
renderWindow->setView(m_pPlayerView);
XEngine::GetInstance().GetXMap()->Render(renderWindow, vPosition);
renderWindow->draw(animatedSprite);
animatedSprite.play(*currentAnimation);
animatedSprite.update(sf::seconds(deltaTime));
}
//************************************
// Method: Move
// FullName: XPlayer::Input
// Access: public
// Returns: void
// Qualifier:
// Parameter: float dt
//************************************
void XPlayer::Input(float deltaTime) {
// Check for all the buttons pressed
if (sf::Keyboard::isKeyPressed(sf::Keyboard::B)) {
isRunning = true;
animatedSprite.setFrameTime(sf::seconds(fRunSpeed / 2));
} else {
isRunning = false;
animatedSprite.setFrameTime(sf::seconds(fWalkSpeed));
}
if (!isMoving) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
fNextSpot = vPosition.y + TILESIZE;
nDirection = UP;
currentAnimation = &walkingAnimation[isRunning ? UP + 4 : UP];
if (g_XEngine.GetXMap()->isCollision(
{(int) (vStartPos.x - vPosition.x), (int) (vStartPos.y + 4 - fNextSpot)})) {
return;
}
isMoving = true;
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
fNextSpot = vPosition.y - TILESIZE;
nDirection = DOWN;
currentAnimation = &walkingAnimation[isRunning ? DOWN + 4 : DOWN];
if (g_XEngine.GetXMap()->isCollision(
{(int) (vStartPos.x - vPosition.x), (int) (vStartPos.y + 4 - fNextSpot)})) {
return;
}
isMoving = true;
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
fNextSpot = vPosition.x + TILESIZE;
nDirection = LEFT;
currentAnimation = &walkingAnimation[isRunning ? LEFT + 4 : LEFT];
if (g_XEngine.GetXMap()->isCollision(
{(int) (vStartPos.x - fNextSpot), (int) (vStartPos.y + 4 - vPosition.y)})) {
return;
}
isMoving = true;
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
fNextSpot = vPosition.x - TILESIZE;
nDirection = RIGHT;
currentAnimation = &walkingAnimation[isRunning ? RIGHT + 4 : RIGHT];
if (g_XEngine.GetXMap()->isCollision(
{(int) (vStartPos.x - fNextSpot), (int) (vStartPos.y + 4 - vPosition.y)})) {
return;
}
isMoving = true;
}
}
// Do the actual movement
if (isMoving) {
switch (nDirection) {
case UP: {
vPosition.y += nMoveSpeed * (isRunning ? 2 : 1) * deltaTime;
if (vPosition.y >= fNextSpot) {
vPosition.y = fNextSpot;
vCurrentPos = vPosition;
isMoving = false;
isRunning = false;
}
}
break;
case DOWN:
vPosition.y -= nMoveSpeed * (isRunning ? 2 : 1) * deltaTime;
if (vPosition.y <= fNextSpot) {
vPosition.y = fNextSpot;
vCurrentPos = vPosition;
isMoving = false;
isRunning = false;
}
break;
case LEFT:
vPosition.x += nMoveSpeed * (isRunning ? 2 : 1) * deltaTime;
if (vPosition.x >= fNextSpot) {
vPosition.x = fNextSpot;
vCurrentPos = vPosition;
isMoving = false;
isRunning = false;
}
break;
case RIGHT:
vPosition.x -= nMoveSpeed * (isRunning ? 2 : 1) * deltaTime;
if (vPosition.x <= fNextSpot) {
vPosition.x = fNextSpot;
vCurrentPos = vPosition;
isMoving = false;
isRunning = false;
}
break;
default:
break;
}
} else {
isRunning = false;
currentAnimation = &walkingAnimation[nDirection];
animatedSprite.stop();
}
}
void XPlayer::Update(float deltaTime) {
g_XEngine.GetXMap()->Update();
}<|endoftext|>
|
<commit_before>#ifndef BUILTIN_UTIL_I_HH
#define BUILTIN_UTIL_I_HH
#ifndef BUILTIN_UTIL_HH
#error "Please include via parent file"
#endif
#include <stack>
#include <vector>
#include <array>
#include <cstdio>
#include <iterator>
#include "util.hh"
#include "lisp_ptr.hh"
#include "cons.hh"
#include "vm.hh"
template<bool dot_list, typename StackT>
Lisp_ptr stack_to_list(StackT& st){
Lisp_ptr argc = st.back();
st.pop_back();
if(argc.get<int>() == 0){
return Cons::NIL;
}
Cons* c = new Cons;
Cons* prev_c = c;
Lisp_ptr ret = c;
for(int i = 0; i < argc.get<int>(); ++i){
c->rplaca(st.back());
st.pop_back();
Cons* newc = new Cons;
c->rplacd(newc);
prev_c = c;
c = newc;
}
if(dot_list){
if(c != prev_c){
prev_c->rplacd(c->car());
}else{
ret = c->car();
}
delete c;
}else{
c->rplacd(Cons::NIL);
}
return ret;
}
template<typename StackT, typename VectorT>
void stack_to_vector(StackT& st, VectorT& v){
Lisp_ptr argc = st.back();
st.pop_back();
auto arg_start = st.end() - argc.get<int>();
auto arg_end = st.end();
for(auto i = arg_start; i != arg_end; ++i){
v.push_back(*i);
}
st.erase(arg_start, arg_end);
}
template<typename StackT>
int list_to_stack(const char* opname, Lisp_ptr l, StackT& st){
std::stack<Lisp_ptr> tmp;
do_list(l,
[&](Cons* c) -> bool {
tmp.push(c->car());
return true;
},
[&](Lisp_ptr last_cdr){
if(!nullp(last_cdr)){
fprintf(zs::err, "eval warning: dot list has read as proper list. (in %s)\n",
opname);
tmp.push(last_cdr);
}
});
int ret = 0;
while(!tmp.empty()){
st.push_back(tmp.top());
tmp.pop();
++ret;
}
return ret;
}
template<int size>
std::array<Lisp_ptr, size> pick_args(){
Lisp_ptr argc = vm.stack.back();
vm.stack.pop_back();
auto ret = std::array<Lisp_ptr, size>();
if(argc.get<int>() != size){
ret.fill({});
return ret;
}
for(int i = 0; i < size; ++i){
ret[i] = vm.stack[vm.stack.size() - size + i];
}
vm.stack.erase(vm.stack.end() - size, vm.stack.end());
return ret;
}
#endif //BUILTIN_UTIL_I_HH
<commit_msg>fixed list, list*<commit_after>#ifndef BUILTIN_UTIL_I_HH
#define BUILTIN_UTIL_I_HH
#ifndef BUILTIN_UTIL_HH
#error "Please include via parent file"
#endif
#include <stack>
#include <vector>
#include <array>
#include <cstdio>
#include <iterator>
#include "util.hh"
#include "lisp_ptr.hh"
#include "cons.hh"
#include "vm.hh"
template<bool dot_list, typename StackT>
Lisp_ptr stack_to_list(StackT& st){
Lisp_ptr argc = st.back();
st.pop_back();
if(argc.get<int>() == 0){
return Cons::NIL;
}
Cons* c = new Cons;
Cons* prev_c = c;
Lisp_ptr ret = c;
auto arg_start = st.end() - argc.get<int>();
auto arg_end = st.end();
auto i = arg_start;
while(1){
c->rplaca(*i);
++i;
if(i == arg_end) break;
Cons* newc = new Cons;
c->rplacd(newc);
prev_c = c;
c = newc;
}
if(dot_list){
if(c != prev_c){
prev_c->rplacd(c->car());
}else{
ret = c->car();
}
delete c;
}else{
c->rplacd(Cons::NIL);
}
st.erase(arg_start, arg_end);
return ret;
}
template<typename StackT, typename VectorT>
void stack_to_vector(StackT& st, VectorT& v){
Lisp_ptr argc = st.back();
st.pop_back();
auto arg_start = st.end() - argc.get<int>();
auto arg_end = st.end();
for(auto i = arg_start; i != arg_end; ++i){
v.push_back(*i);
}
st.erase(arg_start, arg_end);
}
template<typename StackT>
int list_to_stack(const char* opname, Lisp_ptr l, StackT& st){
std::stack<Lisp_ptr> tmp;
do_list(l,
[&](Cons* c) -> bool {
tmp.push(c->car());
return true;
},
[&](Lisp_ptr last_cdr){
if(!nullp(last_cdr)){
fprintf(zs::err, "eval warning: dot list has read as proper list. (in %s)\n",
opname);
tmp.push(last_cdr);
}
});
int ret = 0;
while(!tmp.empty()){
st.push_back(tmp.top());
tmp.pop();
++ret;
}
return ret;
}
template<int size>
std::array<Lisp_ptr, size> pick_args(){
Lisp_ptr argc = vm.stack.back();
vm.stack.pop_back();
auto ret = std::array<Lisp_ptr, size>();
if(argc.get<int>() != size){
ret.fill({});
return ret;
}
for(int i = 0; i < size; ++i){
ret[i] = vm.stack[vm.stack.size() - size + i];
}
vm.stack.erase(vm.stack.end() - size, vm.stack.end());
return ret;
}
#endif //BUILTIN_UTIL_I_HH
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver.
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mainwindow.h"
#include "tdriver_tabbededitor.h"
#include "tdriver_runconsole.h"
#include "tdriver_debugconsole.h"
#include "tdriver_rubyinteract.h"
#include <tdriver_editbar.h>
#include <tdriver_editor_common.h>
#include <tdriver_rubyinterface.h>
#include <QApplication>
#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QLabel>
#include <QMessageBox>
#include <QMenu>
#include <QDockWidget>
#include <QSettings>
#include <QCloseEvent>
#include <QStringList>
#include <tdriver_debug_macros.h>
MainWindow::MainWindow(QStringList filelist, QWidget *parent) :
QMainWindow(parent)
{
TDriverRubyInterface::startGlobalInstance();
tabs = new TDriverTabbedEditor(this, this);
runConsole = new TDriverRunConsole(true, this);
debugConsole = new TDriverDebugConsole(this);
irConsole = new TDriverRubyInteract(this);
tabs->setObjectName("editor");
runConsole->setObjectName("run");
debugConsole->setObjectName("debug");
createMenu();
setCentralWidget(tabs);
QDockWidget *runDock = new QDockWidget("Ruby Script Output");
runDock->setObjectName("run");
addDockWidget(Qt::RightDockWidgetArea, runDock);
runDock->setWidget(runConsole);
runDock->setVisible(false);
QDockWidget *debugDock = new QDockWidget("Debugger Console");
debugDock->setObjectName("debug");
addDockWidget(Qt::RightDockWidgetArea, debugDock);
debugDock->setWidget(debugConsole);
debugDock->setVisible(false);
QDockWidget *irDock = new QDockWidget("Ruby interaction Console");
irDock->setObjectName("iruby");
addDockWidget(Qt::BottomDockWidgetArea, irDock);
irDock->setWidget(irConsole);
irDock->setVisible(false);
QDockWidget *searchBarDock = new QDockWidget("Search Bar");
searchBarDock->setObjectName("searchbar");
addDockWidget(Qt::TopDockWidgetArea, searchBarDock);
searchBarDock->setWidget(tabs->searchBar());
searchBarDock->setVisible(true);
searchBarDock->setFeatures(QDockWidget::NoDockWidgetFeatures);
tabs->connectConsoles(runConsole, runDock, debugConsole, debugDock, irConsole, irDock);
connect(tabs, SIGNAL(requestRunPreparations(QString)), tabs, SLOT(proceedRun()));
restoreGeometry(MEC::settings->value("editor/geometry").toByteArray());
restoreState(MEC::settings->value("editor/windowstate").toByteArray());
// note: code below must be after connectConsoles
if (filelist.isEmpty()) {
tabs->newFile();
}
else {
foreach (QString file, filelist) {
if (!tabs->loadFile(file)) tabs->newFile(file);
}
}
}
void MainWindow::createMenu()
{
QAction *exitAction = new QAction(tr("E&xit"), this);
exitAction->setObjectName("exit");
QAction *aboutAct = new QAction(tr("About"), this);
aboutAct->setObjectName("about");
QAction *aboutQtAct = new QAction(tr("About Qt"), this);
aboutQtAct->setObjectName("aboutqt");
connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
menuBar()->actions().last()->setObjectName("file");
fileMenu->setObjectName("file");
fileMenu->addActions(tabs->fileActions());
fileMenu->addSeparator();
fileMenu->addActions(tabs->recentFileActions());
tabs->updateRecentFileActions();
fileMenu->addSeparator();
fileMenu->addAction(exitAction);
QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
menuBar()->actions().last()->setObjectName("edit");
editMenu->setObjectName("edit");
editMenu->addActions(tabs->editActions());
editMenu->addSeparator();
editMenu->addActions(tabs->codeActions());
QMenu *optMenu = menuBar()->addMenu(tr("&Toggles"));
menuBar()->actions().last()->setObjectName("opt");
optMenu->setObjectName("opt");
optMenu->addActions(tabs->optionActions());
QMenu *runMenu = menuBar()->addMenu(tr("&Run"));
menuBar()->actions().last()->setObjectName("run");
runMenu->setObjectName("run");
runMenu->addActions(tabs->runActions());
QMenu* aboutMenu = menuBar()->addMenu(tr("&About"));
menuBar()->actions().last()->setObjectName("about");
aboutMenu->setObjectName("about");
aboutMenu->addAction(aboutAct);
aboutMenu->addAction(aboutQtAct);
}
void MainWindow::closeEvent(QCloseEvent *ev)
{
if (!tabs->mainCloseEvent(ev)) {
//qDebug() << FFL << "tabs rejected close, ignoring event";
ev->ignore();
}
else {
//qDebug() << FFL << "doing saveGeometry and saveState";
MEC::settings->setValue("editor/geometry", saveGeometry());
MEC::settings->setValue("editor/windowstate", saveState());
ev->accept();
}
}
void MainWindow::about()
{
QMessageBox::about(this, tr("About"), tr("TDriver Visualizer") + "\n" + tr("Code Editor, standalone version."));
}
<commit_msg>Now editor_proto loads command line arguments with absolute file path<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver.
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mainwindow.h"
#include "tdriver_tabbededitor.h"
#include "tdriver_runconsole.h"
#include "tdriver_debugconsole.h"
#include "tdriver_rubyinteract.h"
#include <tdriver_editbar.h>
#include <tdriver_editor_common.h>
#include <tdriver_rubyinterface.h>
#include <QApplication>
#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QLabel>
#include <QMessageBox>
#include <QMenu>
#include <QDockWidget>
#include <QSettings>
#include <QCloseEvent>
#include <QStringList>
#include <tdriver_debug_macros.h>
MainWindow::MainWindow(QStringList filelist, QWidget *parent) :
QMainWindow(parent)
{
TDriverRubyInterface::startGlobalInstance();
tabs = new TDriverTabbedEditor(this, this);
runConsole = new TDriverRunConsole(true, this);
debugConsole = new TDriverDebugConsole(this);
irConsole = new TDriverRubyInteract(this);
tabs->setObjectName("editor");
runConsole->setObjectName("run");
debugConsole->setObjectName("debug");
createMenu();
setCentralWidget(tabs);
QDockWidget *runDock = new QDockWidget("Ruby Script Output");
runDock->setObjectName("run");
addDockWidget(Qt::RightDockWidgetArea, runDock);
runDock->setWidget(runConsole);
runDock->setVisible(false);
QDockWidget *debugDock = new QDockWidget("Debugger Console");
debugDock->setObjectName("debug");
addDockWidget(Qt::RightDockWidgetArea, debugDock);
debugDock->setWidget(debugConsole);
debugDock->setVisible(false);
QDockWidget *irDock = new QDockWidget("Ruby interaction Console");
irDock->setObjectName("iruby");
addDockWidget(Qt::BottomDockWidgetArea, irDock);
irDock->setWidget(irConsole);
irDock->setVisible(false);
QDockWidget *searchBarDock = new QDockWidget("Search Bar");
searchBarDock->setObjectName("searchbar");
addDockWidget(Qt::TopDockWidgetArea, searchBarDock);
searchBarDock->setWidget(tabs->searchBar());
searchBarDock->setVisible(true);
searchBarDock->setFeatures(QDockWidget::NoDockWidgetFeatures);
tabs->connectConsoles(runConsole, runDock, debugConsole, debugDock, irConsole, irDock);
connect(tabs, SIGNAL(requestRunPreparations(QString)), tabs, SLOT(proceedRun()));
restoreGeometry(MEC::settings->value("editor/geometry").toByteArray());
restoreState(MEC::settings->value("editor/windowstate").toByteArray());
// note: code below must be after connectConsoles
if (filelist.isEmpty()) {
tabs->newFile();
}
else {
foreach (QString file, filelist) {
file = MEC::absoluteFilePath(file);
if (!tabs->loadFile(file)) tabs->newFile(file);
}
}
}
void MainWindow::createMenu()
{
QAction *exitAction = new QAction(tr("E&xit"), this);
exitAction->setObjectName("exit");
QAction *aboutAct = new QAction(tr("About"), this);
aboutAct->setObjectName("about");
QAction *aboutQtAct = new QAction(tr("About Qt"), this);
aboutQtAct->setObjectName("aboutqt");
connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
menuBar()->actions().last()->setObjectName("file");
fileMenu->setObjectName("file");
fileMenu->addActions(tabs->fileActions());
fileMenu->addSeparator();
fileMenu->addActions(tabs->recentFileActions());
tabs->updateRecentFileActions();
fileMenu->addSeparator();
fileMenu->addAction(exitAction);
QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
menuBar()->actions().last()->setObjectName("edit");
editMenu->setObjectName("edit");
editMenu->addActions(tabs->editActions());
editMenu->addSeparator();
editMenu->addActions(tabs->codeActions());
QMenu *optMenu = menuBar()->addMenu(tr("&Toggles"));
menuBar()->actions().last()->setObjectName("opt");
optMenu->setObjectName("opt");
optMenu->addActions(tabs->optionActions());
QMenu *runMenu = menuBar()->addMenu(tr("&Run"));
menuBar()->actions().last()->setObjectName("run");
runMenu->setObjectName("run");
runMenu->addActions(tabs->runActions());
QMenu* aboutMenu = menuBar()->addMenu(tr("&About"));
menuBar()->actions().last()->setObjectName("about");
aboutMenu->setObjectName("about");
aboutMenu->addAction(aboutAct);
aboutMenu->addAction(aboutQtAct);
}
void MainWindow::closeEvent(QCloseEvent *ev)
{
if (!tabs->mainCloseEvent(ev)) {
//qDebug() << FFL << "tabs rejected close, ignoring event";
ev->ignore();
}
else {
//qDebug() << FFL << "doing saveGeometry and saveState";
MEC::settings->setValue("editor/geometry", saveGeometry());
MEC::settings->setValue("editor/windowstate", saveState());
ev->accept();
}
}
void MainWindow::about()
{
QMessageBox::about(this, tr("About"), tr("TDriver Visualizer") + "\n" + tr("Code Editor, standalone version."));
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
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 <organization> 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 <COPYRIGHT HOLDER> 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 <algorithm>
#include <cstring>
#include "httpd.h"
#define KTKEY 0
#define KTSKEY 1
libhttppp::HTTPDCmd::HTTPDCmd() {
_Key = NULL;
_SKey = '\0';
_Value = NULL;
_Help = NULL;
_Found = false;
_Required = false;
_nextHTTPDCmd = NULL;
}
const char *libhttppp::HTTPDCmd::getKey() {
return _Key;
}
const char libhttppp::HTTPDCmd::getShortkey() {
return _SKey;
}
const char *libhttppp::HTTPDCmd::getValue() {
return _Value;
}
size_t libhttppp::HTTPDCmd::getValueSize_t() {
return atoi(_Value);
}
int libhttppp::HTTPDCmd::getValueInt() {
return atoi(_Value);
}
const char *libhttppp::HTTPDCmd::getHelp() {
return _Help;
}
bool libhttppp::HTTPDCmd::getFound() {
return _Found;
}
bool libhttppp::HTTPDCmd::getRequired() {
return _Required;
}
libhttppp::HTTPDCmd *libhttppp::HTTPDCmd::nextHTTPDCmd() {
return _nextHTTPDCmd;
}
libhttppp::HTTPDCmd::~HTTPDCmd() {
delete[] _Key;
delete[] _Value;
delete[] _Help;
delete _nextHTTPDCmd;
}
libhttppp::HTTPDCmdController::HTTPDCmdController() {
_firstHTTPDCmd = NULL;
_lastHTTPDCmd = NULL;
}
void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey,bool required, const char *defaultvalue, const char *help) {
if (!key || !skey || !help) {
_httpexception.Cirtical("cmd parser key,skey or help not set!");
throw _httpexception;
}
/*if key exist overwriting options*/
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd=curhttpdcmd->nextHTTPDCmd()) {
if (strncmp(curhttpdcmd->getKey(), key, strlen(curhttpdcmd->getKey())) == 0) {
/*set new shortkey*/
curhttpdcmd->_SKey = skey;
/*set reqirement flag*/
curhttpdcmd->_Required = required;
/*set new value*/
delete[] curhttpdcmd->_Value;
curhttpdcmd->_Value = new char[strlen(defaultvalue)+1];
std::copy(defaultvalue, defaultvalue+strlen(defaultvalue),curhttpdcmd->_Value);
curhttpdcmd->_Value[strlen(defaultvalue)] = '\0';
/*set new help*/
delete[] curhttpdcmd->_Help;
curhttpdcmd->_Help = new char[strlen(help) + 1];
std::copy(help, help + strlen(help), curhttpdcmd->_Help);
curhttpdcmd->_Help[strlen(help)] = '\0';
return;
}
}
/*create new key value store*/
if (!_firstHTTPDCmd) {
_firstHTTPDCmd = new HTTPDCmd;
_lastHTTPDCmd = _firstHTTPDCmd;
}
else {
_lastHTTPDCmd->_nextHTTPDCmd = new HTTPDCmd;
_lastHTTPDCmd = _lastHTTPDCmd->_nextHTTPDCmd;
}
/*set new key*/
_lastHTTPDCmd->_Key = new char[strlen(key) + 1];
std::copy(key,key+strlen(key),_lastHTTPDCmd->_Key);
_lastHTTPDCmd->_Key[strlen(key)] = '\0';
/*set new shortkey*/
_lastHTTPDCmd->_SKey = skey;
/*set reqirement flag*/
_lastHTTPDCmd->_Required = required;
/*set new value*/
if (defaultvalue) {
_lastHTTPDCmd->_Value = new char[strlen(defaultvalue) + 1];
std::copy(defaultvalue, defaultvalue + strlen(defaultvalue), _lastHTTPDCmd->_Value);
_lastHTTPDCmd->_Value[strlen(defaultvalue)] = '\0';
}
/*set new help*/
_lastHTTPDCmd->_Help = new char[strlen(help) + 1];
std::copy(help, help + strlen(help), _lastHTTPDCmd->_Help);
_lastHTTPDCmd->_Help[strlen(help)] = '\0';
}
void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, size_t defaultvalue, const char *help) {
char buf[255];
snprintf(buf, sizeof(buf), "%zu", defaultvalue);
registerCmd(key,skey,required,buf,help);
}
void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, int defaultvalue, const char *help) {
char buf[255];
snprintf(buf, sizeof(buf), "%d", defaultvalue);
registerCmd(key, skey, required, buf, help);
}
void libhttppp::HTTPDCmdController::parseCmd(int argc, char** argv){
for (int args = 1; args < argc; args++) {
int keytype = -1;
if (argv[args][0]=='-' && argv[args][1] == '-') {
keytype = KTKEY;
}else if (argv[args][0] == '-'){
keytype = KTSKEY;
}else {
break;
}
size_t kendpos = strlen(argv[args]);
for (size_t cmdpos = 0; cmdpos < strlen(argv[args])+1; cmdpos++) {
switch (argv[args][cmdpos]) {
case '=': {
kendpos = cmdpos;
};
}
}
char *key = NULL;
char skey = '0';
if (keytype == KTKEY) {
key = new char[kendpos-1];
std::copy(argv[args] +2, argv[args] +kendpos, key);
key[kendpos - 2] = '\0';
} else if (keytype == KTSKEY){
skey = argv[args][1];
}
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
if (keytype == KTKEY) {
if (strncmp(curhttpdcmd->getKey(), key, strlen(curhttpdcmd->getKey())) == 0) {
curhttpdcmd->_Found = true;
int valuesize = (strlen(argv[args]) - (kendpos+1));
if (valuesize > 0) {
curhttpdcmd->_Value = new char[valuesize+1];
std::copy(argv[args]+(kendpos+1), argv[args] + strlen(argv[args]),curhttpdcmd->_Value);
curhttpdcmd->_Value[valuesize] = '\0';
}
}
} else if (keytype == KTSKEY) {
if (curhttpdcmd->getShortkey()== skey) {
curhttpdcmd->_Found = true;
int valuesize = (strlen(argv[args]) - (kendpos + 1));
if (valuesize > 0) {
curhttpdcmd->_Value = new char[valuesize + 1];
std::copy(argv[args] + (kendpos + 1), argv[args] + strlen(argv[args]), curhttpdcmd->_Value);
curhttpdcmd->_Value[valuesize] = '\0';
}
}
}
}
delete[] key;
}
}
bool libhttppp::HTTPDCmdController::checkRequired() {
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
if (curhttpdcmd->getRequired() && !curhttpdcmd->_Found) {
return false;
}
}
return true;
}
void libhttppp::HTTPDCmdController::printHelp() {
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
printf("--%s -%c %s\n",curhttpdcmd->getKey(),curhttpdcmd->getShortkey(),curhttpdcmd->getHelp());
}
}
libhttppp::HTTPDCmd *libhttppp::HTTPDCmdController::getHTTPDCmdbyKey(const char *key) {
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
if (strncmp(curhttpdcmd->getKey(), key, strlen(curhttpdcmd->getKey())) == 0) {
return curhttpdcmd;
}
}
return NULL;
}
libhttppp::HTTPDCmdController::~HTTPDCmdController() {
delete _firstHTTPDCmd;
_lastHTTPDCmd = NULL;
}
libhttppp::HttpD::HttpD(int argc, char** argv) : HTTPDCmdController::HTTPDCmdController(){
/*Register Parameters*/
registerCmd("help", 'h', false, (const char*) NULL, "Helpmenu");
registerCmd("httpaddr",'a', true,"0.0.0.0","Address to listen");
#ifndef Windows
registerCmd("httpport", 'p', false, 0, "Port to listen");
#else
registerCmd("httpport", 'p', true,0, "Port to listen");
#endif
registerCmd("maxconnections", 'm',false, MAXDEFAULTCONN, "Max connections that can connect");
registerCmd("httpscert", 'c',false,(const char*) NULL, "HTTPS Certfile");
registerCmd("httpskey", 'k',false, (const char*) NULL, "HTTPS Keyfile");
/*Parse Parameters*/
parseCmd(argc,argv);
if (!checkRequired()) {
printHelp();
_httpexception.Cirtical("cmd parser not enough arguments given");
throw _httpexception;
}
if (getHTTPDCmdbyKey("help") && getHTTPDCmdbyKey("help")->getFound()) {
printHelp();
return;
}
/*get port from console paramter*/
int port = 0;
if(getHTTPDCmdbyKey("httpport"))
port = getHTTPDCmdbyKey("httpport")->getValueInt();
/*get httpaddress from console paramter*/
const char *httpaddr = NULL;
if (getHTTPDCmdbyKey("httpaddr"))
httpaddr = getHTTPDCmdbyKey("httpaddr")->getValue();
/*get max connections from console paramter*/
int maxconnections = 0;
if (getHTTPDCmdbyKey("maxconnections"))
maxconnections = getHTTPDCmdbyKey("maxconnections")->getValueInt();
/*get httpaddress from console paramter*/
const char *sslcertpath = NULL;
if (getHTTPDCmdbyKey("httpscert"))
sslcertpath = getHTTPDCmdbyKey("httpscert")->getValue();
/*get httpaddress from console paramter*/
const char *sslkeypath = NULL;
if (getHTTPDCmdbyKey("httpskey"))
sslkeypath = getHTTPDCmdbyKey("httpskey")->getValue();
try {
if (port != 0)
_ServerSocket = new ServerSocket(httpaddr, port, maxconnections);
#ifndef Windows
else
_ServerSocket = new ServerSocket(httpaddr, maxconnections);
#endif
if (!_ServerSocket) {
throw _httpexception;
}
_ServerSocket->setnonblocking();
_ServerSocket->listenSocket();
if (sslcertpath && sslkeypath) {
printf("%s : %s", sslcertpath, sslkeypath);
_ServerSocket->createContext();
_ServerSocket->loadCertfile(sslcertpath);
_ServerSocket->loadKeyfile(sslkeypath);
}
}catch (HTTPException &e) {
}
}
libhttppp::ServerSocket *libhttppp::HttpD::getServerSocket(){
return _ServerSocket;
}
libhttppp::HttpD::~HttpD(){
delete _ServerSocket;
}
<commit_msg>fixed memory leak httpd<commit_after>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
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 <organization> 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 <COPYRIGHT HOLDER> 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 <algorithm>
#include <cstring>
#include "httpd.h"
#define KTKEY 0
#define KTSKEY 1
libhttppp::HTTPDCmd::HTTPDCmd() {
_Key = NULL;
_SKey = '\0';
_Value = NULL;
_Help = NULL;
_Found = false;
_Required = false;
_nextHTTPDCmd = NULL;
}
const char *libhttppp::HTTPDCmd::getKey() {
return _Key;
}
const char libhttppp::HTTPDCmd::getShortkey() {
return _SKey;
}
const char *libhttppp::HTTPDCmd::getValue() {
return _Value;
}
size_t libhttppp::HTTPDCmd::getValueSize_t() {
return atoi(_Value);
}
int libhttppp::HTTPDCmd::getValueInt() {
return atoi(_Value);
}
const char *libhttppp::HTTPDCmd::getHelp() {
return _Help;
}
bool libhttppp::HTTPDCmd::getFound() {
return _Found;
}
bool libhttppp::HTTPDCmd::getRequired() {
return _Required;
}
libhttppp::HTTPDCmd *libhttppp::HTTPDCmd::nextHTTPDCmd() {
return _nextHTTPDCmd;
}
libhttppp::HTTPDCmd::~HTTPDCmd() {
delete[] _Key;
delete[] _Value;
delete[] _Help;
delete _nextHTTPDCmd;
}
libhttppp::HTTPDCmdController::HTTPDCmdController() {
_firstHTTPDCmd = NULL;
_lastHTTPDCmd = NULL;
}
void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey,bool required, const char *defaultvalue, const char *help) {
if (!key || !skey || !help) {
_httpexception.Cirtical("cmd parser key,skey or help not set!");
throw _httpexception;
}
/*if key exist overwriting options*/
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd=curhttpdcmd->nextHTTPDCmd()) {
if (strncmp(curhttpdcmd->getKey(), key, strlen(curhttpdcmd->getKey())) == 0) {
/*set new shortkey*/
curhttpdcmd->_SKey = skey;
/*set reqirement flag*/
curhttpdcmd->_Required = required;
/*set new value*/
delete[] curhttpdcmd->_Value;
curhttpdcmd->_Value = new char[strlen(defaultvalue)+1];
std::copy(defaultvalue, defaultvalue+strlen(defaultvalue),curhttpdcmd->_Value);
curhttpdcmd->_Value[strlen(defaultvalue)] = '\0';
/*set new help*/
delete[] curhttpdcmd->_Help;
curhttpdcmd->_Help = new char[strlen(help) + 1];
std::copy(help, help + strlen(help), curhttpdcmd->_Help);
curhttpdcmd->_Help[strlen(help)] = '\0';
return;
}
}
/*create new key value store*/
if (!_firstHTTPDCmd) {
_firstHTTPDCmd = new HTTPDCmd;
_lastHTTPDCmd = _firstHTTPDCmd;
}
else {
_lastHTTPDCmd->_nextHTTPDCmd = new HTTPDCmd;
_lastHTTPDCmd = _lastHTTPDCmd->_nextHTTPDCmd;
}
/*set new key*/
_lastHTTPDCmd->_Key = new char[strlen(key) + 1];
std::copy(key,key+strlen(key),_lastHTTPDCmd->_Key);
_lastHTTPDCmd->_Key[strlen(key)] = '\0';
/*set new shortkey*/
_lastHTTPDCmd->_SKey = skey;
/*set reqirement flag*/
_lastHTTPDCmd->_Required = required;
/*set new value*/
if (defaultvalue) {
_lastHTTPDCmd->_Value = new char[strlen(defaultvalue) + 1];
std::copy(defaultvalue, defaultvalue + strlen(defaultvalue), _lastHTTPDCmd->_Value);
_lastHTTPDCmd->_Value[strlen(defaultvalue)] = '\0';
}
/*set new help*/
_lastHTTPDCmd->_Help = new char[strlen(help) + 1];
std::copy(help, help + strlen(help), _lastHTTPDCmd->_Help);
_lastHTTPDCmd->_Help[strlen(help)] = '\0';
}
void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, size_t defaultvalue, const char *help) {
char buf[255];
snprintf(buf, sizeof(buf), "%zu", defaultvalue);
registerCmd(key,skey,required,buf,help);
}
void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, int defaultvalue, const char *help) {
char buf[255];
snprintf(buf, sizeof(buf), "%d", defaultvalue);
registerCmd(key, skey, required, buf, help);
}
void libhttppp::HTTPDCmdController::parseCmd(int argc, char** argv){
for (int args = 1; args < argc; args++) {
int keytype = -1;
if (argv[args][0]=='-' && argv[args][1] == '-') {
keytype = KTKEY;
}else if (argv[args][0] == '-'){
keytype = KTSKEY;
}else {
break;
}
size_t kendpos = strlen(argv[args]);
for (size_t cmdpos = 0; cmdpos < strlen(argv[args])+1; cmdpos++) {
switch (argv[args][cmdpos]) {
case '=': {
kendpos = cmdpos;
};
}
}
char *key = NULL;
char skey = '0';
if (keytype == KTKEY) {
key = new char[kendpos-1];
std::copy(argv[args] +2, argv[args] +kendpos, key);
key[kendpos - 2] = '\0';
} else if (keytype == KTSKEY){
skey = argv[args][1];
}
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
if (keytype == KTKEY) {
if (strncmp(curhttpdcmd->getKey(), key, strlen(curhttpdcmd->getKey())) == 0) {
curhttpdcmd->_Found = true;
int valuesize = (strlen(argv[args]) - (kendpos+1));
if (valuesize > 0) {
delete[] curhttpdcmd->_Value;
curhttpdcmd->_Value = new char[valuesize+1];
std::copy(argv[args]+(kendpos+1), argv[args] + strlen(argv[args]),curhttpdcmd->_Value);
curhttpdcmd->_Value[valuesize] = '\0';
}
}
} else if (keytype == KTSKEY) {
if (curhttpdcmd->getShortkey()== skey) {
curhttpdcmd->_Found = true;
int valuesize = (strlen(argv[args]) - (kendpos + 1));
if (valuesize > 0) {
delete[] curhttpdcmd->_Value;
curhttpdcmd->_Value = new char[valuesize + 1];
std::copy(argv[args] + (kendpos + 1), argv[args] + strlen(argv[args]), curhttpdcmd->_Value);
curhttpdcmd->_Value[valuesize] = '\0';
}
}
}
}
delete[] key;
}
}
bool libhttppp::HTTPDCmdController::checkRequired() {
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
if (curhttpdcmd->getRequired() && !curhttpdcmd->_Found) {
return false;
}
}
return true;
}
void libhttppp::HTTPDCmdController::printHelp() {
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
printf("--%s -%c %s\n",curhttpdcmd->getKey(),curhttpdcmd->getShortkey(),curhttpdcmd->getHelp());
}
}
libhttppp::HTTPDCmd *libhttppp::HTTPDCmdController::getHTTPDCmdbyKey(const char *key) {
for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
if (strncmp(curhttpdcmd->getKey(), key, strlen(curhttpdcmd->getKey())) == 0) {
return curhttpdcmd;
}
}
return NULL;
}
libhttppp::HTTPDCmdController::~HTTPDCmdController() {
delete _firstHTTPDCmd;
_lastHTTPDCmd = NULL;
}
libhttppp::HttpD::HttpD(int argc, char** argv) : HTTPDCmdController::HTTPDCmdController(){
/*Register Parameters*/
registerCmd("help", 'h', false, (const char*) NULL, "Helpmenu");
registerCmd("httpaddr",'a', true,"0.0.0.0","Address to listen");
#ifndef Windows
registerCmd("httpport", 'p', false, 0, "Port to listen");
#else
registerCmd("httpport", 'p', true,0, "Port to listen");
#endif
registerCmd("maxconnections", 'm',false, MAXDEFAULTCONN, "Max connections that can connect");
registerCmd("httpscert", 'c',false,(const char*) NULL, "HTTPS Certfile");
registerCmd("httpskey", 'k',false, (const char*) NULL, "HTTPS Keyfile");
/*Parse Parameters*/
parseCmd(argc,argv);
if (!checkRequired()) {
printHelp();
_httpexception.Cirtical("cmd parser not enough arguments given");
throw _httpexception;
}
if (getHTTPDCmdbyKey("help") && getHTTPDCmdbyKey("help")->getFound()) {
printHelp();
return;
}
/*get port from console paramter*/
int port = 0;
if(getHTTPDCmdbyKey("httpport"))
port = getHTTPDCmdbyKey("httpport")->getValueInt();
/*get httpaddress from console paramter*/
const char *httpaddr = NULL;
if (getHTTPDCmdbyKey("httpaddr"))
httpaddr = getHTTPDCmdbyKey("httpaddr")->getValue();
/*get max connections from console paramter*/
int maxconnections = 0;
if (getHTTPDCmdbyKey("maxconnections"))
maxconnections = getHTTPDCmdbyKey("maxconnections")->getValueInt();
/*get httpaddress from console paramter*/
const char *sslcertpath = NULL;
if (getHTTPDCmdbyKey("httpscert"))
sslcertpath = getHTTPDCmdbyKey("httpscert")->getValue();
/*get httpaddress from console paramter*/
const char *sslkeypath = NULL;
if (getHTTPDCmdbyKey("httpskey"))
sslkeypath = getHTTPDCmdbyKey("httpskey")->getValue();
try {
if (port != 0)
_ServerSocket = new ServerSocket(httpaddr, port, maxconnections);
#ifndef Windows
else
_ServerSocket = new ServerSocket(httpaddr, maxconnections);
#endif
if (!_ServerSocket) {
throw _httpexception;
}
_ServerSocket->setnonblocking();
_ServerSocket->listenSocket();
if (sslcertpath && sslkeypath) {
printf("%s : %s", sslcertpath, sslkeypath);
_ServerSocket->createContext();
_ServerSocket->loadCertfile(sslcertpath);
_ServerSocket->loadKeyfile(sslkeypath);
}
}catch (HTTPException &e) {
}
}
libhttppp::ServerSocket *libhttppp::HttpD::getServerSocket(){
return _ServerSocket;
}
libhttppp::HttpD::~HttpD(){
delete _ServerSocket;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "Quaternion.h"
#include "Vector3.h"
#include "LuaStack.h"
#include "LuaEnvironment.h"
namespace crown
{
//-----------------------------------------------------------------------------
static int quaternionbox_new(lua_State* L)
{
LuaStack stack(L);
Quaternion q;
if (stack.num_args() == 2)
{
const Vector3& v = stack.get_vector3(1);
q.x = v.x;
q.y = v.y;
q.z = v.z;
q.w = stack.get_float(2);
}
else if (stack.num_args() == 4)
{
q.x = stack.get_float(1);
q.y = stack.get_float(2);
q.z = stack.get_float(3);
q.w = stack.get_float(4);
}
stack.push_quaternionbox(q);
return 1;
}
//-----------------------------------------------------------------------------
static int quaternionbox_ctor(lua_State* L)
{
LuaStack stack(L);
stack.remove(1); // Remove table
return quaternionbox_new(L);
}
//-----------------------------------------------------------------------------
static int quaternionbox_store(lua_State* L)
{
LuaStack stack(L);
Quaternion& q = stack.get_quaternionbox(1);
if (stack.num_args() == 3)
{
const Vector3& v = stack.get_vector3(1);
q.x = v.x;
q.y = v.y;
q.z = v.z;
q.w = stack.get_float(2);
}
else if (stack.num_args() == 5)
{
q.x = stack.get_float(1);
q.y = stack.get_float(2);
q.z = stack.get_float(3);
q.w = stack.get_float(4);
}
return 0;
}
//-----------------------------------------------------------------------------
static int quaternionbox_unbox(lua_State* L)
{
LuaStack stack(L);
Quaternion& q = stack.get_quaternionbox(1);
stack.push_quaternion(q);
return 1;
}
//-----------------------------------------------------------------------------
static int quaternionbox_tostring(lua_State* L)
{
LuaStack stack(L);
Quaternion& q = stack.get_quaternionbox(1);
stack.push_fstring("QuaternionBox (%p)", &q);
return 1;
}
//-----------------------------------------------------------------------------
void load_quaternionbox(LuaEnvironment& env)
{
env.load_module_function("QuaternionBox", "new", quaternionbox_new);
env.load_module_function("QuaternionBox", "store", quaternionbox_store);
env.load_module_function("QuaternionBox", "unbox", quaternionbox_unbox);
env.load_module_function("QuaternionBox", "__tostring", quaternionbox_tostring);
env.load_module_constructor("QuaternionBox", quaternionbox_ctor);
}
} // namespace crown
<commit_msg>fix LuaQuaternionBox<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "Quaternion.h"
#include "Vector3.h"
#include "LuaStack.h"
#include "LuaEnvironment.h"
namespace crown
{
//-----------------------------------------------------------------------------
static int quaternionbox_new(lua_State* L)
{
LuaStack stack(L);
Quaternion q;
if (stack.num_args() == 1)
{
q = stack.get_quaternion(1);
}
if (stack.num_args() == 2)
{
Quaternion quat(stack.get_vector3(1), stack.get_float(2));
q = quat;
}
else if (stack.num_args() == 4)
{
Quaternion quat(stack.get_float(1), stack.get_float(2), stack.get_float(3), stack.get_float(4));
q = quat;
}
stack.push_quaternionbox(q);
return 1;
}
//-----------------------------------------------------------------------------
static int quaternionbox_ctor(lua_State* L)
{
LuaStack stack(L);
stack.remove(1); // Remove table
return quaternionbox_new(L);
}
//-----------------------------------------------------------------------------
static int quaternionbox_store(lua_State* L)
{
LuaStack stack(L);
Quaternion& q = stack.get_quaternionbox(1);
if (stack.num_args() == 2)
{
q = stack.get_quaternion(2);
}
if (stack.num_args() == 3)
{
Quaternion quat(stack.get_vector3(2), stack.get_float(3));
q = quat;
}
else if (stack.num_args() == 5)
{
Quaternion quat(stack.get_float(2), stack.get_float(3), stack.get_float(4), stack.get_float(5));
q = quat;
}
return 0;
}
//-----------------------------------------------------------------------------
static int quaternionbox_unbox(lua_State* L)
{
LuaStack stack(L);
Quaternion& q = stack.get_quaternionbox(1);
stack.push_quaternion(q);
return 1;
}
//-----------------------------------------------------------------------------
static int quaternionbox_tostring(lua_State* L)
{
LuaStack stack(L);
Quaternion& q = stack.get_quaternionbox(1);
stack.push_fstring("QuaternionBox (%p)", &q);
return 1;
}
//-----------------------------------------------------------------------------
void load_quaternionbox(LuaEnvironment& env)
{
env.load_module_function("QuaternionBox", "new", quaternionbox_new);
env.load_module_function("QuaternionBox", "store", quaternionbox_store);
env.load_module_function("QuaternionBox", "unbox", quaternionbox_unbox);
env.load_module_function("QuaternionBox", "__tostring", quaternionbox_tostring);
env.load_module_constructor("QuaternionBox", quaternionbox_ctor);
}
} // namespace crown
<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both iopd and iop-core, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Satoshi");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/iop/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
<commit_msg>fixed client name<commit_after>// Copyright (c) 2012-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both iopd and iop-core, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("IoP-HD");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/iop/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both bitcoind and bitcoin-core, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Satoshi");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
<commit_msg>0.14.2 rc0<commit_after>// Copyright (c) 2012-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both bitcoind and bitcoin-core, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Satoshi");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX "-rc0"
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "$Format:%h$"
#define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "fnord-cstable/UInt32ColumnReader.h"
#include "fnord-cstable/UInt32ColumnWriter.h"
#include "fnord-cstable/BooleanColumnReader.h"
#include "fnord-cstable/BooleanColumnWriter.h"
#include "fnord-cstable/CSTableWriter.h"
#include "fnord-cstable/CSTableReader.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include "analytics/AnalyticsTableScan.h"
#include "analytics/CTRByPositionQuery.h"
using namespace fnord;
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"input_file",
fnord::cli::FlagParser::T_STRING,
true,
"i",
NULL,
"file",
"<filename>");
flags.defineFlag(
"output_file",
fnord::cli::FlagParser::T_STRING,
true,
"o",
NULL,
"file",
"<filename>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
size_t debug_n = 0;
size_t debug_z = 0;
/* query level */
cstable::UInt32ColumnWriter jq_page_col(1, 1, 100);
cstable::UInt32ColumnWriter jq_lang_col(1, 1, kMaxLanguage);
/* query item level */
cstable::UInt32ColumnWriter jqi_position_col(2, 2, 64);
cstable::BooleanColumnWriter jqi_clicked_col(2, 2);
uint64_t r = 0;
uint64_t n = 0;
auto add_session = [&] (const cm::JoinedSession& sess) {
++n;
for (const auto& q : sess.queries) {
auto pg_str = cm::extractAttr(q.attrs, "pg");
if (pg_str.isEmpty()) {
jq_page_col.addNull(r, 1);
} else {
jq_page_col.addDatum(r, 1, std::stoul(pg_str.get()));
}
auto lang = cm::extractLanguage(q.attrs);
uint32_t l = (uint16_t) lang;
jq_lang_col.addDatum(r, 1, l);
if (q.items.size() == 0) {
jqi_position_col.addNull(r, 1);
jqi_clicked_col.addNull(r, 1);
}
for (const auto& i : q.items) {
jqi_position_col.addDatum(r, 2, i.position);
jqi_clicked_col.addDatum(r, 2, i.clicked);
r = 2;
}
r = 1;
}
r = 0;
};
/* read input tables */
int row_idx = 0;
const auto& sstable = flags.getString("input_file");
fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable);
/* read sstable header */
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable);
exit(1);
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
fnord::logInfo(
"cm.jqcolumnize",
"[$0%] Reading sstable... rows=$1",
(size_t) ((cursor->position() / (double) body_size) * 100),
row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
auto key = cursor->getKeyString();
auto val = cursor->getDataBuffer();
Option<cm::JoinedQuery> q;
try {
q = Some(json::fromJSON<cm::JoinedQuery>(val));
} catch (const Exception& e) {
fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString());
}
if (!q.isEmpty()) {
cm::JoinedSession s;
s.queries.emplace_back(q.get());
add_session(s);
}
if (!cursor->next()) {
break;
}
}
status_line.runForce();
{
cstable::CSTableWriter writer(flags.getString("output_file") + "~", n);
writer.addColumn("queries.page", &jq_page_col);
writer.addColumn("queries.language", &jq_lang_col);
writer.addColumn("queries.items.position", &jqi_position_col);
writer.addColumn("queries.items.clicked", &jqi_clicked_col);
writer.commit();
}
FileUtil::mv(
flags.getString("output_file") + "~",
flags.getString("output_file"));
//{
// cstable::CSTableReader reader(flags.getString("output_file"));
// auto t0 = WallClock::unixMicros();
// cm::AnalyticsTableScan aq;
// cm::CTRByPositionQueryResult res;
// cm::CTRByPositionQuery q(&aq, &res);
// aq.scanTable(&reader);
// auto t1 = WallClock::unixMicros();
// fnord::iputs("scanned $0 rows in $1 ms", res.rows_scanned, (t1 - t0) / 1000.0f);
// for (const auto& p : res.counters) {
// fnord::iputs(
// "pos: $0, views: $1, clicks: $2, ctr: $3",
// p.first, p.second.num_views,
// p.second.num_clicks,
// p.second.num_clicks / (double) p.second.num_views);
// }
//}
return 0;
}
<commit_msg>CTRByGroupResult<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "fnord-cstable/UInt32ColumnReader.h"
#include "fnord-cstable/UInt32ColumnWriter.h"
#include "fnord-cstable/BooleanColumnReader.h"
#include "fnord-cstable/BooleanColumnWriter.h"
#include "fnord-cstable/CSTableWriter.h"
#include "fnord-cstable/CSTableReader.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include "analytics/AnalyticsTableScan.h"
#include "analytics/CTRByPositionQuery.h"
using namespace fnord;
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"input_file",
fnord::cli::FlagParser::T_STRING,
true,
"i",
NULL,
"file",
"<filename>");
flags.defineFlag(
"output_file",
fnord::cli::FlagParser::T_STRING,
true,
"o",
NULL,
"file",
"<filename>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
size_t debug_n = 0;
size_t debug_z = 0;
/* query level */
cstable::UInt32ColumnWriter jq_page_col(1, 1, 100);
cstable::UInt32ColumnWriter jq_lang_col(1, 1, kMaxLanguage);
/* query item level */
cstable::UInt32ColumnWriter jqi_position_col(2, 2, 64);
cstable::BooleanColumnWriter jqi_clicked_col(2, 2);
uint64_t r = 0;
uint64_t n = 0;
auto add_session = [&] (const cm::JoinedSession& sess) {
++n;
for (const auto& q : sess.queries) {
auto pg_str = cm::extractAttr(q.attrs, "pg");
if (pg_str.isEmpty()) {
jq_page_col.addNull(r, 1);
} else {
jq_page_col.addDatum(r, 1, std::stoul(pg_str.get()));
}
auto lang = cm::extractLanguage(q.attrs);
uint32_t l = (uint16_t) lang;
jq_lang_col.addDatum(r, 1, l);
if (q.items.size() == 0) {
jqi_position_col.addNull(r, 1);
jqi_clicked_col.addNull(r, 1);
}
for (const auto& i : q.items) {
jqi_position_col.addDatum(r, 2, i.position);
jqi_clicked_col.addDatum(r, 2, i.clicked);
r = 2;
}
r = 1;
}
r = 0;
};
/* read input tables */
int row_idx = 0;
const auto& sstable = flags.getString("input_file");
fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable);
/* read sstable header */
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable);
exit(1);
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
fnord::logInfo(
"cm.jqcolumnize",
"[$0%] Reading sstable... rows=$1",
(size_t) ((cursor->position() / (double) body_size) * 100),
row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
auto key = cursor->getKeyString();
auto val = cursor->getDataBuffer();
Option<cm::JoinedQuery> q;
try {
q = Some(json::fromJSON<cm::JoinedQuery>(val));
} catch (const Exception& e) {
fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString());
}
if (!q.isEmpty()) {
cm::JoinedSession s;
s.queries.emplace_back(q.get());
add_session(s);
}
if (!cursor->next()) {
break;
}
}
status_line.runForce();
{
cstable::CSTableWriter writer(flags.getString("output_file") + "~", n);
writer.addColumn("queries.page", &jq_page_col);
writer.addColumn("queries.language", &jq_lang_col);
writer.addColumn("queries.items.position", &jqi_position_col);
writer.addColumn("queries.items.clicked", &jqi_clicked_col);
writer.commit();
}
FileUtil::mv(
flags.getString("output_file") + "~",
flags.getString("output_file"));
//{
// cstable::CSTableReader reader(flags.getString("output_file"));
// auto t0 = WallClock::unixMicros();
// cm::AnalyticsTableScan aq;
// cm::CTRByGroupResult res;
// cm::CTRByPositionQuery q(&aq, &res);
// aq.scanTable(&reader);
// auto t1 = WallClock::unixMicros();
// fnord::iputs("scanned $0 rows in $1 ms", res.rows_scanned, (t1 - t0) / 1000.0f);
// for (const auto& p : res.counters) {
// fnord::iputs(
// "pos: $0, views: $1, clicks: $2, ctr: $3",
// p.first, p.second.num_views,
// p.second.num_clicks,
// p.second.num_clicks / (double) p.second.num_views);
// }
//}
return 0;
}
<|endoftext|>
|
<commit_before>#include "tx.h"
#include <iostream> // cerr
#include <iterator>
#include <set>
#include <sstream>
#include <vector>
#include "base58.h"
#include "crypto.h"
#include "node.h"
#include "node_factory.h"
#include "openssl/sha.h"
bytes_t UnspentTxo::GetSigningAddress() const {
if (script.size() == 25 &&
script[0] == 0x76 && script[1] == 0xa9 && script[2] == 0x14 &&
script[23] == 0x88 && script[24] == 0xac) {
// Standard Pay-to-PubkeyHash.
// https://en.bitcoin.it/wiki/Transactions
return bytes_t(script.begin() + 3, script.begin() + 3 + 20);
}
if (script.size() == 23 &&
script[0] == 0xa9 && script[1] == 0x14 &&
script[22] == 0x87) {
// Standard Pay-to-ScriptHash.
// https://en.bitcoin.it/wiki/Transactions
return bytes_t(script.begin() + 2, script.begin() + 2 + 20);
}
return bytes_t();
}
TxOut::TxOut(const bytes_t& hash_, uint64_t value_) :
hash(hash_), value(value_) {}
Tx::Tx(const Node& sending_node,
const unspent_txos_t unspent_txos,
const bytes_t recipient_hash160,
uint64_t value,
uint64_t fee,
uint32_t change_index) :
sending_node_(sending_node),
unspent_txos_(unspent_txos),
recipient_hash160_(recipient_hash160),
value_(value),
fee_(fee),
change_index_(change_index),
change_value_(0) {
}
Tx::~Tx() {
}
bool Tx::CreateSignedTransaction(bytes_t& signed_tx) {
required_unspent_txos_.clear();
change_value_ = 0;
// Identify enough unspent_txos to cover transaction value.
uint64_t required_value = fee_ + value_;
for (unspent_txos_t::const_reverse_iterator i = unspent_txos_.rbegin();
i != unspent_txos_.rend();
++i) {
if (required_value == 0) {
break;
}
required_unspent_txos_.push_back(*i);
if (required_value >= i->value) {
required_value -= i->value;
} else {
change_value_ = i->value - required_value;
required_value = 0;
}
}
if (required_value != 0) {
// Not enough funds to cover transaction.
std::cerr << "Not enough funds" << std::endl;
return false;
}
// We know which unspent_txos we intend to use. Create a set of
// required addresses. Note that an address here is the hash160,
// because that's the format embedded in the script.
std::set<bytes_t> required_signing_addresses;
for (unspent_txos_t::reverse_iterator i = required_unspent_txos_.rbegin();
i != required_unspent_txos_.rend();
++i) {
required_signing_addresses.insert(i->GetSigningAddress());
}
// Do we have all the keys for the required addresses? Generate
// them. For now we're going to assume no account has more than 16
// addresses, so that's the farthest we'll walk down the chain.
uint32_t start = 0;
uint32_t count = 16;
signing_addresses_to_keys_.clear();
for (uint32_t i = 0; i < count; ++i) {
std::stringstream node_path;
node_path << "m/" << (start + i);
Node* node =
NodeFactory::DeriveChildNodeWithPath(sending_node_, node_path.str());
bytes_t hash160 = Base58::toHash160(node->public_key());
if (required_signing_addresses.find(hash160) !=
required_signing_addresses.end()) {
signing_addresses_to_keys_[hash160] = node->secret_key();
}
delete node;
if (signing_addresses_to_keys_.size() ==
required_signing_addresses.size()) {
break;
}
}
if (signing_addresses_to_keys_.size() !=
required_signing_addresses.size()) {
// We don't have all the keys we need to spend these funds.
std::cerr << "missing some keys" << std::endl;
return false;
}
recipients_.clear();
TxOut txout(recipient_hash160_, value_);
recipients_.push_back(txout);
if (change_value_ != 0) {
// Derive the change address
std::stringstream node_path;
node_path << "m/" << (change_index_);
Node* node =
NodeFactory::DeriveChildNodeWithPath(sending_node_, node_path.str());
bytes_t hash160 = Base58::toHash160(node->public_key());
recipients_.push_back(TxOut(hash160, change_value_));
delete node;
}
// Now loop through and sign each txin individually.
// https://en.bitcoin.it/w/images/en/7/70/Bitcoin_OpCheckSig_InDetail.png
for (unspent_txos_t::iterator
i = required_unspent_txos_.begin();
i != required_unspent_txos_.end();
++i) {
bytes_t script_sig;
// TODO(miket): this is actually supposed to be the serialization
// of the previous txo's script. We're just assuming it's a
// standard P2PH and reconstructing what it would have been.
script_sig.push_back(0x76); // OP_DUP
script_sig.push_back(0xa9); // OP_HASH160
script_sig.push_back(0x14); // 20 bytes, should probably assert == hashlen
bytes_t signing_address = i->GetSigningAddress();
script_sig.insert(script_sig.end(),
signing_address.begin(),
signing_address.end());
script_sig.push_back(0x88); // OP_EQUALVERIFY
script_sig.push_back(0xac); // OP_CHECKSIG
i->script_sig = script_sig;
bytes_t tx_with_one_script_sig = SerializeTransaction();
// SIGHASH_ALL
tx_with_one_script_sig.push_back(1);
tx_with_one_script_sig.push_back(0);
tx_with_one_script_sig.push_back(0);
tx_with_one_script_sig.push_back(0);
bytes_t digest;
digest.resize(SHA256_DIGEST_LENGTH);
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256,
&tx_with_one_script_sig[0],
tx_with_one_script_sig.size());
SHA256_Final(&digest[0], &sha256);
SHA256_Init(&sha256);
SHA256_Update(&sha256, &digest[0], digest.capacity());
SHA256_Final(&digest[0], &sha256);
bytes_t signature;
Crypto::Sign(signing_addresses_to_keys_[signing_address],
digest,
signature);
script_sigs_.push_back(signature);
// And clear the sig again for the next one.
i->script_sig.clear();
}
// We now have all the signatures. Stick them in.
unspent_txos_t::iterator i = required_unspent_txos_.begin();
std::vector<bytes_t>::const_iterator j = script_sigs_.begin();
for (;
i != required_unspent_txos_.end();
++i, ++j) {
i->script_sig = *j;
}
// And finally serialize once more with all the signatures installed.
signed_tx = SerializeTransaction();
//std::cerr << to_hex(signed_tx) << std::endl;
return true;
}
bytes_t Tx::SerializeTransaction() {
bytes_t signed_tx;
signed_tx.resize(0);
// https://en.bitcoin.it/wiki/Transactions
// Version 1
signed_tx.push_back(1);
signed_tx.push_back(0);
signed_tx.push_back(0);
signed_tx.push_back(0);
// Number of inputs
if (required_unspent_txos_.size() >= 0xfd) {
// TODO: implement varint
std::cerr << "too many inputs" << std::endl;
return bytes_t();
}
signed_tx.push_back(required_unspent_txos_.size() & 0xff);
// txin
for (unspent_txos_t::const_iterator i = required_unspent_txos_.begin();
i != required_unspent_txos_.end();
++i) {
// For some stupid reason the hash is serialized backwards.
for (bytes_t::const_reverse_iterator j = i->hash.rbegin();
j != i->hash.rend();
++j) {
signed_tx.push_back(*j);
}
// Previous TXO index
signed_tx.push_back((i->output_n) & 0xff);
signed_tx.push_back((i->output_n >> 8) & 0xff);
signed_tx.push_back((i->output_n >> 16) & 0xff);
signed_tx.push_back((i->output_n >> 24) & 0xff);
// TODO ScriptSig
// https://en.bitcoin.it/wiki/OP_CHECKSIG
if (i->script_sig.size() > 0xfd) {
// TODO: implement varint
std::cerr << "script_sig too big" << std::endl;
return bytes_t();
}
signed_tx.push_back(i->script_sig.size() & 0xff);
signed_tx.insert(signed_tx.end(),
i->script_sig.begin(),
i->script_sig.end());
// sequence_no
signed_tx.push_back(0xff);
signed_tx.push_back(0xff);
signed_tx.push_back(0xff);
signed_tx.push_back(0xff);
}
// Number of outputs
if (recipients_.size() >= 0xfd) {
// TODO: implement varint
std::cerr << "too many recipients" << std::endl;
return bytes_t();
}
signed_tx.push_back(recipients_.size() & 0xff);
for (tx_outs_t::iterator i = recipients_.begin();
i != recipients_.end();
++i) {
uint64_t recipient_value = i->value;
signed_tx.push_back((recipient_value) & 0xff);
signed_tx.push_back((recipient_value >> 8) & 0xff);
signed_tx.push_back((recipient_value >> 16) & 0xff);
signed_tx.push_back((recipient_value >> 24) & 0xff);
signed_tx.push_back((recipient_value >> 32) & 0xff);
signed_tx.push_back((recipient_value >> 40) & 0xff);
signed_tx.push_back((recipient_value >> 48) & 0xff);
signed_tx.push_back((recipient_value >> 56) & 0xff);
bytes_t script;
script.push_back(0x76); // OP_DUP
script.push_back(0xa9); // OP_HASH160
script.push_back(0x14); // 20 bytes, should probably assert == hashlen
script.insert(script.end(), i->hash.begin(), i->hash.end());
script.push_back(0x88); // OP_EQUALVERIFY
script.push_back(0xac); // OP_CHECKSIG
signed_tx.push_back(script.size() & 0xff);
signed_tx.insert(signed_tx.end(), script.begin(), script.end());
}
// Lock time
signed_tx.push_back(0);
signed_tx.push_back(0);
signed_tx.push_back(0);
signed_tx.push_back(0);
// std::cerr << to_hex(signed_tx) << std::endl;
return signed_tx;
}
<commit_msg>Docs.<commit_after>#include "tx.h"
#include <iostream> // cerr
#include <iterator>
#include <set>
#include <sstream>
#include <vector>
#include "base58.h"
#include "crypto.h"
#include "node.h"
#include "node_factory.h"
#include "openssl/sha.h"
bytes_t UnspentTxo::GetSigningAddress() const {
if (script.size() == 25 &&
script[0] == 0x76 && script[1] == 0xa9 && script[2] == 0x14 &&
script[23] == 0x88 && script[24] == 0xac) {
// Standard Pay-to-PubkeyHash.
// https://en.bitcoin.it/wiki/Transactions
return bytes_t(script.begin() + 3, script.begin() + 3 + 20);
}
if (script.size() == 23 &&
script[0] == 0xa9 && script[1] == 0x14 &&
script[22] == 0x87) {
// Standard Pay-to-ScriptHash.
// https://en.bitcoin.it/wiki/Transactions
return bytes_t(script.begin() + 2, script.begin() + 2 + 20);
}
return bytes_t();
}
TxOut::TxOut(const bytes_t& hash_, uint64_t value_) :
hash(hash_), value(value_) {}
Tx::Tx(const Node& sending_node,
const unspent_txos_t unspent_txos,
const bytes_t recipient_hash160,
uint64_t value,
uint64_t fee,
uint32_t change_index) :
sending_node_(sending_node),
unspent_txos_(unspent_txos),
recipient_hash160_(recipient_hash160),
value_(value),
fee_(fee),
change_index_(change_index),
change_value_(0) {
}
Tx::~Tx() {
}
bool Tx::CreateSignedTransaction(bytes_t& signed_tx) {
required_unspent_txos_.clear();
change_value_ = 0;
// Identify enough unspent_txos to cover transaction value.
uint64_t required_value = fee_ + value_;
for (unspent_txos_t::const_reverse_iterator i = unspent_txos_.rbegin();
i != unspent_txos_.rend();
++i) {
if (required_value == 0) {
break;
}
required_unspent_txos_.push_back(*i);
if (required_value >= i->value) {
required_value -= i->value;
} else {
change_value_ = i->value - required_value;
required_value = 0;
}
}
if (required_value != 0) {
// Not enough funds to cover transaction.
std::cerr << "Not enough funds" << std::endl;
return false;
}
// We know which unspent_txos we intend to use. Create a set of
// required addresses. Note that an address here is the hash160,
// because that's the format embedded in the script.
std::set<bytes_t> required_signing_addresses;
for (unspent_txos_t::reverse_iterator i = required_unspent_txos_.rbegin();
i != required_unspent_txos_.rend();
++i) {
required_signing_addresses.insert(i->GetSigningAddress());
}
// Do we have all the keys for the required addresses? Generate
// them. For now we're going to assume no account has more than 16
// addresses, so that's the farthest we'll walk down the chain.
uint32_t start = 0;
uint32_t count = 16;
signing_addresses_to_keys_.clear();
for (uint32_t i = 0; i < count; ++i) {
std::stringstream node_path;
node_path << "m/" << (start + i);
Node* node =
NodeFactory::DeriveChildNodeWithPath(sending_node_, node_path.str());
bytes_t hash160 = Base58::toHash160(node->public_key());
if (required_signing_addresses.find(hash160) !=
required_signing_addresses.end()) {
signing_addresses_to_keys_[hash160] = node->secret_key();
}
delete node;
if (signing_addresses_to_keys_.size() ==
required_signing_addresses.size()) {
break;
}
}
if (signing_addresses_to_keys_.size() !=
required_signing_addresses.size()) {
// We don't have all the keys we need to spend these funds.
std::cerr << "missing some keys" << std::endl;
return false;
}
recipients_.clear();
TxOut txout(recipient_hash160_, value_);
recipients_.push_back(txout);
if (change_value_ != 0) {
// Derive the change address
std::stringstream node_path;
node_path << "m/" << (change_index_);
Node* node =
NodeFactory::DeriveChildNodeWithPath(sending_node_, node_path.str());
bytes_t hash160 = Base58::toHash160(node->public_key());
recipients_.push_back(TxOut(hash160, change_value_));
delete node;
}
// Now loop through and sign each txin individually.
// https://en.bitcoin.it/w/images/en/7/70/Bitcoin_OpCheckSig_InDetail.png
for (unspent_txos_t::iterator
i = required_unspent_txos_.begin();
i != required_unspent_txos_.end();
++i) {
bytes_t script_sig;
// TODO(miket): this is actually supposed to be the serialization
// of the previous txo's script. We're just assuming it's a
// standard P2PH and reconstructing what it would have been.
script_sig.push_back(0x76); // OP_DUP
script_sig.push_back(0xa9); // OP_HASH160
script_sig.push_back(0x14); // 20 bytes, should probably assert == hashlen
bytes_t signing_address = i->GetSigningAddress();
script_sig.insert(script_sig.end(),
signing_address.begin(),
signing_address.end());
script_sig.push_back(0x88); // OP_EQUALVERIFY
script_sig.push_back(0xac); // OP_CHECKSIG
i->script_sig = script_sig;
bytes_t tx_with_one_script_sig = SerializeTransaction();
// SIGHASH_ALL
tx_with_one_script_sig.push_back(1);
tx_with_one_script_sig.push_back(0);
tx_with_one_script_sig.push_back(0);
tx_with_one_script_sig.push_back(0);
bytes_t digest;
digest.resize(SHA256_DIGEST_LENGTH);
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256,
&tx_with_one_script_sig[0],
tx_with_one_script_sig.size());
SHA256_Final(&digest[0], &sha256);
SHA256_Init(&sha256);
SHA256_Update(&sha256, &digest[0], digest.capacity());
SHA256_Final(&digest[0], &sha256);
bytes_t signature;
Crypto::Sign(signing_addresses_to_keys_[signing_address],
digest,
signature);
script_sigs_.push_back(signature);
// And clear the sig again for the next one.
i->script_sig.clear();
}
// We now have all the signatures. Stick them in.
unspent_txos_t::iterator i = required_unspent_txos_.begin();
std::vector<bytes_t>::const_iterator j = script_sigs_.begin();
for (;
i != required_unspent_txos_.end();
++i, ++j) {
i->script_sig = *j;
}
// And finally serialize once more with all the signatures installed.
signed_tx = SerializeTransaction();
// https://blockchain.info/decode-tx
//std::cerr << to_hex(signed_tx) << std::endl;
return true;
}
bytes_t Tx::SerializeTransaction() {
bytes_t signed_tx;
signed_tx.resize(0);
// https://en.bitcoin.it/wiki/Transactions
// Version 1
signed_tx.push_back(1);
signed_tx.push_back(0);
signed_tx.push_back(0);
signed_tx.push_back(0);
// Number of inputs
if (required_unspent_txos_.size() >= 0xfd) {
// TODO: implement varint
std::cerr << "too many inputs" << std::endl;
return bytes_t();
}
signed_tx.push_back(required_unspent_txos_.size() & 0xff);
// txin
for (unspent_txos_t::const_iterator i = required_unspent_txos_.begin();
i != required_unspent_txos_.end();
++i) {
// For some stupid reason the hash is serialized backwards.
for (bytes_t::const_reverse_iterator j = i->hash.rbegin();
j != i->hash.rend();
++j) {
signed_tx.push_back(*j);
}
// Previous TXO index
signed_tx.push_back((i->output_n) & 0xff);
signed_tx.push_back((i->output_n >> 8) & 0xff);
signed_tx.push_back((i->output_n >> 16) & 0xff);
signed_tx.push_back((i->output_n >> 24) & 0xff);
// TODO ScriptSig
// https://en.bitcoin.it/wiki/OP_CHECKSIG
if (i->script_sig.size() > 0xfd) {
// TODO: implement varint
std::cerr << "script_sig too big" << std::endl;
return bytes_t();
}
signed_tx.push_back(i->script_sig.size() & 0xff);
signed_tx.insert(signed_tx.end(),
i->script_sig.begin(),
i->script_sig.end());
// sequence_no
signed_tx.push_back(0xff);
signed_tx.push_back(0xff);
signed_tx.push_back(0xff);
signed_tx.push_back(0xff);
}
// Number of outputs
if (recipients_.size() >= 0xfd) {
// TODO: implement varint
std::cerr << "too many recipients" << std::endl;
return bytes_t();
}
signed_tx.push_back(recipients_.size() & 0xff);
for (tx_outs_t::iterator i = recipients_.begin();
i != recipients_.end();
++i) {
uint64_t recipient_value = i->value;
signed_tx.push_back((recipient_value) & 0xff);
signed_tx.push_back((recipient_value >> 8) & 0xff);
signed_tx.push_back((recipient_value >> 16) & 0xff);
signed_tx.push_back((recipient_value >> 24) & 0xff);
signed_tx.push_back((recipient_value >> 32) & 0xff);
signed_tx.push_back((recipient_value >> 40) & 0xff);
signed_tx.push_back((recipient_value >> 48) & 0xff);
signed_tx.push_back((recipient_value >> 56) & 0xff);
bytes_t script;
script.push_back(0x76); // OP_DUP
script.push_back(0xa9); // OP_HASH160
script.push_back(0x14); // 20 bytes, should probably assert == hashlen
script.insert(script.end(), i->hash.begin(), i->hash.end());
script.push_back(0x88); // OP_EQUALVERIFY
script.push_back(0xac); // OP_CHECKSIG
signed_tx.push_back(script.size() & 0xff);
signed_tx.insert(signed_tx.end(), script.begin(), script.end());
}
// Lock time
signed_tx.push_back(0);
signed_tx.push_back(0);
signed_tx.push_back(0);
signed_tx.push_back(0);
// std::cerr << to_hex(signed_tx) << std::endl;
return signed_tx;
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// rpc_queryplan.cpp
//
// Identification: /peloton/tests/networking/rpc_queryplan.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "harness.h"
#include "backend/networking/rpc_utils.h"
#include "backend/networking/rpc_server.h"
#include "backend/networking/peloton_service.h"
#include "backend/planner/seq_scan_plan.h"
namespace peloton {
namespace test {
class RpcQueryPlanTests : public PelotonTest {};
TEST_F(RpcQueryPlanTests, BasicTest) {
TupleDesc tuple_desc = (TupleDesc) malloc(sizeof(struct tupleDesc));
tuple_desc->attrs = NULL;
tuple_desc->constr = NULL;
tuple_desc->natts = 0;
tuple_desc->tdhasoid = true;
tuple_desc->tdrefcount = 10;
tuple_desc->tdtypeid = 123;
tuple_desc->tdtypmod = 789;
peloton::planner::SeqScanPlan mapped_plan_ptr;
const peloton::PlanNodeType type = mapped_plan_ptr.GetPlanNodeType();
peloton::networking::QueryPlanExecRequest request;
request.set_plan_type(static_cast<int>(type));
peloton::networking::TupleDescMsg* tuple_desc_msg = request.mutable_tuple_dec();
peloton::networking::SetTupleDescMsg(tuple_desc, *tuple_desc_msg);
int atts_count = tuple_desc->natts;
int repeate_count = tuple_desc_msg->attrs_size();
EXPECT_EQ(atts_count, repeate_count);
peloton::networking::TupleDescMsg tdmsg = request.tuple_dec();
int size1 = tdmsg.natts();
int size2 = tdmsg.attrs_size();
EXPECT_EQ(size1, size2);
peloton::CopySerializeOutput output_plan;
bool serialize = mapped_plan_ptr.SerializeTo(output_plan);
// Becuase the plan is not completed, so it is false
EXPECT_EQ(serialize, false);
free(tuple_desc);
}
}
}
<commit_msg>add new and delete for unit test<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// rpc_queryplan.cpp
//
// Identification: /peloton/tests/networking/rpc_queryplan.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "harness.h"
#include "backend/networking/rpc_utils.h"
#include "backend/networking/rpc_server.h"
#include "backend/networking/peloton_service.h"
#include "backend/planner/seq_scan_plan.h"
namespace peloton {
namespace test {
class RpcQueryPlanTests : public PelotonTest {};
TEST_F(RpcQueryPlanTests, BasicTest) {
TupleDesc tuple_desc = new tupleDesc;
tuple_desc->attrs = NULL;
tuple_desc->constr = NULL;
tuple_desc->natts = 0;
tuple_desc->tdhasoid = true;
tuple_desc->tdrefcount = 10;
tuple_desc->tdtypeid = 123;
tuple_desc->tdtypmod = 789;
peloton::planner::SeqScanPlan mapped_plan_ptr;
const peloton::PlanNodeType type = mapped_plan_ptr.GetPlanNodeType();
peloton::networking::QueryPlanExecRequest request;
request.set_plan_type(static_cast<int>(type));
peloton::networking::TupleDescMsg* tuple_desc_msg = request.mutable_tuple_dec();
peloton::networking::SetTupleDescMsg(tuple_desc, *tuple_desc_msg);
int atts_count = tuple_desc->natts;
int repeate_count = tuple_desc_msg->attrs_size();
EXPECT_EQ(atts_count, repeate_count);
peloton::networking::TupleDescMsg tdmsg = request.tuple_dec();
int size1 = tdmsg.natts();
int size2 = tdmsg.attrs_size();
EXPECT_EQ(size1, size2);
peloton::CopySerializeOutput output_plan;
bool serialize = mapped_plan_ptr.SerializeTo(output_plan);
// Becuase the plan is not completed, so it is false
EXPECT_EQ(serialize, false);
delete tuple_desc;
}
}
}
<|endoftext|>
|
<commit_before>#include <string>
#include <iostream>
#include <functional>
#include <system_error>
#include <vector>
#include <cstring>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <libcgroup.h>
#include <fcntl.h>
#include <sched.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <syscall.h>
#include <pwd.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include "sandbox.h"
#include "utils.h"
#include "cgroup.h"
#include "semaphore.h"
#include "pipe.h"
namespace fs = boost::filesystem;
using std::string;
using std::vector;
using boost::format;
// Make sure fd 0,1,2 exists.
static void RedirectIO(const string &std_input, const string &std_output,
const string &std_error, int nullfd)
{
int inputfd, outputfd, errorfd;
if (std_input != "")
{
inputfd = Ensure(open(std_input.c_str(), O_RDONLY));
}
else
{
inputfd = nullfd;
}
Ensure(dup2(inputfd, STDIN_FILENO));
if (std_output != "")
{
outputfd = Ensure(open(std_output.c_str(), O_WRONLY | O_TRUNC | O_CREAT,
S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP));
}
else
{
outputfd = nullfd;
}
Ensure(dup2(outputfd, STDOUT_FILENO));
if (std_error != "")
{
if (std_error == std_output)
{
errorfd = outputfd;
}
else
{
errorfd = Ensure(open(std_error.c_str(), O_WRONLY | O_TRUNC | O_CREAT,
S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP));
}
}
else
{
errorfd = nullfd;
}
Ensure(dup2(errorfd, STDERR_FILENO));
}
struct ExecutionParameter
{
const SandboxParameter ¶meter;
PosixSemaphore semaphore1, semaphore2;
// This pipe is used to forward error message from the child process to the parent.
PosixPipe pipefd;
ExecutionParameter(const SandboxParameter ¶m, int pipeOptions) : parameter(param),
semaphore1(true, 0),
semaphore2(true, 0),
pipefd(pipeOptions)
{
}
};
static int ChildProcess(void *param_ptr)
{
ExecutionParameter &execParam = *reinterpret_cast<ExecutionParameter *>(param_ptr);
// We obtain a full copy of parameters here. The arguments may be destoryed after some time.
SandboxParameter parameter = execParam.parameter;
try
{
Ensure(close(execParam.pipefd[0]));
passwd *newUser = nullptr;
if (parameter.userName != "")
{
// Get the user info before chroot, or it will be unable to open /etc/passwd
newUser = CheckNull(getpwnam(parameter.userName.c_str()));
}
int nullfd = Ensure(open("/dev/null", O_RDWR));
if (parameter.redirectBeforeChroot)
{
RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection,
parameter.stderrRedirection, nullfd);
}
Ensure(mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL)); // Make root private
Ensure(mount(parameter.chrootDirectory.string().c_str(),
parameter.chrootDirectory.string().c_str(), "", MS_BIND | MS_RDONLY | MS_REC, ""));
Ensure(mount("", parameter.chrootDirectory.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, ""));
for (MountInfo &info : parameter.mounts)
{
fs::path target = parameter.chrootDirectory / info.dst;
Ensure(mount(info.src.string().c_str(), target.string().c_str(), "", MS_BIND | MS_REC, ""));
if (info.limit == 0)
{
Ensure(mount("", target.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, ""));
}
else if (info.limit != -1)
{
// TODO: implement.
}
}
Ensure(chroot(parameter.chrootDirectory.string().c_str()));
Ensure(chdir(parameter.workingDirectory.string().c_str()));
if (parameter.mountProc)
{
Ensure(mount("proc", "/proc", "proc", 0, NULL));
}
if (!parameter.redirectBeforeChroot)
{
RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection,
parameter.stderrRedirection, nullfd);
}
const char *newHostname = "BraveNewWorld";
Ensure(sethostname(newHostname, strlen(newHostname)));
if (parameter.stackSize != -2)
{
rlimit rlim;
rlim.rlim_max = rlim.rlim_cur = parameter.stackSize != -1 ? parameter.stackSize : RLIM_INFINITY;
Ensure(setrlimit(RLIMIT_STACK, &rlim));
}
if (newUser != nullptr)
{
Ensure(syscall(SYS_setgid, newUser->pw_gid));
Ensure(syscall(SYS_setuid, newUser->pw_uid));
}
vector<char *> params = StringToPtr(parameter.executableParameters),
envi = StringToPtr(parameter.environmentVariables);
int temp = -1;
// Inform the parent that no exception occurred.
Ensure(write(execParam.pipefd[1], &temp, sizeof(int)));
// Inform our parent that we are ready to go.
execParam.semaphore1.Post();
// Wait for parent's reply.
execParam.semaphore2.Wait();
Ensure(execve(parameter.executablePath.c_str(), ¶ms[0], &envi[0]));
// If execve returns, then we meet an error.
raise(SIGABRT);
return 255;
}
catch (std::exception &err)
{
// TODO: implement error handling
// abort(); // This will cause segmentation fault.
// throw;
// return 222;
const char *errMessage = err.what();
int len = strlen(errMessage);
try
{
Ensure(write(execParam.pipefd[1], &len, sizeof(int)));
Ensure(write(execParam.pipefd[1], errMessage, len));
Ensure(close(execParam.pipefd[1]));
execParam.semaphore1.Post();
return 126;
}
catch (...)
{
return 125;
}
}
catch (...)
{
return 125;
}
}
// The child stack is only used before `execve`, so it does not need much space.
const int childStackSize = 1024 * 700;
pid_t StartSandbox(const SandboxParameter ¶meter
/* ,std::function<void(pid_t)> reportPid*/) // Let's use some fancy C++11 feature.
{
pid_t container_pid = -1;
try
{
// char* childStack = new char[childStackSize];
std::vector<char> childStack(childStackSize); // I don't want to call `delete`
ExecutionParameter execParam(parameter, O_CLOEXEC | O_NONBLOCK);
container_pid = Ensure(clone(ChildProcess, &*childStack.end(),
CLONE_NEWNET | CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD,
const_cast<void *>(reinterpret_cast<const void *>(&execParam))));
CgroupInfo memInfo("memory", parameter.cgroupName),
cpuInfo("cpuacct", parameter.cgroupName),
pidInfo("pids", parameter.cgroupName);
vector<CgroupInfo *> infos = {&memInfo, &cpuInfo, &pidInfo};
for (auto &item : infos)
{
CreateGroup(*item);
KillGroupMembers(*item);
WriteGroupProperty(*item, "tasks", container_pid);
}
#define WRITE_WITH_CHECK(__where, __name, __value) \
{ \
if ((__value) >= 0) \
{ \
WriteGroupProperty((__where), (__name), (__value)); \
} \
else \
{ \
WriteGroupProperty((__where), (__name), string("max")); \
} \
}
// Forcibly clear any memory usage by cache.
WriteGroupProperty(memInfo, "memory.force_empty", 0);
WriteGroupProperty(memInfo, "memory.memsw.limit_in_bytes", -1);
WriteGroupProperty(memInfo, "memory.limit_in_bytes", -1);
WRITE_WITH_CHECK(memInfo, "memory.limit_in_bytes", parameter.memoryLimit);
WRITE_WITH_CHECK(memInfo, "memory.memsw.limit_in_bytes", parameter.memoryLimit);
WRITE_WITH_CHECK(pidInfo, "pids.max", parameter.processLimit);
// Wait for at most 100ms. If the child process hasn't posted the semaphore,
// We will assume that the child has already dead.
bool waitResult = execParam.semaphore1.TimedWait(100);
int errLen, bytesRead = read(execParam.pipefd[0], &errLen, sizeof(int));
// Child will be killed once the error has been thrown.
if (!waitResult || bytesRead == 0 || bytesRead == -1)
{
// No information available.
throw std::runtime_error("The child process has exited unexpectedly.");
}
else if (errLen != -1) // -1 indicates OK.
{
vector<char> buf(errLen);
Ensure(read(execParam.pipefd[0], &*buf.begin(), errLen));
string errstr(buf.begin(), buf.end());
throw std::runtime_error((format("The child process has reported the following error: %1%") % errstr).str());
}
// Clear usage stats.
WriteGroupProperty(memInfo, "memory.memsw.max_usage_in_bytes", 0);
WriteGroupProperty(cpuInfo, "cpuacct.usage", 0);
// Continue the child.
execParam.semaphore2.Post();
// Wait for 1ms to prevent the child stack deallocated before execve.
// TODO: Find a better way to handle this.
usleep(1000);
return container_pid;
}
catch (std::exception &ex)
{
// Do the cleanups; we don't care whether these operations are successful.
if (container_pid != -1)
{
(void)kill(container_pid, SIGKILL);
(void)waitpid(container_pid, NULL, WNOHANG);
}
throw;
}
}
ExecutionResult
SBWaitForProcess(pid_t pid)
{
ExecutionResult result;
int status;
Ensure(waitpid(pid, &status, 0));
if (WIFEXITED(status))
{
result.Status = EXITED;
result.Code = WEXITSTATUS(status);
}
else if (WIFSIGNALED(status))
{
result.Status = SIGNALED;
result.Code = WTERMSIG(status);
}
return result;
}<commit_msg>Disable force_empty for speed.<commit_after>#include <string>
#include <iostream>
#include <functional>
#include <system_error>
#include <vector>
#include <cstring>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <libcgroup.h>
#include <fcntl.h>
#include <sched.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <syscall.h>
#include <pwd.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include "sandbox.h"
#include "utils.h"
#include "cgroup.h"
#include "semaphore.h"
#include "pipe.h"
namespace fs = boost::filesystem;
using std::string;
using std::vector;
using boost::format;
// Make sure fd 0,1,2 exists.
static void RedirectIO(const string &std_input, const string &std_output,
const string &std_error, int nullfd)
{
int inputfd, outputfd, errorfd;
if (std_input != "")
{
inputfd = Ensure(open(std_input.c_str(), O_RDONLY));
}
else
{
inputfd = nullfd;
}
Ensure(dup2(inputfd, STDIN_FILENO));
if (std_output != "")
{
outputfd = Ensure(open(std_output.c_str(), O_WRONLY | O_TRUNC | O_CREAT,
S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP));
}
else
{
outputfd = nullfd;
}
Ensure(dup2(outputfd, STDOUT_FILENO));
if (std_error != "")
{
if (std_error == std_output)
{
errorfd = outputfd;
}
else
{
errorfd = Ensure(open(std_error.c_str(), O_WRONLY | O_TRUNC | O_CREAT,
S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP));
}
}
else
{
errorfd = nullfd;
}
Ensure(dup2(errorfd, STDERR_FILENO));
}
struct ExecutionParameter
{
const SandboxParameter ¶meter;
PosixSemaphore semaphore1, semaphore2;
// This pipe is used to forward error message from the child process to the parent.
PosixPipe pipefd;
ExecutionParameter(const SandboxParameter ¶m, int pipeOptions) : parameter(param),
semaphore1(true, 0),
semaphore2(true, 0),
pipefd(pipeOptions)
{
}
};
static int ChildProcess(void *param_ptr)
{
ExecutionParameter &execParam = *reinterpret_cast<ExecutionParameter *>(param_ptr);
// We obtain a full copy of parameters here. The arguments may be destoryed after some time.
SandboxParameter parameter = execParam.parameter;
try
{
Ensure(close(execParam.pipefd[0]));
passwd *newUser = nullptr;
if (parameter.userName != "")
{
// Get the user info before chroot, or it will be unable to open /etc/passwd
newUser = CheckNull(getpwnam(parameter.userName.c_str()));
}
int nullfd = Ensure(open("/dev/null", O_RDWR));
if (parameter.redirectBeforeChroot)
{
RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection,
parameter.stderrRedirection, nullfd);
}
Ensure(mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL)); // Make root private
Ensure(mount(parameter.chrootDirectory.string().c_str(),
parameter.chrootDirectory.string().c_str(), "", MS_BIND | MS_RDONLY | MS_REC, ""));
Ensure(mount("", parameter.chrootDirectory.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, ""));
for (MountInfo &info : parameter.mounts)
{
fs::path target = parameter.chrootDirectory / info.dst;
Ensure(mount(info.src.string().c_str(), target.string().c_str(), "", MS_BIND | MS_REC, ""));
if (info.limit == 0)
{
Ensure(mount("", target.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, ""));
}
else if (info.limit != -1)
{
// TODO: implement.
}
}
Ensure(chroot(parameter.chrootDirectory.string().c_str()));
Ensure(chdir(parameter.workingDirectory.string().c_str()));
if (parameter.mountProc)
{
Ensure(mount("proc", "/proc", "proc", 0, NULL));
}
if (!parameter.redirectBeforeChroot)
{
RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection,
parameter.stderrRedirection, nullfd);
}
const char *newHostname = "BraveNewWorld";
Ensure(sethostname(newHostname, strlen(newHostname)));
if (parameter.stackSize != -2)
{
rlimit rlim;
rlim.rlim_max = rlim.rlim_cur = parameter.stackSize != -1 ? parameter.stackSize : RLIM_INFINITY;
Ensure(setrlimit(RLIMIT_STACK, &rlim));
}
if (newUser != nullptr)
{
Ensure(syscall(SYS_setgid, newUser->pw_gid));
Ensure(syscall(SYS_setuid, newUser->pw_uid));
}
vector<char *> params = StringToPtr(parameter.executableParameters),
envi = StringToPtr(parameter.environmentVariables);
int temp = -1;
// Inform the parent that no exception occurred.
Ensure(write(execParam.pipefd[1], &temp, sizeof(int)));
// Inform our parent that we are ready to go.
execParam.semaphore1.Post();
// Wait for parent's reply.
execParam.semaphore2.Wait();
Ensure(execve(parameter.executablePath.c_str(), ¶ms[0], &envi[0]));
// If execve returns, then we meet an error.
raise(SIGABRT);
return 255;
}
catch (std::exception &err)
{
// TODO: implement error handling
// abort(); // This will cause segmentation fault.
// throw;
// return 222;
const char *errMessage = err.what();
int len = strlen(errMessage);
try
{
Ensure(write(execParam.pipefd[1], &len, sizeof(int)));
Ensure(write(execParam.pipefd[1], errMessage, len));
Ensure(close(execParam.pipefd[1]));
execParam.semaphore1.Post();
return 126;
}
catch (...)
{
return 125;
}
}
catch (...)
{
return 125;
}
}
// The child stack is only used before `execve`, so it does not need much space.
const int childStackSize = 1024 * 700;
pid_t StartSandbox(const SandboxParameter ¶meter
/* ,std::function<void(pid_t)> reportPid*/) // Let's use some fancy C++11 feature.
{
pid_t container_pid = -1;
try
{
// char* childStack = new char[childStackSize];
std::vector<char> childStack(childStackSize); // I don't want to call `delete`
ExecutionParameter execParam(parameter, O_CLOEXEC | O_NONBLOCK);
container_pid = Ensure(clone(ChildProcess, &*childStack.end(),
CLONE_NEWNET | CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD,
const_cast<void *>(reinterpret_cast<const void *>(&execParam))));
CgroupInfo memInfo("memory", parameter.cgroupName),
cpuInfo("cpuacct", parameter.cgroupName),
pidInfo("pids", parameter.cgroupName);
vector<CgroupInfo *> infos = {&memInfo, &cpuInfo, &pidInfo};
for (auto &item : infos)
{
CreateGroup(*item);
KillGroupMembers(*item);
WriteGroupProperty(*item, "tasks", container_pid);
}
#define WRITE_WITH_CHECK(__where, __name, __value) \
{ \
if ((__value) >= 0) \
{ \
WriteGroupProperty((__where), (__name), (__value)); \
} \
else \
{ \
WriteGroupProperty((__where), (__name), string("max")); \
} \
}
// Forcibly clear any memory usage by cache.
// WriteGroupProperty(memInfo, "memory.force_empty", 0); // This is too slow!!!!
WriteGroupProperty(memInfo, "memory.memsw.limit_in_bytes", -1);
WriteGroupProperty(memInfo, "memory.limit_in_bytes", -1);
WRITE_WITH_CHECK(memInfo, "memory.limit_in_bytes", parameter.memoryLimit);
WRITE_WITH_CHECK(memInfo, "memory.memsw.limit_in_bytes", parameter.memoryLimit);
WRITE_WITH_CHECK(pidInfo, "pids.max", parameter.processLimit);
// Wait for at most 100ms. If the child process hasn't posted the semaphore,
// We will assume that the child has already dead.
bool waitResult = execParam.semaphore1.TimedWait(100);
int errLen, bytesRead = read(execParam.pipefd[0], &errLen, sizeof(int));
// Child will be killed once the error has been thrown.
if (!waitResult || bytesRead == 0 || bytesRead == -1)
{
// No information available.
throw std::runtime_error("The child process has exited unexpectedly.");
}
else if (errLen != -1) // -1 indicates OK.
{
vector<char> buf(errLen);
Ensure(read(execParam.pipefd[0], &*buf.begin(), errLen));
string errstr(buf.begin(), buf.end());
throw std::runtime_error((format("The child process has reported the following error: %1%") % errstr).str());
}
// Clear usage stats.
WriteGroupProperty(memInfo, "memory.memsw.max_usage_in_bytes", 0);
WriteGroupProperty(cpuInfo, "cpuacct.usage", 0);
// Continue the child.
execParam.semaphore2.Post();
// Wait for 1ms to prevent the child stack deallocated before execve.
// TODO: Find a better way to handle this.
usleep(1000);
return container_pid;
}
catch (std::exception &ex)
{
// Do the cleanups; we don't care whether these operations are successful.
if (container_pid != -1)
{
(void)kill(container_pid, SIGKILL);
(void)waitpid(container_pid, NULL, WNOHANG);
}
throw;
}
}
ExecutionResult
SBWaitForProcess(pid_t pid)
{
ExecutionResult result;
int status;
Ensure(waitpid(pid, &status, 0));
if (WIFEXITED(status))
{
result.Status = EXITED;
result.Code = WEXITSTATUS(status);
}
else if (WIFSIGNALED(status))
{
result.Status = SIGNALED;
result.Code = WTERMSIG(status);
}
return result;
}<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning(4:4786)
#endif
#include <string>
#include <fstream>
#include <stdio.h>
#include "Bundle.h"
Bundle::Bundle(const Bundle *pBundle)
{
if (pBundle == NULL)
return;
mappings = pBundle->mappings;
}
void Bundle::load(const std::string &path)
{
std::string untranslated;
std::string translated;
char buffer[1024];
std::ifstream poStrm(path.c_str());
if (!poStrm.good())
return;
poStrm.getline(buffer,1024);
while (poStrm.good()) {
std::string line = buffer;
std::string data;
TLineType type = parseLine(line, data);
if (type == tMSGID) {
if (untranslated.length() > 0) {
mappings.erase(untranslated);
ensureNormalText(translated);
mappings.insert(std::pair<std::string,std::string>(untranslated, translated));
}
untranslated = data;
translated.resize(0);
}
else if (type == tMSGSTR) {
if (untranslated.length() > 0)
translated = data;
}
else if (type == tAPPEND) {
if (untranslated.length() > 0)
translated += data;
}
else if (type == tERROR) {
}
poStrm.getline(buffer,1024);
}
if ((untranslated.length() > 0) && (translated.length() > 0)) {
mappings.erase(untranslated);
ensureNormalText(translated);
mappings.insert(std::pair<std::string,std::string>(untranslated, translated));
}
}
Bundle::TLineType Bundle::parseLine(const std::string &line, std::string &data) const
{
int startPos, endPos;
TLineType type;
data.resize(0);
startPos = line.find_first_not_of("\t \r\n");
if ((startPos < 0) || (line.at(startPos) == '#'))
return tCOMMENT;
else if (line.at(startPos) == '"') {
endPos = line.find_first_of('"', startPos+1);
if (endPos < 0)
endPos = line.length();
data = line.substr(startPos+1, endPos-startPos-1);
return tAPPEND;
}
endPos = line.find_first_of("\t \r\n\"");
if (endPos < 0)
endPos = line.length();
std::string key = line.substr(startPos, endPos-startPos);
if (key == "msgid")
type = tMSGID;
else if (key == "msgstr")
type = tMSGSTR;
else
return tERROR;
startPos = line.find_first_of('"', endPos + 1);
if (startPos >= 0) {
startPos++;
endPos = line.find_first_of('"', startPos);
if (endPos < 0)
endPos = line.length();
data = line.substr( startPos, endPos-startPos);
}
return type;
}
/*
#include <set>
static std::set<std::string> unmapped;
*/
std::string Bundle::getLocalString(const std::string &key) const
{
BundleStringMap::const_iterator it = mappings.find(key);
if (it != mappings.end())
return it->second;
else
{
/*
if (unmapped.find( key ) == unmapped.end( ))
unmapped.insert( key );
*/
return key;
}
}
void Bundle::ensureNormalText(std::string &msg)
{
// This is an ugly hack. If you don't like it fix it.
// BZFlag's font bitmaps don't contain letters with accents, so strip them here
// Would be nice if some kind sole added them.
for (std::string::size_type i = 0; i < msg.length(); i++) {
char c = msg.at(i);
switch (c) {
case '':
case '':
case '':
case '':
case '':
case '':
msg[i] = 'a';
break;
case '':
msg[i] = 'a';
i++;
msg.insert(i, 1, 'a');
break;
case '':
case '':
msg[i] = 'a';
i++;
msg.insert(i, 1, 'e');
break;
case '':
case '':
case '':
msg[i] = 'A';
break;
case '':
case '':
msg[i] = 'A';
i++;
msg.insert(i, 1, 'e');
break;
case '':
msg[i] = 'A';
i++;
msg.insert(i, 1, 'a');
break;
case '':
msg[i] = 'c';
break;
case '':
case '':
case '':
case '':
msg[i] = 'e';
break;
case '':
case '':
case '':
case '':
msg[i] = 'i';
break;
case '':
case '':
case '':
case '':
msg[i] = 'o';
break;
case '':
case '':
msg[i] = 'o';
i++;
msg.insert(i, 1, 'e');
break;
case '':
msg[i] = 'O';
break;
case '':
case '':
msg[i] = 'O';
i++;
msg.insert(i, 1, 'e');
break;
case '':
case '':
case '':
msg[i] = 'u';
break;
case '':
msg[i] = 'u';
i++;
msg.insert(i, 1, 'e');
break;
case '':
msg[i] = 'U';
i++;
msg.insert(i, 1, 'e');
break;
case '':
msg[i] = 'n';
break;
case '':
msg[i] = 'Y';
break;
case '':
msg[i] = 's';
i++;
msg.insert(i, 1, 's');
break;
case '':
case '':
msg[i] = ' ';
break;
default: // A temporary patch, to catch untranslated chars.. To be removed eventually
if (((c >= 'A') && (c <= 'Z'))
|| ((c >= 'a') && (c <= 'z'))
|| ((c >= '0') && (c <= '9'))
|| (c == '}') || (c == '{') || (c == ' ')
|| (c == ':') || (c == '/') || (c == '-')
|| (c == ',') || (c == '&') || (c == '?')
|| (c == '<') || (c == '>') || (c == '.')
|| (c == '(') || (c == ')') || (c == '%')
|| (c == '!') || (c == '+') || (c == '-')
|| (c == '$') || (c == ';') || (c == '@')
|| (c == '[') || (c == ']')
|| (c == '=') || (c == '\''))
;
else {
msg = std::string("unsupported char:") + c;
return;
}
break;
}
}
}
std::string Bundle::formatMessage(const std::string &key, const std::vector<std::string> *parms) const
{
std::string messageIn = getLocalString(key);
std::string messageOut;
if (!parms || (parms->size() == 0))
return messageIn;
int parmCnt = parms->size();
int startPos = 0;
int lCurlyPos = messageIn.find_first_of("{");
while (lCurlyPos >= 0) {
messageOut += messageIn.substr( startPos, lCurlyPos - startPos);
int rCurlyPos = messageIn.find_first_of("}", lCurlyPos++);
if (rCurlyPos < 0) {
messageOut += messageIn.substr(lCurlyPos);
return messageOut;
}
std::string numStr = messageIn.substr(lCurlyPos, rCurlyPos-lCurlyPos);
int num;
if (sscanf(numStr.c_str(), "%d", &num) != 1)
messageOut += messageIn.substr(lCurlyPos, rCurlyPos-lCurlyPos);
else {
num--;
if ((num >= 0) && (num < parmCnt))
messageOut += (*parms)[num];
}
startPos = rCurlyPos+1;
lCurlyPos = messageIn.find_first_of("{", startPos);
}
messageOut += messageIn.substr(startPos);
return messageOut;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>print unmapped locale strings on debug level 4<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning(4:4786)
#endif
#include <string>
#include <fstream>
#include <stdio.h>
#include "Bundle.h"
#include "StateDatabase.h"
Bundle::Bundle(const Bundle *pBundle)
{
if (pBundle == NULL)
return;
mappings = pBundle->mappings;
}
void Bundle::load(const std::string &path)
{
std::string untranslated;
std::string translated;
char buffer[1024];
std::ifstream poStrm(path.c_str());
if (!poStrm.good())
return;
poStrm.getline(buffer,1024);
while (poStrm.good()) {
std::string line = buffer;
std::string data;
TLineType type = parseLine(line, data);
if (type == tMSGID) {
if (untranslated.length() > 0) {
mappings.erase(untranslated);
ensureNormalText(translated);
mappings.insert(std::pair<std::string,std::string>(untranslated, translated));
}
untranslated = data;
translated.resize(0);
}
else if (type == tMSGSTR) {
if (untranslated.length() > 0)
translated = data;
}
else if (type == tAPPEND) {
if (untranslated.length() > 0)
translated += data;
}
else if (type == tERROR) {
}
poStrm.getline(buffer,1024);
}
if ((untranslated.length() > 0) && (translated.length() > 0)) {
mappings.erase(untranslated);
ensureNormalText(translated);
mappings.insert(std::pair<std::string,std::string>(untranslated, translated));
}
}
Bundle::TLineType Bundle::parseLine(const std::string &line, std::string &data) const
{
int startPos, endPos;
TLineType type;
data.resize(0);
startPos = line.find_first_not_of("\t \r\n");
if ((startPos < 0) || (line.at(startPos) == '#'))
return tCOMMENT;
else if (line.at(startPos) == '"') {
endPos = line.find_first_of('"', startPos+1);
if (endPos < 0)
endPos = line.length();
data = line.substr(startPos+1, endPos-startPos-1);
return tAPPEND;
}
endPos = line.find_first_of("\t \r\n\"");
if (endPos < 0)
endPos = line.length();
std::string key = line.substr(startPos, endPos-startPos);
if (key == "msgid")
type = tMSGID;
else if (key == "msgstr")
type = tMSGSTR;
else
return tERROR;
startPos = line.find_first_of('"', endPos + 1);
if (startPos >= 0) {
startPos++;
endPos = line.find_first_of('"', startPos);
if (endPos < 0)
endPos = line.length();
data = line.substr( startPos, endPos-startPos);
}
return type;
}
#include <set>
static std::set<std::string> unmapped;
std::string Bundle::getLocalString(const std::string &key) const
{
BundleStringMap::const_iterator it = mappings.find(key);
if (it != mappings.end())
return it->second;
else
{
if (BZDB.getDebug()) {
if (unmapped.find( key ) == unmapped.end( )) {
unmapped.insert( key );
std::string debugStr = "Unmapped Locale String: " + key + "\n";
DEBUG1( debugStr.c_str( ));
}
}
return key;
}
}
void Bundle::ensureNormalText(std::string &msg)
{
// This is an ugly hack. If you don't like it fix it.
// BZFlag's font bitmaps don't contain letters with accents, so strip them here
// Would be nice if some kind sole added them.
for (std::string::size_type i = 0; i < msg.length(); i++) {
char c = msg.at(i);
switch (c) {
case '':
case '':
case '':
case '':
case '':
case '':
msg[i] = 'a';
break;
case '':
msg[i] = 'a';
i++;
msg.insert(i, 1, 'a');
break;
case '':
case '':
msg[i] = 'a';
i++;
msg.insert(i, 1, 'e');
break;
case '':
case '':
case '':
msg[i] = 'A';
break;
case '':
case '':
msg[i] = 'A';
i++;
msg.insert(i, 1, 'e');
break;
case '':
msg[i] = 'A';
i++;
msg.insert(i, 1, 'a');
break;
case '':
msg[i] = 'c';
break;
case '':
case '':
case '':
case '':
msg[i] = 'e';
break;
case '':
case '':
case '':
case '':
msg[i] = 'i';
break;
case '':
case '':
case '':
case '':
msg[i] = 'o';
break;
case '':
case '':
msg[i] = 'o';
i++;
msg.insert(i, 1, 'e');
break;
case '':
msg[i] = 'O';
break;
case '':
case '':
msg[i] = 'O';
i++;
msg.insert(i, 1, 'e');
break;
case '':
case '':
case '':
msg[i] = 'u';
break;
case '':
msg[i] = 'u';
i++;
msg.insert(i, 1, 'e');
break;
case '':
msg[i] = 'U';
i++;
msg.insert(i, 1, 'e');
break;
case '':
msg[i] = 'n';
break;
case '':
msg[i] = 'Y';
break;
case '':
msg[i] = 's';
i++;
msg.insert(i, 1, 's');
break;
case '':
case '':
msg[i] = ' ';
break;
default: // A temporary patch, to catch untranslated chars.. To be removed eventually
if (((c >= 'A') && (c <= 'Z'))
|| ((c >= 'a') && (c <= 'z'))
|| ((c >= '0') && (c <= '9'))
|| (c == '}') || (c == '{') || (c == ' ')
|| (c == ':') || (c == '/') || (c == '-')
|| (c == ',') || (c == '&') || (c == '?')
|| (c == '<') || (c == '>') || (c == '.')
|| (c == '(') || (c == ')') || (c == '%')
|| (c == '!') || (c == '+') || (c == '-')
|| (c == '$') || (c == ';') || (c == '@')
|| (c == '[') || (c == ']')
|| (c == '=') || (c == '\''))
;
else {
msg = std::string("unsupported char:") + c;
return;
}
break;
}
}
}
std::string Bundle::formatMessage(const std::string &key, const std::vector<std::string> *parms) const
{
std::string messageIn = getLocalString(key);
std::string messageOut;
if (!parms || (parms->size() == 0))
return messageIn;
int parmCnt = parms->size();
int startPos = 0;
int lCurlyPos = messageIn.find_first_of("{");
while (lCurlyPos >= 0) {
messageOut += messageIn.substr( startPos, lCurlyPos - startPos);
int rCurlyPos = messageIn.find_first_of("}", lCurlyPos++);
if (rCurlyPos < 0) {
messageOut += messageIn.substr(lCurlyPos);
return messageOut;
}
std::string numStr = messageIn.substr(lCurlyPos, rCurlyPos-lCurlyPos);
int num;
if (sscanf(numStr.c_str(), "%d", &num) != 1)
messageOut += messageIn.substr(lCurlyPos, rCurlyPos-lCurlyPos);
else {
num--;
if ((num >= 0) && (num < parmCnt))
messageOut += (*parms)[num];
}
startPos = rCurlyPos+1;
lCurlyPos = messageIn.find_first_of("{", startPos);
}
messageOut += messageIn.substr(startPos);
return messageOut;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/*
C++ interface test
*/
#include "libmemcached/memcached.hh"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"
#include "test.h"
#include <string>
using namespace std;
extern "C" {
test_return basic_test(memcached_st *memc);
test_return increment_test(memcached_st *memc);
test_return basic_master_key_test(memcached_st *memc);
test_return mget_result_function(memcached_st *memc);
test_return mget_test(memcached_st *memc);
memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
memcached_result_st *result __attribute__((unused)),
void *context);
void *world_create(void);
void world_destroy(void *p);
}
test_return basic_test(memcached_st *memc)
{
Memcached foo(memc);
const string value_set("This is some data");
string value;
size_t value_length;
foo.set("mine", value_set, 0, 0);
value= foo.get("mine", &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
return TEST_SUCCESS;
}
test_return increment_test(memcached_st *memc)
{
Memcached mcach(memc);
bool rc;
const string key("inctest");
const string inc_value("1");
string ret_value;
uint64_t int_inc_value;
uint64_t int_ret_value;
size_t value_length;
mcach.set(key, inc_value, 0, 0);
ret_value= mcach.get(key, &value_length);
printf("\nretvalue %s\n",ret_value.c_str());
int_inc_value= uint64_t(atol(inc_value.c_str()));
int_ret_value= uint64_t(atol(ret_value.c_str()));
assert(int_ret_value == int_inc_value);
rc= mcach.increment(key, 1, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 2);
rc= mcach.increment(key, 1, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 3);
rc= mcach.increment(key, 5, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 8);
return TEST_SUCCESS;
}
test_return basic_master_key_test(memcached_st *memc)
{
Memcached foo(memc);
const string value_set("Data for server A");
const string master_key_a("server-a");
const string master_key_b("server-b");
const string key("xyz");
string value;
size_t value_length;
foo.set_by_key(master_key_a, key, value_set, 0, 0);
value= foo.get_by_key(master_key_a, key, &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
value= foo.get_by_key(master_key_b, key, &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
return TEST_SUCCESS;
}
/* Count the results */
memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
memcached_result_st *result __attribute__((unused)),
void *context)
{
unsigned int *counter= static_cast<unsigned int *>(context);
*counter= *counter + 1;
return MEMCACHED_SUCCESS;
}
test_return mget_result_function(memcached_st *memc)
{
Memcached mc(memc);
bool rc;
string key1("fudge");
string key2("son");
string key3("food");
vector<string> keys;
keys.reserve(3);
keys.push_back(key1);
keys.push_back(key2);
keys.push_back(key3);
unsigned int counter;
memcached_execute_function callbacks[1];
/* We need to empty the server before we continue the test */
rc= mc.flush(0);
rc= mc.set_all(keys, keys, 50, 9);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
callbacks[0]= &callback_counter;
counter= 0;
rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);
assert(counter == 3);
return TEST_SUCCESS;
}
test_return mget_test(memcached_st *memc)
{
Memcached mc(memc);
bool rc;
memcached_return mc_rc;
vector<string> keys;
keys.reserve(3);
keys.push_back("fudge");
keys.push_back("son");
keys.push_back("food");
uint32_t flags;
string return_key;
size_t return_key_length;
string return_value;
size_t return_value_length;
/* We need to empty the server before we continue the test */
rc= mc.flush(0);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
while (mc.fetch(return_key, return_value, &return_key_length,
&return_value_length, &flags, &mc_rc))
{
assert(return_value.length() != 0);
}
assert(return_value_length == 0);
assert(mc_rc == MEMCACHED_END);
rc= mc.set_all(keys, keys, 50, 9);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
while ((mc.fetch(return_key, return_value, &return_key_length,
&return_value_length, &flags, &mc_rc)))
{
assert(return_value.length() != 0);
assert(mc_rc == MEMCACHED_SUCCESS);
assert(return_key_length == return_value_length);
assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
}
return TEST_SUCCESS;
}
test_st tests[] ={
{ "basic", 0, basic_test },
{ "basic_master_key", 0, basic_master_key_test },
{ "increment_test", 0, increment_test },
{ "mget", 1, mget_test },
{ "mget_result_function", 1, mget_result_function },
{0, 0, 0}
};
collection_st collection[] ={
{"block", 0, 0, tests},
{0, 0, 0, 0}
};
#define SERVERS_TO_CREATE 1
extern "C" void *world_create(void)
{
server_startup_st *construct;
construct= (server_startup_st *)malloc(sizeof(server_startup_st));
memset(construct, 0, sizeof(server_startup_st));
construct->count= SERVERS_TO_CREATE;
server_startup(construct);
return construct;
}
void world_destroy(void *p)
{
server_startup_st *construct= static_cast<server_startup_st *>(p);
memcached_server_st *servers=
static_cast<memcached_server_st *>(construct->servers);
memcached_server_list_free(servers);
server_shutdown(construct);
free(construct);
}
void get_world(world_st *world)
{
world->collections= collection;
world->create= world_create;
world->destroy= world_destroy;
}
<commit_msg>Fixing the usage of __attribute__(unused) for solaris builds.<commit_after>/*
C++ interface test
*/
#include "libmemcached/memcached.hh"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"
#include "test.h"
#include <string>
using namespace std;
extern "C" {
test_return basic_test(memcached_st *memc);
test_return increment_test(memcached_st *memc);
test_return basic_master_key_test(memcached_st *memc);
test_return mget_result_function(memcached_st *memc);
test_return mget_test(memcached_st *memc);
memcached_return callback_counter(memcached_st *,
memcached_result_st *,
void *context);
void *world_create(void);
void world_destroy(void *p);
}
test_return basic_test(memcached_st *memc)
{
Memcached foo(memc);
const string value_set("This is some data");
string value;
size_t value_length;
foo.set("mine", value_set, 0, 0);
value= foo.get("mine", &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
return TEST_SUCCESS;
}
test_return increment_test(memcached_st *memc)
{
Memcached mcach(memc);
bool rc;
const string key("inctest");
const string inc_value("1");
string ret_value;
uint64_t int_inc_value;
uint64_t int_ret_value;
size_t value_length;
mcach.set(key, inc_value, 0, 0);
ret_value= mcach.get(key, &value_length);
printf("\nretvalue %s\n",ret_value.c_str());
int_inc_value= uint64_t(atol(inc_value.c_str()));
int_ret_value= uint64_t(atol(ret_value.c_str()));
assert(int_ret_value == int_inc_value);
rc= mcach.increment(key, 1, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 2);
rc= mcach.increment(key, 1, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 3);
rc= mcach.increment(key, 5, &int_ret_value);
assert(rc == true);
assert(int_ret_value == 8);
return TEST_SUCCESS;
}
test_return basic_master_key_test(memcached_st *memc)
{
Memcached foo(memc);
const string value_set("Data for server A");
const string master_key_a("server-a");
const string master_key_b("server-b");
const string key("xyz");
string value;
size_t value_length;
foo.set_by_key(master_key_a, key, value_set, 0, 0);
value= foo.get_by_key(master_key_a, key, &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
value= foo.get_by_key(master_key_b, key, &value_length);
assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));
return TEST_SUCCESS;
}
/* Count the results */
memcached_return callback_counter(memcached_st *,
memcached_result_st *,
void *context)
{
unsigned int *counter= static_cast<unsigned int *>(context);
*counter= *counter + 1;
return MEMCACHED_SUCCESS;
}
test_return mget_result_function(memcached_st *memc)
{
Memcached mc(memc);
bool rc;
string key1("fudge");
string key2("son");
string key3("food");
vector<string> keys;
keys.reserve(3);
keys.push_back(key1);
keys.push_back(key2);
keys.push_back(key3);
unsigned int counter;
memcached_execute_function callbacks[1];
/* We need to empty the server before we continue the test */
rc= mc.flush(0);
rc= mc.set_all(keys, keys, 50, 9);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
callbacks[0]= &callback_counter;
counter= 0;
rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);
assert(counter == 3);
return TEST_SUCCESS;
}
test_return mget_test(memcached_st *memc)
{
Memcached mc(memc);
bool rc;
memcached_return mc_rc;
vector<string> keys;
keys.reserve(3);
keys.push_back("fudge");
keys.push_back("son");
keys.push_back("food");
uint32_t flags;
string return_key;
size_t return_key_length;
string return_value;
size_t return_value_length;
/* We need to empty the server before we continue the test */
rc= mc.flush(0);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
while (mc.fetch(return_key, return_value, &return_key_length,
&return_value_length, &flags, &mc_rc))
{
assert(return_value.length() != 0);
}
assert(return_value_length == 0);
assert(mc_rc == MEMCACHED_END);
rc= mc.set_all(keys, keys, 50, 9);
assert(rc == true);
rc= mc.mget(keys);
assert(rc == true);
while ((mc.fetch(return_key, return_value, &return_key_length,
&return_value_length, &flags, &mc_rc)))
{
assert(return_value.length() != 0);
assert(mc_rc == MEMCACHED_SUCCESS);
assert(return_key_length == return_value_length);
assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
}
return TEST_SUCCESS;
}
test_st tests[] ={
{ "basic", 0, basic_test },
{ "basic_master_key", 0, basic_master_key_test },
{ "increment_test", 0, increment_test },
{ "mget", 1, mget_test },
{ "mget_result_function", 1, mget_result_function },
{0, 0, 0}
};
collection_st collection[] ={
{"block", 0, 0, tests},
{0, 0, 0, 0}
};
#define SERVERS_TO_CREATE 1
extern "C" void *world_create(void)
{
server_startup_st *construct;
construct= (server_startup_st *)malloc(sizeof(server_startup_st));
memset(construct, 0, sizeof(server_startup_st));
construct->count= SERVERS_TO_CREATE;
server_startup(construct);
return construct;
}
void world_destroy(void *p)
{
server_startup_st *construct= static_cast<server_startup_st *>(p);
memcached_server_st *servers=
static_cast<memcached_server_st *>(construct->servers);
memcached_server_list_free(servers);
server_shutdown(construct);
free(construct);
}
void get_world(world_st *world)
{
world->collections= collection;
world->create= world_create;
world->destroy= world_destroy;
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------
#include "stdafx.h"
#include "Common.h"
#include "config.h" // for MASHAPE_API_URL, MASHAPE_API_ID
#include "version.h" // for VERSION_PRODUCT_NAME, MAIN_PRODUCT_VERSION_STR_A
#include <json/json.h>
#ifdef __MINGW32__
// MinGW gcc does not support std::this_thread for some reason (gcc 4.8.1). So use native Windows API:
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#else
#include <chrono>
#include <thread>
#endif
//------------------------------------------------------
#ifdef _MSC_VER
//#pragma comment (lib, "jsoncpp.lib")
#endif // _MSC_VER > 1000
//------------------------------------------------------
using namespace std;
//------------------------------------------------------
volatile bool g_bTerminateProgram = false;
//------------------------------------------------------
ProbeApiRequester::Request::Request(const std::string& sRequestWithArgs)
{
eMethod = HTTP_GET;
sUrl = MASHAPE_API_URL + sRequestWithArgs;
headers.emplace_back("X-Mashape-Key", MASHAPE_API_ID);
headers.emplace_back("Accept", "application/json");
sUserAgent = VERSION_PRODUCT_NAME " HTTP client v." MAIN_PRODUCT_VERSION_STR_A;
nHttpTimeoutSec = 2 * 60;
bKnownBadSslCertificate = false;
}
//------------------------------------------------------
ProbeApiRequester::Reply ProbeApiRequester::DoRequest(const ProbeApiRequester::Request& requestInfo, const bool bVerbose)
{
ProbeApiRequester::Reply reply = HttpRequester::DoRequest(requestInfo, bVerbose);
// reply HTTP code: 401 Unauthorized
// Content-Type: application/json
// {"message":"Missing Mashape application key. Go to http:\/\/docs.mashape.com\/api-keys to learn how to get your API application key."}
//
// reply HTTP code: 402
// Content-Type: application/json
// {"message":"You need to subscribe to a plan before consuming the API"}
//
// reply HTTP code : 403
// Content-Type: application/json
// {"message":"Invalid Mashape Key"}
//
// reply HTTP code: 404
// Content-Type: text/html; charset=UTF-8
// <body>
// <div id="content">
// <p class="heading1">Service</p>
// <p>Endpoint not found.</p>
// </div>
// </body>
const bool bJsonReply = begins(reply.sContentType, "application/json");
if (reply.bSucceeded)
{
if (reply.nHttpCode != 200 && bJsonReply)
{
string sMessage;
{
Json::Reader reader;
Json::Value root;
const bool parsedOK = reader.parse(reply.sBody, root);
if (parsedOK)
{
sMessage = root.get("message", "").asString();
}
}
reply.bSucceeded = false;
reply.sErrorDescription = OSSFMT("Bad HTTP reply code: " << reply.nHttpCode << "; message: " << sMessage);
}
else if (!bJsonReply)
{
reply.bSucceeded = false;
reply.sErrorDescription = OSSFMT("Bad reply format. HTTP code: " << reply.nHttpCode << "; Content-Type: " << reply.sContentType);
}
}
if (bVerbose)
{
HttpReplyDebugPrint(reply);
}
return reply;
}
//------------------------------------------------------
void ProbeApiRequester::HttpReplyDebugPrint(const ProbeApiRequester::Reply &reply)
{
cout << "request succeeded: " << reply.bSucceeded << endl;
cout << "request error desc: " << reply.sErrorDescription << endl;
cout << "reply HTTP code: " << reply.nHttpCode << endl;
cout << "reply EffectiveUrl: " << reply.sEffectiveUrl << endl;
cout << "reply Content-Type: " << reply.sContentType << endl;
cout << "reply body length: " << reply.sBody.length() << endl;
cout << "REPLY BODY: [[[" << reply.sBody << "]]]" << endl;
}
//------------------------------------------------------
void MySleep(const uint32_t nSleepMs)
{
#ifdef __MINGW32__
Sleep(nSleepMs);
#else
std::this_thread::sleep_for(std::chrono::milliseconds(nSleepMs));
#endif
}
//------------------------------------------------------
template<class T>
inline T findandreplaceConstT(const T& source, const T& find, const T& replace)
{
if (find.empty() || source.empty())
return source;
ptrdiff_t nPredictReplaces = 0;
for (std::size_t pos = source.find(find); pos != source.npos; pos = source.find(find, pos))
{
++nPredictReplaces;
pos += find.length();
}
T res;
res.reserve(source.length() + nPredictReplaces * (replace.length() - find.length()));
typename T::size_type posPrev = 0;
for (std::size_t pos = source.find(find); pos != source.npos; pos = source.find(find, pos))
{
if (pos > posPrev)
{
res += source.substr(posPrev, pos - posPrev);
}
res += replace;
pos += find.length();
posPrev = pos;
}
if (posPrev != T::npos)
{
// Copy rest of the string:
res += source.substr(posPrev);
}
return res;
}
//------------------------------------------------------
template<class T>
inline void findandreplaceT(T& source, const T& find, const T& replace)
{
if (find.empty() || source.empty())
return;
// Optimize performance if find and replace have different size.
// In this case we can't replace in-place without moving rest of string in memory.
if (find.length() != replace.length())
{
#ifdef _MSC_VER
std::swap(source, findandreplaceConstT(source, find, replace));
#else
// FIXME: there should be more effective way like MSVC allow, but I don't know how to write it for gcc:
source = findandreplaceConstT(source, find, replace);
#endif
return;
}
// Fast in-place string replacement:
typename T::size_type pos = 0;
while ((pos = source.find(find, pos)) != T::npos)
{
source.replace(pos, find.length(), replace);
pos += replace.length();
}
}
//------------------------------------------------------
std::string findandreplaceConst(const std::string& source, const std::string& find, const std::string& replace)
{
return findandreplaceConstT(source, find, replace);
}
std::wstring findandreplaceConst(const std::wstring& source, const std::wstring& find, const std::wstring& replace)
{
return findandreplaceConstT(source, find, replace);
}
//------------------------------------------------------
void findandreplace(std::string& source, const std::string& find, const std::string& replace)
{
findandreplaceT(source, find, replace);
}
void findandreplace(std::wstring& source, const std::wstring& find, const std::wstring& replace)
{
findandreplaceT(source, find, replace);
}
//------------------------------------------------------
<commit_msg>support error description in format {"Message":"bla-bla"}<commit_after>//------------------------------------------------------
#include "stdafx.h"
#include "Common.h"
#include "config.h" // for MASHAPE_API_URL, MASHAPE_API_ID
#include "version.h" // for VERSION_PRODUCT_NAME, MAIN_PRODUCT_VERSION_STR_A
#include <json/json.h>
#ifdef __MINGW32__
// MinGW gcc does not support std::this_thread for some reason (gcc 4.8.1). So use native Windows API:
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#else
#include <chrono>
#include <thread>
#endif
//------------------------------------------------------
#ifdef _MSC_VER
//#pragma comment (lib, "jsoncpp.lib")
#endif // _MSC_VER > 1000
//------------------------------------------------------
using namespace std;
//------------------------------------------------------
volatile bool g_bTerminateProgram = false;
//------------------------------------------------------
ProbeApiRequester::Request::Request(const std::string& sRequestWithArgs)
{
eMethod = HTTP_GET;
sUrl = MASHAPE_API_URL + sRequestWithArgs;
headers.emplace_back("X-Mashape-Key", MASHAPE_API_ID);
headers.emplace_back("Accept", "application/json");
sUserAgent = VERSION_PRODUCT_NAME " HTTP client v." MAIN_PRODUCT_VERSION_STR_A;
nHttpTimeoutSec = 2 * 60;
bKnownBadSslCertificate = false;
}
//------------------------------------------------------
ProbeApiRequester::Reply ProbeApiRequester::DoRequest(const ProbeApiRequester::Request& requestInfo, const bool bVerbose)
{
ProbeApiRequester::Reply reply = HttpRequester::DoRequest(requestInfo, bVerbose);
// reply HTTP code: 401 Unauthorized
// Content-Type: application/json
// {"message":"Missing Mashape application key. Go to http:\/\/docs.mashape.com\/api-keys to learn how to get your API application key."}
//
// reply HTTP code: 402
// Content-Type: application/json
// {"message":"You need to subscribe to a plan before consuming the API"}
//
// reply HTTP code : 403
// Content-Type: application/json
// {"message":"Invalid Mashape Key"}
//
// reply HTTP code: 404
// Content-Type: text/html; charset=UTF-8
// <body>
// <div id="content">
// <p class="heading1">Service</p>
// <p>Endpoint not found.</p>
// </div>
// </body>
const bool bJsonReply = begins(reply.sContentType, "application/json");
if (reply.bSucceeded)
{
if (reply.nHttpCode != 200 && bJsonReply)
{
string sMessage;
{
Json::Reader reader;
Json::Value root;
const bool parsedOK = reader.parse(reply.sBody, root);
if (parsedOK)
{
sMessage = root.get("message", "").asString();
if (sMessage.empty())
{
sMessage = root.get("Message", "").asString();
}
}
}
reply.bSucceeded = false;
reply.sErrorDescription = OSSFMT("Bad HTTP reply code: " << reply.nHttpCode << "; message: " << sMessage);
}
else if (!bJsonReply)
{
reply.bSucceeded = false;
reply.sErrorDescription = OSSFMT("Bad reply format. HTTP code: " << reply.nHttpCode << "; Content-Type: " << reply.sContentType);
}
}
if (bVerbose)
{
HttpReplyDebugPrint(reply);
}
return reply;
}
//------------------------------------------------------
void ProbeApiRequester::HttpReplyDebugPrint(const ProbeApiRequester::Reply &reply)
{
cout << "request succeeded: " << reply.bSucceeded << endl;
cout << "request error desc: " << reply.sErrorDescription << endl;
cout << "reply HTTP code: " << reply.nHttpCode << endl;
cout << "reply EffectiveUrl: " << reply.sEffectiveUrl << endl;
cout << "reply Content-Type: " << reply.sContentType << endl;
cout << "reply body length: " << reply.sBody.length() << endl;
cout << "REPLY BODY: [[[" << reply.sBody << "]]]" << endl;
}
//------------------------------------------------------
void MySleep(const uint32_t nSleepMs)
{
#ifdef __MINGW32__
Sleep(nSleepMs);
#else
std::this_thread::sleep_for(std::chrono::milliseconds(nSleepMs));
#endif
}
//------------------------------------------------------
template<class T>
inline T findandreplaceConstT(const T& source, const T& find, const T& replace)
{
if (find.empty() || source.empty())
return source;
ptrdiff_t nPredictReplaces = 0;
for (std::size_t pos = source.find(find); pos != source.npos; pos = source.find(find, pos))
{
++nPredictReplaces;
pos += find.length();
}
T res;
res.reserve(source.length() + nPredictReplaces * (replace.length() - find.length()));
typename T::size_type posPrev = 0;
for (std::size_t pos = source.find(find); pos != source.npos; pos = source.find(find, pos))
{
if (pos > posPrev)
{
res += source.substr(posPrev, pos - posPrev);
}
res += replace;
pos += find.length();
posPrev = pos;
}
if (posPrev != T::npos)
{
// Copy rest of the string:
res += source.substr(posPrev);
}
return res;
}
//------------------------------------------------------
template<class T>
inline void findandreplaceT(T& source, const T& find, const T& replace)
{
if (find.empty() || source.empty())
return;
// Optimize performance if find and replace have different size.
// In this case we can't replace in-place without moving rest of string in memory.
if (find.length() != replace.length())
{
#ifdef _MSC_VER
std::swap(source, findandreplaceConstT(source, find, replace));
#else
// FIXME: there should be more effective way like MSVC allow, but I don't know how to write it for gcc:
source = findandreplaceConstT(source, find, replace);
#endif
return;
}
// Fast in-place string replacement:
typename T::size_type pos = 0;
while ((pos = source.find(find, pos)) != T::npos)
{
source.replace(pos, find.length(), replace);
pos += replace.length();
}
}
//------------------------------------------------------
std::string findandreplaceConst(const std::string& source, const std::string& find, const std::string& replace)
{
return findandreplaceConstT(source, find, replace);
}
std::wstring findandreplaceConst(const std::wstring& source, const std::wstring& find, const std::wstring& replace)
{
return findandreplaceConstT(source, find, replace);
}
//------------------------------------------------------
void findandreplace(std::string& source, const std::string& find, const std::string& replace)
{
findandreplaceT(source, find, replace);
}
void findandreplace(std::wstring& source, const std::wstring& find, const std::wstring& replace)
{
findandreplaceT(source, find, replace);
}
//------------------------------------------------------
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System
*
* This tool acts as an entry point for all the server-related
* cvmfs tasks, such as uploading files and checking the sanity of
* a repository.
*/
#include "cvmfs_config.h"
#include "swissknife.h"
#include <unistd.h>
#include <vector>
#include "logging.h"
#include "download.h"
#include "signature.h"
#include "swissknife_zpipe.h"
#include "swissknife_check.h"
#include "swissknife_lsrepo.h"
#include "swissknife_pull.h"
#include "swissknife_sign.h"
#include "swissknife_letter.h"
#include "swissknife_sync.h"
#include "swissknife_info.h"
#include "swissknife_history.h"
#include "swissknife_migrate.h"
#include "swissknife_scrub.h"
#include "swissknife_gc.h"
using namespace std; // NOLINT
using namespace swissknife;
vector<swissknife::Command *> command_list;
download::DownloadManager *swissknife::g_download_manager;
signature::SignatureManager *swissknife::g_signature_manager;
void swissknife::Usage() {
LogCvmfs(kLogCvmfs, kLogStdout,
"CernVM-FS repository storage management commands\n"
"Version %s\n"
"Usage (normally called from cvmfs_server):\n"
" cvmfs_swissknife <command> [options]\n",
VERSION);
for (unsigned i = 0; i < command_list.size(); ++i) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "\n"
"Command %s\n"
"--------", command_list[i]->GetName().c_str());
for (unsigned j = 0; j < command_list[i]->GetName().length(); ++j) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "-");
}
LogCvmfs(kLogCvmfs, kLogStdout, "");
LogCvmfs(kLogCvmfs, kLogStdout, "%s",
command_list[i]->GetDescription().c_str());
swissknife::ParameterList params = command_list[i]->GetParams();
if (!params.empty()) {
LogCvmfs(kLogCvmfs, kLogStdout, "Options:");
for (unsigned j = 0; j < params.size(); ++j) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, " -%c %s",
params[j].key(), params[j].description().c_str());
if (params[j].optional())
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, " (optional)");
LogCvmfs(kLogCvmfs, kLogStdout, "");
}
} // Parameter list
} // Command list
LogCvmfs(kLogCvmfs, kLogStdout, "");
}
int main(int argc, char **argv) {
g_download_manager = new download::DownloadManager();
g_signature_manager = new signature::SignatureManager();
command_list.push_back(new swissknife::CommandCreate());
command_list.push_back(new swissknife::CommandUpload());
command_list.push_back(new swissknife::CommandRemove());
command_list.push_back(new swissknife::CommandPeek());
command_list.push_back(new swissknife::CommandSync());
command_list.push_back(new swissknife::CommandApplyDirtab());
command_list.push_back(new swissknife::CommandCreateTag());
command_list.push_back(new swissknife::CommandRemoveTag());
command_list.push_back(new swissknife::CommandListTags());
command_list.push_back(new swissknife::CommandInfoTag());
command_list.push_back(new swissknife::CommandRollbackTag());
command_list.push_back(new swissknife::CommandSign());
command_list.push_back(new swissknife::CommandLetter());
command_list.push_back(new swissknife::CommandCheck());
command_list.push_back(new swissknife::CommandListCatalogs());
command_list.push_back(new swissknife::CommandPull());
command_list.push_back(new swissknife::CommandZpipe());
command_list.push_back(new swissknife::CommandInfo());
command_list.push_back(new swissknife::CommandVersion());
command_list.push_back(new swissknife::CommandMigrate());
command_list.push_back(new swissknife::CommandScrub());
command_list.push_back(new swissknife::CommandGc());
if (argc < 2) {
swissknife::Usage();
return 1;
}
if ((string(argv[1]) == "--help")) {
swissknife::Usage();
return 0;
}
if ((string(argv[1]) == "--version")) {
swissknife::CommandVersion().Main(swissknife::ArgumentList());
return 0;
}
for (unsigned i = 0; i < command_list.size(); ++i) {
if (command_list[i]->GetName() == string(argv[1])) {
swissknife::ArgumentList args;
optind = 1;
string option_string = "";
swissknife::ParameterList params = command_list[i]->GetParams();
for (unsigned j = 0; j < params.size(); ++j) {
option_string.push_back(params[j].key());
if (!params[j].switch_only())
option_string.push_back(':');
}
int c;
while ((c = getopt(argc, argv, option_string.c_str())) != -1) {
bool valid_option = false;
for (unsigned j = 0; j < params.size(); ++j) {
if (c == params[j].key()) {
valid_option = true;
string *argument = NULL;
if (!params[j].switch_only()) {
argument = new string(optarg);
}
args[c] = argument;
break;
}
}
if (!valid_option) {
swissknife::Usage();
return 1;
}
}
for (unsigned j = 0; j < params.size(); ++j) {
if (!params[j].optional()) {
if (args.find(params[j].key()) == args.end()) {
LogCvmfs(kLogCvmfs, kLogStderr, "parameter -%c missing",
params[j].key());
return 1;
}
}
}
return command_list[i]->Main(args);
}
}
delete g_signature_manager;
delete g_download_manager;
swissknife::Usage();
return 1;
}
<commit_msg>register new swissknife command<commit_after>/**
* This file is part of the CernVM File System
*
* This tool acts as an entry point for all the server-related
* cvmfs tasks, such as uploading files and checking the sanity of
* a repository.
*/
#include "cvmfs_config.h"
#include "swissknife.h"
#include <unistd.h>
#include <vector>
#include "logging.h"
#include "download.h"
#include "signature.h"
#include "swissknife_zpipe.h"
#include "swissknife_check.h"
#include "swissknife_lsrepo.h"
#include "swissknife_pull.h"
#include "swissknife_sign.h"
#include "swissknife_letter.h"
#include "swissknife_sync.h"
#include "swissknife_info.h"
#include "swissknife_history.h"
#include "swissknife_migrate.h"
#include "swissknife_scrub.h"
#include "swissknife_gc.h"
using namespace std; // NOLINT
using namespace swissknife;
vector<swissknife::Command *> command_list;
download::DownloadManager *swissknife::g_download_manager;
signature::SignatureManager *swissknife::g_signature_manager;
void swissknife::Usage() {
LogCvmfs(kLogCvmfs, kLogStdout,
"CernVM-FS repository storage management commands\n"
"Version %s\n"
"Usage (normally called from cvmfs_server):\n"
" cvmfs_swissknife <command> [options]\n",
VERSION);
for (unsigned i = 0; i < command_list.size(); ++i) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "\n"
"Command %s\n"
"--------", command_list[i]->GetName().c_str());
for (unsigned j = 0; j < command_list[i]->GetName().length(); ++j) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "-");
}
LogCvmfs(kLogCvmfs, kLogStdout, "");
LogCvmfs(kLogCvmfs, kLogStdout, "%s",
command_list[i]->GetDescription().c_str());
swissknife::ParameterList params = command_list[i]->GetParams();
if (!params.empty()) {
LogCvmfs(kLogCvmfs, kLogStdout, "Options:");
for (unsigned j = 0; j < params.size(); ++j) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, " -%c %s",
params[j].key(), params[j].description().c_str());
if (params[j].optional())
LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, " (optional)");
LogCvmfs(kLogCvmfs, kLogStdout, "");
}
} // Parameter list
} // Command list
LogCvmfs(kLogCvmfs, kLogStdout, "");
}
int main(int argc, char **argv) {
g_download_manager = new download::DownloadManager();
g_signature_manager = new signature::SignatureManager();
command_list.push_back(new swissknife::CommandCreate());
command_list.push_back(new swissknife::CommandUpload());
command_list.push_back(new swissknife::CommandRemove());
command_list.push_back(new swissknife::CommandPeek());
command_list.push_back(new swissknife::CommandSync());
command_list.push_back(new swissknife::CommandApplyDirtab());
command_list.push_back(new swissknife::CommandCreateTag());
command_list.push_back(new swissknife::CommandRemoveTag());
command_list.push_back(new swissknife::CommandListTags());
command_list.push_back(new swissknife::CommandInfoTag());
command_list.push_back(new swissknife::CommandRollbackTag());
command_list.push_back(new swissknife::CommandEmptyRecycleBin());
command_list.push_back(new swissknife::CommandSign());
command_list.push_back(new swissknife::CommandLetter());
command_list.push_back(new swissknife::CommandCheck());
command_list.push_back(new swissknife::CommandListCatalogs());
command_list.push_back(new swissknife::CommandPull());
command_list.push_back(new swissknife::CommandZpipe());
command_list.push_back(new swissknife::CommandInfo());
command_list.push_back(new swissknife::CommandVersion());
command_list.push_back(new swissknife::CommandMigrate());
command_list.push_back(new swissknife::CommandScrub());
command_list.push_back(new swissknife::CommandGc());
if (argc < 2) {
swissknife::Usage();
return 1;
}
if ((string(argv[1]) == "--help")) {
swissknife::Usage();
return 0;
}
if ((string(argv[1]) == "--version")) {
swissknife::CommandVersion().Main(swissknife::ArgumentList());
return 0;
}
for (unsigned i = 0; i < command_list.size(); ++i) {
if (command_list[i]->GetName() == string(argv[1])) {
swissknife::ArgumentList args;
optind = 1;
string option_string = "";
swissknife::ParameterList params = command_list[i]->GetParams();
for (unsigned j = 0; j < params.size(); ++j) {
option_string.push_back(params[j].key());
if (!params[j].switch_only())
option_string.push_back(':');
}
int c;
while ((c = getopt(argc, argv, option_string.c_str())) != -1) {
bool valid_option = false;
for (unsigned j = 0; j < params.size(); ++j) {
if (c == params[j].key()) {
valid_option = true;
string *argument = NULL;
if (!params[j].switch_only()) {
argument = new string(optarg);
}
args[c] = argument;
break;
}
}
if (!valid_option) {
swissknife::Usage();
return 1;
}
}
for (unsigned j = 0; j < params.size(); ++j) {
if (!params[j].optional()) {
if (args.find(params[j].key()) == args.end()) {
LogCvmfs(kLogCvmfs, kLogStderr, "parameter -%c missing",
params[j].key());
return 1;
}
}
}
return command_list[i]->Main(args);
}
}
delete g_signature_manager;
delete g_download_manager;
swissknife::Usage();
return 1;
}
<|endoftext|>
|
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/extensions/format.hpp>
#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>
namespace blackhole {
namespace testing {
using ::testing::_;
namespace mock {
namespace {
class handler_t : public ::blackhole::handler_t {
public:
MOCK_METHOD1(execute, void(const record_t&));
};
} // namespace
} // namespace mock
TEST(RootLogger, Log) {
// Can be initialized with none handlers, does nothing.
root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, ForwardToHandler) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
auto& mock = *handler.get();
std::vector<std::unique_ptr<handler_t>> handlers;
handlers.push_back(std::move(handler));
root_logger_t logger(std::move(handlers));
EXPECT_CALL(mock, execute(_))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.1");
}
// TEST(wrapper, call) {
// using attribute::value_t;
// using attribute::owned_t;
//
// root_logger_t root({});
//
// wrapper_t wrapper1{root, {
// {"key#0", owned_t(0)},
// {"key#1", owned_t("value#1")}
// }};
//
// wrapper_t wrapper2{wrapper1, {
// {"key#2", owned_t(2)},
// {"key#3", owned_t("value#3")}
// }};
//
// logger_facade<wrapper_t> logger(wrapper2);
//
// logger.log(0,
// {
// {"key#4", value_t(42)},
// {"key#5", value_t(3.1415)},
// {"key#6", value_t("value")}
// }, "{} - {} [{}] 'GET {} HTTP/1.0' {} {}",
// "[::]",
// "esafronov",
// "10/Oct/2000:13:55:36 -0700",
// "/porn.png",
// 200,
// 2326
// );
// }
} // namespace testing
} // namespace blackhole
<commit_msg>chore(testing): add multiple handlers check<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/extensions/format.hpp>
#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>
namespace blackhole {
namespace testing {
using ::testing::_;
namespace mock {
namespace {
class handler_t : public ::blackhole::handler_t {
public:
MOCK_METHOD1(execute, void(const record_t&));
};
} // namespace
} // namespace mock
TEST(RootLogger, Log) {
// Can be initialized with none handlers, does nothing.
root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, ForwardToHandler) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
auto& mock = *handler.get();
std::vector<std::unique_ptr<handler_t>> handlers;
handlers.push_back(std::move(handler));
root_logger_t logger(std::move(handlers));
EXPECT_CALL(mock, execute(_))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, ForwardToHandlers) {
std::vector<std::unique_ptr<handler_t>> handlers;
std::vector<mock::handler_t*> handlers_view;
for (int i = 0; i < 4; ++i) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
handlers_view.push_back(handler.get());
handlers.push_back(std::move(handler));
}
root_logger_t logger(std::move(handlers));
for (auto handler : handlers_view) {
EXPECT_CALL(*handler, execute(_))
.Times(1);
}
logger.log(0, "GET /porn.png HTTP/1.1");
}
// TEST(wrapper, call) {
// using attribute::value_t;
// using attribute::owned_t;
//
// root_logger_t root({});
//
// wrapper_t wrapper1{root, {
// {"key#0", owned_t(0)},
// {"key#1", owned_t("value#1")}
// }};
//
// wrapper_t wrapper2{wrapper1, {
// {"key#2", owned_t(2)},
// {"key#3", owned_t("value#3")}
// }};
//
// logger_facade<wrapper_t> logger(wrapper2);
//
// logger.log(0,
// {
// {"key#4", value_t(42)},
// {"key#5", value_t(3.1415)},
// {"key#6", value_t("value")}
// }, "{} - {} [{}] 'GET {} HTTP/1.0' {} {}",
// "[::]",
// "esafronov",
// "10/Oct/2000:13:55:36 -0700",
// "/porn.png",
// 200,
// 2326
// );
// }
} // namespace testing
} // namespace blackhole
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 German Aerospace Center (DLR/SC)
*
* Created: 2018-08-06 Martin Siggel <Martin.Siggel@dlr.de>
*
* 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 "CTiglPointsToBSplineInterpolation.h"
#include "CTiglError.h"
#include "CTiglBSplineAlgorithms.h"
#include <BSplCLib.hxx>
#include <math_Gauss.hxx>
#include <GeomConvert.hxx>
#include <Geom_TrimmedCurve.hxx>
#include <algorithm>
namespace
{
Handle(TColStd_HArray1OfReal) toArray(const std::vector<double>& vector)
{
Handle(TColStd_HArray1OfReal) array = new TColStd_HArray1OfReal(1, static_cast<int>(vector.size()));
int ipos = 1;
for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); ++it, ipos++) {
array->SetValue(ipos, *it);
}
return array;
}
void clamp(Handle(Geom_BSplineCurve)& curve, double min, double max)
{
Handle(Geom_Curve) c = new Geom_TrimmedCurve(curve, min, max);
curve = GeomConvert::CurveToBSplineCurve(c);
}
} // namespace
namespace tigl
{
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt)& points, unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_degree(maxDegree)
, m_C2Continuous(continuousIfClosed)
{
m_params = CTiglBSplineAlgorithms::computeParamsBSplineCurve(points);
}
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt)& points, const std::vector<double> ¶meters, unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_params(parameters)
, m_degree(maxDegree)
, m_C2Continuous(continuousIfClosed)
{
if (m_params.size() != m_pnts->Length()) {
throw CTiglError("Number of parameters and points don't match in CTiglPointsToBSplineInterpolation");
}
}
Handle(Geom_BSplineCurve) CTiglPointsToBSplineInterpolation::Curve() const
{
unsigned int degree = Degree();
std::vector<double> params = m_params;
std::vector<double> knots = CTiglBSplineAlgorithms::knotsFromCurveParameters(params, degree, isClosed());
if (isClosed()) {
// we remove the last parameter, since it is implicitly
// included by wrapping the control points
params.pop_back();
}
math_Matrix bsplMat = CTiglBSplineAlgorithms::bsplineBasisMat(degree, toArray(knots)->Array1(), toArray(params)->Array1());
// build left hand side of the linear system
int nParams = params.size();
math_Matrix lhs(1, nParams, 1, nParams, 0.);
for (int iCol = 1; iCol <= nParams; ++iCol) {
lhs.SetCol(iCol, bsplMat.Col(iCol));
}
if (isClosed()) {
// sets the continuity constraints for closed curves on the left hand side if requested
// by wrapping around the control points
// This is a trick to make the matrix square and enforce the endpoint conditions
for (int iCol = 1; iCol <= degree; ++iCol) {
lhs.SetCol(iCol, lhs.Col(iCol) + bsplMat.Col(nParams + iCol));
}
}
// right hand side
math_Vector rhsx(1, nParams, 0.);
math_Vector rhsy(1, nParams, 0.);
math_Vector rhsz(1, nParams, 0.);
for (int i = 1; i <= nParams; ++i) {
const gp_Pnt& p = m_pnts->Value(i);
rhsx(i) = p.X();
rhsy(i) = p.Y();
rhsz(i) = p.Z();
}
math_Gauss solver(lhs);
math_Vector cp_x(1, nParams);
math_Vector cp_y(1, nParams);
math_Vector cp_z(1, nParams);
solver.Solve(rhsx, cp_x);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsy, cp_y);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsz, cp_z);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
int nCtrPnts = m_params.size();
if (isClosed()) {
nCtrPnts += degree - 1;
}
if (needsShifting()) {
nCtrPnts += 1;
}
TColgp_Array1OfPnt poles(1, nCtrPnts);
for (Standard_Integer icp = 1; icp <= nParams; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(icp, pnt);
}
if (isClosed()) {
// wrap control points
for (Standard_Integer icp = 1; icp <= degree; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(nParams + icp, pnt);
}
}
if (needsShifting()) {
// add a new control point and knot
knots.push_back(knots.back() + knots[2*degree+1] - knots[2*degree]);
poles.SetValue(nParams + degree + 1, poles.Value(degree+1));
// shift back the knots
for (size_t iknot = 0; iknot < knots.size(); ++iknot) {
knots[iknot] -= params[0];
}
}
Handle(TColStd_HArray1OfReal) occFlatKnots = toArray(knots);
int knotsLen = BSplCLib::KnotsLength(occFlatKnots->Array1());
TColStd_Array1OfReal occKnots(1, knotsLen);
TColStd_Array1OfInteger occMults(1, knotsLen);
BSplCLib::Knots(occFlatKnots->Array1(), occKnots, occMults);
Handle(Geom_BSplineCurve) result = new Geom_BSplineCurve(poles, occKnots, occMults, degree, false);
// clamp bspline
if (isClosed()) {
clamp(result, m_params.front(), m_params.back());
}
return result;
}
double CTiglPointsToBSplineInterpolation::maxDistanceOfBoundingBox(const TColgp_Array1OfPnt& points) const
{
double distance;
double maxDistance = 0.;
for (int i = points.Lower(); i <= points.Upper(); ++i) {
for (int j = points.Lower(); j <= points.Upper(); ++j) {
distance = std::max( distance, points.Value(i).Distance(points.Value(j)));
}
}
return maxDistance;
}
bool CTiglPointsToBSplineInterpolation::isClosed() const
{
double maxDistance = maxDistanceOfBoundingBox(m_pnts->Array1());
double error = 1e-12*maxDistance;
return m_pnts->Value(m_pnts->Lower()).IsEqual(m_pnts->Value(m_pnts->Upper()), error) && m_C2Continuous;
}
bool CTiglPointsToBSplineInterpolation::needsShifting() const
{
return (Degree() % 2) == 0 && isClosed();
}
CTiglPointsToBSplineInterpolation::operator Handle(Geom_BSplineCurve)() const
{
return Curve();
}
const std::vector<double>& CTiglPointsToBSplineInterpolation::Parameters() const
{
return m_params;
}
unsigned int CTiglPointsToBSplineInterpolation::Degree() const
{
return std::min(m_pnts->Length(), m_degree);
}
} // namespace tigl
<commit_msg>Fixed some warnings<commit_after>/*
* Copyright (C) 2018 German Aerospace Center (DLR/SC)
*
* Created: 2018-08-06 Martin Siggel <Martin.Siggel@dlr.de>
*
* 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 "CTiglPointsToBSplineInterpolation.h"
#include "CTiglError.h"
#include "CTiglBSplineAlgorithms.h"
#include <BSplCLib.hxx>
#include <math_Gauss.hxx>
#include <GeomConvert.hxx>
#include <Geom_TrimmedCurve.hxx>
#include <algorithm>
namespace
{
Handle(TColStd_HArray1OfReal) toArray(const std::vector<double>& vector)
{
Handle(TColStd_HArray1OfReal) array = new TColStd_HArray1OfReal(1, static_cast<int>(vector.size()));
int ipos = 1;
for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); ++it, ipos++) {
array->SetValue(ipos, *it);
}
return array;
}
void clamp(Handle(Geom_BSplineCurve)& curve, double min, double max)
{
Handle(Geom_Curve) c = new Geom_TrimmedCurve(curve, min, max);
curve = GeomConvert::CurveToBSplineCurve(c);
}
} // namespace
namespace tigl
{
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt)& points, unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_degree(maxDegree)
, m_C2Continuous(continuousIfClosed)
{
m_params = CTiglBSplineAlgorithms::computeParamsBSplineCurve(points);
}
CTiglPointsToBSplineInterpolation::CTiglPointsToBSplineInterpolation(const Handle(TColgp_HArray1OfPnt)& points, const std::vector<double> ¶meters, unsigned int maxDegree, bool continuousIfClosed)
: m_pnts(points)
, m_params(parameters)
, m_degree(maxDegree)
, m_C2Continuous(continuousIfClosed)
{
if (m_params.size() != m_pnts->Length()) {
throw CTiglError("Number of parameters and points don't match in CTiglPointsToBSplineInterpolation");
}
}
Handle(Geom_BSplineCurve) CTiglPointsToBSplineInterpolation::Curve() const
{
int degree = static_cast<int>(Degree());
std::vector<double> params = m_params;
std::vector<double> knots = CTiglBSplineAlgorithms::knotsFromCurveParameters(params, static_cast<unsigned int>(degree), isClosed());
if (isClosed()) {
// we remove the last parameter, since it is implicitly
// included by wrapping the control points
params.pop_back();
}
math_Matrix bsplMat = CTiglBSplineAlgorithms::bsplineBasisMat(degree, toArray(knots)->Array1(), toArray(params)->Array1());
// build left hand side of the linear system
int nParams = static_cast<int>(params.size());
math_Matrix lhs(1, nParams, 1, nParams, 0.);
for (int iCol = 1; iCol <= nParams; ++iCol) {
lhs.SetCol(iCol, bsplMat.Col(iCol));
}
if (isClosed()) {
// sets the continuity constraints for closed curves on the left hand side if requested
// by wrapping around the control points
// This is a trick to make the matrix square and enforce the endpoint conditions
for (int iCol = 1; iCol <= degree; ++iCol) {
lhs.SetCol(iCol, lhs.Col(iCol) + bsplMat.Col(nParams + iCol));
}
}
// right hand side
math_Vector rhsx(1, nParams, 0.);
math_Vector rhsy(1, nParams, 0.);
math_Vector rhsz(1, nParams, 0.);
for (int i = 1; i <= nParams; ++i) {
const gp_Pnt& p = m_pnts->Value(i);
rhsx(i) = p.X();
rhsy(i) = p.Y();
rhsz(i) = p.Z();
}
math_Gauss solver(lhs);
math_Vector cp_x(1, nParams);
math_Vector cp_y(1, nParams);
math_Vector cp_z(1, nParams);
solver.Solve(rhsx, cp_x);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsy, cp_y);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
solver.Solve(rhsz, cp_z);
if (!solver.IsDone()) {
throw CTiglError("Singular Matrix", TIGL_MATH_ERROR);
}
int nCtrPnts = static_cast<int>(m_params.size());
if (isClosed()) {
nCtrPnts += degree - 1;
}
if (needsShifting()) {
nCtrPnts += 1;
}
TColgp_Array1OfPnt poles(1, nCtrPnts);
for (Standard_Integer icp = 1; icp <= nParams; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(icp, pnt);
}
if (isClosed()) {
// wrap control points
for (Standard_Integer icp = 1; icp <= degree; ++icp) {
gp_Pnt pnt(cp_x.Value(icp), cp_y.Value(icp), cp_z.Value(icp));
poles.SetValue(nParams + icp, pnt);
}
}
if (needsShifting()) {
// add a new control point and knot
knots.push_back(knots.back() + knots[2*degree+1] - knots[2*degree]);
poles.SetValue(nParams + degree + 1, poles.Value(degree+1));
// shift back the knots
for (size_t iknot = 0; iknot < knots.size(); ++iknot) {
knots[iknot] -= params[0];
}
}
Handle(TColStd_HArray1OfReal) occFlatKnots = toArray(knots);
int knotsLen = BSplCLib::KnotsLength(occFlatKnots->Array1());
TColStd_Array1OfReal occKnots(1, knotsLen);
TColStd_Array1OfInteger occMults(1, knotsLen);
BSplCLib::Knots(occFlatKnots->Array1(), occKnots, occMults);
Handle(Geom_BSplineCurve) result = new Geom_BSplineCurve(poles, occKnots, occMults, degree, false);
// clamp bspline
if (isClosed()) {
clamp(result, m_params.front(), m_params.back());
}
return result;
}
double CTiglPointsToBSplineInterpolation::maxDistanceOfBoundingBox(const TColgp_Array1OfPnt& points) const
{
double distance;
double maxDistance = 0.;
for (int i = points.Lower(); i <= points.Upper(); ++i) {
for (int j = points.Lower(); j <= points.Upper(); ++j) {
distance = std::max( distance, points.Value(i).Distance(points.Value(j)));
}
}
return maxDistance;
}
bool CTiglPointsToBSplineInterpolation::isClosed() const
{
double maxDistance = maxDistanceOfBoundingBox(m_pnts->Array1());
double error = 1e-12*maxDistance;
return m_pnts->Value(m_pnts->Lower()).IsEqual(m_pnts->Value(m_pnts->Upper()), error) && m_C2Continuous;
}
bool CTiglPointsToBSplineInterpolation::needsShifting() const
{
return (Degree() % 2) == 0 && isClosed();
}
CTiglPointsToBSplineInterpolation::operator Handle(Geom_BSplineCurve)() const
{
return Curve();
}
const std::vector<double>& CTiglPointsToBSplineInterpolation::Parameters() const
{
return m_params;
}
unsigned int CTiglPointsToBSplineInterpolation::Degree() const
{
return std::min(m_pnts->Length(), m_degree);
}
} // namespace tigl
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_type2.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:04:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ADC_PE_TYPE2_HXX
#define ADC_PE_TYPE2_HXX
// USED SERVICES
// BASE CLASSES
#include<s2_luidl/parsenv2.hxx>
#include<s2_luidl/pestate.hxx>
// COMPONENTS
#include<ary/qualiname.hxx>
// PARAMETERS
namespace csi
{
namespace uidl
{
class PE_Type : public UnoIDL_PE,
public ParseEnvState
{
public:
PE_Type(
ary::idl::Type_id & o_rResult );
virtual ~PE_Type();
virtual void ProcessToken(
const Token & i_rToken );
virtual void Process_Identifier(
const TokIdentifier &
i_rToken );
virtual void Process_NameSeparator();
virtual void Process_Punctuation(
const TokPunctuation &
i_rToken );
virtual void Process_BuiltInType(
const TokBuiltInType &
i_rToken );
virtual void Process_TypeModifier(
const TokTypeModifier &
i_rToken );
virtual void Process_Default();
private:
enum E_State
{
e_none = 0,
expect_type,
expect_quname_part,
expect_quname_separator,
in_template_type
};
void Finish();
PE_Type & MyTemplateType();
virtual void InitData();
virtual void TransferData();
virtual UnoIDL_PE & MyPE();
// DATA
ary::idl::Type_id * pResult;
uintt nIsSequenceCounter;
uintt nSequenceDownCounter;
bool bIsUnsigned;
ary::QualifiedName sFullType;
E_State eState;
String sLastPart;
Dyn<PE_Type> pPE_TemplateType; /// @attention Recursion, only initiate, if needed!
ary::idl::Type_id nTemplateType;
};
// IMPLEMENTATION
} // namespace uidl
} // namespace csi
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.80); FILE MERGED 2008/03/28 16:02:58 rt 1.4.80.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_type2.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef ADC_PE_TYPE2_HXX
#define ADC_PE_TYPE2_HXX
// USED SERVICES
// BASE CLASSES
#include<s2_luidl/parsenv2.hxx>
#include<s2_luidl/pestate.hxx>
// COMPONENTS
#include<ary/qualiname.hxx>
// PARAMETERS
namespace csi
{
namespace uidl
{
class PE_Type : public UnoIDL_PE,
public ParseEnvState
{
public:
PE_Type(
ary::idl::Type_id & o_rResult );
virtual ~PE_Type();
virtual void ProcessToken(
const Token & i_rToken );
virtual void Process_Identifier(
const TokIdentifier &
i_rToken );
virtual void Process_NameSeparator();
virtual void Process_Punctuation(
const TokPunctuation &
i_rToken );
virtual void Process_BuiltInType(
const TokBuiltInType &
i_rToken );
virtual void Process_TypeModifier(
const TokTypeModifier &
i_rToken );
virtual void Process_Default();
private:
enum E_State
{
e_none = 0,
expect_type,
expect_quname_part,
expect_quname_separator,
in_template_type
};
void Finish();
PE_Type & MyTemplateType();
virtual void InitData();
virtual void TransferData();
virtual UnoIDL_PE & MyPE();
// DATA
ary::idl::Type_id * pResult;
uintt nIsSequenceCounter;
uintt nSequenceDownCounter;
bool bIsUnsigned;
ary::QualifiedName sFullType;
E_State eState;
String sLastPart;
Dyn<PE_Type> pPE_TemplateType; /// @attention Recursion, only initiate, if needed!
ary::idl::Type_id nTemplateType;
};
// IMPLEMENTATION
} // namespace uidl
} // namespace csi
#endif
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015 gRPC 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 "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/tcp_server.h"
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
#include <vector>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/iocp_windows.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/pollset_windows.h"
#include "src/core/lib/surface/init.h"
#define LOG_TEST(x) gpr_log(GPR_INFO, "%s", #x)
int main(int argc, char **argv) {
grpc_init();
// Create three threads that all start queueing for work.
//
// The first one becomes the active poller for work and the two other
// threads go into the poller queue.
//
// When work arrives, the first one notifies the next active poller,
// this wakes the second thread - however all this does is return from
// the grpc_pollset_work function. It's up to that thread to figure
// out if it still wants to queue for more work or if it should kick
// other pollers.
//
// Previously that kick only affected pollers in the same pollset, thus
// leaving the third thread stuck in the poller queue. Now the pollset-
// specific grpc_pollset_kick will also kick pollers from other pollsets
// if there are no pollers in the current pollset. This frees up the
// last thread and completes the test.
std::condition_variable cv;
std::mutex m;
int complete = 0;
std::vector<std::thread> threads;
for (int i = 0; i < 3; i++) {
threads.push_back(std::thread([&]() {
grpc_core::ExecCtx exec_ctx;
gpr_mu *g_mu;
grpc_pollset g_pollset = {};
grpc_pollset_init(&g_pollset, &g_mu);
gpr_mu_lock(g_mu);
// Queue for work and once we're done, make sure to kick the remaining
// threads.
grpc_error *error;
error = grpc_pollset_work(&g_pollset, NULL, GRPC_MILLIS_INF_FUTURE);
error = grpc_pollset_kick(&g_pollset, NULL);
gpr_mu_unlock(g_mu);
{
std::unique_lock<std::mutex> lock(m);
complete++;
cv.notify_all();
}
}));
}
// Wait for the threads to start working and then kick one of them.
std::this_thread::sleep_for(std::chrono::milliseconds(10));
grpc_iocp_kick();
// Wait for the threads to complete.
{
std::unique_lock<std::mutex> lock(m);
if (!cv.wait_for(lock, std::chrono::seconds(1),
[&] { return complete == 3; }))
return EXIT_FAILURE;
}
for (auto &t : threads)
t.join();
return EXIT_SUCCESS;
}
<commit_msg>Clang format<commit_after>/*
*
* Copyright 2015 gRPC 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 "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/tcp_server.h"
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
#include <vector>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/iocp_windows.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/pollset_windows.h"
#include "src/core/lib/surface/init.h"
#define LOG_TEST(x) gpr_log(GPR_INFO, "%s", #x)
int main(int argc, char** argv) {
grpc_init();
// Create three threads that all start queueing for work.
//
// The first one becomes the active poller for work and the two other
// threads go into the poller queue.
//
// When work arrives, the first one notifies the next active poller,
// this wakes the second thread - however all this does is return from
// the grpc_pollset_work function. It's up to that thread to figure
// out if it still wants to queue for more work or if it should kick
// other pollers.
//
// Previously that kick only affected pollers in the same pollset, thus
// leaving the third thread stuck in the poller queue. Now the pollset-
// specific grpc_pollset_kick will also kick pollers from other pollsets
// if there are no pollers in the current pollset. This frees up the
// last thread and completes the test.
std::condition_variable cv;
std::mutex m;
int complete = 0;
std::vector<std::thread> threads;
for (int i = 0; i < 3; i++) {
threads.push_back(std::thread([&]() {
grpc_core::ExecCtx exec_ctx;
gpr_mu* g_mu;
grpc_pollset g_pollset = {};
grpc_pollset_init(&g_pollset, &g_mu);
gpr_mu_lock(g_mu);
// Queue for work and once we're done, make sure to kick the remaining
// threads.
grpc_error* error;
error = grpc_pollset_work(&g_pollset, NULL, GRPC_MILLIS_INF_FUTURE);
error = grpc_pollset_kick(&g_pollset, NULL);
gpr_mu_unlock(g_mu);
{
std::unique_lock<std::mutex> lock(m);
complete++;
cv.notify_all();
}
}));
}
// Wait for the threads to start working and then kick one of them.
std::this_thread::sleep_for(std::chrono::milliseconds(10));
grpc_iocp_kick();
// Wait for the threads to complete.
{
std::unique_lock<std::mutex> lock(m);
if (!cv.wait_for(lock, std::chrono::seconds(1),
[&] { return complete == 3; }))
return EXIT_FAILURE;
}
for (auto& t : threads) t.join();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/**
* _____
* / _ \
* / _/ \ \
* / / \_/ \
* / \_/ _ \ ___ _ ___ ___ ____ ____ ___ _____ _ _
* \ / \_/ \ / / _\| | | __| / _ \ | ++ \ | ++ \ / _ \ |_ _|| | | |
* \ \_/ \_/ / | | | | | ++ | |_| || ++ / | ++_/| |_| | | | | +-+ |
* \ \_/ / | |_ | |_ | ++ | _ || |\ \ | | | _ | | | | +-+ |
* \_____/ \___/|___||___||_| |_||_| \_\|_| |_| |_| |_| |_| |_|
* ROBOTICS™
*
* File: kinova_tool_pose_action.cpp
* Desc: Class for moving/querying kinova arm.
* Auth: Alex Bencz, Jeff Schmidt
*
* Copyright (c) 2013, Clearpath Robotics, Inc.
* All Rights Reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Clearpath Robotics, Inc. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CLEARPATH ROBOTICS, INC. 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.
*
* Please send comments, questions, or patches to skynet@clearpathrobotics.com
*
*/
#include "kinova_driver/kinova_tool_pose_action.h"
#include <kinova/KinovaTypes.h>
#include "kinova_driver/kinova_ros_types.h"
#include <string>
#include <ros/console.h>
namespace kinova
{
KinovaPoseActionServer::KinovaPoseActionServer(KinovaComm &arm_comm, const ros::NodeHandle &nh, const std::string &kinova_robotType)
: arm_comm_(arm_comm),
node_handle_(nh, "pose_action"),
kinova_robotType_(kinova_robotType),
action_server_(node_handle_, "tool_pose",
boost::bind(&KinovaPoseActionServer::actionCallback, this, _1), false)
{
double position_tolerance;
double EulerAngle_tolerance;
node_handle_.param<double>("stall_interval_seconds", stall_interval_seconds_, 1.0);
node_handle_.param<double>("stall_threshold", stall_threshold_, 0.005);
node_handle_.param<double>("rate_hz", rate_hz_, 10.0);
node_handle_.param<double>("position_tolerance", position_tolerance, 0.01);
node_handle_.param<double>("EulerAngle_tolerance", EulerAngle_tolerance, 2.0*M_PI/180);
// tf_prefix_ = kinova_robotType_ + "_" + boost::lexical_cast<string>(same_type_index); // in case of multiple same_type robots
tf_prefix_ = kinova_robotType_ + "_";
position_tolerance_ = static_cast<float>(position_tolerance);
EulerAngle_tolerance_ = static_cast<float>(EulerAngle_tolerance);
std::stringstream ss;
ss << tf_prefix_ << "link_base";
link_base_frame_ = ss.str();
action_server_.start();
if(ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug))
{
ros::console::notifyLoggerLevelsChanged();
}
}
KinovaPoseActionServer::~KinovaPoseActionServer()
{
}
void KinovaPoseActionServer::actionCallback(const kinova_msgs::ArmPoseGoalConstPtr &goal)
{
kinova_msgs::ArmPoseFeedback feedback;
kinova_msgs::ArmPoseResult result;
feedback.pose.header.frame_id = goal->pose.header.frame_id;
result.pose.header.frame_id = goal->pose.header.frame_id;
ros::Time current_time = ros::Time::now();
KinovaPose current_pose;
geometry_msgs::PoseStamped local_pose;
local_pose.header.frame_id = link_base_frame_;
try
{
// Put the goal pose into the frame used by the arm
if (ros::ok()
&& !listener.canTransform(link_base_frame_, goal->pose.header.frame_id,
goal->pose.header.stamp))
{
ROS_ERROR("Could not get transfrom from %s to %s, aborting cartesian movement",
link_base_frame_.c_str(), goal->pose.header.frame_id.c_str());
action_server_.setAborted(result);
return;
}
listener.transformPose(local_pose.header.frame_id, goal->pose, local_pose);
arm_comm_.getCartesianPosition(current_pose);
if (arm_comm_.isStopped())
{
ROS_INFO("Could not complete cartesian action because the arm is 'stopped'.");
local_pose.pose = current_pose.constructPoseMsg();
listener.transformPose(result.pose.header.frame_id, local_pose, result.pose);
action_server_.setAborted(result);
return;
}
last_nonstall_time_ = current_time;
last_nonstall_pose_ = current_pose;
KinovaPose target(local_pose.pose);
ROS_DEBUG_STREAM(std::endl << std::endl << "***-----------------------***" << std::endl << __PRETTY_FUNCTION__ << ": target X " << target.X << "; Y "<< target.Y << "; Z "<< target.Z << "; ThetaX " << target.ThetaX << "; ThetaY " << target.ThetaY << "; ThetaZ " << target.ThetaZ << std::endl << "***-----------------------***" << std::endl );
arm_comm_.setCartesianPosition(target);
while (ros::ok())
{
// without setCartesianPosition() in while loop, robot stopped in the half way, and the goal won't be reached.
arm_comm_.setCartesianPosition(target);
ros::spinOnce();
if (action_server_.isPreemptRequested() || !ros::ok())
{
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": action server isPreemptRequested");
result.pose = feedback.pose;
arm_comm_.stopAPI();
arm_comm_.startAPI();
action_server_.setPreempted(result);
return;
}
else if (arm_comm_.isStopped())
{
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": arm_comm_.isStopped()");
result.pose = feedback.pose;
action_server_.setAborted(result);
return;
}
arm_comm_.getCartesianPosition(current_pose);
current_time = ros::Time::now();
local_pose.pose = current_pose.constructPoseMsg();
listener.transformPose(feedback.pose.header.frame_id, local_pose, feedback.pose);
// action_server_.publishFeedback(feedback);
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": current_pose X " << current_pose.X << "; Y "<< current_pose.Y << "; Z "<< current_pose.Z << "; ThetaX " << current_pose.ThetaX << "; ThetaY " << current_pose.ThetaY << "; ThetaZ " << current_pose.ThetaZ );
if (target.isCloseToOther(current_pose, position_tolerance_, EulerAngle_tolerance_))
{
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": arm_comm_.isCloseToOther");
result.pose = feedback.pose;
action_server_.setSucceeded(result);
return;
}
else if (!last_nonstall_pose_.isCloseToOther(current_pose, stall_threshold_, stall_threshold_))
{
// Check if we are outside of a potential stall condition
last_nonstall_time_ = current_time;
last_nonstall_pose_ = current_pose;
}
else if ((current_time - last_nonstall_time_).toSec() > stall_interval_seconds_)
{
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": stall_interval_seconds_");
// Check if the full stall condition has been meet
result.pose = feedback.pose;
arm_comm_.stopAPI();
arm_comm_.startAPI();
action_server_.setPreempted(result);
return;
}
ros::Rate(rate_hz_).sleep();
}
}
catch(const std::exception& e)
{
result.pose = feedback.pose;
ROS_ERROR_STREAM(e.what());
action_server_.setAborted(result);
}
}
} // namespace kinova
<commit_msg>disable debug log in terminal<commit_after>/**
* _____
* / _ \
* / _/ \ \
* / / \_/ \
* / \_/ _ \ ___ _ ___ ___ ____ ____ ___ _____ _ _
* \ / \_/ \ / / _\| | | __| / _ \ | ++ \ | ++ \ / _ \ |_ _|| | | |
* \ \_/ \_/ / | | | | | ++ | |_| || ++ / | ++_/| |_| | | | | +-+ |
* \ \_/ / | |_ | |_ | ++ | _ || |\ \ | | | _ | | | | +-+ |
* \_____/ \___/|___||___||_| |_||_| \_\|_| |_| |_| |_| |_| |_|
* ROBOTICS™
*
* File: kinova_tool_pose_action.cpp
* Desc: Class for moving/querying kinova arm.
* Auth: Alex Bencz, Jeff Schmidt
*
* Copyright (c) 2013, Clearpath Robotics, Inc.
* All Rights Reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Clearpath Robotics, Inc. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CLEARPATH ROBOTICS, INC. 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.
*
* Please send comments, questions, or patches to skynet@clearpathrobotics.com
*
*/
#include "kinova_driver/kinova_tool_pose_action.h"
#include <kinova/KinovaTypes.h>
#include "kinova_driver/kinova_ros_types.h"
#include <string>
#include <ros/console.h>
namespace kinova
{
KinovaPoseActionServer::KinovaPoseActionServer(KinovaComm &arm_comm, const ros::NodeHandle &nh, const std::string &kinova_robotType)
: arm_comm_(arm_comm),
node_handle_(nh, "pose_action"),
kinova_robotType_(kinova_robotType),
action_server_(node_handle_, "tool_pose",
boost::bind(&KinovaPoseActionServer::actionCallback, this, _1), false)
{
double position_tolerance;
double EulerAngle_tolerance;
node_handle_.param<double>("stall_interval_seconds", stall_interval_seconds_, 1.0);
node_handle_.param<double>("stall_threshold", stall_threshold_, 0.005);
node_handle_.param<double>("rate_hz", rate_hz_, 10.0);
node_handle_.param<double>("position_tolerance", position_tolerance, 0.01);
node_handle_.param<double>("EulerAngle_tolerance", EulerAngle_tolerance, 2.0*M_PI/180);
// tf_prefix_ = kinova_robotType_ + "_" + boost::lexical_cast<string>(same_type_index); // in case of multiple same_type robots
tf_prefix_ = kinova_robotType_ + "_";
position_tolerance_ = static_cast<float>(position_tolerance);
EulerAngle_tolerance_ = static_cast<float>(EulerAngle_tolerance);
std::stringstream ss;
ss << tf_prefix_ << "link_base";
link_base_frame_ = ss.str();
action_server_.start();
// if(ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug))
// {
// ros::console::notifyLoggerLevelsChanged();
// }
}
KinovaPoseActionServer::~KinovaPoseActionServer()
{
}
void KinovaPoseActionServer::actionCallback(const kinova_msgs::ArmPoseGoalConstPtr &goal)
{
kinova_msgs::ArmPoseFeedback feedback;
kinova_msgs::ArmPoseResult result;
feedback.pose.header.frame_id = goal->pose.header.frame_id;
result.pose.header.frame_id = goal->pose.header.frame_id;
ros::Time current_time = ros::Time::now();
KinovaPose current_pose;
geometry_msgs::PoseStamped local_pose;
local_pose.header.frame_id = link_base_frame_;
try
{
// Put the goal pose into the frame used by the arm
if (ros::ok()
&& !listener.canTransform(link_base_frame_, goal->pose.header.frame_id,
goal->pose.header.stamp))
{
ROS_ERROR("Could not get transfrom from %s to %s, aborting cartesian movement",
link_base_frame_.c_str(), goal->pose.header.frame_id.c_str());
action_server_.setAborted(result);
return;
}
listener.transformPose(local_pose.header.frame_id, goal->pose, local_pose);
arm_comm_.getCartesianPosition(current_pose);
if (arm_comm_.isStopped())
{
ROS_INFO("Could not complete cartesian action because the arm is 'stopped'.");
local_pose.pose = current_pose.constructPoseMsg();
listener.transformPose(result.pose.header.frame_id, local_pose, result.pose);
action_server_.setAborted(result);
return;
}
last_nonstall_time_ = current_time;
last_nonstall_pose_ = current_pose;
KinovaPose target(local_pose.pose);
ROS_DEBUG_STREAM(std::endl << std::endl << "***-----------------------***" << std::endl << __PRETTY_FUNCTION__ << ": target X " << target.X << "; Y "<< target.Y << "; Z "<< target.Z << "; ThetaX " << target.ThetaX << "; ThetaY " << target.ThetaY << "; ThetaZ " << target.ThetaZ << std::endl << "***-----------------------***" << std::endl );
arm_comm_.setCartesianPosition(target);
while (ros::ok())
{
// without setCartesianPosition() in while loop, robot stopped in the half way, and the goal won't be reached.
arm_comm_.setCartesianPosition(target);
ros::spinOnce();
if (action_server_.isPreemptRequested() || !ros::ok())
{
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": action server isPreemptRequested");
result.pose = feedback.pose;
arm_comm_.stopAPI();
arm_comm_.startAPI();
action_server_.setPreempted(result);
return;
}
else if (arm_comm_.isStopped())
{
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": arm_comm_.isStopped()");
result.pose = feedback.pose;
action_server_.setAborted(result);
return;
}
arm_comm_.getCartesianPosition(current_pose);
current_time = ros::Time::now();
local_pose.pose = current_pose.constructPoseMsg();
listener.transformPose(feedback.pose.header.frame_id, local_pose, feedback.pose);
// action_server_.publishFeedback(feedback);
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": current_pose X " << current_pose.X << "; Y "<< current_pose.Y << "; Z "<< current_pose.Z << "; ThetaX " << current_pose.ThetaX << "; ThetaY " << current_pose.ThetaY << "; ThetaZ " << current_pose.ThetaZ );
if (target.isCloseToOther(current_pose, position_tolerance_, EulerAngle_tolerance_))
{
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": arm_comm_.isCloseToOther");
result.pose = feedback.pose;
action_server_.setSucceeded(result);
return;
}
else if (!last_nonstall_pose_.isCloseToOther(current_pose, stall_threshold_, stall_threshold_))
{
// Check if we are outside of a potential stall condition
last_nonstall_time_ = current_time;
last_nonstall_pose_ = current_pose;
}
else if ((current_time - last_nonstall_time_).toSec() > stall_interval_seconds_)
{
ROS_DEBUG_STREAM("" << __PRETTY_FUNCTION__ << ": stall_interval_seconds_");
// Check if the full stall condition has been meet
result.pose = feedback.pose;
arm_comm_.stopAPI();
arm_comm_.startAPI();
action_server_.setPreempted(result);
return;
}
ros::Rate(rate_hz_).sleep();
}
}
catch(const std::exception& e)
{
result.pose = feedback.pose;
ROS_ERROR_STREAM(e.what());
action_server_.setAborted(result);
}
}
} // namespace kinova
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: XMLTextMasterPageExport.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: dvo $ $Date: 2001-06-29 21:07:22 $
*
* 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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLTEXTMASTERPAGEEXPORT_HXX
#include "XMLTextMasterPageExport.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::beans;
using namespace ::xmloff::token;
XMLTextMasterPageExport::XMLTextMasterPageExport( SvXMLExport& rExp ) :
XMLPageExport( rExp ),
sHeaderText( RTL_CONSTASCII_USTRINGPARAM( "HeaderText" ) ),
sHeaderOn( RTL_CONSTASCII_USTRINGPARAM( "HeaderIsOn" ) ),
sHeaderShareContent( RTL_CONSTASCII_USTRINGPARAM( "HeaderIsShared" ) ),
sHeaderTextLeft( RTL_CONSTASCII_USTRINGPARAM( "HeaderTextLeft" ) ),
sFooterText( RTL_CONSTASCII_USTRINGPARAM( "FooterText" ) ),
sFooterOn( RTL_CONSTASCII_USTRINGPARAM( "FooterIsOn" ) ),
sFooterShareContent( RTL_CONSTASCII_USTRINGPARAM( "FooterIsShared" ) ),
sFooterTextLeft( RTL_CONSTASCII_USTRINGPARAM( "FooterTextLeft" ) )
{
}
XMLTextMasterPageExport::~XMLTextMasterPageExport()
{
}
void XMLTextMasterPageExport::exportHeaderFooterContent(
const Reference< XText >& rText,
sal_Bool bAutoStyles, sal_Bool bExportParagraph )
{
DBG_ASSERT( rText.is(), "There is the text" );
// tracked changes (autostyles + changes list)
GetExport().GetTextParagraphExport()->recordTrackedChangesForXText(rText);
GetExport().GetTextParagraphExport()->exportTrackedChanges(rText,
bAutoStyles);
if( bAutoStyles )
GetExport().GetTextParagraphExport()
->collectTextAutoStyles( rText, sal_False, bExportParagraph );
else
{
GetExport().GetTextParagraphExport()->exportTextDeclarations( rText );
GetExport().GetTextParagraphExport()->exportText( rText, sal_False, bExportParagraph );
}
// tracked changes (end of XText)
GetExport().GetTextParagraphExport()->recordTrackedChangesNoXText();
}
void XMLTextMasterPageExport::exportMasterPageContent(
const Reference < XPropertySet > & rPropSet,
sal_Bool bAutoStyles )
{
Any aAny;
Reference < XText > xHeaderText;
aAny = rPropSet->getPropertyValue( sHeaderText );
aAny >>= xHeaderText;
Reference < XText > xHeaderTextLeft;
aAny = rPropSet->getPropertyValue( sHeaderTextLeft );
aAny >>= xHeaderTextLeft;
Reference < XText > xFooterText;
aAny = rPropSet->getPropertyValue( sFooterText );
aAny >>= xFooterText;
Reference < XText > xFooterTextLeft;
aAny = rPropSet->getPropertyValue( sFooterTextLeft );
aAny >>= xFooterTextLeft;
if( bAutoStyles )
{
if( xHeaderText.is() )
exportHeaderFooterContent( xHeaderText, sal_True );
if( xHeaderTextLeft.is() && xHeaderTextLeft != xHeaderText )
exportHeaderFooterContent( xHeaderTextLeft, sal_True );
if( xFooterText.is() )
exportHeaderFooterContent( xFooterText, sal_True );
if( xFooterTextLeft.is() && xFooterTextLeft != xFooterText )
exportHeaderFooterContent( xFooterTextLeft, sal_True );
}
else
{
aAny = rPropSet->getPropertyValue( sHeaderOn );
sal_Bool bHeader = *(sal_Bool *)aAny.getValue();
sal_Bool bHeaderLeft = sal_False;
if( bHeader )
{
aAny = rPropSet->getPropertyValue( sHeaderShareContent );
bHeaderLeft = !*(sal_Bool *)aAny.getValue();
}
if( xHeaderText.is() )
{
if( !bHeader )
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_DISPLAY, XML_FALSE );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_HEADER, sal_True, sal_True );
exportHeaderFooterContent( xHeaderText, sal_False );
}
if( xHeaderTextLeft.is() && xHeaderTextLeft != xHeaderText )
{
if( !bHeaderLeft )
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_DISPLAY, XML_FALSE );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_HEADER_LEFT, sal_True, sal_True );
exportHeaderFooterContent( xHeaderTextLeft, sal_False );
}
aAny = rPropSet->getPropertyValue( sFooterOn );
sal_Bool bFooter = *(sal_Bool *)aAny.getValue();
sal_Bool bFooterLeft = sal_False;
if( bFooter )
{
aAny = rPropSet->getPropertyValue( sFooterShareContent );
bFooterLeft = !*(sal_Bool *)aAny.getValue();
}
if( xFooterText.is() )
{
if( !bFooter )
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_DISPLAY, XML_FALSE );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_FOOTER, sal_True, sal_True );
exportHeaderFooterContent( xFooterText, sal_False );
}
if( xFooterTextLeft.is() && xFooterTextLeft != xFooterText )
{
if( !bFooterLeft )
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_DISPLAY, XML_FALSE );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_FOOTER_LEFT, sal_True, sal_True );
exportHeaderFooterContent( xFooterTextLeft, sal_False );
}
}
}
<commit_msg>#92682# also count paragraphs in headers/footers for progress bar (text documents only)<commit_after>/*************************************************************************
*
* $RCSfile: XMLTextMasterPageExport.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: dvo $ $Date: 2001-10-09 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): _______________________________________
*
*
************************************************************************/
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLTEXTMASTERPAGEEXPORT_HXX
#include "XMLTextMasterPageExport.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::beans;
using namespace ::xmloff::token;
XMLTextMasterPageExport::XMLTextMasterPageExport( SvXMLExport& rExp ) :
XMLPageExport( rExp ),
sHeaderText( RTL_CONSTASCII_USTRINGPARAM( "HeaderText" ) ),
sHeaderOn( RTL_CONSTASCII_USTRINGPARAM( "HeaderIsOn" ) ),
sHeaderShareContent( RTL_CONSTASCII_USTRINGPARAM( "HeaderIsShared" ) ),
sHeaderTextLeft( RTL_CONSTASCII_USTRINGPARAM( "HeaderTextLeft" ) ),
sFooterText( RTL_CONSTASCII_USTRINGPARAM( "FooterText" ) ),
sFooterOn( RTL_CONSTASCII_USTRINGPARAM( "FooterIsOn" ) ),
sFooterShareContent( RTL_CONSTASCII_USTRINGPARAM( "FooterIsShared" ) ),
sFooterTextLeft( RTL_CONSTASCII_USTRINGPARAM( "FooterTextLeft" ) )
{
}
XMLTextMasterPageExport::~XMLTextMasterPageExport()
{
}
void XMLTextMasterPageExport::exportHeaderFooterContent(
const Reference< XText >& rText,
sal_Bool bAutoStyles, sal_Bool bExportParagraph )
{
DBG_ASSERT( rText.is(), "There is the text" );
// tracked changes (autostyles + changes list)
GetExport().GetTextParagraphExport()->recordTrackedChangesForXText(rText);
GetExport().GetTextParagraphExport()->exportTrackedChanges(rText,
bAutoStyles);
if( bAutoStyles )
GetExport().GetTextParagraphExport()
->collectTextAutoStyles( rText, sal_True, bExportParagraph );
else
{
GetExport().GetTextParagraphExport()->exportTextDeclarations( rText );
GetExport().GetTextParagraphExport()->exportText( rText, sal_True, bExportParagraph );
}
// tracked changes (end of XText)
GetExport().GetTextParagraphExport()->recordTrackedChangesNoXText();
}
void XMLTextMasterPageExport::exportMasterPageContent(
const Reference < XPropertySet > & rPropSet,
sal_Bool bAutoStyles )
{
Any aAny;
Reference < XText > xHeaderText;
aAny = rPropSet->getPropertyValue( sHeaderText );
aAny >>= xHeaderText;
Reference < XText > xHeaderTextLeft;
aAny = rPropSet->getPropertyValue( sHeaderTextLeft );
aAny >>= xHeaderTextLeft;
Reference < XText > xFooterText;
aAny = rPropSet->getPropertyValue( sFooterText );
aAny >>= xFooterText;
Reference < XText > xFooterTextLeft;
aAny = rPropSet->getPropertyValue( sFooterTextLeft );
aAny >>= xFooterTextLeft;
if( bAutoStyles )
{
if( xHeaderText.is() )
exportHeaderFooterContent( xHeaderText, sal_True );
if( xHeaderTextLeft.is() && xHeaderTextLeft != xHeaderText )
exportHeaderFooterContent( xHeaderTextLeft, sal_True );
if( xFooterText.is() )
exportHeaderFooterContent( xFooterText, sal_True );
if( xFooterTextLeft.is() && xFooterTextLeft != xFooterText )
exportHeaderFooterContent( xFooterTextLeft, sal_True );
}
else
{
aAny = rPropSet->getPropertyValue( sHeaderOn );
sal_Bool bHeader = *(sal_Bool *)aAny.getValue();
sal_Bool bHeaderLeft = sal_False;
if( bHeader )
{
aAny = rPropSet->getPropertyValue( sHeaderShareContent );
bHeaderLeft = !*(sal_Bool *)aAny.getValue();
}
if( xHeaderText.is() )
{
if( !bHeader )
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_DISPLAY, XML_FALSE );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_HEADER, sal_True, sal_True );
exportHeaderFooterContent( xHeaderText, sal_False );
}
if( xHeaderTextLeft.is() && xHeaderTextLeft != xHeaderText )
{
if( !bHeaderLeft )
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_DISPLAY, XML_FALSE );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_HEADER_LEFT, sal_True, sal_True );
exportHeaderFooterContent( xHeaderTextLeft, sal_False );
}
aAny = rPropSet->getPropertyValue( sFooterOn );
sal_Bool bFooter = *(sal_Bool *)aAny.getValue();
sal_Bool bFooterLeft = sal_False;
if( bFooter )
{
aAny = rPropSet->getPropertyValue( sFooterShareContent );
bFooterLeft = !*(sal_Bool *)aAny.getValue();
}
if( xFooterText.is() )
{
if( !bFooter )
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_DISPLAY, XML_FALSE );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_FOOTER, sal_True, sal_True );
exportHeaderFooterContent( xFooterText, sal_False );
}
if( xFooterTextLeft.is() && xFooterTextLeft != xFooterText )
{
if( !bFooterLeft )
GetExport().AddAttribute( XML_NAMESPACE_STYLE,
XML_DISPLAY, XML_FALSE );
SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
XML_FOOTER_LEFT, sal_True, sal_True );
exportHeaderFooterContent( xFooterTextLeft, sal_False );
}
}
}
<|endoftext|>
|
<commit_before>#include "player.hpp"
#include <utility>
#include <robocup2Dsim/common/entity.hpp>
#include <robocup2Dsim/engine/math.hpp>
namespace rem = robocup2Dsim::engine::math;
namespace ren = robocup2Dsim::engine;
namespace rru = robocup2Dsim::runtime;
namespace robocup2Dsim {
namespace common {
ren::physics_ptr<ren::dynamics::body> make_torso(
rru::ecs_db& db,
const std::string& player_name,
const ren::physics::vec2& position,
const std::uint16_t angle_degree)
{
ren::physics& physics = ren::update_physics_instance(db);
ren::physics::body_def body_def;
body_def.type = ren::physics::body_type::b2_dynamicBody;
body_def.linearDamping = 0.15f;
body_def.angularDamping = 0.15f;
std::string torso_name(player_name);
torso_name.append(" torso");
rru::ecs_db::entity_table_type::key_type entity_id = db.insert_entity(torso_name);
ren::physics_ptr<ren::dynamics::body> body = std::move(physics.make_body(entity_id, body_def));
ren::physics::mass_data mass;
body->GetMassData(&mass);
mass.I = 1.0f;
body->SetMassData(&mass);
body->SetTransform(position, angle_degree * rem::deg2rad);
std::array<ren::physics::vec2, 8> vertices;
vertices[0].Set(1, -1);
vertices[1].Set(1, 1);
vertices[2].Set(0.5, 2);
vertices[3].Set(-0.5, 2);
vertices[4].Set(-1, 1);
vertices[5].Set(-1, -1);
vertices[6].Set(-0.5, -2);
vertices[7].Set(0.5, -2);
ren::physics::polygon_shape shape;
shape.Set(vertices.data(), vertices.max_size());
ren::contact_config<entity::collision_category> collision_config(ren::contact_result::collide, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::ball_sensor, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::marker_sensor, ren::contact_result::pass_over);
ren::physics::fixture_def fixture_def = physics.make_fixture_def(
entity_id,
static_cast<std::underlying_type<entity::fixture_name>::type>(entity::fixture_name::torso),
entity::collision_category::player_body,
collision_config);
fixture_def.shape = &shape;
fixture_def.density = 4.0f;
physics.make_fixture(*body, fixture_def);
return std::move(body);
}
void make_vision(
ren::physics& physics,
rru::ecs_db::entity_table_type::key_type entity_id,
ren::dynamics::body& body,
std::size_t vision_radius,
const std::uint16_t arc_degree,
const std::int16_t offset_degree)
{
ren::physics::polygon_shape shape;
std::array<ren::physics::vec2, 8> vertices;
vertices[0].Set(0, 0);
for (std::size_t vertex = 0; vertex < (vertices.max_size() - 1); ++vertex)
{
float angle = ((vertex / (vertices.max_size() - 2.0) * arc_degree) + offset_degree) * rem::deg2rad;
vertices[vertex + 1].Set(vision_radius * cosf(angle), vision_radius * sinf(angle));
}
shape.Set(vertices.data(), vertices.max_size());
ren::contact_config<entity::collision_category> collision_config(ren::contact_result::collide, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::player_sensor, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::ball_sensor, ren::contact_result::pass_over);
ren::physics::fixture_def fixture_def = physics.make_fixture_def(
entity_id,
static_cast<std::underlying_type<entity::fixture_name>::type>(entity::fixture_name::vision),
entity::collision_category::player_sensor,
collision_config);
fixture_def.shape = &shape;
fixture_def.density = 0;
fixture_def.isSensor = true;
physics.make_fixture(body, fixture_def);
}
ren::physics_ptr<ren::dynamics::body> make_head(
rru::ecs_db& db,
const std::string& player_name,
const ren::physics::vec2& position,
const std::uint16_t angle_degree,
std::size_t vision_radius,
const std::uint16_t vision_degree)
{
ren::physics& physics = ren::update_physics_instance(db);
ren::physics::body_def body_def;
body_def.type = ren::physics::body_type::b2_dynamicBody;
body_def.linearDamping = 0.15f;
body_def.angularDamping = 0.15f;
std::string head_name(player_name);
head_name.append(" head");
rru::ecs_db::entity_table_type::key_type entity_id = db.insert_entity(head_name);
ren::physics_ptr<ren::dynamics::body> body = std::move(physics.make_body(entity_id, body_def));
ren::physics::mass_data mass;
body->GetMassData(&mass);
mass.I = 1.0f;
body->SetMassData(&mass);
body->SetTransform(position, angle_degree * rem::deg2rad);
ren::physics::circle_shape shape;
shape.m_p.Set(0, 0);
shape.m_radius = 1;
ren::contact_config<entity::collision_category> collision_config(ren::contact_result::collide, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::ball_sensor, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::marker_sensor, ren::contact_result::pass_over);
ren::physics::fixture_def fixture_def = physics.make_fixture_def(
entity_id,
static_cast<std::underlying_type<entity::fixture_name>::type>(entity::fixture_name::head),
entity::collision_category::player_body,
collision_config);
fixture_def.shape = &shape;
physics.make_fixture(*body, fixture_def);
const std::size_t arc_degree = vision_degree / 4;
make_vision(physics, entity_id, *body, vision_radius, arc_degree, arc_degree * -2);
make_vision(physics, entity_id, *body, vision_radius, arc_degree, arc_degree * -1);
make_vision(physics, entity_id, *body, vision_radius, arc_degree, 0);
make_vision(physics, entity_id, *body, vision_radius, arc_degree, arc_degree);
return std::move(body);
}
ren::physics_ptr<ren::dynamics::body> make_foot(
rru::ecs_db& db,
const std::string& player_name,
const ren::physics::vec2& position,
const std::uint16_t angle_degree)
{
ren::physics& physics = ren::update_physics_instance(db);
ren::physics::body_def body_def;
body_def.type = ren::physics::body_type::b2_dynamicBody;
body_def.linearDamping = 0.15f;
body_def.angularDamping = 0.15f;
std::string foot_name(player_name);
foot_name.append(" foot");
rru::ecs_db::entity_table_type::key_type entity_id = db.insert_entity(foot_name);
ren::physics_ptr<ren::dynamics::body> body = std::move(physics.make_body(entity_id, body_def));
ren::physics::mass_data mass;
body->GetMassData(&mass);
mass.I = 1.0f;
body->SetMassData(&mass);
body->SetTransform(position, angle_degree * rem::deg2rad);
std::array<ren::physics::vec2, 4> vertices;
vertices[0].Set(1, 0.5);
vertices[1].Set(1, -0.5);
vertices[2].Set(-1, -0.5);
vertices[3].Set(-1, 0.5);
ren::physics::polygon_shape shape;
shape.Set(vertices.data(), vertices.max_size());
ren::contact_config<entity::collision_category> collision_config(ren::contact_result::collide, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::ball_sensor, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::marker_sensor, ren::contact_result::pass_over);
ren::physics::fixture_def fixture_def = physics.make_fixture_def(
entity_id,
static_cast<std::underlying_type<entity::fixture_name>::type>(entity::fixture_name::foot),
entity::collision_category::player_body,
collision_config);
fixture_def.shape = &shape;
physics.make_fixture(*body, fixture_def);
return std::move(body);
}
player_components make_player(
rru::ecs_db& db,
const std::string& name,
const ren::physics::vec2& position,
const std::uint16_t angle_degree)
{
ren::physics_ptr<ren::dynamics::body> torso = make_torso(db, name, position, angle_degree);
ren::physics_ptr<ren::dynamics::body> head = make_head(db, name, position, angle_degree, 360, 120);
ren::physics_ptr<ren::dynamics::body> foot = make_foot(db, name, position, angle_degree);
player_components result{
std::move(torso),
std::move(head),
std::move(foot)};
return std::move(result);
}
} // namespace common
} // namespace robocup2Dsim
<commit_msg>added the player's neck<commit_after>#include "player.hpp"
#include <utility>
#include <robocup2Dsim/common/entity.hpp>
#include <robocup2Dsim/engine/math.hpp>
namespace rem = robocup2Dsim::engine::math;
namespace ren = robocup2Dsim::engine;
namespace rru = robocup2Dsim::runtime;
namespace robocup2Dsim {
namespace common {
ren::physics_ptr<ren::dynamics::body> make_torso(
rru::ecs_db& db,
const std::string& player_name,
const ren::physics::vec2& position,
const std::uint16_t angle_degree)
{
ren::physics& physics = ren::update_physics_instance(db);
ren::physics::body_def body_def;
body_def.type = ren::physics::body_type::b2_dynamicBody;
body_def.linearDamping = 0.15f;
body_def.angularDamping = 0.15f;
std::string torso_name(player_name);
torso_name.append(" torso");
rru::ecs_db::entity_table_type::key_type entity_id = db.insert_entity(torso_name);
ren::physics_ptr<ren::dynamics::body> body = std::move(physics.make_body(entity_id, body_def));
ren::physics::mass_data mass;
body->GetMassData(&mass);
mass.I = 1.0f;
body->SetMassData(&mass);
body->SetTransform(position, angle_degree * rem::deg2rad);
std::array<ren::physics::vec2, 8> vertices;
vertices[0].Set(1, -1);
vertices[1].Set(1, 1);
vertices[2].Set(0.5, 2);
vertices[3].Set(-0.5, 2);
vertices[4].Set(-1, 1);
vertices[5].Set(-1, -1);
vertices[6].Set(-0.5, -2);
vertices[7].Set(0.5, -2);
ren::physics::polygon_shape shape;
shape.Set(vertices.data(), vertices.max_size());
ren::contact_config<entity::collision_category> collision_config(ren::contact_result::collide, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::ball_sensor, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::marker_sensor, ren::contact_result::pass_over);
ren::physics::fixture_def fixture_def = physics.make_fixture_def(
entity_id,
static_cast<std::underlying_type<entity::fixture_name>::type>(entity::fixture_name::torso),
entity::collision_category::player_body,
collision_config);
fixture_def.shape = &shape;
fixture_def.density = 4.0f;
physics.make_fixture(*body, fixture_def);
return std::move(body);
}
void make_vision(
ren::physics& physics,
rru::ecs_db::entity_table_type::key_type entity_id,
ren::dynamics::body& body,
std::size_t vision_radius,
const std::uint16_t arc_degree,
const std::int16_t offset_degree)
{
ren::physics::polygon_shape shape;
std::array<ren::physics::vec2, 8> vertices;
vertices[0].Set(0, 0);
for (std::size_t vertex = 0; vertex < (vertices.max_size() - 1); ++vertex)
{
float angle = ((vertex / (vertices.max_size() - 2.0) * arc_degree) + offset_degree) * rem::deg2rad;
vertices[vertex + 1].Set(vision_radius * cosf(angle), vision_radius * sinf(angle));
}
shape.Set(vertices.data(), vertices.max_size());
ren::contact_config<entity::collision_category> collision_config(ren::contact_result::collide, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::player_sensor, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::ball_sensor, ren::contact_result::pass_over);
ren::physics::fixture_def fixture_def = physics.make_fixture_def(
entity_id,
static_cast<std::underlying_type<entity::fixture_name>::type>(entity::fixture_name::vision),
entity::collision_category::player_sensor,
collision_config);
fixture_def.shape = &shape;
fixture_def.density = 0;
fixture_def.isSensor = true;
physics.make_fixture(body, fixture_def);
}
ren::physics_ptr<ren::dynamics::body> make_head(
rru::ecs_db& db,
const std::string& player_name,
const ren::physics::vec2& position,
const std::uint16_t angle_degree,
std::size_t vision_radius,
const std::uint16_t vision_degree)
{
ren::physics& physics = ren::update_physics_instance(db);
ren::physics::body_def body_def;
body_def.type = ren::physics::body_type::b2_dynamicBody;
body_def.linearDamping = 0.15f;
body_def.angularDamping = 0.15f;
std::string head_name(player_name);
head_name.append(" head");
rru::ecs_db::entity_table_type::key_type entity_id = db.insert_entity(head_name);
ren::physics_ptr<ren::dynamics::body> body = std::move(physics.make_body(entity_id, body_def));
ren::physics::mass_data mass;
body->GetMassData(&mass);
mass.I = 1.0f;
body->SetMassData(&mass);
body->SetTransform(position, angle_degree * rem::deg2rad);
ren::physics::circle_shape shape;
shape.m_p.Set(0, 0);
shape.m_radius = 1;
ren::contact_config<entity::collision_category> collision_config(ren::contact_result::collide, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::ball_sensor, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::marker_sensor, ren::contact_result::pass_over);
ren::physics::fixture_def fixture_def = physics.make_fixture_def(
entity_id,
static_cast<std::underlying_type<entity::fixture_name>::type>(entity::fixture_name::head),
entity::collision_category::player_body,
collision_config);
fixture_def.shape = &shape;
physics.make_fixture(*body, fixture_def);
const std::size_t arc_degree = vision_degree / 4;
make_vision(physics, entity_id, *body, vision_radius, arc_degree, arc_degree * -2);
make_vision(physics, entity_id, *body, vision_radius, arc_degree, arc_degree * -1);
make_vision(physics, entity_id, *body, vision_radius, arc_degree, 0);
make_vision(physics, entity_id, *body, vision_radius, arc_degree, arc_degree);
return std::move(body);
}
ren::physics_ptr<ren::dynamics::body> make_foot(
rru::ecs_db& db,
const std::string& player_name,
const ren::physics::vec2& position,
const std::uint16_t angle_degree)
{
ren::physics& physics = ren::update_physics_instance(db);
ren::physics::body_def body_def;
body_def.type = ren::physics::body_type::b2_dynamicBody;
body_def.linearDamping = 0.15f;
body_def.angularDamping = 0.15f;
std::string foot_name(player_name);
foot_name.append(" foot");
rru::ecs_db::entity_table_type::key_type entity_id = db.insert_entity(foot_name);
ren::physics_ptr<ren::dynamics::body> body = std::move(physics.make_body(entity_id, body_def));
ren::physics::mass_data mass;
body->GetMassData(&mass);
mass.I = 1.0f;
body->SetMassData(&mass);
body->SetTransform(position, angle_degree * rem::deg2rad);
std::array<ren::physics::vec2, 4> vertices;
vertices[0].Set(1, 0.5);
vertices[1].Set(1, -0.5);
vertices[2].Set(-1, -0.5);
vertices[3].Set(-1, 0.5);
ren::physics::polygon_shape shape;
shape.Set(vertices.data(), vertices.max_size());
ren::contact_config<entity::collision_category> collision_config(ren::contact_result::collide, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::ball_sensor, ren::contact_result::pass_over);
collision_config.set(entity::collision_category::marker_sensor, ren::contact_result::pass_over);
ren::physics::fixture_def fixture_def = physics.make_fixture_def(
entity_id,
static_cast<std::underlying_type<entity::fixture_name>::type>(entity::fixture_name::foot),
entity::collision_category::player_body,
collision_config);
fixture_def.shape = &shape;
physics.make_fixture(*body, fixture_def);
return std::move(body);
}
void make_neck(
ren::physics& physics,
ren::dynamics::body& torso,
ren::dynamics::body& head,
const std::int16_t min_angle_degree,
const std::int16_t max_angle_degree)
{
ren::physics::revolute_joint_def joint_def;
joint_def.bodyA = &torso;
joint_def.bodyB = &head;
joint_def.collideConnected = false;
joint_def.localAnchorA.Set(0, 0);
joint_def.localAnchorB.Set(0, 0);
joint_def.referenceAngle = 0;
joint_def.enableLimit = true;
joint_def.lowerAngle = min_angle_degree * rem::deg2rad;
joint_def.upperAngle = max_angle_degree * rem::deg2rad;
physics.make_joint(joint_def);
}
player_components make_player(
rru::ecs_db& db,
const std::string& name,
const ren::physics::vec2& position,
const std::uint16_t angle_degree)
{
ren::physics_ptr<ren::dynamics::body> torso = make_torso(db, name, position, angle_degree);
ren::physics_ptr<ren::dynamics::body> head = make_head(db, name, position, angle_degree, 360, 120);
ren::physics_ptr<ren::dynamics::body> foot = make_foot(db, name, position, angle_degree);
make_neck(ren::update_physics_instance(db), *torso, *head, -60, 60);
player_components result{
std::move(torso),
std::move(head),
std::move(foot)};
return std::move(result);
}
} // namespace common
} // namespace robocup2Dsim
<|endoftext|>
|
<commit_before>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#include "FlipperConnectionManagerImpl.h"
#include <folly/String.h>
#include <folly/futures/Future.h>
#include <folly/io/async/AsyncSocketException.h>
#include <folly/io/async/SSLContext.h>
#include <folly/json.h>
#include <rsocket/Payload.h>
#include <rsocket/RSocket.h>
#include <rsocket/transports/tcp/TcpConnectionFactory.h>
#include <stdexcept>
#include <thread>
#include "ConnectionContextStore.h"
#include "FireAndForgetBasedFlipperResponder.h"
#include "FlipperRSocketResponder.h"
#include "FlipperResponderImpl.h"
#include "FlipperStep.h"
#include "Log.h"
#include "yarpl/Single.h"
#define WRONG_THREAD_EXIT_MSG \
"ERROR: Aborting flipper initialization because it's not running in the flipper thread."
static constexpr int reconnectIntervalSeconds = 2;
static constexpr int connectionKeepaliveSeconds = 10;
static constexpr int maxPayloadSize = 0xFFFFFF;
// Not a public-facing version number.
// Used for compatibility checking with desktop flipper.
// To be bumped for every core platform interface change.
static constexpr int sdkVersion = 2;
namespace facebook {
namespace flipper {
class ConnectionEvents : public rsocket::RSocketConnectionEvents {
private:
FlipperConnectionManagerImpl* websocket_;
public:
ConnectionEvents(FlipperConnectionManagerImpl* websocket)
: websocket_(websocket) {}
void onConnected() {
websocket_->isOpen_ = true;
if (websocket_->connectionIsTrusted_) {
websocket_->callbacks_->onConnected();
}
}
void onDisconnected(const folly::exception_wrapper&) {
if (!websocket_->isOpen_)
return;
websocket_->isOpen_ = false;
if (websocket_->connectionIsTrusted_) {
websocket_->connectionIsTrusted_ = false;
websocket_->callbacks_->onDisconnected();
}
websocket_->reconnect();
}
void onClosed(const folly::exception_wrapper& e) {
onDisconnected(e);
}
};
FlipperConnectionManagerImpl::FlipperConnectionManagerImpl(
FlipperInitConfig config,
std::shared_ptr<FlipperState> state,
std::shared_ptr<ConnectionContextStore> contextStore)
: deviceData_(config.deviceData),
flipperState_(state),
insecurePort(config.insecurePort),
securePort(config.securePort),
flipperEventBase_(config.callbackWorker),
connectionEventBase_(config.connectionWorker),
contextStore_(contextStore) {
CHECK_THROW(config.callbackWorker, std::invalid_argument);
CHECK_THROW(config.connectionWorker, std::invalid_argument);
}
FlipperConnectionManagerImpl::~FlipperConnectionManagerImpl() {
stop();
}
void FlipperConnectionManagerImpl::start() {
auto step = flipperState_->start("Start connection thread");
folly::makeFuture()
.via(flipperEventBase_->getEventBase())
.delayed(std::chrono::milliseconds(0))
.thenValue([this, step](auto&&) {
step->complete();
startSync();
});
}
void FlipperConnectionManagerImpl::startSync() {
if (!isRunningInOwnThread()) {
log(WRONG_THREAD_EXIT_MSG);
return;
}
if (isOpen()) {
log("Already connected");
return;
}
bool isClientSetupStep = isCertificateExchangeNeeded();
auto step = flipperState_->start(
isClientSetupStep ? "Establish pre-setup connection"
: "Establish main connection");
try {
if (isClientSetupStep) {
doCertificateExchange();
} else {
connectSecurely();
}
step->complete();
} catch (const folly::AsyncSocketException& e) {
if (e.getType() == folly::AsyncSocketException::NOT_OPEN ||
e.getType() == folly::AsyncSocketException::NETWORK_ERROR) {
// The expected code path when flipper desktop is not running.
// Don't count as a failed attempt, or it would invalidate the connection
// files for no reason. On iOS devices, we can always connect to the local
// port forwarding server even when it can't connect to flipper. In that
// case we get a Network error instead of a Port not open error, so we
// treat them the same.
step->fail(
"No route to flipper found. Is flipper desktop running? Retrying...");
} else {
if (e.getType() == folly::AsyncSocketException::SSL_ERROR) {
auto message = std::string(e.what()) +
"\nMake sure the date and time of your device is up to date.";
log(message);
step->fail(message);
} else {
log(e.what());
step->fail(e.what());
}
failedConnectionAttempts_++;
}
reconnect();
} catch (const std::exception& e) {
log(e.what());
step->fail(e.what());
failedConnectionAttempts_++;
reconnect();
}
}
void FlipperConnectionManagerImpl::doCertificateExchange() {
rsocket::SetupParameters parameters;
folly::SocketAddress address;
parameters.payload = rsocket::Payload(folly::toJson(folly::dynamic::object(
"os", deviceData_.os)("device", deviceData_.device)(
"app", deviceData_.app)("sdk_version", sdkVersion)));
address.setFromHostPort(deviceData_.host, insecurePort);
auto connectingInsecurely = flipperState_->start("Connect insecurely");
connectionIsTrusted_ = false;
client_ =
rsocket::RSocket::createConnectedClient(
std::make_unique<rsocket::TcpConnectionFactory>(
*connectionEventBase_->getEventBase(), std::move(address)),
std::move(parameters),
nullptr,
std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval
nullptr, // stats
std::make_shared<ConnectionEvents>(this))
.get();
connectingInsecurely->complete();
requestSignedCertFromFlipper();
}
void FlipperConnectionManagerImpl::connectSecurely() {
rsocket::SetupParameters parameters;
folly::SocketAddress address;
auto loadingDeviceId = flipperState_->start("Load Device Id");
auto deviceId = contextStore_->getDeviceId();
if (deviceId.compare("unknown")) {
loadingDeviceId->complete();
}
parameters.payload = rsocket::Payload(
folly::toJson(folly::dynamic::object("os", deviceData_.os)(
"device", deviceData_.device)("device_id", deviceId)(
"app", deviceData_.app)("sdk_version", sdkVersion)));
address.setFromHostPort(deviceData_.host, securePort);
std::shared_ptr<folly::SSLContext> sslContext =
contextStore_->getSSLContext();
auto connectingSecurely = flipperState_->start("Connect securely");
connectionIsTrusted_ = true;
client_ =
rsocket::RSocket::createConnectedClient(
std::make_unique<rsocket::TcpConnectionFactory>(
*connectionEventBase_->getEventBase(),
std::move(address),
std::move(sslContext)),
std::move(parameters),
std::make_shared<FlipperRSocketResponder>(this, connectionEventBase_),
std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval
nullptr, // stats
std::make_shared<ConnectionEvents>(this))
.get();
connectingSecurely->complete();
failedConnectionAttempts_ = 0;
}
void FlipperConnectionManagerImpl::reconnect() {
folly::makeFuture()
.via(flipperEventBase_->getEventBase())
.delayed(std::chrono::seconds(reconnectIntervalSeconds))
.thenValue([this](auto&&) { startSync(); });
}
void FlipperConnectionManagerImpl::stop() {
if (client_) {
client_->disconnect();
}
client_ = nullptr;
}
bool FlipperConnectionManagerImpl::isOpen() const {
return isOpen_ && connectionIsTrusted_;
}
void FlipperConnectionManagerImpl::setCallbacks(Callbacks* callbacks) {
callbacks_ = callbacks;
}
void FlipperConnectionManagerImpl::sendMessage(const folly::dynamic& message) {
flipperEventBase_->add([this, message]() {
try {
rsocket::Payload payload = toRSocketPayload(message);
if (client_) {
client_->getRequester()
->fireAndForget(std::move(payload))
->subscribe([]() {});
}
} catch (std::length_error& e) {
// Skip sending messages that are too large.
log(e.what());
return;
}
});
}
void FlipperConnectionManagerImpl::onMessageReceived(
const folly::dynamic& message,
std::unique_ptr<FlipperResponder> responder) {
callbacks_->onMessageReceived(message, std::move(responder));
}
bool FlipperConnectionManagerImpl::isCertificateExchangeNeeded() {
if (failedConnectionAttempts_ >= 2) {
return true;
}
auto step = flipperState_->start("Check required certificates are present");
bool hasRequiredFiles = contextStore_->hasRequiredFiles();
if (hasRequiredFiles) {
step->complete();
}
return !hasRequiredFiles;
}
void FlipperConnectionManagerImpl::requestSignedCertFromFlipper() {
auto generatingCSR = flipperState_->start("Generate CSR");
std::string csr = contextStore_->getCertificateSigningRequest();
generatingCSR->complete();
folly::dynamic message =
folly::dynamic::object("method", "signCertificate")("csr", csr.c_str())(
"destination", contextStore_->getCertificateDirectoryPath().c_str());
auto gettingCert = flipperState_->start("Getting cert from desktop");
flipperEventBase_->add([this, message, gettingCert]() {
client_->getRequester()
->requestResponse(rsocket::Payload(folly::toJson(message)))
->subscribe(
[this, gettingCert](rsocket::Payload p) {
auto response = p.moveDataToString();
if (!response.empty()) {
folly::dynamic config = folly::parseJson(response);
contextStore_->storeConnectionConfig(config);
}
gettingCert->complete();
log("Certificate exchange complete.");
// Disconnect after message sending is complete.
// This will trigger a reconnect which should use the secure
// channel.
// TODO: Connect immediately, without waiting for reconnect
client_ = nullptr;
},
[this, message, gettingCert](folly::exception_wrapper e) {
e.handle(
[&](rsocket::ErrorWithPayload& errorWithPayload) {
std::string errorMessage =
errorWithPayload.payload.moveDataToString();
if (errorMessage.compare("not implemented")) {
auto error =
"Desktop failed to provide certificates. Error from flipper desktop:\n" +
errorMessage;
log(error);
gettingCert->fail(error);
client_ = nullptr;
} else {
sendLegacyCertificateRequest(message);
}
},
[e, gettingCert](...) {
gettingCert->fail(e.what().c_str());
});
});
});
failedConnectionAttempts_ = 0;
}
void FlipperConnectionManagerImpl::sendLegacyCertificateRequest(
folly::dynamic message) {
// Desktop is using an old version of Flipper.
// Fall back to fireAndForget, instead of requestResponse.
auto sendingRequest =
flipperState_->start("Sending fallback certificate request");
client_->getRequester()
->fireAndForget(rsocket::Payload(folly::toJson(message)))
->subscribe([this, sendingRequest]() {
sendingRequest->complete();
folly::dynamic config = folly::dynamic::object();
contextStore_->storeConnectionConfig(config);
client_ = nullptr;
});
}
bool FlipperConnectionManagerImpl::isRunningInOwnThread() {
return flipperEventBase_->isInEventBaseThread();
}
rsocket::Payload toRSocketPayload(dynamic data) {
std::string json = folly::toJson(data);
rsocket::Payload payload = rsocket::Payload(json);
auto payloadLength = payload.data->computeChainDataLength();
if (payloadLength > maxPayloadSize) {
auto logMessage =
std::string(
"Error: Skipping sending message larger than max rsocket payload: ") +
json.substr(0, 100) + "...";
log(logMessage);
DCHECK_LE(payloadLength, maxPayloadSize);
throw new std::length_error(logMessage);
}
return payload;
}
} // namespace flipper
} // namespace facebook
<commit_msg>Fix app crash when payload is too large<commit_after>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#include "FlipperConnectionManagerImpl.h"
#include <folly/String.h>
#include <folly/futures/Future.h>
#include <folly/io/async/AsyncSocketException.h>
#include <folly/io/async/SSLContext.h>
#include <folly/json.h>
#include <rsocket/Payload.h>
#include <rsocket/RSocket.h>
#include <rsocket/transports/tcp/TcpConnectionFactory.h>
#include <stdexcept>
#include <thread>
#include "ConnectionContextStore.h"
#include "FireAndForgetBasedFlipperResponder.h"
#include "FlipperRSocketResponder.h"
#include "FlipperResponderImpl.h"
#include "FlipperStep.h"
#include "Log.h"
#include "yarpl/Single.h"
#define WRONG_THREAD_EXIT_MSG \
"ERROR: Aborting flipper initialization because it's not running in the flipper thread."
static constexpr int reconnectIntervalSeconds = 2;
static constexpr int connectionKeepaliveSeconds = 10;
static constexpr int maxPayloadSize = 0xFFFFFF;
// Not a public-facing version number.
// Used for compatibility checking with desktop flipper.
// To be bumped for every core platform interface change.
static constexpr int sdkVersion = 2;
namespace facebook {
namespace flipper {
class ConnectionEvents : public rsocket::RSocketConnectionEvents {
private:
FlipperConnectionManagerImpl* websocket_;
public:
ConnectionEvents(FlipperConnectionManagerImpl* websocket)
: websocket_(websocket) {}
void onConnected() {
websocket_->isOpen_ = true;
if (websocket_->connectionIsTrusted_) {
websocket_->callbacks_->onConnected();
}
}
void onDisconnected(const folly::exception_wrapper&) {
if (!websocket_->isOpen_)
return;
websocket_->isOpen_ = false;
if (websocket_->connectionIsTrusted_) {
websocket_->connectionIsTrusted_ = false;
websocket_->callbacks_->onDisconnected();
}
websocket_->reconnect();
}
void onClosed(const folly::exception_wrapper& e) {
onDisconnected(e);
}
};
FlipperConnectionManagerImpl::FlipperConnectionManagerImpl(
FlipperInitConfig config,
std::shared_ptr<FlipperState> state,
std::shared_ptr<ConnectionContextStore> contextStore)
: deviceData_(config.deviceData),
flipperState_(state),
insecurePort(config.insecurePort),
securePort(config.securePort),
flipperEventBase_(config.callbackWorker),
connectionEventBase_(config.connectionWorker),
contextStore_(contextStore) {
CHECK_THROW(config.callbackWorker, std::invalid_argument);
CHECK_THROW(config.connectionWorker, std::invalid_argument);
}
FlipperConnectionManagerImpl::~FlipperConnectionManagerImpl() {
stop();
}
void FlipperConnectionManagerImpl::start() {
auto step = flipperState_->start("Start connection thread");
folly::makeFuture()
.via(flipperEventBase_->getEventBase())
.delayed(std::chrono::milliseconds(0))
.thenValue([this, step](auto&&) {
step->complete();
startSync();
});
}
void FlipperConnectionManagerImpl::startSync() {
if (!isRunningInOwnThread()) {
log(WRONG_THREAD_EXIT_MSG);
return;
}
if (isOpen()) {
log("Already connected");
return;
}
bool isClientSetupStep = isCertificateExchangeNeeded();
auto step = flipperState_->start(
isClientSetupStep ? "Establish pre-setup connection"
: "Establish main connection");
try {
if (isClientSetupStep) {
doCertificateExchange();
} else {
connectSecurely();
}
step->complete();
} catch (const folly::AsyncSocketException& e) {
if (e.getType() == folly::AsyncSocketException::NOT_OPEN ||
e.getType() == folly::AsyncSocketException::NETWORK_ERROR) {
// The expected code path when flipper desktop is not running.
// Don't count as a failed attempt, or it would invalidate the connection
// files for no reason. On iOS devices, we can always connect to the local
// port forwarding server even when it can't connect to flipper. In that
// case we get a Network error instead of a Port not open error, so we
// treat them the same.
step->fail(
"No route to flipper found. Is flipper desktop running? Retrying...");
} else {
if (e.getType() == folly::AsyncSocketException::SSL_ERROR) {
auto message = std::string(e.what()) +
"\nMake sure the date and time of your device is up to date.";
log(message);
step->fail(message);
} else {
log(e.what());
step->fail(e.what());
}
failedConnectionAttempts_++;
}
reconnect();
} catch (const std::exception& e) {
log(e.what());
step->fail(e.what());
failedConnectionAttempts_++;
reconnect();
}
}
void FlipperConnectionManagerImpl::doCertificateExchange() {
rsocket::SetupParameters parameters;
folly::SocketAddress address;
parameters.payload = rsocket::Payload(folly::toJson(folly::dynamic::object(
"os", deviceData_.os)("device", deviceData_.device)(
"app", deviceData_.app)("sdk_version", sdkVersion)));
address.setFromHostPort(deviceData_.host, insecurePort);
auto connectingInsecurely = flipperState_->start("Connect insecurely");
connectionIsTrusted_ = false;
client_ =
rsocket::RSocket::createConnectedClient(
std::make_unique<rsocket::TcpConnectionFactory>(
*connectionEventBase_->getEventBase(), std::move(address)),
std::move(parameters),
nullptr,
std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval
nullptr, // stats
std::make_shared<ConnectionEvents>(this))
.get();
connectingInsecurely->complete();
requestSignedCertFromFlipper();
}
void FlipperConnectionManagerImpl::connectSecurely() {
rsocket::SetupParameters parameters;
folly::SocketAddress address;
auto loadingDeviceId = flipperState_->start("Load Device Id");
auto deviceId = contextStore_->getDeviceId();
if (deviceId.compare("unknown")) {
loadingDeviceId->complete();
}
parameters.payload = rsocket::Payload(
folly::toJson(folly::dynamic::object("os", deviceData_.os)(
"device", deviceData_.device)("device_id", deviceId)(
"app", deviceData_.app)("sdk_version", sdkVersion)));
address.setFromHostPort(deviceData_.host, securePort);
std::shared_ptr<folly::SSLContext> sslContext =
contextStore_->getSSLContext();
auto connectingSecurely = flipperState_->start("Connect securely");
connectionIsTrusted_ = true;
client_ =
rsocket::RSocket::createConnectedClient(
std::make_unique<rsocket::TcpConnectionFactory>(
*connectionEventBase_->getEventBase(),
std::move(address),
std::move(sslContext)),
std::move(parameters),
std::make_shared<FlipperRSocketResponder>(this, connectionEventBase_),
std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval
nullptr, // stats
std::make_shared<ConnectionEvents>(this))
.get();
connectingSecurely->complete();
failedConnectionAttempts_ = 0;
}
void FlipperConnectionManagerImpl::reconnect() {
folly::makeFuture()
.via(flipperEventBase_->getEventBase())
.delayed(std::chrono::seconds(reconnectIntervalSeconds))
.thenValue([this](auto&&) { startSync(); });
}
void FlipperConnectionManagerImpl::stop() {
if (client_) {
client_->disconnect();
}
client_ = nullptr;
}
bool FlipperConnectionManagerImpl::isOpen() const {
return isOpen_ && connectionIsTrusted_;
}
void FlipperConnectionManagerImpl::setCallbacks(Callbacks* callbacks) {
callbacks_ = callbacks;
}
void FlipperConnectionManagerImpl::sendMessage(const folly::dynamic& message) {
flipperEventBase_->add([this, message]() {
try {
rsocket::Payload payload = toRSocketPayload(message);
if (client_) {
client_->getRequester()
->fireAndForget(std::move(payload))
->subscribe([]() {});
}
} catch (std::length_error& e) {
// Skip sending messages that are too large.
log(e.what());
return;
}
});
}
void FlipperConnectionManagerImpl::onMessageReceived(
const folly::dynamic& message,
std::unique_ptr<FlipperResponder> responder) {
callbacks_->onMessageReceived(message, std::move(responder));
}
bool FlipperConnectionManagerImpl::isCertificateExchangeNeeded() {
if (failedConnectionAttempts_ >= 2) {
return true;
}
auto step = flipperState_->start("Check required certificates are present");
bool hasRequiredFiles = contextStore_->hasRequiredFiles();
if (hasRequiredFiles) {
step->complete();
}
return !hasRequiredFiles;
}
void FlipperConnectionManagerImpl::requestSignedCertFromFlipper() {
auto generatingCSR = flipperState_->start("Generate CSR");
std::string csr = contextStore_->getCertificateSigningRequest();
generatingCSR->complete();
folly::dynamic message =
folly::dynamic::object("method", "signCertificate")("csr", csr.c_str())(
"destination", contextStore_->getCertificateDirectoryPath().c_str());
auto gettingCert = flipperState_->start("Getting cert from desktop");
flipperEventBase_->add([this, message, gettingCert]() {
client_->getRequester()
->requestResponse(rsocket::Payload(folly::toJson(message)))
->subscribe(
[this, gettingCert](rsocket::Payload p) {
auto response = p.moveDataToString();
if (!response.empty()) {
folly::dynamic config = folly::parseJson(response);
contextStore_->storeConnectionConfig(config);
}
gettingCert->complete();
log("Certificate exchange complete.");
// Disconnect after message sending is complete.
// This will trigger a reconnect which should use the secure
// channel.
// TODO: Connect immediately, without waiting for reconnect
client_ = nullptr;
},
[this, message, gettingCert](folly::exception_wrapper e) {
e.handle(
[&](rsocket::ErrorWithPayload& errorWithPayload) {
std::string errorMessage =
errorWithPayload.payload.moveDataToString();
if (errorMessage.compare("not implemented")) {
auto error =
"Desktop failed to provide certificates. Error from flipper desktop:\n" +
errorMessage;
log(error);
gettingCert->fail(error);
client_ = nullptr;
} else {
sendLegacyCertificateRequest(message);
}
},
[e, gettingCert](...) {
gettingCert->fail(e.what().c_str());
});
});
});
failedConnectionAttempts_ = 0;
}
void FlipperConnectionManagerImpl::sendLegacyCertificateRequest(
folly::dynamic message) {
// Desktop is using an old version of Flipper.
// Fall back to fireAndForget, instead of requestResponse.
auto sendingRequest =
flipperState_->start("Sending fallback certificate request");
client_->getRequester()
->fireAndForget(rsocket::Payload(folly::toJson(message)))
->subscribe([this, sendingRequest]() {
sendingRequest->complete();
folly::dynamic config = folly::dynamic::object();
contextStore_->storeConnectionConfig(config);
client_ = nullptr;
});
}
bool FlipperConnectionManagerImpl::isRunningInOwnThread() {
return flipperEventBase_->isInEventBaseThread();
}
rsocket::Payload toRSocketPayload(dynamic data) {
std::string json = folly::toJson(data);
rsocket::Payload payload = rsocket::Payload(json);
auto payloadLength = payload.data->computeChainDataLength();
if (payloadLength > maxPayloadSize) {
auto logMessage =
std::string(
"Error: Skipping sending message larger than max rsocket payload: ") +
json.substr(0, 100) + "...";
log(logMessage);
DCHECK_LE(payloadLength, maxPayloadSize);
throw std::length_error(logMessage);
}
return payload;
}
} // namespace flipper
} // namespace facebook
<|endoftext|>
|
<commit_before>#include "./nodes.h"
#include <QDebug>
#include <string>
#include <vector>
#include "./math/eigen.h"
#include "./utils/persister.h"
#include "./importer.h"
#include "./mesh_node.h"
#include "./volume_node.h"
#include "./label_node.h"
#include "./obb_node.h"
#include "./camera_node.h"
#include "./coordinate_system_node.h"
Nodes::Nodes()
{
coordinateSystemNode = std::make_shared<CoordinateSystemNode>();
addNode(coordinateSystemNode);
cameraNode = std::make_shared<CameraNode>();
addNode(cameraNode);
}
Nodes::~Nodes()
{
qInfo() << "Destructor of Nodes";
}
std::vector<std::shared_ptr<LabelNode>> Nodes::getLabelNodes()
{
std::vector<std::shared_ptr<LabelNode>> result;
for (auto &node : nodes)
{
std::shared_ptr<LabelNode> labelNode =
std::dynamic_pointer_cast<LabelNode>(node);
if (labelNode.get())
result.push_back(labelNode);
}
return result;
}
void Nodes::addNode(std::shared_ptr<Node> node)
{
nodes.push_back(node);
if (onNodeAdded)
onNodeAdded(node);
}
void Nodes::removeNode(std::shared_ptr<Node> node)
{
nodes.erase(std::remove(nodes.begin(), nodes.end(), node), nodes.end());
}
std::vector<std::shared_ptr<Node>> Nodes::getNodes()
{
return nodes;
}
std::vector<std::shared_ptr<Node>> Nodes::getNodesForObb()
{
auto result = getNodes();
if (cameraOriginVisualizerNode.get())
result.push_back(cameraOriginVisualizerNode);
return result;
}
std::shared_ptr<CameraNode> Nodes::getCameraNode()
{
return cameraNode;
}
void Nodes::setCameraNode(std::shared_ptr<CameraNode> node)
{
if (cameraNode.get())
removeNode(cameraNode);
cameraNode = node;
addNode(node);
}
void Nodes::addSceneNodesFrom(std::string filename)
{
qDebug() << "Nodes::addSceneNodesFrom" << filename.c_str();
auto loadedNodes =
Persister::load<std::vector<std::shared_ptr<Node>>>(filename);
for (auto &node : loadedNodes)
{
std::shared_ptr<CameraNode> camera =
std::dynamic_pointer_cast<CameraNode>(node);
if (camera.get())
setCameraNode(camera);
addNode(node);
}
}
void Nodes::importMeshFrom(std::string filename)
{
Importer importer;
auto meshes = importer.importAll(filename);
for (size_t i = 0; i < meshes.size(); ++i)
{
auto transformation =
importer.getTransformationFor(filename, static_cast<int>(i));
addNode(std::make_shared<MeshNode>(filename, i, meshes[i], transformation));
}
}
void Nodes::importVolume(std::string volumeFilename,
std::string transferFunctionFilename)
{
addNode(std::make_shared<VolumeNode>(volumeFilename, transferFunctionFilename,
Eigen::Matrix4f::Identity()));
}
void Nodes::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
auto allNodes = nodes;
for (auto &node : allNodes)
node->render(gl, managers, renderData);
renderCameraOriginVisualizer(gl, managers, renderData);
if (showBoundingVolumes)
{
for (auto &node : obbNodes)
node->render(gl, managers, renderData);
}
}
void Nodes::renderLabels(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
for (auto labelNode : getLabelNodes())
{
labelNode->renderLabelAndConnector(gl, managers, renderData);
}
}
void Nodes::renderOverlays(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (forcesVisualizerNode.get())
{
forcesVisualizerNode->render(gl, managers, renderData);
}
}
void Nodes::saveSceneTo(std::string filename)
{
std::vector<std::shared_ptr<Node>> persistableNodes;
for (auto node : nodes)
if (node->isPersistable())
persistableNodes.push_back(node);
Persister::save(persistableNodes, filename);
}
void Nodes::clear()
{
clearForShutdown();
addNode(cameraNode);
}
void Nodes::clearForShutdown()
{
nodes.clear();
obbNodes.clear();
}
void Nodes::toggleBoundingVolumes()
{
showBoundingVolumes = !showBoundingVolumes;
if (showBoundingVolumes)
{
obbNodes.clear();
for (auto &node : nodes)
{
if (node->getObb().isInitialized())
{
obbNodes.push_back(std::make_shared<ObbNode>(node->getObb()));
}
}
}
}
void Nodes::toggleCoordinateSystem()
{
coordinateSystemNode->toggleVisibility();
}
void Nodes::toggleCameraOriginVisualizer()
{
cameraOriginVisualizerNode->toggleVisibility();
}
void Nodes::addForcesVisualizerNode(std::shared_ptr<Node> node)
{
forcesVisualizerNode = node;
}
void Nodes::removeForcesVisualizerNode()
{
forcesVisualizerNode.reset();
}
void
Nodes::setOnNodeAdded(std::function<void(std::shared_ptr<Node>)> onNodeAdded)
{
this->onNodeAdded = onNodeAdded;
}
void Nodes::createCameraOriginVisualizer()
{
Importer importer;
std::string filename = "assets/cameraOrigin.dae";
auto cameraOriginSphere = importer.import(filename, 0);
cameraOriginVisualizerNode = std::make_shared<MeshNode>(
filename, 0, cameraOriginSphere, Eigen::Matrix4f::Identity());
}
void Nodes::renderCameraOriginVisualizer(
Graphics::Gl *gl, std::shared_ptr<Graphics::Managers> managers,
const RenderData &renderData)
{
if (!cameraOriginVisualizerNode.get())
{
createCameraOriginVisualizer();
}
auto origin = cameraNode->getCamera()->getOrigin();
auto originNDC = project(renderData.viewProjectionMatrix, origin);
float sizeNDC = 16.0f / renderData.windowPixelSize.x();
Eigen::Vector3f sizeWorld =
calculateWorldScale(Eigen::Vector4f(sizeNDC, sizeNDC, originNDC.z(), 1),
renderData.projectionMatrix);
Eigen::Affine3f transformation(Eigen::Translation3f(origin) *
Eigen::Scaling(sizeWorld.x()));
cameraOriginVisualizerNode->setTransformation(transformation.matrix());
cameraOriginVisualizerNode->render(gl, managers, renderData);
}
<commit_msg>Hide coordinate system and camera origin visualizer by default.<commit_after>#include "./nodes.h"
#include <QDebug>
#include <string>
#include <vector>
#include "./math/eigen.h"
#include "./utils/persister.h"
#include "./importer.h"
#include "./mesh_node.h"
#include "./volume_node.h"
#include "./label_node.h"
#include "./obb_node.h"
#include "./camera_node.h"
#include "./coordinate_system_node.h"
Nodes::Nodes()
{
coordinateSystemNode = std::make_shared<CoordinateSystemNode>();
coordinateSystemNode->setIsVisible(false);
addNode(coordinateSystemNode);
cameraNode = std::make_shared<CameraNode>();
addNode(cameraNode);
}
Nodes::~Nodes()
{
qInfo() << "Destructor of Nodes";
}
std::vector<std::shared_ptr<LabelNode>> Nodes::getLabelNodes()
{
std::vector<std::shared_ptr<LabelNode>> result;
for (auto &node : nodes)
{
std::shared_ptr<LabelNode> labelNode =
std::dynamic_pointer_cast<LabelNode>(node);
if (labelNode.get())
result.push_back(labelNode);
}
return result;
}
void Nodes::addNode(std::shared_ptr<Node> node)
{
nodes.push_back(node);
if (onNodeAdded)
onNodeAdded(node);
}
void Nodes::removeNode(std::shared_ptr<Node> node)
{
nodes.erase(std::remove(nodes.begin(), nodes.end(), node), nodes.end());
}
std::vector<std::shared_ptr<Node>> Nodes::getNodes()
{
return nodes;
}
std::vector<std::shared_ptr<Node>> Nodes::getNodesForObb()
{
auto result = getNodes();
if (cameraOriginVisualizerNode.get())
result.push_back(cameraOriginVisualizerNode);
return result;
}
std::shared_ptr<CameraNode> Nodes::getCameraNode()
{
return cameraNode;
}
void Nodes::setCameraNode(std::shared_ptr<CameraNode> node)
{
if (cameraNode.get())
removeNode(cameraNode);
cameraNode = node;
addNode(node);
}
void Nodes::addSceneNodesFrom(std::string filename)
{
qDebug() << "Nodes::addSceneNodesFrom" << filename.c_str();
auto loadedNodes =
Persister::load<std::vector<std::shared_ptr<Node>>>(filename);
for (auto &node : loadedNodes)
{
std::shared_ptr<CameraNode> camera =
std::dynamic_pointer_cast<CameraNode>(node);
if (camera.get())
setCameraNode(camera);
addNode(node);
}
}
void Nodes::importMeshFrom(std::string filename)
{
Importer importer;
auto meshes = importer.importAll(filename);
for (size_t i = 0; i < meshes.size(); ++i)
{
auto transformation =
importer.getTransformationFor(filename, static_cast<int>(i));
addNode(std::make_shared<MeshNode>(filename, i, meshes[i], transformation));
}
}
void Nodes::importVolume(std::string volumeFilename,
std::string transferFunctionFilename)
{
addNode(std::make_shared<VolumeNode>(volumeFilename, transferFunctionFilename,
Eigen::Matrix4f::Identity()));
}
void Nodes::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
auto allNodes = nodes;
for (auto &node : allNodes)
node->render(gl, managers, renderData);
renderCameraOriginVisualizer(gl, managers, renderData);
if (showBoundingVolumes)
{
for (auto &node : obbNodes)
node->render(gl, managers, renderData);
}
}
void Nodes::renderLabels(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
for (auto labelNode : getLabelNodes())
{
labelNode->renderLabelAndConnector(gl, managers, renderData);
}
}
void Nodes::renderOverlays(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (forcesVisualizerNode.get())
{
forcesVisualizerNode->render(gl, managers, renderData);
}
}
void Nodes::saveSceneTo(std::string filename)
{
std::vector<std::shared_ptr<Node>> persistableNodes;
for (auto node : nodes)
if (node->isPersistable())
persistableNodes.push_back(node);
Persister::save(persistableNodes, filename);
}
void Nodes::clear()
{
clearForShutdown();
addNode(cameraNode);
}
void Nodes::clearForShutdown()
{
nodes.clear();
obbNodes.clear();
}
void Nodes::toggleBoundingVolumes()
{
showBoundingVolumes = !showBoundingVolumes;
if (showBoundingVolumes)
{
obbNodes.clear();
for (auto &node : nodes)
{
if (node->getObb().isInitialized())
{
obbNodes.push_back(std::make_shared<ObbNode>(node->getObb()));
}
}
}
}
void Nodes::toggleCoordinateSystem()
{
coordinateSystemNode->toggleVisibility();
}
void Nodes::toggleCameraOriginVisualizer()
{
cameraOriginVisualizerNode->toggleVisibility();
}
void Nodes::addForcesVisualizerNode(std::shared_ptr<Node> node)
{
forcesVisualizerNode = node;
}
void Nodes::removeForcesVisualizerNode()
{
forcesVisualizerNode.reset();
}
void
Nodes::setOnNodeAdded(std::function<void(std::shared_ptr<Node>)> onNodeAdded)
{
this->onNodeAdded = onNodeAdded;
}
void Nodes::createCameraOriginVisualizer()
{
Importer importer;
std::string filename = "assets/cameraOrigin.dae";
auto cameraOriginSphere = importer.import(filename, 0);
cameraOriginVisualizerNode = std::make_shared<MeshNode>(
filename, 0, cameraOriginSphere, Eigen::Matrix4f::Identity());
cameraOriginVisualizerNode->setIsVisible(false);
}
void Nodes::renderCameraOriginVisualizer(
Graphics::Gl *gl, std::shared_ptr<Graphics::Managers> managers,
const RenderData &renderData)
{
if (!cameraOriginVisualizerNode.get())
{
createCameraOriginVisualizer();
}
auto origin = cameraNode->getCamera()->getOrigin();
auto originNDC = project(renderData.viewProjectionMatrix, origin);
float sizeNDC = 16.0f / renderData.windowPixelSize.x();
Eigen::Vector3f sizeWorld =
calculateWorldScale(Eigen::Vector4f(sizeNDC, sizeNDC, originNDC.z(), 1),
renderData.projectionMatrix);
Eigen::Affine3f transformation(Eigen::Translation3f(origin) *
Eigen::Scaling(sizeWorld.x()));
cameraOriginVisualizerNode->setTransformation(transformation.matrix());
cameraOriginVisualizerNode->render(gl, managers, renderData);
}
<|endoftext|>
|
<commit_before>#include "./nodes.h"
#include <QDebug>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./utils/persister.h"
#include "./importer.h"
#include "./mesh_node.h"
#include "./volume_node.h"
#include "./label_node.h"
#include "./obb_node.h"
#include "./camera_node.h"
#include "./coordinate_system_node.h"
Nodes::Nodes()
{
addNode(std::make_shared<CoordinateSystemNode>());
cameraNode = std::make_shared<CameraNode>();
addNode(cameraNode);
}
Nodes::~Nodes()
{
qInfo() << "Destructor of Nodes";
}
std::vector<std::shared_ptr<LabelNode>> Nodes::getLabelNodes()
{
std::vector<std::shared_ptr<LabelNode>> result;
for (auto &node : nodes)
{
std::shared_ptr<LabelNode> labelNode =
std::dynamic_pointer_cast<LabelNode>(node);
if (labelNode.get())
result.push_back(labelNode);
}
return result;
}
void Nodes::addNode(std::shared_ptr<Node> node)
{
nodes.push_back(node);
if (onNodeAdded)
onNodeAdded(node);
}
void Nodes::removeNode(std::shared_ptr<Node> node)
{
nodes.erase(std::remove(nodes.begin(), nodes.end(), node), nodes.end());
}
std::vector<std::shared_ptr<Node>> Nodes::getNodes()
{
return nodes;
}
std::shared_ptr<CameraNode> Nodes::getCameraNode()
{
return cameraNode;
}
void Nodes::setCameraNode(std::shared_ptr<CameraNode> node)
{
if (cameraNode.get())
removeNode(cameraNode);
cameraNode = node;
addNode(node);
}
void Nodes::addSceneNodesFrom(std::string filename)
{
qDebug() << "Nodes::addSceneNodesFrom" << filename.c_str();
auto loadedNodes =
Persister::load<std::vector<std::shared_ptr<Node>>>(filename);
for (auto &node : loadedNodes)
{
std::shared_ptr<CameraNode> camera =
std::dynamic_pointer_cast<CameraNode>(node);
if (camera.get())
setCameraNode(camera);
addNode(node);
}
}
void Nodes::importMeshFrom(std::string filename)
{
Importer importer;
auto meshes = importer.importAll(filename);
for (size_t i = 0; i < meshes.size(); ++i)
{
auto transformation =
importer.getTransformationFor(filename, static_cast<int>(i));
addNode(std::make_shared<MeshNode>(filename, i, meshes[i], transformation));
}
}
void Nodes::importVolume(std::string volumeFilename,
std::string transferFunctionFilename)
{
addNode(std::make_shared<VolumeNode>(volumeFilename, transferFunctionFilename,
Eigen::Matrix4f::Identity()));
}
void Nodes::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
auto allNodes = nodes;
for (auto &node : allNodes)
node->render(gl, managers, renderData);
renderCameraOriginVisualizer(gl, managers, renderData);
if (showBoundingVolumes)
{
for (auto &node : obbNodes)
node->render(gl, managers, renderData);
}
}
void Nodes::renderLabels(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
for (auto labelNode : getLabelNodes())
{
labelNode->renderLabelAndConnector(gl, managers, renderData);
}
}
void Nodes::renderOverlays(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (forcesVisualizerNode.get())
{
forcesVisualizerNode->render(gl, managers, renderData);
}
}
void Nodes::saveSceneTo(std::string filename)
{
std::vector<std::shared_ptr<Node>> persistableNodes;
for (auto node : nodes)
if (node->isPersistable())
persistableNodes.push_back(node);
Persister::save(persistableNodes, filename);
}
void Nodes::clear()
{
nodes.clear();
obbNodes.clear();
addNode(cameraNode);
}
void Nodes::toggleBoundingVolumes()
{
showBoundingVolumes = !showBoundingVolumes;
if (showBoundingVolumes)
{
obbNodes.clear();
for (auto &node : nodes)
{
if (node->getObb().isInitialized())
{
obbNodes.push_back(std::make_shared<ObbNode>(node->getObb()));
}
}
}
}
void Nodes::addForcesVisualizerNode(std::shared_ptr<Node> node)
{
forcesVisualizerNode = node;
}
void Nodes::removeForcesVisualizerNode()
{
forcesVisualizerNode.reset();
}
void
Nodes::setOnNodeAdded(std::function<void(std::shared_ptr<Node>)> onNodeAdded)
{
this->onNodeAdded = onNodeAdded;
}
void Nodes::createCameraOriginVisualizer()
{
Importer importer;
std::string filename = "assets/cameraOrigin.dae";
auto cameraOriginSphere = importer.import(filename, 0);
cameraOriginVisualizerNode = std::make_shared<MeshNode>(
filename, 0, cameraOriginSphere, Eigen::Matrix4f::Identity());
}
void Nodes::renderCameraOriginVisualizer(
Graphics::Gl *gl, std::shared_ptr<Graphics::Managers> managers,
const RenderData &renderData)
{
if (!cameraOriginVisualizerNode.get())
{
createCameraOriginVisualizer();
}
Eigen::Affine3f transformation(
Eigen::Translation3f(cameraNode->getCamera()->getOrigin()) *
Eigen::Scaling(0.01f));
cameraOriginVisualizerNode->setTransformation(transformation.matrix());
cameraOriginVisualizerNode->render(gl, managers, renderData);
}
<commit_msg>Render camera origin visualizer with constant screen space size.<commit_after>#include "./nodes.h"
#include <QDebug>
#include <string>
#include <vector>
#include "./math/eigen.h"
#include "./utils/persister.h"
#include "./importer.h"
#include "./mesh_node.h"
#include "./volume_node.h"
#include "./label_node.h"
#include "./obb_node.h"
#include "./camera_node.h"
#include "./coordinate_system_node.h"
Nodes::Nodes()
{
addNode(std::make_shared<CoordinateSystemNode>());
cameraNode = std::make_shared<CameraNode>();
addNode(cameraNode);
}
Nodes::~Nodes()
{
qInfo() << "Destructor of Nodes";
}
std::vector<std::shared_ptr<LabelNode>> Nodes::getLabelNodes()
{
std::vector<std::shared_ptr<LabelNode>> result;
for (auto &node : nodes)
{
std::shared_ptr<LabelNode> labelNode =
std::dynamic_pointer_cast<LabelNode>(node);
if (labelNode.get())
result.push_back(labelNode);
}
return result;
}
void Nodes::addNode(std::shared_ptr<Node> node)
{
nodes.push_back(node);
if (onNodeAdded)
onNodeAdded(node);
}
void Nodes::removeNode(std::shared_ptr<Node> node)
{
nodes.erase(std::remove(nodes.begin(), nodes.end(), node), nodes.end());
}
std::vector<std::shared_ptr<Node>> Nodes::getNodes()
{
return nodes;
}
std::shared_ptr<CameraNode> Nodes::getCameraNode()
{
return cameraNode;
}
void Nodes::setCameraNode(std::shared_ptr<CameraNode> node)
{
if (cameraNode.get())
removeNode(cameraNode);
cameraNode = node;
addNode(node);
}
void Nodes::addSceneNodesFrom(std::string filename)
{
qDebug() << "Nodes::addSceneNodesFrom" << filename.c_str();
auto loadedNodes =
Persister::load<std::vector<std::shared_ptr<Node>>>(filename);
for (auto &node : loadedNodes)
{
std::shared_ptr<CameraNode> camera =
std::dynamic_pointer_cast<CameraNode>(node);
if (camera.get())
setCameraNode(camera);
addNode(node);
}
}
void Nodes::importMeshFrom(std::string filename)
{
Importer importer;
auto meshes = importer.importAll(filename);
for (size_t i = 0; i < meshes.size(); ++i)
{
auto transformation =
importer.getTransformationFor(filename, static_cast<int>(i));
addNode(std::make_shared<MeshNode>(filename, i, meshes[i], transformation));
}
}
void Nodes::importVolume(std::string volumeFilename,
std::string transferFunctionFilename)
{
addNode(std::make_shared<VolumeNode>(volumeFilename, transferFunctionFilename,
Eigen::Matrix4f::Identity()));
}
void Nodes::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
auto allNodes = nodes;
for (auto &node : allNodes)
node->render(gl, managers, renderData);
renderCameraOriginVisualizer(gl, managers, renderData);
if (showBoundingVolumes)
{
for (auto &node : obbNodes)
node->render(gl, managers, renderData);
}
}
void Nodes::renderLabels(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
for (auto labelNode : getLabelNodes())
{
labelNode->renderLabelAndConnector(gl, managers, renderData);
}
}
void Nodes::renderOverlays(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (forcesVisualizerNode.get())
{
forcesVisualizerNode->render(gl, managers, renderData);
}
}
void Nodes::saveSceneTo(std::string filename)
{
std::vector<std::shared_ptr<Node>> persistableNodes;
for (auto node : nodes)
if (node->isPersistable())
persistableNodes.push_back(node);
Persister::save(persistableNodes, filename);
}
void Nodes::clear()
{
nodes.clear();
obbNodes.clear();
addNode(cameraNode);
}
void Nodes::toggleBoundingVolumes()
{
showBoundingVolumes = !showBoundingVolumes;
if (showBoundingVolumes)
{
obbNodes.clear();
for (auto &node : nodes)
{
if (node->getObb().isInitialized())
{
obbNodes.push_back(std::make_shared<ObbNode>(node->getObb()));
}
}
}
}
void Nodes::addForcesVisualizerNode(std::shared_ptr<Node> node)
{
forcesVisualizerNode = node;
}
void Nodes::removeForcesVisualizerNode()
{
forcesVisualizerNode.reset();
}
void
Nodes::setOnNodeAdded(std::function<void(std::shared_ptr<Node>)> onNodeAdded)
{
this->onNodeAdded = onNodeAdded;
}
void Nodes::createCameraOriginVisualizer()
{
Importer importer;
std::string filename = "assets/cameraOrigin.dae";
auto cameraOriginSphere = importer.import(filename, 0);
cameraOriginVisualizerNode = std::make_shared<MeshNode>(
filename, 0, cameraOriginSphere, Eigen::Matrix4f::Identity());
}
void Nodes::renderCameraOriginVisualizer(
Graphics::Gl *gl, std::shared_ptr<Graphics::Managers> managers,
const RenderData &renderData)
{
if (!cameraOriginVisualizerNode.get())
{
createCameraOriginVisualizer();
}
auto origin = cameraNode->getCamera()->getOrigin();
auto originNDC = project(renderData.viewProjectionMatrix, origin);
float sizeNDC = 16.0f / renderData.windowPixelSize.x();
Eigen::Vector3f sizeWorld =
calculateWorldScale(Eigen::Vector4f(sizeNDC, sizeNDC, originNDC.z(), 1),
renderData.projectionMatrix);
Eigen::Affine3f transformation(Eigen::Translation3f(origin) *
Eigen::Scaling(sizeWorld.x()));
cameraOriginVisualizerNode->setTransformation(transformation.matrix());
cameraOriginVisualizerNode->render(gl, managers, renderData);
}
<|endoftext|>
|
<commit_before>/**
* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent project.
*
* iotagent is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with iotagent. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with iot_support at tid dot es
*/
#include <boost/asio.hpp>
#include <rest/process.h>
#include "rest/riot_conf.h"
#include "rest/types.h"
#include "util/iot_url.h"
#ifdef IOTA_USE_LOG4CPP
#include <log4cpp/Category.hh>
#include <log4cpp/RollingFileAppender.hh>
#include <log4cpp/PatternLayout.hh>
#else
#include <log4cplus/fileappender.h>
#endif
#include "util/common.h"
#include "util/arguments.h"
#include "services/admin_mgmt_service.h"
void config_error(const std::string& err) {
std::cerr << "ERROR" << err << std::endl;
}
int main(int argc, const char* argv[]) {
iota::Arguments arguments;
iota::Configurator* conf_iotagent = NULL;
std::string error = arguments.parser(argc, argv);
if (!error.empty()) {
std::cout << error << std::endl;
return 1;
}
/* Process initialization */
iota::Process& process =
iota::Process::initialize(arguments.get_url_base(), 8);
// Initialization Configurator
if (!arguments.get_standalone_config_file().empty()) {
conf_iotagent =
iota::Configurator::initialize(arguments.get_standalone_config_file());
} else if (!arguments.get_service_config_file().empty()) {
conf_iotagent =
iota::Configurator::initialize(arguments.get_service_config_file());
}
if (conf_iotagent == NULL) {
config_error("Configuration error. Check configuration file");
return 1;
}
iota::Configurator::instance()->set_listen_port(arguments.get_port());
iota::Configurator::instance()->set_listen_ip(arguments.get_prov_ip());
// add iotagent name
if (!arguments.get_iotagent_name().empty()) {
iota::Configurator::instance()->set_iotagent_name(
arguments.get_iotagent_name());
}
// add iotagent identifier
if (!arguments.get_iotagent_identifier().empty()) {
iota::Configurator::instance()->set_iotagent_identifier(
arguments.get_iotagent_identifier());
}
// Path logs
std::string dir_log("/tmp/");
try {
const iota::JsonValue& log_obj = iota::Configurator::instance()->get(
iota::types::CONF_FILE_DIR_LOG.c_str());
if (log_obj.IsString()) {
dir_log.assign(log_obj.GetString());
}
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
pion::logger pion_log(PION_GET_LOGGER("pion"));
pion::logger main_log(PION_GET_LOGGER(process.get_logger_name()));
std::string log_file(dir_log);
log_file.append(arguments.get_log_file());
std::string log_level = arguments.get_log_level();
if (arguments.get_verbose_flag()) {
if (log_level.empty() == true) {
PION_LOG_SETLEVEL_INFO(pion_log);
PION_LOG_SETLEVEL_INFO(main_log);
} else if (log_level.compare("FATAL") == 0) {
PION_LOG_SETLEVEL_FATAL(pion_log);
PION_LOG_SETLEVEL_FATAL(main_log);
} else if (log_level.compare("ERROR") == 0) {
PION_LOG_SETLEVEL_ERROR(pion_log);
PION_LOG_SETLEVEL_ERROR(main_log);
} else if (log_level.compare("WARNING") == 0) {
PION_LOG_SETLEVEL_ERROR(pion_log);
PION_LOG_SETLEVEL_WARN(main_log);
} else if (log_level.compare("INFO") == 0) {
PION_LOG_SETLEVEL_ERROR(pion_log);
PION_LOG_SETLEVEL_INFO(main_log);
} else if (log_level.compare("DEBUG") == 0) {
PION_LOG_SETLEVEL_INFO(pion_log);
PION_LOG_SETLEVEL_DEBUG(main_log);
}
} else {
PION_LOG_SETLEVEL_ERROR(pion_log);
PION_LOG_SETLEVEL_ERROR(main_log);
}
#ifdef IOTA_USE_LOG4CPP
log4cpp::Appender* ptrApp = new log4cpp::RollingFileAppender(
"cppApp", log_file, 10 * 1024 * 1024, 5, true);
std::string pattern = "time=%d{%Y-%m-%dT%H:%M:%S,%l%Z} | lvl=%5p | comp=" +
component_name + " %m %n";
log4cpp::Layout* layout = new log4cpp::PatternLayout();
((log4cpp::PatternLayout*)layout)->setConversionPattern(pattern);
ptrApp->setLayout(layout);
log4cpp::Category::getRoot().setAppender(ptrApp);
#else
log4cplus::SharedAppenderPtr ptrApp(
new log4cplus::RollingFileAppender(log_file, 10 * 1024 * 1024, 5, true));
log4cplus::tstring pattern =
LOG4CPLUS_TEXT("time=%D{%Y-%m-%dT%H:%M:%S,%Q%Z} | lvl=%5p | comp=" +
arguments.get_component_name() + " %m %n");
// LOG4CPLUS_TEXT("%-5p %D{%d-%m-%y %H:%M:%S,%Q %Z} [%t][%b] - %m %n");
ptrApp->setLayout(
std::auto_ptr<log4cplus::Layout>(new log4cplus::PatternLayout(pattern)));
pion_log.addAppender(ptrApp);
main_log.addAppender(ptrApp);
#endif
if (arguments.get_iotagent_name().empty() == true) {
PION_LOG_CONFIG_BASIC;
}
try {
std::string endpoint_http_container(arguments.get_ZERO_IP());
endpoint_http_container.append(":");
endpoint_http_container.append(
boost::lexical_cast<std::string>(arguments.get_port()));
pion::http::plugin_server_ptr http_server =
process.add_http_server("", endpoint_http_container);
if (!arguments.get_manager()) {
IOTA_LOG_INFO(main_log, "======== IoTAgent StartingWebServer: "
<< http_server->get_address() << " ========");
} else {
IOTA_LOG_INFO(main_log, "======== IoTAgent Manager StartingWebServer: "
<< http_server->get_address() << " ========");
}
// static service
iota::AdminService* AdminService_ptr;
if (arguments.get_manager()) {
AdminService_ptr = new iota::AdminManagerService();
} else {
AdminService_ptr = new iota::AdminService();
}
process.set_admin_service(AdminService_ptr);
if (arguments.get_ssl_flag()) {
#ifdef PION_HAVE_SSL
// configure server for SSL
IOTA_LOG_INFO(pion_log, "SSL support enabled using key file: "
<< arguments.get_ssl_pem_file());
http_server->set_ssl_key_file(arguments.get_ssl_pem_file());
/*
web_server->get_ssl_context_type().set_options(boost::asio::ssl::context::default_workarounds
|
boost::asio::ssl::context::no_sslv2
|
boost::asio::ssl::context::single_dh_use);
web_server->get_ssl_context_type().set_verify_mode(boost::asio::ssl::verify_peer
|
boost::asio::ssl::verify_fail_if_no_peer_cert);
web_server->get_ssl_context_type().use_certificate_file(ssl_pem_file,
boost::asio::ssl::context::pem);
web_server->get_ssl_context_type().use_private_key_file(ssl_pem_file,
boost::asio::ssl::context::pem);
web_server->get_ssl_context_type().load_verify_file("/home/develop/Projects/fiware-IoTAgent-Cplusplus/build/Debug/server.crt");
*/
#else
IOTA_LOG_ERROR(main_log, "SSL support is not enabled");
#endif
}
if (arguments.get_service_config_file().empty()) {
arguments.set_service_options(http_server);
} else if (!arguments.get_manager()) {
// load services using the configuration file
try {
IOTA_LOG_DEBUG(main_log, "Config file "
<< arguments.get_service_config_file());
const iota::JsonValue& resources = iota::Configurator::instance()->get(
iota::types::CONF_FILE_RESOURCES.c_str());
if (!resources.IsArray()) {
IOTA_LOG_FATAL(main_log, "ERROR in Config File "
<< arguments.get_service_config_file()
<< " Configuration error [resources]");
return 1;
}
for (rapidjson::SizeType i = 0; i < resources.Size(); i++) {
try {
if (resources[i].HasMember(
iota::types::CONF_FILE_RESOURCE.c_str())) {
std::string res =
resources[i][iota::types::CONF_FILE_RESOURCE.c_str()]
.GetString();
if (resources[i].HasMember(
iota::types::CONF_FILE_OPTIONS.c_str())) {
const iota::JsonValue& options =
resources[i][iota::types::CONF_FILE_OPTIONS.c_str()];
if ((options.HasMember(
iota::types::CONF_FILE_FILE_NAME.c_str())) &&
(options[iota::types::CONF_FILE_FILE_NAME.c_str()]
.IsString())) {
std::string s_n(
options[iota::types::CONF_FILE_FILE_NAME.c_str()]
.GetString());
IOTA_LOG_DEBUG(main_log, "Starting___ " << res);
// If resource has tcp url, it is a TCP service
try {
iota::IoTUrl resource_url(res);
IOTA_LOG_DEBUG(main_log, res);
if (resource_url.getProtocol() == URL_PROTOCOL_TCP) {
// Add service tcp
std::string str_endpoint =
resource_url.getHost() + ":" +
boost::lexical_cast<std::string>(
resource_url.getPort());
IOTA_LOG_DEBUG(main_log, "tcp server: " + str_endpoint);
process.add_tcp_server("", str_endpoint);
// Creating plugin
IOTA_LOG_DEBUG(main_log, res + " " + s_n);
pion::http::plugin_service* plugin_ptr =
process.add_tcp_service(res, s_n);
for (iota::JsonValue::ConstMemberIterator it_r =
options.MemberBegin();
it_r != options.MemberEnd(); ++it_r) {
std::string name(it_r->name.GetString());
std::string value(it_r->value.GetString());
IOTA_LOG_DEBUG(main_log, "set_service_option: "
<< name << " " << value);
try {
plugin_ptr->set_option(name, value);
} catch (boost::exception& e) {
IOTA_LOG_INFO(
main_log,
"Setting option "
<< boost::diagnostic_information(e));
}
}
// Additional option: plugin must know endpoint
// registering tcp service
plugin_ptr->set_option(
"ServerEndpoint",
resource_url.getHost() + ":" +
boost::lexical_cast<std::string>(
resource_url.getPort()));
plugin_ptr->set_resource(resource_url.getPath());
plugin_ptr->start();
}
} catch (std::exception& e) {
IOTA_LOG_INFO(
main_log,
"No tcp address " + pion::diagnostic_information(e));
http_server->load_service(res, s_n);
for (iota::JsonValue::ConstMemberIterator it_r =
options.MemberBegin();
it_r != options.MemberEnd(); ++it_r) {
std::string name(it_r->name.GetString());
std::string value(it_r->value.GetString());
IOTA_LOG_DEBUG(main_log, "set_service_option: "
<< name << " " << value);
try {
http_server->set_service_option(res, name, value);
} catch (boost::exception& e) {
IOTA_LOG_INFO(main_log,
"Setting option "
<< boost::diagnostic_information(e));
}
}
}
}
}
}
} catch (std::exception& e) {
IOTA_LOG_FATAL(main_log, e.what());
}
}
} catch (std::exception& e) {
IOTA_LOG_FATAL(main_log, "ERROR in Config File "
<< arguments.get_service_config_file());
IOTA_LOG_FATAL(main_log, e.what());
return 1;
}
}
// Start
process.start();
iota::Process::wait_for_shutdown();
process.shutdown();
} catch (std::exception& e) {
IOTA_LOG_FATAL(pion_log, pion::diagnostic_information(e));
}
}
<commit_msg>plugin directory option is lost<commit_after>/**
* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent project.
*
* iotagent is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with iotagent. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with iot_support at tid dot es
*/
#include <boost/asio.hpp>
#include <rest/process.h>
#include "rest/riot_conf.h"
#include "rest/types.h"
#include "util/iot_url.h"
#ifdef IOTA_USE_LOG4CPP
#include <log4cpp/Category.hh>
#include <log4cpp/RollingFileAppender.hh>
#include <log4cpp/PatternLayout.hh>
#else
#include <log4cplus/fileappender.h>
#endif
#include "util/common.h"
#include "util/arguments.h"
#include "services/admin_mgmt_service.h"
void config_error(const std::string& err) {
std::cerr << "ERROR" << err << std::endl;
}
int main(int argc, const char* argv[]) {
iota::Arguments arguments;
iota::Configurator* conf_iotagent = NULL;
std::string error = arguments.parser(argc, argv);
if (!error.empty()) {
std::cout << error << std::endl;
return 1;
}
/* Process initialization */
iota::Process& process =
iota::Process::initialize(arguments.get_url_base(), 8);
try {
pion::plugin::add_plugin_directory(arguments.get_plugin_directory());
} catch(pion::error::directory_not_found& e) {
std::cerr << "Plugin directory does not exist " << arguments.get_plugin_directory() << std::endl;
return 1;
}
// Initialization Configurator
if (!arguments.get_standalone_config_file().empty()) {
conf_iotagent =
iota::Configurator::initialize(arguments.get_standalone_config_file());
} else if (!arguments.get_service_config_file().empty()) {
conf_iotagent =
iota::Configurator::initialize(arguments.get_service_config_file());
}
if (conf_iotagent == NULL) {
config_error("Configuration error. Check configuration file");
return 1;
}
iota::Configurator::instance()->set_listen_port(arguments.get_port());
iota::Configurator::instance()->set_listen_ip(arguments.get_prov_ip());
// add iotagent name
if (!arguments.get_iotagent_name().empty()) {
iota::Configurator::instance()->set_iotagent_name(
arguments.get_iotagent_name());
}
// add iotagent identifier
if (!arguments.get_iotagent_identifier().empty()) {
iota::Configurator::instance()->set_iotagent_identifier(
arguments.get_iotagent_identifier());
}
// Path logs
std::string dir_log("/tmp/");
try {
const iota::JsonValue& log_obj = iota::Configurator::instance()->get(
iota::types::CONF_FILE_DIR_LOG.c_str());
if (log_obj.IsString()) {
dir_log.assign(log_obj.GetString());
}
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
pion::logger pion_log(PION_GET_LOGGER("pion"));
pion::logger main_log(PION_GET_LOGGER(process.get_logger_name()));
std::string log_file(dir_log);
log_file.append(arguments.get_log_file());
std::string log_level = arguments.get_log_level();
if (arguments.get_verbose_flag()) {
if (log_level.empty() == true) {
PION_LOG_SETLEVEL_INFO(pion_log);
PION_LOG_SETLEVEL_INFO(main_log);
} else if (log_level.compare("FATAL") == 0) {
PION_LOG_SETLEVEL_FATAL(pion_log);
PION_LOG_SETLEVEL_FATAL(main_log);
} else if (log_level.compare("ERROR") == 0) {
PION_LOG_SETLEVEL_ERROR(pion_log);
PION_LOG_SETLEVEL_ERROR(main_log);
} else if (log_level.compare("WARNING") == 0) {
PION_LOG_SETLEVEL_ERROR(pion_log);
PION_LOG_SETLEVEL_WARN(main_log);
} else if (log_level.compare("INFO") == 0) {
PION_LOG_SETLEVEL_ERROR(pion_log);
PION_LOG_SETLEVEL_INFO(main_log);
} else if (log_level.compare("DEBUG") == 0) {
PION_LOG_SETLEVEL_INFO(pion_log);
PION_LOG_SETLEVEL_DEBUG(main_log);
}
} else {
PION_LOG_SETLEVEL_ERROR(pion_log);
PION_LOG_SETLEVEL_ERROR(main_log);
}
#ifdef IOTA_USE_LOG4CPP
log4cpp::Appender* ptrApp = new log4cpp::RollingFileAppender(
"cppApp", log_file, 10 * 1024 * 1024, 5, true);
std::string pattern = "time=%d{%Y-%m-%dT%H:%M:%S,%l%Z} | lvl=%5p | comp=" +
component_name + " %m %n";
log4cpp::Layout* layout = new log4cpp::PatternLayout();
((log4cpp::PatternLayout*)layout)->setConversionPattern(pattern);
ptrApp->setLayout(layout);
log4cpp::Category::getRoot().setAppender(ptrApp);
#else
log4cplus::SharedAppenderPtr ptrApp(
new log4cplus::RollingFileAppender(log_file, 10 * 1024 * 1024, 5, true));
log4cplus::tstring pattern =
LOG4CPLUS_TEXT("time=%D{%Y-%m-%dT%H:%M:%S,%Q%Z} | lvl=%5p | comp=" +
arguments.get_component_name() + " %m %n");
// LOG4CPLUS_TEXT("%-5p %D{%d-%m-%y %H:%M:%S,%Q %Z} [%t][%b] - %m %n");
ptrApp->setLayout(
std::auto_ptr<log4cplus::Layout>(new log4cplus::PatternLayout(pattern)));
pion_log.addAppender(ptrApp);
main_log.addAppender(ptrApp);
#endif
if (arguments.get_iotagent_name().empty() == true) {
PION_LOG_CONFIG_BASIC;
}
try {
std::string endpoint_http_container(arguments.get_ZERO_IP());
endpoint_http_container.append(":");
endpoint_http_container.append(
boost::lexical_cast<std::string>(arguments.get_port()));
pion::http::plugin_server_ptr http_server =
process.add_http_server("", endpoint_http_container);
if (!arguments.get_manager()) {
IOTA_LOG_INFO(main_log, "======== IoTAgent StartingWebServer: "
<< http_server->get_address() << " ========");
} else {
IOTA_LOG_INFO(main_log, "======== IoTAgent Manager StartingWebServer: "
<< http_server->get_address() << " ========");
}
// static service
iota::AdminService* AdminService_ptr;
if (arguments.get_manager()) {
AdminService_ptr = new iota::AdminManagerService();
} else {
AdminService_ptr = new iota::AdminService();
}
process.set_admin_service(AdminService_ptr);
if (arguments.get_ssl_flag()) {
#ifdef PION_HAVE_SSL
// configure server for SSL
IOTA_LOG_INFO(pion_log, "SSL support enabled using key file: "
<< arguments.get_ssl_pem_file());
http_server->set_ssl_key_file(arguments.get_ssl_pem_file());
/*
web_server->get_ssl_context_type().set_options(boost::asio::ssl::context::default_workarounds
|
boost::asio::ssl::context::no_sslv2
|
boost::asio::ssl::context::single_dh_use);
web_server->get_ssl_context_type().set_verify_mode(boost::asio::ssl::verify_peer
|
boost::asio::ssl::verify_fail_if_no_peer_cert);
web_server->get_ssl_context_type().use_certificate_file(ssl_pem_file,
boost::asio::ssl::context::pem);
web_server->get_ssl_context_type().use_private_key_file(ssl_pem_file,
boost::asio::ssl::context::pem);
web_server->get_ssl_context_type().load_verify_file("/home/develop/Projects/fiware-IoTAgent-Cplusplus/build/Debug/server.crt");
*/
#else
IOTA_LOG_ERROR(main_log, "SSL support is not enabled");
#endif
}
if (arguments.get_service_config_file().empty()) {
arguments.set_service_options(http_server);
} else if (!arguments.get_manager()) {
// load services using the configuration file
try {
IOTA_LOG_DEBUG(main_log, "Config file "
<< arguments.get_service_config_file());
const iota::JsonValue& resources = iota::Configurator::instance()->get(
iota::types::CONF_FILE_RESOURCES.c_str());
if (!resources.IsArray()) {
IOTA_LOG_FATAL(main_log, "ERROR in Config File "
<< arguments.get_service_config_file()
<< " Configuration error [resources]");
return 1;
}
for (rapidjson::SizeType i = 0; i < resources.Size(); i++) {
try {
if (resources[i].HasMember(
iota::types::CONF_FILE_RESOURCE.c_str())) {
std::string res =
resources[i][iota::types::CONF_FILE_RESOURCE.c_str()]
.GetString();
if (resources[i].HasMember(
iota::types::CONF_FILE_OPTIONS.c_str())) {
const iota::JsonValue& options =
resources[i][iota::types::CONF_FILE_OPTIONS.c_str()];
if ((options.HasMember(
iota::types::CONF_FILE_FILE_NAME.c_str())) &&
(options[iota::types::CONF_FILE_FILE_NAME.c_str()]
.IsString())) {
std::string s_n(
options[iota::types::CONF_FILE_FILE_NAME.c_str()]
.GetString());
IOTA_LOG_DEBUG(main_log, "Starting___ " << res);
// If resource has tcp url, it is a TCP service
try {
iota::IoTUrl resource_url(res);
IOTA_LOG_DEBUG(main_log, res);
if (resource_url.getProtocol() == URL_PROTOCOL_TCP) {
// Add service tcp
std::string str_endpoint =
resource_url.getHost() + ":" +
boost::lexical_cast<std::string>(
resource_url.getPort());
IOTA_LOG_DEBUG(main_log, "tcp server: " + str_endpoint);
process.add_tcp_server("", str_endpoint);
// Creating plugin
IOTA_LOG_DEBUG(main_log, res + " " + s_n);
pion::http::plugin_service* plugin_ptr =
process.add_tcp_service(res, s_n);
for (iota::JsonValue::ConstMemberIterator it_r =
options.MemberBegin();
it_r != options.MemberEnd(); ++it_r) {
std::string name(it_r->name.GetString());
std::string value(it_r->value.GetString());
IOTA_LOG_DEBUG(main_log, "set_service_option: "
<< name << " " << value);
try {
plugin_ptr->set_option(name, value);
} catch (boost::exception& e) {
IOTA_LOG_INFO(
main_log,
"Setting option "
<< boost::diagnostic_information(e));
}
}
// Additional option: plugin must know endpoint
// registering tcp service
plugin_ptr->set_option(
"ServerEndpoint",
resource_url.getHost() + ":" +
boost::lexical_cast<std::string>(
resource_url.getPort()));
plugin_ptr->set_resource(resource_url.getPath());
plugin_ptr->start();
}
} catch (std::exception& e) {
IOTA_LOG_INFO(
main_log,
"No tcp address " + pion::diagnostic_information(e));
http_server->load_service(res, s_n);
for (iota::JsonValue::ConstMemberIterator it_r =
options.MemberBegin();
it_r != options.MemberEnd(); ++it_r) {
std::string name(it_r->name.GetString());
std::string value(it_r->value.GetString());
IOTA_LOG_DEBUG(main_log, "set_service_option: "
<< name << " " << value);
try {
http_server->set_service_option(res, name, value);
} catch (boost::exception& e) {
IOTA_LOG_INFO(main_log,
"Setting option "
<< boost::diagnostic_information(e));
}
}
}
}
}
}
} catch (std::exception& e) {
IOTA_LOG_FATAL(main_log, e.what());
}
}
} catch (std::exception& e) {
IOTA_LOG_FATAL(main_log, "ERROR in Config File "
<< arguments.get_service_config_file());
IOTA_LOG_FATAL(main_log, e.what());
return 1;
}
}
// Start
process.start();
iota::Process::wait_for_shutdown();
process.shutdown();
} catch (std::exception& e) {
IOTA_LOG_FATAL(pion_log, pion::diagnostic_information(e));
}
}
<|endoftext|>
|
<commit_before>
#include <filesystem>
#include <fstream>
#include <map>
#include <string>
#include "base/array.hpp"
#include "base/hexadecimal.hpp"
#include "ksp_plugin/frames.hpp"
#include "ksp_plugin/plugin.hpp"
#include "geometry/grassmann.hpp"
#include "glog/logging.h"
#include "google/protobuf/io/coded_stream.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "serialization/physics.pb.h"
#include "serialization/ksp_plugin.pb.h"
namespace principia {
namespace ksp_plugin {
namespace internal_plugin {
using base::Array;
using base::UniqueBytes;
using base::HexadecimalDecode;
using geometry::Bivector;
using geometry::Trivector;
using geometry::Vector;
using quantities::Length;
using quantities::si::Hour;
using quantities::si::Metre;
using quantities::si::Radian;
using quantities::si::Second;
using ::testing::AllOf;
using ::testing::AnyOf;
using ::testing::Gt;
using ::testing::Lt;
class TestablePlugin : public Plugin {
public:
void KeepAllVessels();
std::map<GUID, not_null<Vessel const*>> vessels() const;
static not_null<std::unique_ptr<TestablePlugin>> ReadFromMessage(
serialization::Plugin const& message);
};
void TestablePlugin::KeepAllVessels() {
for (auto const& pair : vessels_) {
auto const& vessel = pair.second;
kept_vessels_.insert(vessel.get());
}
}
std::map<GUID, not_null<Vessel const*>> TestablePlugin::vessels() const {
std::map<GUID, not_null<Vessel const*>> result;
for (auto const& pair : vessels_) {
auto const& guid = pair.first;
Vessel const* const vessel = pair.second.get();
result.insert(std::make_pair(guid, vessel));
}
return result;
}
not_null<std::unique_ptr<TestablePlugin>> TestablePlugin::ReadFromMessage(
serialization::Plugin const& message) {
std::unique_ptr<Plugin> plugin = Plugin::ReadFromMessage(message);
return std::unique_ptr<TestablePlugin>(
static_cast<TestablePlugin*>(plugin.release()));
}
class PluginCompatibilityTest : public testing::Test {
protected:
serialization::Plugin ReadFromFile(std::string const& filename) {
// Open the file and read hexadecimal data.
std::fstream file =
std::fstream(SOLUTION_DIR / "ksp_plugin_test" / filename);
CHECK(file.good());
std::string hex;
while (!file.eof()) {
std::string line;
std::getline(file, line);
for (auto const c : line) {
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
hex.append(1, c);
}
}
}
file.close();
// Parse the hexadecimal data and convert it to binary data.
auto const bin = HexadecimalDecode(
Array<std::uint8_t const>(
reinterpret_cast<std::uint8_t const*>(hex.c_str()), hex.size()));
// Construct a protocol buffer from the binary data.
google::protobuf::io::CodedInputStream coded_input_stream(
bin.data.get(), static_cast<int>(bin.size));
serialization::Plugin message;
CHECK(message.MergeFromCodedStream(&coded_input_stream));
return message;
}
};
TEST_F(PluginCompatibilityTest, PreCartan) {
// This space for rent.
}
} // namespace internal_plugin
} // namespace ksp_plugin
} // namespace principia
<commit_msg>another one<commit_after>
#include <filesystem>
#include <fstream>
#include <map>
#include <string>
#include "base/array.hpp"
#include "base/hexadecimal.hpp"
#include "ksp_plugin/frames.hpp"
#include "ksp_plugin/plugin.hpp"
#include "geometry/grassmann.hpp"
#include "glog/logging.h"
#include "google/protobuf/io/coded_stream.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "serialization/physics.pb.h"
#include "serialization/ksp_plugin.pb.h"
namespace principia {
namespace ksp_plugin {
namespace internal_plugin {
using base::Array;
using base::UniqueBytes;
using base::HexadecimalDecode;
using geometry::Bivector;
using geometry::Trivector;
using geometry::Vector;
using quantities::Length;
using quantities::si::Hour;
using quantities::si::Metre;
using quantities::si::Radian;
using quantities::si::Second;
using ::testing::AllOf;
using ::testing::AnyOf;
using ::testing::Gt;
using ::testing::Lt;
class TestablePlugin : public Plugin {
public:
void KeepAllVessels();
std::map<GUID, not_null<Vessel const*>> vessels() const;
static not_null<std::unique_ptr<TestablePlugin>> ReadFromMessage(
serialization::Plugin const& message);
};
void TestablePlugin::KeepAllVessels() {
for (auto const& pair : vessels_) {
auto const& vessel = pair.second;
kept_vessels_.insert(vessel.get());
}
}
std::map<GUID, not_null<Vessel const*>> TestablePlugin::vessels() const {
std::map<GUID, not_null<Vessel const*>> result;
for (auto const& pair : vessels_) {
auto const& guid = pair.first;
Vessel const* const vessel = pair.second.get();
result.insert(std::make_pair(guid, vessel));
}
return result;
}
not_null<std::unique_ptr<TestablePlugin>> TestablePlugin::ReadFromMessage(
serialization::Plugin const& message) {
std::unique_ptr<Plugin> plugin = Plugin::ReadFromMessage(message);
return std::unique_ptr<TestablePlugin>(
static_cast<TestablePlugin*>(plugin.release()));
}
class PluginCompatibilityTest : public testing::Test {
protected:
serialization::Plugin ReadFromFile(std::string const& filename) {
// Open the file and read hexadecimal data.
std::fstream file =
std::fstream(SOLUTION_DIR / "ksp_plugin_test" / filename);
CHECK(file.good());
std::string hex;
while (!file.eof()) {
std::string line;
std::getline(file, line);
for (auto const c : line) {
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
hex.append(1, c);
}
}
}
file.close();
// Parse the hexadecimal data and convert it to binary data.
auto const bin = HexadecimalDecode(hex);
// Construct a protocol buffer from the binary data.
google::protobuf::io::CodedInputStream coded_input_stream(
bin.data.get(), static_cast<int>(bin.size));
serialization::Plugin message;
CHECK(message.MergeFromCodedStream(&coded_input_stream));
return message;
}
};
TEST_F(PluginCompatibilityTest, PreCartan) {
// This space for rent.
}
} // namespace internal_plugin
} // namespace ksp_plugin
} // namespace principia
<|endoftext|>
|
<commit_before>/*
* SessionRequest.hpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef SESSION_REQUEST_HPP
#define SESSION_REQUEST_HPP
#include <core/Error.hpp>
#include <core/system/Environment.hpp>
#include <session/http/SessionRequest.hpp>
#if !defined(_WIN32)
#include <core/http/TcpIpBlockingClient.hpp>
#include <core/http/LocalStreamBlockingClient.hpp>
#include <core/http/ConnectionRetryProfile.hpp>
#else
#include <core/http/NamedPipeBlockingClient.hpp>
#endif
#if !defined(_WIN32)
#include <session/SessionLocalStreams.hpp>
#endif
#include <session/SessionConstants.hpp>
namespace rstudio {
namespace session {
namespace http {
// this function sends an request directly to the session; it's inlined so that
// it can be used both from the postback executable (which does not link with
// rsession) and the session itself
inline core::Error sendSessionRequest(const std::string& uri,
const std::string& body, core::http::Response* pResponse)
{
// build request
core::http::Request request;
request.setMethod("POST");
request.setUri(uri);
request.setHeader("Accept", "*/*");
request.setHeader("Connection", "close");
request.setBody(body);
#ifdef _WIN32
// get local peer
std::string pipeName = core::system::getenv("RS_LOCAL_PEER");
request.setHeader("X-Shared-Secret",
core::system::getenv("RS_SHARED_SECRET"));
return core::http::sendRequest(pipeName,
request,
core::http::ConnectionRetryProfile(
boost::posix_time::seconds(10),
boost::posix_time::milliseconds(50)),
pResponse);
#else
std::string tcpipPort = core::system::getenv(kRSessionStandalonePortNumber);
if (tcpipPort.empty())
{
// if no standalone port, make an authenticated session request
tcpipPort = core::system::getenv(kRSessionPortNumber);
request.setHeader("X-Shared-Secret",
core::system::getenv("RS_SHARED_SECRET"));
return core::http::sendRequest("127.0.0.1", tcpipPort, request,
pResponse);
}
else
{
// determine stream path -- check server environment variable first
core::FilePath streamPath;
std::string stream = core::system::getenv(kRStudioSessionStream);
if (stream.empty())
{
// if no server environment variable, check desktop variant
streamPath = core::FilePath(core::system::getenv("RS_LOCAL_PEER"));
request.setHeader("X-Shared-Secret",
core::system::getenv("RS_SHARED_SECRET"));
}
else
{
streamPath = session::local_streams::streamPath(stream);
}
return core::http::sendRequest(streamPath, request, pResponse);
}
#endif
return core::Success();
}
} // namespace http
} // namespace session
} // namespace rstudio
#endif
<commit_msg>fix up chunk execution on Windows<commit_after>/*
* SessionRequest.hpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef SESSION_REQUEST_HPP
#define SESSION_REQUEST_HPP
#include <core/Error.hpp>
#include <core/system/Environment.hpp>
#include <session/http/SessionRequest.hpp>
#include <core/http/TcpIpBlockingClient.hpp>
#include <core/http/ConnectionRetryProfile.hpp>
#ifndef _WIN32
# include <core/http/LocalStreamBlockingClient.hpp>
# include <session/SessionLocalStreams.hpp>
#endif
#include <session/SessionConstants.hpp>
namespace rstudio {
namespace session {
namespace http {
// this function sends an request directly to the session; it's inlined so that
// it can be used both from the postback executable (which does not link with
// rsession) and the session itself
inline core::Error sendSessionRequest(const std::string& uri,
const std::string& body,
core::http::Response* pResponse)
{
// build request
core::http::Request request;
request.setMethod("POST");
request.setUri(uri);
request.setHeader("Accept", "*/*");
request.setHeader("Connection", "close");
request.setBody(body);
std::string tcpipPort = core::system::getenv(kRSessionStandalonePortNumber);
// first, attempt to send a plain old http request
if (tcpipPort.empty())
{
// if no standalone port, make an authenticated session request
tcpipPort = core::system::getenv(kRSessionPortNumber);
request.setHeader("X-Shared-Secret", core::system::getenv("RS_SHARED_SECRET"));
return core::http::sendRequest("127.0.0.1", tcpipPort, request, pResponse);
}
#ifndef _WIN32
// otherwise, attempt communicating over a local stream (unix domain socket)
// determine stream path -- check server environment variable first
core::FilePath streamPath;
std::string stream = core::system::getenv(kRStudioSessionStream);
if (stream.empty())
{
// if no server environment variable, check desktop variant
streamPath = core::FilePath(core::system::getenv("RS_LOCAL_PEER"));
request.setHeader("X-Shared-Secret",
core::system::getenv("RS_SHARED_SECRET"));
}
else
{
streamPath = session::local_streams::streamPath(stream);
}
return core::http::sendRequest(streamPath, request, pResponse);
#endif
return core::Success();
}
} // namespace http
} // namespace session
} // namespace rstudio
#endif
<|endoftext|>
|
<commit_before>#if defined(__STDC_LIB_EXT1__)
#define __STDC_WANT_LIB_EXT1__ 1
#endif
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cxxopts.hpp>
#include "ast.h"
#include "gen.h"
using namespace std;
extern FILE *yyin, *yyout;
extern int yyparse();
extern NBlock *programBlock;
int main(int argc, char **argv) {
cxxopts::Options options("The xy Language Compiler",
"A toy complier based on LLVM JIT.");
options.add_options()("d,debug", "Enable debugging")(
"f,file", "Input file name", cxxopts::value<std::string>())(
"o,output", "Output file name", cxxopts::value<std::string>())(
"v,verbose", "Verbose output",
cxxopts::value<bool>()->default_value("false"))("h,help", "Print usage");
auto result = options.parse(argc, argv);
if (result.count("help")) {
std::cout << options.help() << std::endl;
exit(0);
}
if (result.count("file")) {
auto inputFilePath = result["file"].as<std::string>();
#if defined(__STDC_LIB_EXT1__)
fopen_s(&yyin, inputFilePath.c_str(), "r");
#else
yyin = fopen(inputFilePath.c_str(), "r");
#endif
}
if (result.count("output")) {
auto outputFilePath = result["output"].as<std::string>();
#if defined(__STDC_LIB_EXT1__)
fopen_s(&yyout, outputFilePath.c_str(), "w");
#else
yyout = fopen(outputFilePath.c_str(), "w");
#endif
}
yyparse();
std::cout << programBlock << endl;
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
InitializeNativeTargetAsmParser();
CodeGenContext context;
context.generateCode(*programBlock);
context.runCode();
std::cout << "Exiting...\n";
return 0;
}
<commit_msg>add show version<commit_after>#if defined(__STDC_LIB_EXT1__)
#define __STDC_WANT_LIB_EXT1__ 1
#endif
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cxxopts.hpp>
#include "ast.h"
#include "gen.h"
#include "version.hpp"
using namespace std;
extern FILE *yyin, *yyout;
extern int yyparse();
extern NBlock *programBlock;
int main(int argc, char **argv) {
cxxopts::Options options("The xy Language Compiler",
"A toy complier based on LLVM JIT.");
options.add_options()("d,debug", "Enable debugging")(
"f,file", "Input file name", cxxopts::value<std::string>())(
"o,output", "Output file name", cxxopts::value<std::string>())(
"v,verbose", "Verbose output",
cxxopts::value<bool>()->default_value("false"))("h,help", "Print usage")(
"version", "Print version");
auto result = options.parse(argc, argv);
if (result.count("help")) {
std::cout << options.help() << std::endl;
return 0;
}
if (result.count("version")) {
std::cout << "Version: " << VER << std::endl;
return 0;
}
if (result.count("file")) {
auto inputFilePath = result["file"].as<std::string>();
#if defined(__STDC_LIB_EXT1__) || defined(_MSC_VER)
fopen_s(&yyin, inputFilePath.c_str(), "r");
#else
yyin = fopen(inputFilePath.c_str(), "r");
#endif
}
if (result.count("output")) {
auto outputFilePath = result["output"].as<std::string>();
#if defined(__STDC_LIB_EXT1__) || defined(_MSC_VER)
fopen_s(&yyout, outputFilePath.c_str(), "w");
#else
yyout = fopen(outputFilePath.c_str(), "w");
#endif
}
yyparse();
std::cout << programBlock << endl;
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
InitializeNativeTargetAsmParser();
CodeGenContext context;
context.generateCode(*programBlock);
context.runCode();
std::cout << "Exiting...\n";
return 0;
}
<|endoftext|>
|
<commit_before>/*{{{
Copyright © 2017 Matthias Kretz <kretz@kde.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 names of contributing organizations 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 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 <vir/test.h>
#include <cmath>
#include <limits>
TEST(sanity_checks) //{{{1
{
VERIFY(true);
COMPARE(1, 1);
struct NotComparable {
int x = -0xdeadbeef;
};
COMPARE(NotComparable(), NotComparable()); // compares with memcmp
}
TEST(type_to_string) //{{{1
{
COMPARE((vir::typeToString<std::array<int, 3>>()), "array< int, 3>");
COMPARE((vir::typeToString<std::vector<float>>()), "vector< float>");
COMPARE((vir::typeToString<std::integral_constant<int, 3>>()), "integral_constant<3>");
COMPARE((vir::typeToString<vir::Typelist<>>()), "{}");
COMPARE((vir::typeToString<vir::Typelist<int, float>>()), "{ int, float}");
}
TEST(Typelist) //{{{1
{
using namespace vir;
using _1 = std::integral_constant<int, 1>;
using _2 = std::integral_constant<int, 2>;
using _3 = std::integral_constant<int, 3>;
using _4 = std::integral_constant<int, 4>;
COMPARE(typeid(outer_product<Typelist<_1, _2>, Typelist<_3, _4>>),
typeid(Typelist<Typelist<_1, _3>, Typelist<_1, _4>, Typelist<_2, _3>,
Typelist<_2, _4>>));
}
// test_types[_check] {{{1
std::vector<std::string> seen_types;
TEST_TYPES(T, test_types, (int, float, char))
{
seen_types.push_back(vir::typeToString<T>());
}
TEST(test_types_check)
{
COMPARE(seen_types.size(), 3u);
COMPARE(seen_types[0], " int");
COMPARE(seen_types[1], " float");
COMPARE(seen_types[2], " char");
}
TEST_TYPES(T, testUlpDiff, (double, float, long double)) //{{{1
{
using std::numeric_limits;
using vir::detail::ulpDiffToReference;
using vir::detail::ulpDiffToReferenceSigned;
const auto zero = T();
const auto min = numeric_limits<T>::min();
const auto epsilon = numeric_limits<T>::epsilon();
COMPARE(ulpDiffToReference(zero, zero), 0);
// if 0 is expected, the closest normalized value representation is considered 1 ULP away, even if
// 2 ULP away from 0 is almost the same. But hitting exactly 0 is quite hard sometimes.
COMPARE(ulpDiffToReferenceSigned(min, zero), 1);
COMPARE(ulpDiffToReferenceSigned(-min, zero), -1);
COMPARE(ulpDiffToReferenceSigned(std::nextafter(min, T(1)), zero), 2);
COMPARE(ulpDiffToReferenceSigned(-std::nextafter(min, T(1)), zero), -2);
// if the expectation is nonzero, it is not clear that 0 should be considered 1 ULP away. This may
// be reconsidered given an good argument.
COMPARE(ulpDiffToReferenceSigned(zero, min), -1);
// epsilon is the ULP relative to [1, 2)
COMPARE(ulpDiffToReferenceSigned(T(1), T(1) + epsilon), -1);
COMPARE(ulpDiffToReferenceSigned(T(1) + epsilon, T(1)), 1);
// expected * epsilon(1) = 2 - 1
// => expected = 1 / epsilon
COMPARE(ulpDiffToReferenceSigned(T(2), T(1)), T(1) / epsilon);
// expected * epsilon(2) = expected * epsilon(1) * 2 = 2 - 1
// => expected = .5 / epsilon
COMPARE(ulpDiffToReferenceSigned(T(1), T(2)), T(-.5) / epsilon);
// change of sign - considered far far away
COMPARE(ulpDiffToReferenceSigned(-min, min), -T(2) / epsilon);
COMPARE(ulpDiffToReferenceSigned(min, -min), +T(2) / epsilon);
}
//}}}1
// vim: sw=2 et sts=2 foldmethod=marker
<commit_msg>This is no negative int, make it unsigned<commit_after>/*{{{
Copyright © 2017 Matthias Kretz <kretz@kde.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 names of contributing organizations 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 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 <vir/test.h>
#include <cmath>
#include <limits>
TEST(sanity_checks) //{{{1
{
VERIFY(true);
COMPARE(1, 1);
struct NotComparable {
unsigned int x = 0xdeadbeef;
};
COMPARE(NotComparable(), NotComparable()); // compares with memcmp
}
TEST(type_to_string) //{{{1
{
COMPARE((vir::typeToString<std::array<int, 3>>()), "array< int, 3>");
COMPARE((vir::typeToString<std::vector<float>>()), "vector< float>");
COMPARE((vir::typeToString<std::integral_constant<int, 3>>()), "integral_constant<3>");
COMPARE((vir::typeToString<vir::Typelist<>>()), "{}");
COMPARE((vir::typeToString<vir::Typelist<int, float>>()), "{ int, float}");
}
TEST(Typelist) //{{{1
{
using namespace vir;
using _1 = std::integral_constant<int, 1>;
using _2 = std::integral_constant<int, 2>;
using _3 = std::integral_constant<int, 3>;
using _4 = std::integral_constant<int, 4>;
COMPARE(typeid(outer_product<Typelist<_1, _2>, Typelist<_3, _4>>),
typeid(Typelist<Typelist<_1, _3>, Typelist<_1, _4>, Typelist<_2, _3>,
Typelist<_2, _4>>));
}
// test_types[_check] {{{1
std::vector<std::string> seen_types;
TEST_TYPES(T, test_types, (int, float, char))
{
seen_types.push_back(vir::typeToString<T>());
}
TEST(test_types_check)
{
COMPARE(seen_types.size(), 3u);
COMPARE(seen_types[0], " int");
COMPARE(seen_types[1], " float");
COMPARE(seen_types[2], " char");
}
TEST_TYPES(T, testUlpDiff, (double, float, long double)) //{{{1
{
using std::numeric_limits;
using vir::detail::ulpDiffToReference;
using vir::detail::ulpDiffToReferenceSigned;
const auto zero = T();
const auto min = numeric_limits<T>::min();
const auto epsilon = numeric_limits<T>::epsilon();
COMPARE(ulpDiffToReference(zero, zero), 0);
// if 0 is expected, the closest normalized value representation is considered 1 ULP away, even if
// 2 ULP away from 0 is almost the same. But hitting exactly 0 is quite hard sometimes.
COMPARE(ulpDiffToReferenceSigned(min, zero), 1);
COMPARE(ulpDiffToReferenceSigned(-min, zero), -1);
COMPARE(ulpDiffToReferenceSigned(std::nextafter(min, T(1)), zero), 2);
COMPARE(ulpDiffToReferenceSigned(-std::nextafter(min, T(1)), zero), -2);
// if the expectation is nonzero, it is not clear that 0 should be considered 1 ULP away. This may
// be reconsidered given an good argument.
COMPARE(ulpDiffToReferenceSigned(zero, min), -1);
// epsilon is the ULP relative to [1, 2)
COMPARE(ulpDiffToReferenceSigned(T(1), T(1) + epsilon), -1);
COMPARE(ulpDiffToReferenceSigned(T(1) + epsilon, T(1)), 1);
// expected * epsilon(1) = 2 - 1
// => expected = 1 / epsilon
COMPARE(ulpDiffToReferenceSigned(T(2), T(1)), T(1) / epsilon);
// expected * epsilon(2) = expected * epsilon(1) * 2 = 2 - 1
// => expected = .5 / epsilon
COMPARE(ulpDiffToReferenceSigned(T(1), T(2)), T(-.5) / epsilon);
// change of sign - considered far far away
COMPARE(ulpDiffToReferenceSigned(-min, min), -T(2) / epsilon);
COMPARE(ulpDiffToReferenceSigned(min, -min), +T(2) / epsilon);
}
//}}}1
// vim: sw=2 et sts=2 foldmethod=marker
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Nicolas Pope
*/
#include <string>
#include <iostream>
#include <map>
#include <sstream>
#include <vector>
#include "fdsb/nid.hpp"
#include "fdsb/fabric.hpp"
#include "fdsb/framer.hpp"
using fdsb::Nid;
using fdsb::Framer;
using fdsb::Harc;
using std::map;
using std::string;
using std::vector;
using std::stringstream;
using std::cout;
vector<string> &split(const string &s, char delim, vector<string> &elems) {
stringstream ss(s);
string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
vector<string> split(const string &s, char delim) {
vector<string> elems;
split(s, delim, elems);
return elems;
}
vector<vector<Nid>> build_path(const vector<string> &e, int ix) {
vector<vector<Nid>> p;
vector<Nid> cursub;
for (auto i = ix; i < static_cast<int>(e.size()); ++i) {
if (e[i] == "}") {
break;
} else if (e[i] == "(") {
continue;
} else if (e[i] == ")") {
p.push_back(cursub);
cursub.clear();
} else {
cursub.push_back(Nid::from_string(e[i]));
}
}
if (cursub.size() > 0) {
p.push_back(cursub);
}
return p;
}
/* ======== Command Functions =============================================== */
/*
* Query a hyperarc for its head node. Two node id's are given as arguments
* which identify the tail of the hyperarc.
*/
void command_query(const vector<string> &e) {
if (e.size() != 3) {
std::cout << " Query command expects 2 arguments." << std::endl;
} else {
Nid t1 = Nid::from_string(e[1]);
Nid t2 = Nid::from_string(e[2]);
Nid r = fdsb::fabric.get(t1, t2).query();
std::cout << " " << r << std::endl;
}
}
void command_define(const vector<string> &e) {
// Just a constant definition
if (e.size() == 4) {
Nid t1 = Nid::from_string(e[1]);
Nid t2 = Nid::from_string(e[2]);
Nid h = Nid::from_string(e[3]);
fdsb::fabric.get(t1, t2).define(h);
// Path based definition
} else if (e.size() > 4) {
Nid t1 = Nid::from_string(e[1]);
Nid t2 = Nid::from_string(e[2]);
fdsb::fabric.get(t1, t2).define(build_path(e, 3));
} else {
cout << " Define command expects 3 or more arguments." << std::endl;
}
}
void command_partners(const vector<string> &e) {
if (e.size() < 2) {
cout << " Partners command expects 1 or more arguments." << std::endl;
} else {
if (e[1] == "all") {
Nid n1 = Nid::from_string(e[2]);
auto part = fdsb::fabric.partners(n1);
for (auto i : part) {
cout << " - " << *i << std::endl;
}
} else {
vector<Nid> nodes;
for (int i = 1; i < static_cast<int>(e.size()); ++i) {
Nid n1 = Nid::from_string(e[i]);
nodes.push_back(n1);
}
auto part = Framer::select_partners(nodes, 10);
for (auto i : part) {
cout << " - [" << i->tail().first << " "
<< i->tail().second << "]" << std::endl;
}
}
}
}
void command_path(const vector<string> &e) {
if (e.size() >= 3) {
cout << " " << fdsb::fabric.path(build_path(e, 1)) << std::endl;
} else {
cout << " Path command expects 2 or more arguments." << std::endl;
}
}
void command_array(const vector<string> &e) {
if (e.size() >= 3) {
Nid r = Nid::unique();
for (auto i = 1; i < static_cast<int>(e.size()); ++i) {
r[Nid::from_int(i-1)] = Nid::from_string(e[i]);
}
cout << " " << r << std::endl;
} else {
cout << " Array command expects 2 or more arguments." << std::endl;
}
}
void command_dependants(const vector<string> &e) {
if (e.size() != 3) {
cout << " Dependants command expects 2 arguments." << std::endl;
} else {
Nid t1 = Nid::from_string(e[1]);
Nid t2 = Nid::from_string(e[2]);
auto deps = fdsb::fabric.get(t1, t2).dependants();
for (auto i : deps) {
cout << " - " << *i << std::endl;
}
}
}
void command_details(const vector<string> &e) {
if (e.size() == 3) {
Nid t1 = Nid::from_string(e[1]);
Nid t2 = Nid::from_string(e[2]);
Harc &h = fdsb::fabric.get(t1, t2);
cout << " tail: " << t1 << ", " << t2 << std::endl;
cout << " significance: " << h.significance() << std::endl;
if (h.check_flag(Harc::Flag::defined)) {
cout << " definition: ";
cout << h.definition()->to_string() << std::endl;
} else {
cout << " value: " << h.query() << std::endl;
}
cout << " last query: " << h.last_query() << "s" << std::endl;
} else {
cout << " Details command expects 2 arguments." << std::endl;
}
}
/* ========================================================================== */
/*
* Map command words to associated command function for processing.
*/
map<string, void (*)(const vector<string>&)> commands = {
{ "%query", command_query },
{ "%define", command_define },
{ "%partners", command_partners },
{ "%path", command_path },
{ "%array", command_array },
{ "%dependants", command_dependants },
{ "%details", command_details }
// %string
// %sigpath
// %dependants
// %dependencies
// %definition
};
Nid parse_dsbscript(const vector<string> &tokens) {
Nid cur = Nid::from_string(tokens[0]);
Nid other;
Nid old;
for (int i = 1; i < static_cast<int>(tokens.size()); ++i) {
if (tokens[i] == "=") {
if (tokens[i+1] == "{") {
++i;
fdsb::fabric.get(old, other).define(
build_path(tokens, ++i));
++i;
cur = old;
} else {
fdsb::fabric.get(old, other).define(
Nid::from_string(tokens[++i]));
cur = old;
}
} else {
old = cur;
other = Nid::from_string(tokens[i]);
cur = fdsb::fabric.get(old, other).query();
}
}
return cur;
}
/*
* Read command line entries when in interactive mode and pass to relevant
* command function for processing.
*/
void interactive() {
std::cout << "F-DSB Interactive Mode:" << std::endl;
while (true) {
string line;
std::cout << "> ";
std::cout.flush();
std::getline(std::cin, line);
if (line.size() == 0) continue;
vector<string> elems = split(line, ' ');
if (elems[0] == "%exit") return;
if (elems[0][0] == '%') {
auto it = commands.find(elems[0]);
if (it != commands.end()) {
it->second(elems);
} else {
std::cout << " Unrecognised command: " << elems[0] << std::endl;
}
} else {
cout << " " << parse_dsbscript(elems) << std::endl;
}
}
}
int main(int argc, char *argv[]) {
int i = 1;
bool is_i = false;
while (i < argc) {
if (argv[i][0] == '-') {
switch (argv[i][1]) {
case 'i': is_i = true; break;
default:
cout << "Unrecognised command line argument." << std::endl;
return -1;
}
}
++i;
}
if (is_i) {
interactive();
}
return 0;
}
<commit_msg>daemon listens on zeromq socket<commit_after>/*
* Copyright 2015 Nicolas Pope
*/
#include <iostream>
#include "zmq.hpp"
using std::cout;
int main(int argc, char *argv[]) {
int i = 1;
// Process command line arguments.
while (i < argc) {
if (argv[i][0] == '-') {
switch (argv[i][1]) {
default:
cout << "Unrecognised command line argument." << std::endl;
return -1;
}
}
++i;
}
zmq::context_t context(1);
zmq::socket_t rpc(context, ZMQ_REP);
rpc.bind("tcp://*:7878");
zmq::pollitem_t items [] = {
{ rpc, 0, ZMQ_POLLIN, 0 }
};
while (true) {
zmq::message_t msg;
zmq::poll(&items[0], 1, -1);
if (items[0].revents & ZMQ_POLLIN) {
rpc.recv(&msg);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright 2012 Joe Hermaszewski. 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 JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "ucpp.hpp"
#include <cassert>
#include <cstdio>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <compiler/terminal_types.hpp>
#include <ucpp/cpp.h>
namespace JoeLang
{
namespace Compiler
{
const long UCPPLexerState::s_LexerFlags = WARN_STANDARD |
WARN_ANNOYING |
WARN_TRIGRAPHS |
WARN_TRIGRAPHS_MORE |
WARN_PRAGMA |
CPLUSPLUS_COMMENTS |
HANDLE_ASSERTIONS |
MACRO_VAARG |
LEXER |
HANDLE_TRIGRAPHS;
std::mutex g_UCPPMutex;
std::unique_ptr<UCPPContext> g_UCPPContext;
void InitializeUCPP()
{
static std::once_flag once_flag;
std::call_once( once_flag, [](){g_UCPPContext.reset(new UCPPContext);} );
}
UCPPContext::UCPPContext()
{
// Lock the ucpp resources
std::unique_lock<std::mutex> lock(g_UCPPMutex);
// Initialize static data
init_cpp();
// Define special macros such as __FILE__
no_special_macros = 0;
// Don't define __STDC_VERSION__
c99_compliant = 0;
// Don't define __STDC_HOSTED__
c99_hosted = -1;
// Initialize the macro table including assertions
init_tables(true);
// Set no include paths
init_include_path(nullptr);
// Emit all dependencies
emit_dependencies = false;
// emit #define macros
emit_defines = false;
// emit assertions
emit_assertions = false;
// don't emit things to a file
emit_output = nullptr;
// no transient characters
transient_characters = nullptr;
}
UCPPContext::~UCPPContext()
{
/*
char filename[] = "testfile";
set_init_filename(filename, false);
int error;
while(!(error = lex(&ls)))
{
std::cout << "File: " << current_filename <<
" Line: " << ls.line <<
" type: " << ls.ctok->type <<
" tok: " << ls.ctok->name << "\n";
}
if( error != CPPERR_EOF )
{
std::cout << "Error lexing: " << error << std::endl;
}
std::fclose(f);
*/
// Lock the ucpp resources
std::unique_lock<std::mutex> lock(g_UCPPMutex);
wipeout();
}
UCPPLexerState::UCPPLexerState( const std::string& source,
const std::string& filename )
{
//
// This file shouldn't be opened by ucpp
//
set_init_filename( filename.c_str(), false );
//
// Initialize the lexer members
//
init_lexer_state( &m_LexerState );
//
// Set the lexer to be a lexer
//
init_lexer_mode( &m_LexerState );
//set_init_buffer( &m_LexerState,
////reinterpret_cast<const unsigned char*>(source.c_str()),
//source.size() );
m_LexerState.flags = s_LexerFlags;
}
UCPPLexerState::~UCPPLexerState()
{
m_LexerState.input_buf = nullptr;
free_lexer_state( &m_LexerState );
}
TerminalType UCPPLexerState::Lex( std::string& string )
{
const static std::map<int, TerminalType> s_TokenMap =
{
{ NONE, TerminalType::WHITESPACE }, // whitespace
{ OPT_NONE, TerminalType::WHITESPACE },
{ NEWLINE, TerminalType::WHITESPACE },
{ COMMENT, TerminalType::COMMENT }, // comment
{ NUMBER, TerminalType::INTEGER_LITERAL }, // number constant
//{ NAME, TerminalType:: // identifier
{ BUNCH, TerminalType::UNKNOWN_CHARACTER }, // non-C characters
{ PRAGMA, TerminalType::UNKNOWN_CHARACTER }, // #pragma directive
{ CONTEXT, TerminalType::UNKNOWN_CHARACTER }, // new file or #line
{ STRING, TerminalType::STRING_LITERAL }, // constant "xxx"
{ CHAR, TerminalType::CHARACTER_LITERAL }, // constant 'xxx'
{ SLASH, TerminalType::DIVIDE }, // /
{ ASSLASH, TerminalType::DIVIDE_EQUALS }, // /=
{ MINUS, TerminalType::MINUS }, // -
{ MMINUS, TerminalType::DECREMENT }, // --
{ ASMINUS, TerminalType::MINUS_EQUALS }, // -=
{ ARROW, TerminalType::ARROW }, // ->
{ PLUS, TerminalType::PLUS }, // +
{ PPLUS, TerminalType::INCREMENT }, // ++
{ ASPLUS, TerminalType::PLUS_EQUALS }, // +=
{ LT, TerminalType::LESS_THAN }, // <
{ LEQ, TerminalType::LESS_THAN_EQUALS }, // <=
{ LSH, TerminalType::LEFT_SHIFT }, // <<
{ ASLSH, TerminalType::LEFT_SHIFT_EQUALS }, // <<=
{ GT, TerminalType::GREATER_THAN }, // >
{ GEQ, TerminalType::GREATER_THAN_EQUALS }, // >=
{ RSH, TerminalType::RIGHT_SHIFT }, // >>
{ ASRSH, TerminalType::RIGHT_SHIFT_EQUALS }, // >>=
{ ASGN, TerminalType::EQUALS }, // =
{ SAME, TerminalType::EQUALITY }, // ==
{ NOT, TerminalType::BITWISE_NOT }, // ~
{ NEQ, TerminalType::NOT_EQUALITY }, // !=
{ AND, TerminalType::AND }, // &
{ LAND, TerminalType::LOGICAL_AND }, // &&
{ ASAND, TerminalType::AND_EQUALS }, // &=
{ OR, TerminalType::INCLUSIVE_OR }, // |
{ LOR, TerminalType::LOGICAL_OR }, // ||
{ ASOR, TerminalType::INCLUSIVE_OR_EQUALS }, // |=
{ PCT, TerminalType::MODULO }, // %
{ ASPCT, TerminalType::MODULO_EQUALS }, // %=
{ STAR, TerminalType::MULTIPLY }, // *
{ ASSTAR, TerminalType::MULTIPLY_EQUALS }, // *=
{ CIRC, TerminalType::EXCLUSIVE_OR }, // ^
{ ASCIRC, TerminalType::EXCLUSIVE_OR_EQUALS }, // ^=
{ LNOT, TerminalType::LOGICAL_NOT }, // !
{ LBRA, TerminalType::OPEN_BRACE }, // {
{ RBRA, TerminalType::CLOSE_BRACE }, // }
{ LBRK, TerminalType::OPEN_SQUARE }, // [
{ RBRK, TerminalType::CLOSE_SQUARE }, // ]
{ LPAR, TerminalType::OPEN_ROUND }, // (
{ RPAR, TerminalType::CLOSE_ROUND }, // )
{ COMMA, TerminalType::COMMA }, // ,
{ QUEST, TerminalType::QUERY }, // ?
{ SEMIC, TerminalType::SEMICOLON }, // ;
{ COLON, TerminalType::COLON }, // :
{ DOT, TerminalType::PERIOD }, // .
{ MDOTS, TerminalType::UNKNOWN_CHARACTER }, // ...
{ SHARP, TerminalType::UNKNOWN_CHARACTER }, // #
{ DSHARP, TerminalType::UNKNOWN_CHARACTER }, // ##
{ UPLUS, TerminalType::PLUS }, // unary +
{ UMINUS, TerminalType::MINUS } // unary -
};
const static std::map<std::string, TerminalType> s_KeywordMap =
{
{ "technique", TerminalType::TECHNIQUE, },
{ "pass", TerminalType::PASS, },
{ "compile", TerminalType::COMPILE, },
{ "pixel_shader", TerminalType::PIXEL_SHADER, },
{ "vertex_shader", TerminalType::VERTEX_SHADER, },
{ "return", TerminalType::RETURN, },
//
// Storage class specifiers
//
{ "static", TerminalType::STATIC, },
{ "extern", TerminalType::EXTERN, },
{ "uniform", TerminalType::UNIFORM, },
{ "varying", TerminalType::VARYING, },
{ "in", TerminalType::IN, },
{ "out", TerminalType::OUT, },
{ "inout", TerminalType::INOUT, },
//
// Type qualifiers
//
{ "const", TerminalType::CONST, },
{ "volatile", TerminalType::VOLATILE, },
{ "inline", TerminalType::INLINE, },
//
// Types
//
{ "void", TerminalType::TYPE_VOID, },
{ "bool", TerminalType::TYPE_BOOL, },
{ "char", TerminalType::TYPE_CHAR, },
{ "short", TerminalType::TYPE_SHORT, },
{ "int", TerminalType::TYPE_INT, },
{ "long", TerminalType::TYPE_LONG, },
{ "float", TerminalType::TYPE_FLOAT, },
{ "float2", TerminalType::TYPE_FLOAT2, },
{ "float3", TerminalType::TYPE_FLOAT3, },
{ "float4", TerminalType::TYPE_FLOAT4, },
{ "double", TerminalType::TYPE_DOUBLE, },
{ "signed", TerminalType::TYPE_SIGNED, },
{ "unsigned", TerminalType::TYPE_UNSIGNED, },
{ "string", TerminalType::TYPE_STRING, },
//
// Constants
//
{ "true", TerminalType::TRUE, },
{ "false", TerminalType::FALSE, }
};
int lex_result = lex( &m_LexerState );
if( lex_result == CPPERR_EOF )
return TerminalType::END_OF_INPUT;
assert( lex_result == 0 && "Error lexing" );
string = m_LexerState.ctok->name;
int ucpp_token = m_LexerState.ctok->type;
//
// If we have an identifier check to see if it's a keyword
//
if( ucpp_token == NAME )
{
auto k = s_KeywordMap.find( string );
if( k != s_KeywordMap.end() )
return k->second;
return TerminalType::IDENTIFIER;
}
//
// If we have a number we need to know if it's floating point
//
if( ucpp_token == NUMBER )
{
if( ReadFloatingLiteral( string.begin(), string.end() ) ==
string.end() - string.begin() )
return TerminalType::FLOATING_LITERAL;
return TerminalType::INTEGER_LITERAL;
}
assert( s_TokenMap.find( ucpp_token ) != s_TokenMap.end() &&
"Unknown token from ucpp" );
return s_TokenMap.at( ucpp_token );
}
unsigned UCPPLexerState::GetLineNumber()
{
return m_LexerState.line;
}
} // namespace Compiler
} // namespace JoeLang
<commit_msg>[~] Actually setting the source buffer<commit_after>/*
Copyright 2012 Joe Hermaszewski. 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 JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "ucpp.hpp"
#include <cassert>
#include <cstdio>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <compiler/terminal_types.hpp>
#include <ucpp/cpp.h>
namespace JoeLang
{
namespace Compiler
{
const long UCPPLexerState::s_LexerFlags = WARN_STANDARD |
WARN_ANNOYING |
WARN_TRIGRAPHS |
WARN_TRIGRAPHS_MORE |
WARN_PRAGMA |
CPLUSPLUS_COMMENTS |
HANDLE_ASSERTIONS |
MACRO_VAARG |
LEXER |
HANDLE_TRIGRAPHS;
std::mutex g_UCPPMutex;
std::unique_ptr<UCPPContext> g_UCPPContext;
void InitializeUCPP()
{
static std::once_flag once_flag;
std::call_once( once_flag, [](){g_UCPPContext.reset(new UCPPContext);} );
}
UCPPContext::UCPPContext()
{
// Lock the ucpp resources
std::unique_lock<std::mutex> lock(g_UCPPMutex);
// Initialize static data
init_cpp();
// Define special macros such as __FILE__
no_special_macros = 0;
// Don't define __STDC_VERSION__
c99_compliant = 0;
// Don't define __STDC_HOSTED__
c99_hosted = -1;
// Initialize the macro table including assertions
init_tables(true);
// Set no include paths
init_include_path(nullptr);
// Emit all dependencies
emit_dependencies = false;
// emit #define macros
emit_defines = false;
// emit assertions
emit_assertions = false;
// don't emit things to a file
emit_output = nullptr;
// no transient characters
transient_characters = nullptr;
}
UCPPContext::~UCPPContext()
{
/*
char filename[] = "testfile";
set_init_filename(filename, false);
int error;
while(!(error = lex(&ls)))
{
std::cout << "File: " << current_filename <<
" Line: " << ls.line <<
" type: " << ls.ctok->type <<
" tok: " << ls.ctok->name << "\n";
}
if( error != CPPERR_EOF )
{
std::cout << "Error lexing: " << error << std::endl;
}
std::fclose(f);
*/
// Lock the ucpp resources
std::unique_lock<std::mutex> lock(g_UCPPMutex);
wipeout();
}
UCPPLexerState::UCPPLexerState( const std::string& source,
const std::string& filename )
{
//
// This file shouldn't be opened by ucpp
//
set_init_filename( filename.c_str(), false );
//
// Initialize the lexer members
//
init_lexer_state( &m_LexerState );
//
// Set the lexer to be a lexer
//
init_lexer_mode( &m_LexerState );
set_init_buffer( &m_LexerState,
reinterpret_cast<const unsigned char*>(source.c_str()),
source.size() );
m_LexerState.flags = s_LexerFlags;
}
UCPPLexerState::~UCPPLexerState()
{
m_LexerState.input_buf = nullptr;
free_lexer_state( &m_LexerState );
}
TerminalType UCPPLexerState::Lex( std::string& string )
{
const static std::map<int, TerminalType> s_TokenMap =
{
{ NONE, TerminalType::WHITESPACE }, // whitespace
{ OPT_NONE, TerminalType::WHITESPACE },
{ NEWLINE, TerminalType::WHITESPACE },
{ COMMENT, TerminalType::COMMENT }, // comment
{ NUMBER, TerminalType::INTEGER_LITERAL }, // number constant
//{ NAME, TerminalType:: // identifier
{ BUNCH, TerminalType::UNKNOWN_CHARACTER }, // non-C characters
{ PRAGMA, TerminalType::UNKNOWN_CHARACTER }, // #pragma directive
{ CONTEXT, TerminalType::UNKNOWN_CHARACTER }, // new file or #line
{ STRING, TerminalType::STRING_LITERAL }, // constant "xxx"
{ CHAR, TerminalType::CHARACTER_LITERAL }, // constant 'xxx'
{ SLASH, TerminalType::DIVIDE }, // /
{ ASSLASH, TerminalType::DIVIDE_EQUALS }, // /=
{ MINUS, TerminalType::MINUS }, // -
{ MMINUS, TerminalType::DECREMENT }, // --
{ ASMINUS, TerminalType::MINUS_EQUALS }, // -=
{ ARROW, TerminalType::ARROW }, // ->
{ PLUS, TerminalType::PLUS }, // +
{ PPLUS, TerminalType::INCREMENT }, // ++
{ ASPLUS, TerminalType::PLUS_EQUALS }, // +=
{ LT, TerminalType::LESS_THAN }, // <
{ LEQ, TerminalType::LESS_THAN_EQUALS }, // <=
{ LSH, TerminalType::LEFT_SHIFT }, // <<
{ ASLSH, TerminalType::LEFT_SHIFT_EQUALS }, // <<=
{ GT, TerminalType::GREATER_THAN }, // >
{ GEQ, TerminalType::GREATER_THAN_EQUALS }, // >=
{ RSH, TerminalType::RIGHT_SHIFT }, // >>
{ ASRSH, TerminalType::RIGHT_SHIFT_EQUALS }, // >>=
{ ASGN, TerminalType::EQUALS }, // =
{ SAME, TerminalType::EQUALITY }, // ==
{ NOT, TerminalType::BITWISE_NOT }, // ~
{ NEQ, TerminalType::NOT_EQUALITY }, // !=
{ AND, TerminalType::AND }, // &
{ LAND, TerminalType::LOGICAL_AND }, // &&
{ ASAND, TerminalType::AND_EQUALS }, // &=
{ OR, TerminalType::INCLUSIVE_OR }, // |
{ LOR, TerminalType::LOGICAL_OR }, // ||
{ ASOR, TerminalType::INCLUSIVE_OR_EQUALS }, // |=
{ PCT, TerminalType::MODULO }, // %
{ ASPCT, TerminalType::MODULO_EQUALS }, // %=
{ STAR, TerminalType::MULTIPLY }, // *
{ ASSTAR, TerminalType::MULTIPLY_EQUALS }, // *=
{ CIRC, TerminalType::EXCLUSIVE_OR }, // ^
{ ASCIRC, TerminalType::EXCLUSIVE_OR_EQUALS }, // ^=
{ LNOT, TerminalType::LOGICAL_NOT }, // !
{ LBRA, TerminalType::OPEN_BRACE }, // {
{ RBRA, TerminalType::CLOSE_BRACE }, // }
{ LBRK, TerminalType::OPEN_SQUARE }, // [
{ RBRK, TerminalType::CLOSE_SQUARE }, // ]
{ LPAR, TerminalType::OPEN_ROUND }, // (
{ RPAR, TerminalType::CLOSE_ROUND }, // )
{ COMMA, TerminalType::COMMA }, // ,
{ QUEST, TerminalType::QUERY }, // ?
{ SEMIC, TerminalType::SEMICOLON }, // ;
{ COLON, TerminalType::COLON }, // :
{ DOT, TerminalType::PERIOD }, // .
{ MDOTS, TerminalType::UNKNOWN_CHARACTER }, // ...
{ SHARP, TerminalType::UNKNOWN_CHARACTER }, // #
{ DSHARP, TerminalType::UNKNOWN_CHARACTER }, // ##
{ UPLUS, TerminalType::PLUS }, // unary +
{ UMINUS, TerminalType::MINUS } // unary -
};
const static std::map<std::string, TerminalType> s_KeywordMap =
{
{ "technique", TerminalType::TECHNIQUE, },
{ "pass", TerminalType::PASS, },
{ "compile", TerminalType::COMPILE, },
{ "pixel_shader", TerminalType::PIXEL_SHADER, },
{ "vertex_shader", TerminalType::VERTEX_SHADER, },
{ "return", TerminalType::RETURN, },
//
// Storage class specifiers
//
{ "static", TerminalType::STATIC, },
{ "extern", TerminalType::EXTERN, },
{ "uniform", TerminalType::UNIFORM, },
{ "varying", TerminalType::VARYING, },
{ "in", TerminalType::IN, },
{ "out", TerminalType::OUT, },
{ "inout", TerminalType::INOUT, },
//
// Type qualifiers
//
{ "const", TerminalType::CONST, },
{ "volatile", TerminalType::VOLATILE, },
{ "inline", TerminalType::INLINE, },
//
// Types
//
{ "void", TerminalType::TYPE_VOID, },
{ "bool", TerminalType::TYPE_BOOL, },
{ "char", TerminalType::TYPE_CHAR, },
{ "short", TerminalType::TYPE_SHORT, },
{ "int", TerminalType::TYPE_INT, },
{ "long", TerminalType::TYPE_LONG, },
{ "float", TerminalType::TYPE_FLOAT, },
{ "float2", TerminalType::TYPE_FLOAT2, },
{ "float3", TerminalType::TYPE_FLOAT3, },
{ "float4", TerminalType::TYPE_FLOAT4, },
{ "double", TerminalType::TYPE_DOUBLE, },
{ "signed", TerminalType::TYPE_SIGNED, },
{ "unsigned", TerminalType::TYPE_UNSIGNED, },
{ "string", TerminalType::TYPE_STRING, },
//
// Constants
//
{ "true", TerminalType::TRUE, },
{ "false", TerminalType::FALSE, }
};
int lex_result = lex( &m_LexerState );
if( lex_result == CPPERR_EOF )
return TerminalType::END_OF_INPUT;
assert( lex_result == 0 && "Error lexing" );
string = m_LexerState.ctok->name;
int ucpp_token = m_LexerState.ctok->type;
//
// If we have an identifier check to see if it's a keyword
//
if( ucpp_token == NAME )
{
auto k = s_KeywordMap.find( string );
if( k != s_KeywordMap.end() )
return k->second;
return TerminalType::IDENTIFIER;
}
//
// If we have a number we need to know if it's floating point
//
if( ucpp_token == NUMBER )
{
if( ReadFloatingLiteral( string.begin(), string.end() ) ==
string.end() - string.begin() )
return TerminalType::FLOATING_LITERAL;
return TerminalType::INTEGER_LITERAL;
}
assert( s_TokenMap.find( ucpp_token ) != s_TokenMap.end() &&
"Unknown token from ucpp" );
return s_TokenMap.at( ucpp_token );
}
unsigned UCPPLexerState::GetLineNumber()
{
return m_LexerState.line;
}
} // namespace Compiler
} // namespace JoeLang
<|endoftext|>
|
<commit_before>#include "ostree.h"
#include <stdio.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include "logger.h"
#include <gio/gio.h>
OstreeSysroot *Ostree::LoadSysroot(const std::string &path) {
OstreeSysroot *sysroot = NULL;
if (path.size()) {
sysroot = ostree_sysroot_new(g_file_new_for_path(path.c_str()));
} else {
sysroot = ostree_sysroot_new_default();
}
GCancellable *cancellable = NULL;
GError *error = NULL;
if (!ostree_sysroot_load(sysroot, cancellable, &error)) {
g_error_free (error);
throw std::runtime_error("could not load sysroot");
}
return sysroot;
}
OstreeDeployment *Ostree::getStagedDeployment(const std::string &path) {
OstreeSysroot *sysroot = Ostree::LoadSysroot(path);
GPtrArray *deployments = NULL;
OstreeDeployment *res = NULL;
deployments = ostree_sysroot_get_deployments(sysroot);
if (deployments->len == 0) {
res = NULL;
} else {
OstreeDeployment *d = static_cast<OstreeDeployment *>(deployments->pdata[0]);
res = static_cast<OstreeDeployment *>(g_object_ref(d));
}
g_ptr_array_unref(deployments);
return res;
}
bool Ostree::addRemote(OstreeRepo *repo, const std::string &remote, const std::string &url,
const data::PackageManagerCredentials &cred) {
GCancellable *cancellable = NULL;
GError *error = NULL;
GVariantBuilder b;
GVariant *options;
g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&b, "{s@v}", "gpg-verify", g_variant_new_variant(g_variant_new_boolean(FALSE)));
if (cred.cert_file.size() && cred.pkey_file.size() && cred.ca_file.size()) {
g_variant_builder_add(&b, "{s@v}", "tls-client-cert-path",
g_variant_new_variant(g_variant_new_string(cred.cert_file.c_str())));
g_variant_builder_add(&b, "{s@v}", "tls-client-key-path",
g_variant_new_variant(g_variant_new_string(cred.pkey_file.c_str())));
g_variant_builder_add(&b, "{s@v}", "tls-ca-path",
g_variant_new_variant(g_variant_new_string(cred.ca_file.c_str())));
}
options = g_variant_builder_end(&b);
if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_DELETE_IF_EXISTS, remote.c_str(), url.c_str(),
options, cancellable, &error)) {
LOGGER_LOG(LVL_error, "Error of adding remote: " << error->message);
g_error_free (error);
return false;
}
if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS, remote.c_str(), url.c_str(),
options, cancellable, &error)) {
LOGGER_LOG(LVL_error, "Error of adding remote: " << error->message);
g_error_free (error);
return false;
}
return true;
}
#include "ostree-1/ostree.h"
OstreePackage::OstreePackage(const std::string &ecu_serial_in, const std::string &ref_name_in,
const std::string &desc_in, const std::string &treehub_in)
: ecu_serial(ecu_serial_in), ref_name(ref_name_in), description(desc_in), pull_uri(treehub_in) {
std::size_t pos = ref_name.find_last_of("-");
branch_name = ref_name.substr(0, pos);
refhash = ref_name.substr(pos + 1, std::string::npos);
if (branch_name.empty() || refhash.empty()) throw std::runtime_error("malformed OSTree target name: " + ref_name);
}
data::InstallOutcome OstreePackage::install(const data::PackageManagerCredentials &cred, OstreeConfig config) {
const char remote[] = "aktualizr-remote";
const char *const refs[] = {branch_name.c_str()};
const char *const commit_ids[] = {refhash.c_str()};
const char *opt_osname = NULL;
OstreeRepo *repo = NULL;
GCancellable *cancellable = NULL;
GError *error = NULL;
char *revision;
GVariantBuilder builder;
GVariant *options;
if (config.os.size()) {
opt_osname = config.os.c_str();
}
OstreeSysroot *sysroot = Ostree::LoadSysroot(config.sysroot);
if (!ostree_sysroot_get_repo(sysroot, &repo, cancellable, &error)) {
LOGGER_LOG(LVL_error, "could not get repo");
g_error_free (error);
return data::InstallOutcome(data::INSTALL_FAILED, "could not get repo");
}
if (!Ostree::addRemote(repo, remote, pull_uri, cred)) {
return data::InstallOutcome(data::INSTALL_FAILED, "Error of adding remote");
}
g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&builder, "{s@v}", "flags", g_variant_new_variant(g_variant_new_int32(0)));
g_variant_builder_add(&builder, "{s@v}", "refs", g_variant_new_variant(g_variant_new_strv(refs, 1)));
g_variant_builder_add(&builder, "{s@v}", "override-commit-ids",
g_variant_new_variant(g_variant_new_strv(commit_ids, 1)));
if (cred.access_token.size()) {
GVariantBuilder hdr_builder;
std::string av("Bearer ");
av += cred.access_token;
g_variant_builder_init(&hdr_builder, G_VARIANT_TYPE("a(ss)"));
g_variant_builder_add(&hdr_builder, "(ss)", "Authorization", av.c_str());
g_variant_builder_add(&builder, "{s@v}", "http-headers",
g_variant_new_variant(g_variant_builder_end(&hdr_builder)));
}
options = g_variant_ref_sink(g_variant_builder_end(&builder));
if (!ostree_repo_pull_with_options(repo, remote, options, NULL, cancellable, &error)) {
LOGGER_LOG(LVL_error, "Error of pulling image: " << error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free (error);
return install_outcome;
}
GKeyFile *origin = ostree_sysroot_origin_new_from_refspec(sysroot, branch_name.c_str());
if (!ostree_repo_resolve_rev(repo, refhash.c_str(), FALSE, &revision, &error)) {
LOGGER_LOG(LVL_error, error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free (error);
return install_outcome;
}
OstreeDeployment *merge_deployment = ostree_sysroot_get_merge_deployment(sysroot, opt_osname);
if (merge_deployment == NULL) {
LOGGER_LOG(LVL_error, "No merge deployment");
return data::InstallOutcome(data::INSTALL_FAILED, "No merge deployment");
}
if (!ostree_sysroot_prepare_cleanup(sysroot, cancellable, &error)) {
LOGGER_LOG(LVL_error, error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free (error);
return install_outcome;
}
std::ifstream args_stream("/proc/cmdline");
std::string args_content((std::istreambuf_iterator<char>(args_stream)), std::istreambuf_iterator<char>());
std::vector<std::string> args_vector;
boost::split(args_vector, args_content, boost::is_any_of(" "));
std::vector<const char *> kargs_strv_vector;
kargs_strv_vector.reserve(args_vector.size() + 1);
for (std::vector<std::string>::iterator it = args_vector.begin(); it != args_vector.end(); ++it) {
kargs_strv_vector.push_back((*it).c_str());
}
kargs_strv_vector[args_vector.size()] = 0;
GStrv kargs_strv = const_cast<char **>(&kargs_strv_vector[0]);
OstreeDeployment *new_deployment = NULL;
if (!ostree_sysroot_deploy_tree(sysroot, opt_osname, revision, origin, merge_deployment, kargs_strv, &new_deployment,
cancellable, &error)) {
LOGGER_LOG(LVL_error, "ostree_sysroot_deploy_tree: " << error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free (error);
return install_outcome;
}
if (!ostree_sysroot_simple_write_deployment(sysroot, "", new_deployment, merge_deployment,
OSTREE_SYSROOT_SIMPLE_WRITE_DEPLOYMENT_FLAGS_RETAIN, cancellable,
&error)) {
LOGGER_LOG(LVL_error, "ostree_sysroot_simple_write_deployment:" << error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free (error);
return install_outcome;
}
return data::InstallOutcome(data::OK, "Installation succesfull");
}
OstreeBranch OstreeBranch::getCurrent(const std::string &ecu_serial, const std::string &ostree_sysroot) {
OstreeDeployment *staged_deployment = Ostree::getStagedDeployment(ostree_sysroot);
GKeyFile *origin = ostree_deployment_get_origin(staged_deployment);
const char *ref = ostree_deployment_get_csum(staged_deployment);
char *origin_refspec = g_key_file_get_string(origin, "origin", "refspec", NULL);
OstreePackage package(ecu_serial, std::string(origin_refspec) + "-" + ref, origin_refspec, "");
g_free(origin_refspec);
return OstreeBranch(true, ostree_deployment_get_osname(staged_deployment), package);
}
OstreePackage OstreePackage::fromJson(const Json::Value &json) {
return OstreePackage(json["ecu_serial"].asString(), json["ref_name"].asString(), json["description"].asString(),
json["pull_uri"].asString());
}
Json::Value OstreePackage::toEcuVersion(const Json::Value &custom) {
Json::Value installed_image;
installed_image["filepath"] = ref_name;
installed_image["fileinfo"]["length"] = 0;
installed_image["fileinfo"]["hashes"]["sha256"] = refhash;
Json::Value value;
value["attacks_detected"] = "";
value["installed_image"] = installed_image;
value["ecu_serial"] = ecu_serial;
value["previous_timeserver_time"] = "1970-01-01T00:00:00Z";
value["timeserver_time"] = "1970-01-01T00:00:00Z";
if (custom != Json::nullValue) {
value["custom"] = custom;
}
return value;
}
OstreePackage OstreePackage::getEcu(const std::string &ecu_serial, const std::string &ostree_sysroot) {
return OstreeBranch::getCurrent(ecu_serial, ostree_sysroot).package;
}
<commit_msg>Reformat<commit_after>#include "ostree.h"
#include <stdio.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include "logger.h"
#include <gio/gio.h>
OstreeSysroot *Ostree::LoadSysroot(const std::string &path) {
OstreeSysroot *sysroot = NULL;
if (path.size()) {
sysroot = ostree_sysroot_new(g_file_new_for_path(path.c_str()));
} else {
sysroot = ostree_sysroot_new_default();
}
GCancellable *cancellable = NULL;
GError *error = NULL;
if (!ostree_sysroot_load(sysroot, cancellable, &error)) {
g_error_free(error);
throw std::runtime_error("could not load sysroot");
}
return sysroot;
}
OstreeDeployment *Ostree::getStagedDeployment(const std::string &path) {
OstreeSysroot *sysroot = Ostree::LoadSysroot(path);
GPtrArray *deployments = NULL;
OstreeDeployment *res = NULL;
deployments = ostree_sysroot_get_deployments(sysroot);
if (deployments->len == 0) {
res = NULL;
} else {
OstreeDeployment *d = static_cast<OstreeDeployment *>(deployments->pdata[0]);
res = static_cast<OstreeDeployment *>(g_object_ref(d));
}
g_ptr_array_unref(deployments);
return res;
}
bool Ostree::addRemote(OstreeRepo *repo, const std::string &remote, const std::string &url,
const data::PackageManagerCredentials &cred) {
GCancellable *cancellable = NULL;
GError *error = NULL;
GVariantBuilder b;
GVariant *options;
g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&b, "{s@v}", "gpg-verify", g_variant_new_variant(g_variant_new_boolean(FALSE)));
if (cred.cert_file.size() && cred.pkey_file.size() && cred.ca_file.size()) {
g_variant_builder_add(&b, "{s@v}", "tls-client-cert-path",
g_variant_new_variant(g_variant_new_string(cred.cert_file.c_str())));
g_variant_builder_add(&b, "{s@v}", "tls-client-key-path",
g_variant_new_variant(g_variant_new_string(cred.pkey_file.c_str())));
g_variant_builder_add(&b, "{s@v}", "tls-ca-path",
g_variant_new_variant(g_variant_new_string(cred.ca_file.c_str())));
}
options = g_variant_builder_end(&b);
if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_DELETE_IF_EXISTS, remote.c_str(), url.c_str(),
options, cancellable, &error)) {
LOGGER_LOG(LVL_error, "Error of adding remote: " << error->message);
g_error_free(error);
return false;
}
if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS, remote.c_str(), url.c_str(),
options, cancellable, &error)) {
LOGGER_LOG(LVL_error, "Error of adding remote: " << error->message);
g_error_free(error);
return false;
}
return true;
}
#include "ostree-1/ostree.h"
OstreePackage::OstreePackage(const std::string &ecu_serial_in, const std::string &ref_name_in,
const std::string &desc_in, const std::string &treehub_in)
: ecu_serial(ecu_serial_in), ref_name(ref_name_in), description(desc_in), pull_uri(treehub_in) {
std::size_t pos = ref_name.find_last_of("-");
branch_name = ref_name.substr(0, pos);
refhash = ref_name.substr(pos + 1, std::string::npos);
if (branch_name.empty() || refhash.empty()) throw std::runtime_error("malformed OSTree target name: " + ref_name);
}
data::InstallOutcome OstreePackage::install(const data::PackageManagerCredentials &cred, OstreeConfig config) {
const char remote[] = "aktualizr-remote";
const char *const refs[] = {branch_name.c_str()};
const char *const commit_ids[] = {refhash.c_str()};
const char *opt_osname = NULL;
OstreeRepo *repo = NULL;
GCancellable *cancellable = NULL;
GError *error = NULL;
char *revision;
GVariantBuilder builder;
GVariant *options;
if (config.os.size()) {
opt_osname = config.os.c_str();
}
OstreeSysroot *sysroot = Ostree::LoadSysroot(config.sysroot);
if (!ostree_sysroot_get_repo(sysroot, &repo, cancellable, &error)) {
LOGGER_LOG(LVL_error, "could not get repo");
g_error_free(error);
return data::InstallOutcome(data::INSTALL_FAILED, "could not get repo");
}
if (!Ostree::addRemote(repo, remote, pull_uri, cred)) {
return data::InstallOutcome(data::INSTALL_FAILED, "Error of adding remote");
}
g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&builder, "{s@v}", "flags", g_variant_new_variant(g_variant_new_int32(0)));
g_variant_builder_add(&builder, "{s@v}", "refs", g_variant_new_variant(g_variant_new_strv(refs, 1)));
g_variant_builder_add(&builder, "{s@v}", "override-commit-ids",
g_variant_new_variant(g_variant_new_strv(commit_ids, 1)));
if (cred.access_token.size()) {
GVariantBuilder hdr_builder;
std::string av("Bearer ");
av += cred.access_token;
g_variant_builder_init(&hdr_builder, G_VARIANT_TYPE("a(ss)"));
g_variant_builder_add(&hdr_builder, "(ss)", "Authorization", av.c_str());
g_variant_builder_add(&builder, "{s@v}", "http-headers",
g_variant_new_variant(g_variant_builder_end(&hdr_builder)));
}
options = g_variant_ref_sink(g_variant_builder_end(&builder));
if (!ostree_repo_pull_with_options(repo, remote, options, NULL, cancellable, &error)) {
LOGGER_LOG(LVL_error, "Error of pulling image: " << error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
GKeyFile *origin = ostree_sysroot_origin_new_from_refspec(sysroot, branch_name.c_str());
if (!ostree_repo_resolve_rev(repo, refhash.c_str(), FALSE, &revision, &error)) {
LOGGER_LOG(LVL_error, error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
OstreeDeployment *merge_deployment = ostree_sysroot_get_merge_deployment(sysroot, opt_osname);
if (merge_deployment == NULL) {
LOGGER_LOG(LVL_error, "No merge deployment");
return data::InstallOutcome(data::INSTALL_FAILED, "No merge deployment");
}
if (!ostree_sysroot_prepare_cleanup(sysroot, cancellable, &error)) {
LOGGER_LOG(LVL_error, error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
std::ifstream args_stream("/proc/cmdline");
std::string args_content((std::istreambuf_iterator<char>(args_stream)), std::istreambuf_iterator<char>());
std::vector<std::string> args_vector;
boost::split(args_vector, args_content, boost::is_any_of(" "));
std::vector<const char *> kargs_strv_vector;
kargs_strv_vector.reserve(args_vector.size() + 1);
for (std::vector<std::string>::iterator it = args_vector.begin(); it != args_vector.end(); ++it) {
kargs_strv_vector.push_back((*it).c_str());
}
kargs_strv_vector[args_vector.size()] = 0;
GStrv kargs_strv = const_cast<char **>(&kargs_strv_vector[0]);
OstreeDeployment *new_deployment = NULL;
if (!ostree_sysroot_deploy_tree(sysroot, opt_osname, revision, origin, merge_deployment, kargs_strv, &new_deployment,
cancellable, &error)) {
LOGGER_LOG(LVL_error, "ostree_sysroot_deploy_tree: " << error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
if (!ostree_sysroot_simple_write_deployment(sysroot, "", new_deployment, merge_deployment,
OSTREE_SYSROOT_SIMPLE_WRITE_DEPLOYMENT_FLAGS_RETAIN, cancellable,
&error)) {
LOGGER_LOG(LVL_error, "ostree_sysroot_simple_write_deployment:" << error->message);
data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message);
g_error_free(error);
return install_outcome;
}
return data::InstallOutcome(data::OK, "Installation succesfull");
}
OstreeBranch OstreeBranch::getCurrent(const std::string &ecu_serial, const std::string &ostree_sysroot) {
OstreeDeployment *staged_deployment = Ostree::getStagedDeployment(ostree_sysroot);
GKeyFile *origin = ostree_deployment_get_origin(staged_deployment);
const char *ref = ostree_deployment_get_csum(staged_deployment);
char *origin_refspec = g_key_file_get_string(origin, "origin", "refspec", NULL);
OstreePackage package(ecu_serial, std::string(origin_refspec) + "-" + ref, origin_refspec, "");
g_free(origin_refspec);
return OstreeBranch(true, ostree_deployment_get_osname(staged_deployment), package);
}
OstreePackage OstreePackage::fromJson(const Json::Value &json) {
return OstreePackage(json["ecu_serial"].asString(), json["ref_name"].asString(), json["description"].asString(),
json["pull_uri"].asString());
}
Json::Value OstreePackage::toEcuVersion(const Json::Value &custom) {
Json::Value installed_image;
installed_image["filepath"] = ref_name;
installed_image["fileinfo"]["length"] = 0;
installed_image["fileinfo"]["hashes"]["sha256"] = refhash;
Json::Value value;
value["attacks_detected"] = "";
value["installed_image"] = installed_image;
value["ecu_serial"] = ecu_serial;
value["previous_timeserver_time"] = "1970-01-01T00:00:00Z";
value["timeserver_time"] = "1970-01-01T00:00:00Z";
if (custom != Json::nullValue) {
value["custom"] = custom;
}
return value;
}
OstreePackage OstreePackage::getEcu(const std::string &ecu_serial, const std::string &ostree_sysroot) {
return OstreeBranch::getCurrent(ecu_serial, ostree_sysroot).package;
}
<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------------------
// This file is part of the Lomse library.
// Lomse is copyrighted work (c) 2010-2018. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// For any comment, suggestion or feature request, please contact the manager of
// the project at cecilios@users.sourceforge.net
//---------------------------------------------------------------------------------------
#include "lomse_document_layouter.h"
#include "lomse_graphical_model.h"
#include "lomse_gm_basic.h"
#include "private/lomse_document_p.h"
#include "lomse_layouter.h"
#include "lomse_score_layouter.h"
#include "lomse_calligrapher.h"
namespace lomse
{
//---------------------------------------------------------------------------------------
// DocLayouter implementation
// Main object responsible for laying out a document. It takes care of creating pages,
// adding footers and headers, controlling of margins, available space, page
// numbering, etc. And delegates content layout to ContentLayouter object who, in turn,
// delegates in specialized layouters.
//---------------------------------------------------------------------------------------
DocLayouter::DocLayouter(Document* pDoc, LibraryScope& libraryScope, int constrains,
LUnits width)
: Layouter(libraryScope)
, m_pDoc( pDoc->get_im_root() )
, m_viewWidth(width)
, m_pScoreLayouter(nullptr)
{
m_pStyles = m_pDoc->get_styles();
m_pGModel = LOMSE_NEW GraphicModel();
m_constrains = constrains;
}
//---------------------------------------------------------------------------------------
DocLayouter::~DocLayouter()
{
delete m_pScoreLayouter;
}
//---------------------------------------------------------------------------------------
void DocLayouter::layout_empty_document()
{
GmoBoxDocPage* pPage = create_document_page();
m_pItemMainBox = pPage;
}
//---------------------------------------------------------------------------------------
void DocLayouter::layout_document()
{
int result = k_layout_not_finished;
int numTrials = 0;
while(result == k_layout_not_finished && numTrials < 30)
{
numTrials++;
start_new_page();
result = layout_content();
if (result == k_layout_failed_auto_scale)
{
delete_last_trial();
result = k_layout_not_finished;
}
}
if (result == k_layout_not_finished)
layout_empty_document();
else
fix_document_size();
}
//---------------------------------------------------------------------------------------
void DocLayouter::delete_last_trial()
{
delete m_pScoreLayouter;
delete m_pGModel;
m_result = k_layout_not_finished;
m_pGModel = LOMSE_NEW GraphicModel();
m_pParentLayouter = nullptr;
m_pStyles = nullptr;
m_pItemMainBox = nullptr;
m_pCurLayouter = nullptr;
m_pItem = nullptr;
m_fAddShapesToModel = false;
m_constrains = 0;
m_availableWidth = 0.0f;
m_availableHeight = 0.0f;
m_pScoreLayouter = nullptr;
}
//---------------------------------------------------------------------------------------
GmoBox* DocLayouter::start_new_page()
{
GmoBoxDocPage* pPage = create_document_page();
assign_paper_size_to(pPage);
add_margins_to_page(pPage);
add_headers_to_page(pPage);
add_footers_to_page(pPage);
m_pItemMainBox = pPage;
return pPage;
}
//---------------------------------------------------------------------------------------
GmoBoxDocPage* DocLayouter::create_document_page()
{
GmoBoxDocument* pBoxDoc = m_pGModel->get_root();
GmoBoxDocPage* pPage = pBoxDoc->add_new_page();
return pPage;
}
//---------------------------------------------------------------------------------------
void DocLayouter::assign_paper_size_to(GmoBox* pBox)
{
//width
if (m_constrains & k_infinite_width)
m_availableWidth = LOMSE_INFINITE_LENGTH;
else if (m_constrains & k_use_viewport_width)
{
m_availableWidth = m_viewWidth;
}
else
m_availableWidth = m_pDoc->get_paper_width() / m_pDoc->get_page_content_scale();
//height
m_availableHeight = (m_constrains & k_infinite_height) ? LOMSE_INFINITE_LENGTH
: m_pDoc->get_paper_height() / m_pDoc->get_page_content_scale();
pBox->set_width(m_availableWidth);
pBox->set_height(m_availableHeight);
}
//---------------------------------------------------------------------------------------
void DocLayouter::add_margins_to_page(GmoBoxDocPage* pPage)
{
ImoPageInfo* pInfo = m_pDoc->get_page_info();
LUnits top = pInfo->get_top_margin() / m_pDoc->get_page_content_scale();
LUnits bottom = pInfo->get_bottom_margin() / m_pDoc->get_page_content_scale();
LUnits left = pInfo->get_left_margin() / m_pDoc->get_page_content_scale();
LUnits right = pInfo->get_right_margin() / m_pDoc->get_page_content_scale();
if (pPage->get_number() % 2 == 0)
left += pInfo->get_binding_margin() / m_pDoc->get_page_content_scale();
else
right += pInfo->get_binding_margin() / m_pDoc->get_page_content_scale();
m_pageCursor.x = left;
m_pageCursor.y = top;
m_availableWidth -= (left + right);
m_availableHeight -= (top + bottom);
}
//---------------------------------------------------------------------------------------
void DocLayouter::add_headers_to_page(GmoBoxDocPage* UNUSED(pPage))
{
//TODO: DocLayouter::add_headers_to_page
}
//---------------------------------------------------------------------------------------
void DocLayouter::add_footers_to_page(GmoBoxDocPage* UNUSED(pPage))
{
//TODO: DocLayouter::add_footers_to_page
}
//---------------------------------------------------------------------------------------
void DocLayouter::fix_document_size()
{
if (m_constrains & k_infinite_width)
{
GmoBoxDocPage* pPage = static_cast<GmoBoxDocPage*>(m_pItemMainBox);
GmoBox* pBDPC = pPage->get_child_box(0); //DocPageContent
GmoBox* pBSP = pBDPC->get_child_box(0); //ScorePage
GmoBox* pBSys = pBSP->get_child_box(0); //System
//View height and width are determined by BoxSystem.
//To set page width it is necessary to fix width in BoxDocPage, BoxDocPageContent
//and BoxScorePage.
//To set page height it is only necessary to fix height in BoxDocPage.
//BoxSystem does not exist when error "not enough space in page"
if (pBSys)
{
LUnits width = pBSys->get_size().width + pBSys->get_origin().x;
pBSys->set_width(width);
pBSP->set_width(width);
pBDPC->set_width(width);
width += pBSP->get_origin().x;
pPage->set_width(width);
LUnits height = pBSys->get_size().height + pBSys->get_origin().y;
ImoPageInfo* pInfo = m_pDoc->get_page_info();
height += pInfo->get_bottom_margin() / m_pDoc->get_page_content_scale();
pPage->set_height(height);
}
else
{
//an arbitrary with
LUnits width = 21000.0f;
pBSP->set_width(width);
pBDPC->set_width(width);
width += pBSP->get_origin().x;
pPage->set_width(width);
//height determined by BoxDocPageContent
LUnits height = pBDPC->get_size().height + 2.0f * pBDPC->get_origin().y;
pPage->set_height(height);
}
}
if (m_constrains & k_infinite_height)
{
//TODO: free flow view
}
}
//---------------------------------------------------------------------------------------
int DocLayouter::layout_content()
{
return layout_item(m_pDoc->get_content(), m_pItemMainBox, m_constrains);
}
//---------------------------------------------------------------------------------------
void DocLayouter::save_score_layouter(Layouter* pLayouter)
{
delete m_pScoreLayouter;
m_pScoreLayouter = pLayouter;
}
//---------------------------------------------------------------------------------------
ScoreLayouter* DocLayouter::get_score_layouter()
{
return dynamic_cast<ScoreLayouter*>( m_pScoreLayouter );
}
} //namespace lomse
<commit_msg>Fix page height in ‘single page’ and ‘free flow’ views<commit_after>//---------------------------------------------------------------------------------------
// This file is part of the Lomse library.
// Lomse is copyrighted work (c) 2010-2020. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// For any comment, suggestion or feature request, please contact the manager of
// the project at cecilios@users.sourceforge.net
//---------------------------------------------------------------------------------------
#include "lomse_document_layouter.h"
#include "lomse_graphical_model.h"
#include "lomse_gm_basic.h"
#include "private/lomse_document_p.h"
#include "lomse_layouter.h"
#include "lomse_score_layouter.h"
#include "lomse_calligrapher.h"
#include "lomse_box_system.h"
namespace lomse
{
//---------------------------------------------------------------------------------------
// DocLayouter implementation
// Main object responsible for laying out a document. It takes care of creating pages,
// adding footers and headers, controlling of margins, available space, page
// numbering, etc. And delegates content layout to ContentLayouter object who, in turn,
// delegates in specialized layouters.
//---------------------------------------------------------------------------------------
DocLayouter::DocLayouter(Document* pDoc, LibraryScope& libraryScope, int constrains,
LUnits width)
: Layouter(libraryScope)
, m_pDoc( pDoc->get_im_root() )
, m_viewWidth(width)
, m_pScoreLayouter(nullptr)
{
m_pStyles = m_pDoc->get_styles();
m_pGModel = LOMSE_NEW GraphicModel();
m_constrains = constrains;
}
//---------------------------------------------------------------------------------------
DocLayouter::~DocLayouter()
{
delete m_pScoreLayouter;
}
//---------------------------------------------------------------------------------------
void DocLayouter::layout_empty_document()
{
GmoBoxDocPage* pPage = create_document_page();
m_pItemMainBox = pPage;
}
//---------------------------------------------------------------------------------------
void DocLayouter::layout_document()
{
int result = k_layout_not_finished;
int numTrials = 0;
while(result == k_layout_not_finished && numTrials < 30)
{
numTrials++;
start_new_page();
result = layout_content();
if (result == k_layout_failed_auto_scale)
{
delete_last_trial();
result = k_layout_not_finished;
}
}
if (result == k_layout_not_finished)
layout_empty_document();
else
fix_document_size();
}
//---------------------------------------------------------------------------------------
void DocLayouter::delete_last_trial()
{
delete m_pScoreLayouter;
delete m_pGModel;
m_result = k_layout_not_finished;
m_pGModel = LOMSE_NEW GraphicModel();
m_pParentLayouter = nullptr;
m_pStyles = nullptr;
m_pItemMainBox = nullptr;
m_pCurLayouter = nullptr;
m_pItem = nullptr;
m_fAddShapesToModel = false;
m_constrains = 0;
m_availableWidth = 0.0f;
m_availableHeight = 0.0f;
m_pScoreLayouter = nullptr;
}
//---------------------------------------------------------------------------------------
GmoBox* DocLayouter::start_new_page()
{
GmoBoxDocPage* pPage = create_document_page();
assign_paper_size_to(pPage);
add_margins_to_page(pPage);
add_headers_to_page(pPage);
add_footers_to_page(pPage);
m_pItemMainBox = pPage;
return pPage;
}
//---------------------------------------------------------------------------------------
GmoBoxDocPage* DocLayouter::create_document_page()
{
GmoBoxDocument* pBoxDoc = m_pGModel->get_root();
GmoBoxDocPage* pPage = pBoxDoc->add_new_page();
return pPage;
}
//---------------------------------------------------------------------------------------
void DocLayouter::assign_paper_size_to(GmoBox* pBox)
{
//width
if (m_constrains & k_infinite_width)
m_availableWidth = LOMSE_INFINITE_LENGTH;
else if (m_constrains & k_use_viewport_width)
{
m_availableWidth = m_viewWidth;
}
else
m_availableWidth = m_pDoc->get_paper_width() / m_pDoc->get_page_content_scale();
//height
m_availableHeight = (m_constrains & k_infinite_height) ? LOMSE_INFINITE_LENGTH
: m_pDoc->get_paper_height() / m_pDoc->get_page_content_scale();
pBox->set_width(m_availableWidth);
pBox->set_height(m_availableHeight);
}
//---------------------------------------------------------------------------------------
void DocLayouter::add_margins_to_page(GmoBoxDocPage* pPage)
{
ImoPageInfo* pInfo = m_pDoc->get_page_info();
LUnits top = pInfo->get_top_margin() / m_pDoc->get_page_content_scale();
LUnits bottom = pInfo->get_bottom_margin() / m_pDoc->get_page_content_scale();
LUnits left = pInfo->get_left_margin() / m_pDoc->get_page_content_scale();
LUnits right = pInfo->get_right_margin() / m_pDoc->get_page_content_scale();
if (pPage->get_number() % 2 == 0)
left += pInfo->get_binding_margin() / m_pDoc->get_page_content_scale();
else
right += pInfo->get_binding_margin() / m_pDoc->get_page_content_scale();
m_pageCursor.x = left;
m_pageCursor.y = top;
m_availableWidth -= (left + right);
m_availableHeight -= (top + bottom);
}
//---------------------------------------------------------------------------------------
void DocLayouter::add_headers_to_page(GmoBoxDocPage* UNUSED(pPage))
{
//TODO: DocLayouter::add_headers_to_page
}
//---------------------------------------------------------------------------------------
void DocLayouter::add_footers_to_page(GmoBoxDocPage* UNUSED(pPage))
{
//TODO: DocLayouter::add_footers_to_page
}
//---------------------------------------------------------------------------------------
void DocLayouter::fix_document_size()
{
if (m_constrains & k_infinite_width)
{
GmoBoxDocPage* pPage = static_cast<GmoBoxDocPage*>(m_pItemMainBox);
GmoBox* pBDPC = pPage->get_child_box(0); //DocPageContent
GmoBox* pBSP = pBDPC->get_child_box(0); //ScorePage
GmoBox* pBSys = pBSP->get_child_box(0); //System
//View height and width are determined by BoxSystem.
//To set page width it is necessary to fix width in BoxDocPage, BoxDocPageContent
//and BoxScorePage.
//To set page height it is only necessary to fix height in BoxDocPage.
//BoxSystem does not exist when error "not enough space in page"
if (pBSys)
{
LUnits width = pBSys->get_size().width + pBSys->get_origin().x;
pBSys->set_width(width);
pBSP->set_width(width);
pBDPC->set_width(width);
width += pBSP->get_origin().x;
pPage->set_width(width);
LUnits height = pBSys->get_size().height + pBSys->get_origin().y;
ImoPageInfo* pInfo = m_pDoc->get_page_info();
height += pInfo->get_bottom_margin() / m_pDoc->get_page_content_scale();
pPage->set_height(height);
}
else
{
//an arbitrary with
LUnits width = 21000.0f;
pBSP->set_width(width);
pBDPC->set_width(width);
width += pBSP->get_origin().x;
pPage->set_width(width);
//height determined by BoxDocPageContent
LUnits height = pBDPC->get_size().height + 2.0f * pBDPC->get_origin().y;
pPage->set_height(height);
}
}
if (m_constrains & k_infinite_height)
{
//free flow view, single page view
//height determined by BoxDocPageContent
GmoBoxDocPage* pPage = static_cast<GmoBoxDocPage*>(m_pItemMainBox);
GmoBox* pBDPC = pPage->get_child_box(0); //DocPageContent
LUnits height = pBDPC->get_size().height + 2.0f * pBDPC->get_origin().y;
pPage->set_height(height);
}
}
//---------------------------------------------------------------------------------------
int DocLayouter::layout_content()
{
return layout_item(m_pDoc->get_content(), m_pItemMainBox, m_constrains);
}
//---------------------------------------------------------------------------------------
void DocLayouter::save_score_layouter(Layouter* pLayouter)
{
delete m_pScoreLayouter;
m_pScoreLayouter = pLayouter;
}
//---------------------------------------------------------------------------------------
ScoreLayouter* DocLayouter::get_score_layouter()
{
return dynamic_cast<ScoreLayouter*>( m_pScoreLayouter );
}
} //namespace lomse
<|endoftext|>
|
<commit_before>/****************************************************************************
This file is part of the QtMediaHub project on http://www.gitorious.org.
Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.
Contact: Nokia Corporation (qt-info@nokia.com)**
You may use this file under the terms of the BSD license as follows:
"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 Nokia Corporation and its Subsidiary(-ies) 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 "backend.h"
#include "plugins/qmhplugininterface.h"
#include "plugins/qmhplugin.h"
#include "dataproviders/foldermodel.h"
#include "dataproviders/proxymodel.h"
#include <QDir>
#include <QString>
#include <QPluginLoader>
#include <QCoreApplication>
#include <QVariant>
#include <QDebug>
Backend* Backend::pSelf = 0;
struct BackendPrivate
{
BackendPrivate()
:
#ifdef Q_OS_MAC
platformOffset("/../../.."),
#endif
basePath(QCoreApplication::applicationDirPath() + platformOffset),
skinPath(basePath + "/skins"),
pluginPath(basePath + "/plugins"),
resourcePath(basePath + "/resources"),
qmlEngine(0) { /* */ }
QSet<QString> advertizedEngineRoles;
QList<QObject*> advertizedEngines;
const QString platformOffset;
const QString basePath;
const QString skinPath;
const QString pluginPath;
const QString resourcePath;
QDeclarativeEngine *qmlEngine;
};
Backend::Backend(QObject *parent)
: QObject(parent),
d(new BackendPrivate())
{
}
void Backend::initialize(QDeclarativeEngine *qmlEngine)
{
// register dataproviders to QML
qmlRegisterType<FolderModel>("FolderModel", 1, 0, "FolderModel");
qmlRegisterType<QMHPlugin>("QMHPlugin", 1, 0, "QMHPlugin");
qmlRegisterType<ProxyModel>("ProxyModel", 1, 0, "ProxyModel");
qmlRegisterType<ProxyModelItem>("ProxyModel", 1, 0, "ProxyModelItem");
if (qmlEngine) {
//FIXME: We are clearly failing to keep the backend Declarative free :p
d->qmlEngine = qmlEngine;
qmlEngine->rootContext()->setContextProperty("backend", this);
discoverEngines();
}
}
void Backend::discoverEngines()
{
foreach(const QString fileName, QDir(pluginPath()).entryList(QDir::Files)) {
QString qualifiedFileName(pluginPath() + "/" + fileName);
QPluginLoader pluginLoader(qualifiedFileName);
if(pluginLoader.load()
&& qobject_cast<QMHPluginInterface*>(pluginLoader.instance())) {
QMHPlugin *plugin = new QMHPlugin(qobject_cast<QMHPluginInterface*>(pluginLoader.instance()), this);
plugin->setParent(this);
plugin->registerPlugin(d->qmlEngine->rootContext());
advertizeEngine(plugin);
}
else
qDebug() << "Invalid plugin present" << qualifiedFileName << pluginLoader.errorString();
}
}
QList<QObject*> Backend::engines() const
{
return d->advertizedEngines;
}
Backend* Backend::instance()
{
if(!pSelf) {
pSelf = new Backend();
}
return pSelf;
}
QString Backend::skinPath() const {
return d->skinPath;
}
QString Backend::pluginPath() const {
return d->pluginPath;
}
QString Backend::resourcePath() const {
return d->resourcePath;
}
void Backend::advertizeEngine(QMHPlugin *engine) {
QString role = engine->property("role").toString();
if (role.isEmpty())
return;
if (d->advertizedEngineRoles.contains(role)) {
qWarning() << "Duplicate engine found for role " << role;
return;
}
d->advertizedEngines << engine;
if(d->qmlEngine)
d->qmlEngine->rootContext()->setContextProperty(role + "Engine", engine);
d->advertizedEngineRoles << role;
emit enginesChanged();
}
QObject* Backend::engine(const QString &role) {
foreach(QObject *currentEngine, d->advertizedEngines )
if(qobject_cast<QMHPlugin*>(currentEngine)->role() == role)
return currentEngine;
qWarning() << "Seeking a non-existant plugin, prepare to die";
return 0;
}
<commit_msg>Wrap backend strings in tr<commit_after>/****************************************************************************
This file is part of the QtMediaHub project on http://www.gitorious.org.
Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.
Contact: Nokia Corporation (qt-info@nokia.com)**
You may use this file under the terms of the BSD license as follows:
"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 Nokia Corporation and its Subsidiary(-ies) 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 "backend.h"
#include "plugins/qmhplugininterface.h"
#include "plugins/qmhplugin.h"
#include "dataproviders/foldermodel.h"
#include "dataproviders/proxymodel.h"
#include <QDir>
#include <QString>
#include <QPluginLoader>
#include <QCoreApplication>
#include <QVariant>
#include <QDebug>
Backend* Backend::pSelf = 0;
struct BackendPrivate
{
BackendPrivate()
:
#ifdef Q_OS_MAC
platformOffset("/../../.."),
#endif
basePath(QCoreApplication::applicationDirPath() + platformOffset),
skinPath(basePath + "/skins"),
pluginPath(basePath + "/plugins"),
resourcePath(basePath + "/resources"),
qmlEngine(0) { /* */ }
QSet<QString> advertizedEngineRoles;
QList<QObject*> advertizedEngines;
const QString platformOffset;
const QString basePath;
const QString skinPath;
const QString pluginPath;
const QString resourcePath;
QDeclarativeEngine *qmlEngine;
};
Backend::Backend(QObject *parent)
: QObject(parent),
d(new BackendPrivate())
{
}
void Backend::initialize(QDeclarativeEngine *qmlEngine)
{
// register dataproviders to QML
qmlRegisterType<FolderModel>("FolderModel", 1, 0, "FolderModel");
qmlRegisterType<QMHPlugin>("QMHPlugin", 1, 0, "QMHPlugin");
qmlRegisterType<ProxyModel>("ProxyModel", 1, 0, "ProxyModel");
qmlRegisterType<ProxyModelItem>("ProxyModel", 1, 0, "ProxyModelItem");
if (qmlEngine) {
//FIXME: We are clearly failing to keep the backend Declarative free :p
d->qmlEngine = qmlEngine;
qmlEngine->rootContext()->setContextProperty("backend", this);
discoverEngines();
}
}
void Backend::discoverEngines()
{
foreach(const QString fileName, QDir(pluginPath()).entryList(QDir::Files)) {
QString qualifiedFileName(pluginPath() + "/" + fileName);
QPluginLoader pluginLoader(qualifiedFileName);
if(pluginLoader.load()
&& qobject_cast<QMHPluginInterface*>(pluginLoader.instance())) {
QMHPlugin *plugin = new QMHPlugin(qobject_cast<QMHPluginInterface*>(pluginLoader.instance()), this);
plugin->setParent(this);
plugin->registerPlugin(d->qmlEngine->rootContext());
advertizeEngine(plugin);
}
else
qWarning() << tr("Invalid plugin present %1 $2").arg(qualifiedFileName).arg(pluginLoader.errorString());
}
}
QList<QObject*> Backend::engines() const
{
return d->advertizedEngines;
}
Backend* Backend::instance()
{
if(!pSelf) {
pSelf = new Backend();
}
return pSelf;
}
QString Backend::skinPath() const {
return d->skinPath;
}
QString Backend::pluginPath() const {
return d->pluginPath;
}
QString Backend::resourcePath() const {
return d->resourcePath;
}
void Backend::advertizeEngine(QMHPlugin *engine) {
QString role = engine->property("role").toString();
if (role.isEmpty())
return;
if (d->advertizedEngineRoles.contains(role)) {
qWarning() << tr("Duplicate engine found for role %1").arg(role);
return;
}
d->advertizedEngines << engine;
if(d->qmlEngine)
d->qmlEngine->rootContext()->setContextProperty(role + "Engine", engine);
d->advertizedEngineRoles << role;
emit enginesChanged();
}
QObject* Backend::engine(const QString &role) {
foreach(QObject *currentEngine, d->advertizedEngines )
if(qobject_cast<QMHPlugin*>(currentEngine)->role() == role)
return currentEngine;
qWarning() << tr("Seeking a non-existant plugin, prepare to die");
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: lorn.potter@jollamobile.com
**
** 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.
**
****************************************************************************/
#include "dbustypes.h"
#include "qofonomessagemanager.h"
#include "dbus/ofonomessagemanager.h"
class QOfonoMessageManagerPrivate
{
public:
QOfonoMessageManagerPrivate();
QString modemPath;
OfonoMessageManager *messageManager;
QVariantMap properties;
QStringList messageList;
QString errorMessage;
};
QOfonoMessageManagerPrivate::QOfonoMessageManagerPrivate() :
modemPath(QString())
, messageManager(0)
, messageList(QStringList())
{
}
QOfonoMessageManager::QOfonoMessageManager(QObject *parent) :
QObject(parent)
, d_ptr(new QOfonoMessageManagerPrivate)
{
}
QOfonoMessageManager::~QOfonoMessageManager()
{
delete d_ptr;
}
void QOfonoMessageManager::setModemPath(const QString &path)
{
if (path == d_ptr->modemPath ||
path.isEmpty())
return;
if (path != modemPath()) {
if (d_ptr->messageManager) {
delete d_ptr->messageManager;
d_ptr->messageManager = 0;
d_ptr->properties.clear();
}
d_ptr->messageManager = new OfonoMessageManager("org.ofono", path, QDBusConnection::systemBus(),this);
if (d_ptr->messageManager->isValid()) {
d_ptr->modemPath = path;
connect(d_ptr->messageManager,SIGNAL(PropertyChanged(QString,QDBusVariant)),
this,SLOT(propertyChanged(QString,QDBusVariant)));
connect(d_ptr->messageManager,SIGNAL(ImmediateMessage(QString,QVariantMap)),
this,SIGNAL(immediateMessage(QString,QVariantMap)));
connect(d_ptr->messageManager,SIGNAL(IncomingMessage(QString,QVariantMap)),
this,SIGNAL(incomingMessage(QString,QVariantMap)));
QDBusPendingReply<QVariantMap> reply;
reply = d_ptr->messageManager->GetProperties();
reply.waitForFinished();
d_ptr->properties = reply.value();
QDBusMessage request = QDBusMessage::createMethodCall("org.ofono",
path,
"org.ofono.MessageManager",
"GetMessages");
QDBusConnection::systemBus().callWithCallback(request,
this,
SLOT(getMessagesFinished(ObjectPathPropertiesList)),
SLOT(messagesError(QDBusError)));
}
}
}
QString QOfonoMessageManager::modemPath() const
{
return d_ptr->modemPath;
}
void QOfonoMessageManager::propertyChanged(const QString& property, const QDBusVariant& dbusvalue)
{
QVariant value = dbusvalue.variant();
d_ptr->properties.insert(property,value);
if (property == QLatin1String("ServiceCenterAddress")) {
Q_EMIT serviceCenterAddressChanged(value.value<QString>());
} else if (property == QLatin1String("UseDeliveryReports")) {
Q_EMIT useDeliveryReportsChanged(value.value<bool>());
} else if (property == QLatin1String("Bearer")) {
Q_EMIT bearerChanged(value.value<QString>());
} else if (property == QLatin1String("AlphabetChanged")) {
Q_EMIT alphabetChanged(value.value<QString>());
}
}
QString QOfonoMessageManager::serviceCenterAddress()
{
if (d_ptr->messageManager)
return d_ptr->properties["ServiceCenterAddress"].value<QString>();
else
return QString();
}
void QOfonoMessageManager::setServiceCenterAddress(const QString &address)
{
if (d_ptr->messageManager) {
QDBusPendingReply<> result = d_ptr->messageManager->SetProperty("ServiceCenterAddress",QDBusVariant(address));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(setServiceCenterAddressFinished(QDBusPendingCallWatcher*)));
}
}
bool QOfonoMessageManager::useDeliveryReports()
{
if (d_ptr->messageManager)
return d_ptr->properties["UseDeliveryReports"].value<bool>();
else
return false;
}
void QOfonoMessageManager::setUseDeliveryReports(bool useDeliveryReports)
{
if (d_ptr->messageManager) {
QDBusPendingReply<> result = d_ptr->messageManager->SetProperty("UseDeliveryReports",QDBusVariant(useDeliveryReports));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(setUseDeliveryReportsFinished(QDBusPendingCallWatcher*)));
}
}
QString QOfonoMessageManager::bearer()
{
if (d_ptr->messageManager)
return d_ptr->properties["Bearer"].value<QString>();
else
return QString();
}
void QOfonoMessageManager::setBearer(const QString &bearer)
{
if (d_ptr->messageManager) {
QDBusPendingReply<> result = d_ptr->messageManager->SetProperty("Bearer",QDBusVariant(bearer));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(setBearerFinished(QDBusPendingCallWatcher*)));
}
}
QString QOfonoMessageManager::alphabet()
{
if (d_ptr->messageManager)
return d_ptr->properties["Alphabet"].value<QString>();
else
return QString();
}
void QOfonoMessageManager::setAlphabet(const QString &alphabet)
{
if (d_ptr->messageManager) {
QDBusPendingReply<> result = d_ptr->messageManager->SetProperty("Alphabet",QDBusVariant(alphabet));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(setAlphabetFinished(QDBusPendingCallWatcher*)));
}
}
void QOfonoMessageManager::sendMessage(const QString &numberTo, const QString &message)
{
if (d_ptr->messageManager) {
QDBusPendingReply<QDBusObjectPath> result = d_ptr->messageManager->SendMessage(numberTo,message);
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(sendMessageFinished(QDBusPendingCallWatcher*)));
}
}
QStringList QOfonoMessageManager::messages()
{
if (d_ptr->messageManager)
return d_ptr->messageList;
return QStringList();
}
void QOfonoMessageManager::onMessageAdded(const QString &message)
{
if (d_ptr->messageManager) {
if (!d_ptr->messageList.contains(message)) {
d_ptr->messageList.append(message);
}
}
}
void QOfonoMessageManager::onMessageRemoved(const QString &message)
{
if (d_ptr->messageManager) {
if (d_ptr->messageList.contains(message)) {
d_ptr->messageList.removeOne(message);
}
}
}
bool QOfonoMessageManager::isValid() const
{
return d_ptr->messageManager->isValid();
}
void QOfonoMessageManager::getMessagesFinished(const ObjectPathPropertiesList &list)
{
qDebug() << Q_FUNC_INFO << list.count();
// messages = reply2.value();
foreach(ObjectPathProperties message, list) {
d_ptr->messageList << message.path.path();
}
Q_EMIT messagesFinished();
}
void QOfonoMessageManager::messagesError(const QDBusError &error)
{
qDebug() << Q_FUNC_INFO << error.message();
}
void QOfonoMessageManager::sendMessageFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<QDBusObjectPath> reply = *call;
bool ok = true;
if (reply.isError()) {
qWarning() << Q_FUNC_INFO << "failed:" << reply.error();
d_ptr->errorMessage = reply.error().name() + " " + reply.error().message();
ok = false;
}
Q_EMIT sendMessageComplete(ok, reply.value().path());
}
void QOfonoMessageManager::setServiceCenterAddressFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<> reply = *call;
Q_EMIT setServiceCenterAddressComplete(!reply.isError());
call->deleteLater();
}
void QOfonoMessageManager::setUseDeliveryReportsFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<> reply = *call;
Q_EMIT setUseDeliveryReportsComplete(!reply.isError());
call->deleteLater();
}
void QOfonoMessageManager::setBearerFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<> reply = *call;
Q_EMIT setBearerComplete(!reply.isError());
call->deleteLater();
}
void QOfonoMessageManager::setAlphabetFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<> reply = *call;
Q_EMIT setAlphabetComplete(!reply.isError());
call->deleteLater();
}
<commit_msg>QOfonoMessageManager: Fix typo in property name<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: lorn.potter@jollamobile.com
**
** 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.
**
****************************************************************************/
#include "dbustypes.h"
#include "qofonomessagemanager.h"
#include "dbus/ofonomessagemanager.h"
class QOfonoMessageManagerPrivate
{
public:
QOfonoMessageManagerPrivate();
QString modemPath;
OfonoMessageManager *messageManager;
QVariantMap properties;
QStringList messageList;
QString errorMessage;
};
QOfonoMessageManagerPrivate::QOfonoMessageManagerPrivate() :
modemPath(QString())
, messageManager(0)
, messageList(QStringList())
{
}
QOfonoMessageManager::QOfonoMessageManager(QObject *parent) :
QObject(parent)
, d_ptr(new QOfonoMessageManagerPrivate)
{
}
QOfonoMessageManager::~QOfonoMessageManager()
{
delete d_ptr;
}
void QOfonoMessageManager::setModemPath(const QString &path)
{
if (path == d_ptr->modemPath ||
path.isEmpty())
return;
if (path != modemPath()) {
if (d_ptr->messageManager) {
delete d_ptr->messageManager;
d_ptr->messageManager = 0;
d_ptr->properties.clear();
}
d_ptr->messageManager = new OfonoMessageManager("org.ofono", path, QDBusConnection::systemBus(),this);
if (d_ptr->messageManager->isValid()) {
d_ptr->modemPath = path;
connect(d_ptr->messageManager,SIGNAL(PropertyChanged(QString,QDBusVariant)),
this,SLOT(propertyChanged(QString,QDBusVariant)));
connect(d_ptr->messageManager,SIGNAL(ImmediateMessage(QString,QVariantMap)),
this,SIGNAL(immediateMessage(QString,QVariantMap)));
connect(d_ptr->messageManager,SIGNAL(IncomingMessage(QString,QVariantMap)),
this,SIGNAL(incomingMessage(QString,QVariantMap)));
QDBusPendingReply<QVariantMap> reply;
reply = d_ptr->messageManager->GetProperties();
reply.waitForFinished();
d_ptr->properties = reply.value();
QDBusMessage request = QDBusMessage::createMethodCall("org.ofono",
path,
"org.ofono.MessageManager",
"GetMessages");
QDBusConnection::systemBus().callWithCallback(request,
this,
SLOT(getMessagesFinished(ObjectPathPropertiesList)),
SLOT(messagesError(QDBusError)));
}
}
}
QString QOfonoMessageManager::modemPath() const
{
return d_ptr->modemPath;
}
void QOfonoMessageManager::propertyChanged(const QString& property, const QDBusVariant& dbusvalue)
{
QVariant value = dbusvalue.variant();
d_ptr->properties.insert(property,value);
if (property == QLatin1String("ServiceCenterAddress")) {
Q_EMIT serviceCenterAddressChanged(value.value<QString>());
} else if (property == QLatin1String("UseDeliveryReports")) {
Q_EMIT useDeliveryReportsChanged(value.value<bool>());
} else if (property == QLatin1String("Bearer")) {
Q_EMIT bearerChanged(value.value<QString>());
} else if (property == QLatin1String("Alphabet")) {
Q_EMIT alphabetChanged(value.value<QString>());
}
}
QString QOfonoMessageManager::serviceCenterAddress()
{
if (d_ptr->messageManager)
return d_ptr->properties["ServiceCenterAddress"].value<QString>();
else
return QString();
}
void QOfonoMessageManager::setServiceCenterAddress(const QString &address)
{
if (d_ptr->messageManager) {
QDBusPendingReply<> result = d_ptr->messageManager->SetProperty("ServiceCenterAddress",QDBusVariant(address));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(setServiceCenterAddressFinished(QDBusPendingCallWatcher*)));
}
}
bool QOfonoMessageManager::useDeliveryReports()
{
if (d_ptr->messageManager)
return d_ptr->properties["UseDeliveryReports"].value<bool>();
else
return false;
}
void QOfonoMessageManager::setUseDeliveryReports(bool useDeliveryReports)
{
if (d_ptr->messageManager) {
QDBusPendingReply<> result = d_ptr->messageManager->SetProperty("UseDeliveryReports",QDBusVariant(useDeliveryReports));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(setUseDeliveryReportsFinished(QDBusPendingCallWatcher*)));
}
}
QString QOfonoMessageManager::bearer()
{
if (d_ptr->messageManager)
return d_ptr->properties["Bearer"].value<QString>();
else
return QString();
}
void QOfonoMessageManager::setBearer(const QString &bearer)
{
if (d_ptr->messageManager) {
QDBusPendingReply<> result = d_ptr->messageManager->SetProperty("Bearer",QDBusVariant(bearer));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(setBearerFinished(QDBusPendingCallWatcher*)));
}
}
QString QOfonoMessageManager::alphabet()
{
if (d_ptr->messageManager)
return d_ptr->properties["Alphabet"].value<QString>();
else
return QString();
}
void QOfonoMessageManager::setAlphabet(const QString &alphabet)
{
if (d_ptr->messageManager) {
QDBusPendingReply<> result = d_ptr->messageManager->SetProperty("Alphabet",QDBusVariant(alphabet));
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(setAlphabetFinished(QDBusPendingCallWatcher*)));
}
}
void QOfonoMessageManager::sendMessage(const QString &numberTo, const QString &message)
{
if (d_ptr->messageManager) {
QDBusPendingReply<QDBusObjectPath> result = d_ptr->messageManager->SendMessage(numberTo,message);
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(result, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(sendMessageFinished(QDBusPendingCallWatcher*)));
}
}
QStringList QOfonoMessageManager::messages()
{
if (d_ptr->messageManager)
return d_ptr->messageList;
return QStringList();
}
void QOfonoMessageManager::onMessageAdded(const QString &message)
{
if (d_ptr->messageManager) {
if (!d_ptr->messageList.contains(message)) {
d_ptr->messageList.append(message);
}
}
}
void QOfonoMessageManager::onMessageRemoved(const QString &message)
{
if (d_ptr->messageManager) {
if (d_ptr->messageList.contains(message)) {
d_ptr->messageList.removeOne(message);
}
}
}
bool QOfonoMessageManager::isValid() const
{
return d_ptr->messageManager->isValid();
}
void QOfonoMessageManager::getMessagesFinished(const ObjectPathPropertiesList &list)
{
qDebug() << Q_FUNC_INFO << list.count();
// messages = reply2.value();
foreach(ObjectPathProperties message, list) {
d_ptr->messageList << message.path.path();
}
Q_EMIT messagesFinished();
}
void QOfonoMessageManager::messagesError(const QDBusError &error)
{
qDebug() << Q_FUNC_INFO << error.message();
}
void QOfonoMessageManager::sendMessageFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<QDBusObjectPath> reply = *call;
bool ok = true;
if (reply.isError()) {
qWarning() << Q_FUNC_INFO << "failed:" << reply.error();
d_ptr->errorMessage = reply.error().name() + " " + reply.error().message();
ok = false;
}
Q_EMIT sendMessageComplete(ok, reply.value().path());
}
void QOfonoMessageManager::setServiceCenterAddressFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<> reply = *call;
Q_EMIT setServiceCenterAddressComplete(!reply.isError());
call->deleteLater();
}
void QOfonoMessageManager::setUseDeliveryReportsFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<> reply = *call;
Q_EMIT setUseDeliveryReportsComplete(!reply.isError());
call->deleteLater();
}
void QOfonoMessageManager::setBearerFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<> reply = *call;
Q_EMIT setBearerComplete(!reply.isError());
call->deleteLater();
}
void QOfonoMessageManager::setAlphabetFinished(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<> reply = *call;
Q_EMIT setAlphabetComplete(!reply.isError());
call->deleteLater();
}
<|endoftext|>
|
<commit_before>#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
ui->addressEdit->setVisible(false);
ui->stealthCB->setEnabled(true);
ui->stealthCB->setVisible(true);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
ui->stealthCB->setVisible(false);
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
ui->addressEdit->setVisible(true);
ui->stealthCB->setEnabled(false);
ui->stealthCB->setVisible(true);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
ui->stealthCB->setVisible(false);
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
mapper->addMapping(ui->stealthCB, AddressTableModel::Type);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
{
int typeInd = ui->stealthCB->isChecked() ? AddressTableModel::AT_Stealth : AddressTableModel::AT_Normal;
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text(),
typeInd);
}
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid Okcash address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
<commit_msg>tblemodel up stealth<commit_after>#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
ui->addressEdit->setVisible(false);
ui->stealthCB->setEnabled(true);
ui->stealthCB->setVisible(true);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
ui->stealthCB->setVisible(false);
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
ui->addressEdit->setVisible(true);
ui->stealthCB->setEnabled(false);
ui->stealthCB->setVisible(true);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
ui->stealthCB->setVisible(false);
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
mapper->addMapping(ui->stealthCB, AddressTableModel::Type);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
{
int typeInd = ui->stealthCB->isChecked() ? AT_Stealth : AT_Normal;
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text(),
typeInd);
}
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid Okcash address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
<|endoftext|>
|
<commit_before>#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setDisabled(true);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid %2 address.").arg(ui->addressEdit->text()).arg(BitcoinUnits::baseName()),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
<commit_msg>Added missing include for bitcoinunits.h in editadddressdialog.cpp<commit_after>#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setDisabled(true);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid %2 address.").arg(ui->addressEdit->text()).arg(BitcoinUnits::baseName()),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
<|endoftext|>
|
<commit_before>#ifndef LIST_HPP
#define LIST_HPP
#include <cstddef>
#include "utils/Optional.hpp"
#include "utils/Sanity.hpp"
using namespace std;
template<class T>
struct Node {
Node(const T& value, Node<T>* next) : value(value), next(next) {}
T value;
Node<T>* next;
};
template<class T> class List;
template<class T> class ConstIterator;
template<class T> class Iterator;
#include "container/ConstIterator.hpp"
#include "container/Iterator.hpp"
template<class T>
class List {
protected:
Node<T>* first;
Node<T>* last;
unsigned nbElems;
public:
List();
List(const List<T>&);
~List();
/**
* Adds an element to the list.
*/
virtual void add(const T&);
/**
* Adds all the items contained in the list passed as parameter.
*/
void addAll(const List&);
/**
* Removes all items from the list.
*/
void clear();
/**
* Checks whether the list contains an element matching the provided predicate.
* The provider parameter must have a test method returning a boolean.
*/
template<class P>
bool containsWithPredicate(const P&) const;
/**
* Returns the element at the provided index in the list
*/
T get(unsigned int) const;
/**
* Returns an optional value containing the first element of the list
* matching the provided predicate.
* The provider parameter must have a test method returning a boolean.
*/
template<class P>
Optional<T> getFirstMatching(const P&);
/**
* Returns whether the list contains items or not.
*/
bool isEmpty() const;
/**
* Removes the item at the provided position.
*/
void remove(unsigned);
/**
* Returns the current size of the list.
*/
unsigned size() const;
List<T>& operator=(List<T>);
T operator[](unsigned) const;
friend class ConstIterator<T>;
friend class Iterator<T>;
};
template<class T>
List<T>::List() {
this->first = NULL;
this->last = NULL;
this->nbElems = 0;
}
template<class T>
List<T>::List(const List<T>& list) {
this->first = NULL;
this->last = NULL;
this->nbElems = 0;
this->addAll(list);
}
template<class T>
List<T>::~List() {
this->clear();
}
template<class T>
void List<T>::add(const T& para) {
// Preparing new node
Node<T>* tmp = new Node<T>(para, NULL);
if(!this->first) {
// Adding first
this->first = tmp;
this->last = tmp;
} else {
// Adding at the end
this->last->next = tmp;
}
++this->nbElems;
}
template<class T>
void List<T>::addAll(const List& toAdd) {
ConstIterator<T> it(toAdd);
while(!it.end()) {
this->add(it++.get());
}
}
template<class T>
void List<T>::clear() {
Node<T>* node = this->first;
Node<T>* prev;
while(node) {
prev = node;
node = node->next;
delete prev;
}
this->first = NULL;
this->last = NULL;
this->nbElems = 0;
}
template<class T>
template<class P>
bool List<T>::containsWithPredicate(const P& predicate) const {
ConstIterator<T> it(*this);
while(!it.end()) {
if(predicate.test(it.get())) {
return true;
}
}
return false;
}
template<class T>
T List<T>::get(unsigned int index) const {
Sanity::truthness(index < this->nbElems, "Index out of bounds");
if(index == 0) {
return this->first->value;
}
ConstIterator<T> it(*this);
unsigned int i = 0;
while(true) {
if(i++ == index) {
return it;
}
++it;
}
}
template<class T>
template<class P>
Optional<T> List<T>::getFirstMatching(const P& predicate) {
Iterator<T> it(*this);
while(!it.end()) {
if(predicate.test(it)) {
return Optional<T>(&it.get());
}
++it;
}
return Optional<T>();
}
template<class T>
inline bool List<T>::isEmpty() const {
return this->nbElems == 0;
}
template<class T>
void List<T>::remove(unsigned index) {
Sanity::truthness(index < nbElems, "Index must be lower than the list's size");
Iterator<T> it(*this);
unsigned i = 0;
while(i < index) {
++i;
++it;
}
it.remove();
}
template<class T>
inline unsigned List<T>::size() const {
return this->nbElems;
}
template<class T>
List<T>& List<T>::operator=(List<T> list) {
swap(this->nbElems, list.nbElems);
swap(this->first, list.first);
swap(this->last, list.last);
return *this;
}
template<class T>
inline T List<T>::operator[](unsigned index) const {
return this->get(index);
}
#endif
<commit_msg>Fix adding to the end of the list<commit_after>#ifndef LIST_HPP
#define LIST_HPP
#include <cstddef>
#include "utils/Optional.hpp"
#include "utils/Sanity.hpp"
using namespace std;
template<class T>
struct Node {
Node(const T& value, Node<T>* next) : value(value), next(next) {}
T value;
Node<T>* next;
};
template<class T> class List;
template<class T> class ConstIterator;
template<class T> class Iterator;
#include "container/ConstIterator.hpp"
#include "container/Iterator.hpp"
template<class T>
class List {
protected:
Node<T>* first;
Node<T>* last;
unsigned nbElems;
public:
List();
List(const List<T>&);
~List();
/**
* Adds an element to the list.
*/
virtual void add(const T&);
/**
* Adds all the items contained in the list passed as parameter.
*/
void addAll(const List&);
/**
* Removes all items from the list.
*/
void clear();
/**
* Checks whether the list contains an element matching the provided predicate.
* The provider parameter must have a test method returning a boolean.
*/
template<class P>
bool containsWithPredicate(const P&) const;
/**
* Returns the element at the provided index in the list
*/
T get(unsigned int) const;
/**
* Returns an optional value containing the first element of the list
* matching the provided predicate.
* The provider parameter must have a test method returning a boolean.
*/
template<class P>
Optional<T> getFirstMatching(const P&);
/**
* Returns whether the list contains items or not.
*/
bool isEmpty() const;
/**
* Removes the item at the provided position.
*/
void remove(unsigned);
/**
* Returns the current size of the list.
*/
unsigned size() const;
List<T>& operator=(List<T>);
T operator[](unsigned) const;
friend class ConstIterator<T>;
friend class Iterator<T>;
};
template<class T>
List<T>::List() {
this->first = NULL;
this->last = NULL;
this->nbElems = 0;
}
template<class T>
List<T>::List(const List<T>& list) {
this->first = NULL;
this->last = NULL;
this->nbElems = 0;
this->addAll(list);
}
template<class T>
List<T>::~List() {
this->clear();
}
template<class T>
void List<T>::add(const T& para) {
// Preparing new node
Node<T>* tmp = new Node<T>(para, NULL);
if(!this->first) {
// Adding first
this->first = tmp;
this->last = tmp;
} else {
// Adding at the end
this->last->next = tmp;
this->last = tmp;
}
++this->nbElems;
}
template<class T>
void List<T>::addAll(const List& toAdd) {
ConstIterator<T> it(toAdd);
while(!it.end()) {
this->add(it++.get());
}
}
template<class T>
void List<T>::clear() {
Node<T>* node = this->first;
Node<T>* prev;
while(node) {
prev = node;
node = node->next;
delete prev;
}
this->first = NULL;
this->last = NULL;
this->nbElems = 0;
}
template<class T>
template<class P>
bool List<T>::containsWithPredicate(const P& predicate) const {
ConstIterator<T> it(*this);
while(!it.end()) {
if(predicate.test(it.get())) {
return true;
}
}
return false;
}
template<class T>
T List<T>::get(unsigned int index) const {
Sanity::truthness(index < this->nbElems, "Index out of bounds");
if(index == 0) {
return this->first->value;
}
ConstIterator<T> it(*this);
unsigned int i = 0;
while(true) {
if(i++ == index) {
return it;
}
++it;
}
}
template<class T>
template<class P>
Optional<T> List<T>::getFirstMatching(const P& predicate) {
Iterator<T> it(*this);
while(!it.end()) {
if(predicate.test(it)) {
return Optional<T>(&it.get());
}
++it;
}
return Optional<T>();
}
template<class T>
inline bool List<T>::isEmpty() const {
return this->nbElems == 0;
}
template<class T>
void List<T>::remove(unsigned index) {
Sanity::truthness(index < nbElems, "Index must be lower than the list's size");
Iterator<T> it(*this);
unsigned i = 0;
while(i < index) {
++i;
++it;
}
it.remove();
}
template<class T>
inline unsigned List<T>::size() const {
return this->nbElems;
}
template<class T>
List<T>& List<T>::operator=(List<T> list) {
swap(this->nbElems, list.nbElems);
swap(this->first, list.first);
swap(this->last, list.last);
return *this;
}
template<class T>
inline T List<T>::operator[](unsigned index) const {
return this->get(index);
}
#endif
<|endoftext|>
|
<commit_before>#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <qapplication.h>
#include <qdialog.h>
#include <qframe.h>
#include <qlayout.h>
#include <qmetaobject.h>
#include <qpainter.h>
#include <qpushbutton.h>
#include <qvariant.h>
#include <qwhatsthis.h>
#include <private/qucomextra_p.h>
#include "data/Data2D.hpp"
#include "data/DataSource2D.hpp"
#include "statistics/StatisticalSerie2D.hpp"
class QFrame;
class QGridLayout;
class QHBoxLayout;
class QPushButton;
class QSpacerItem;
class QVBoxLayout;
class Application : public QDialog {
Q_OBJECT
public:
Application(const StatisticalSerie2D*);
~Application();
QPushButton* doneButton;
QPushButton* drawButton;
QPushButton* selectButton;
QPushButton* refreshButton;
QFrame* thePaintingFrame;
public slots:
virtual void refresh();
virtual void drawLine();
virtual void done();
virtual void select();
protected:
virtual void mouseMoveEvent(QMouseEvent*);
virtual void mouseReleaseEvent(QMouseEvent*);
virtual void mousePressEvent(QMouseEvent*);
protected slots:
virtual void languageChange();
private:
static const unsigned int WIDTH;
static const unsigned int HEIGHT;
QPoint startingPoint;
QPoint endingPoint;
bool isMouseButtonDown;
float e1;
float e2;
float maxX, maxY, minX, minY;
const StatisticalSerie2D* serie2D;
unsigned transformX(float) const;
unsigned transformY(float) const;
};
#endif
<commit_msg>More cleanup<commit_after>#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <qapplication.h>
#include <qdialog.h>
#include <qframe.h>
#include <qmetaobject.h>
#include <qpainter.h>
#include <qpushbutton.h>
#include <private/qucomextra_p.h>
#include "data/Data2D.hpp"
#include "data/DataSource2D.hpp"
#include "statistics/StatisticalSerie2D.hpp"
class QFrame;
class QGridLayout;
class QHBoxLayout;
class QPushButton;
class QSpacerItem;
class QVBoxLayout;
class Application : public QDialog {
Q_OBJECT
public:
Application(const StatisticalSerie2D*);
~Application();
QPushButton* doneButton;
QPushButton* drawButton;
QPushButton* selectButton;
QPushButton* refreshButton;
QFrame* thePaintingFrame;
public slots:
virtual void refresh();
virtual void drawLine();
virtual void done();
virtual void select();
protected:
virtual void mouseMoveEvent(QMouseEvent*);
virtual void mouseReleaseEvent(QMouseEvent*);
virtual void mousePressEvent(QMouseEvent*);
protected slots:
virtual void languageChange();
private:
static const unsigned int WIDTH;
static const unsigned int HEIGHT;
QPoint startingPoint;
QPoint endingPoint;
bool isMouseButtonDown;
float e1;
float e2;
float maxX, maxY, minX, minY;
const StatisticalSerie2D* serie2D;
unsigned transformX(float) const;
unsigned transformY(float) const;
};
#endif
<|endoftext|>
|
<commit_before>#include "core/Solution.hpp"
#include "core/Genome.hpp"
#include <cstdlib>
#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
Solution::Solution() {
init(NULL, NULL);
}
Solution::Solution(Genome * genome) {
init(new Genome(genome, false), NULL);
//evaluateFitness();
}
Solution::Solution(Solution * copyTarget, bool randomize) {
Genome * genome = new Genome(copyTarget->getGenome(), randomize);
if (randomize) {
init(genome, NULL);
//evaluateFitness();
} else {
init(genome, copyTarget->getProperties());
}
}
Solution::Solution(Solution * copyTarget, int rawGenes[]) {
Genome * genome = new Genome(copyTarget->getGenome(), rawGenes);
init(genome, NULL);
//evaluateFitness();
}
Solution::Solution(vector<Locus*> loci) {
Genome * genome = new Genome(loci);
init(genome, NULL);
//evaluateFitness();
}
Solution::~Solution() {
if (genome != NULL) {
delete(genome);
}
if (properties != NULL) {
delete(properties);
}
}
void Solution::init(Genome * genome, PropertiesList * properties) {
this->genome = genome;
this->properties = properties;
}
int Solution::getFitness() {
return this->properties->getFitness();
}
PropertiesList * Solution::getProperties() {
return this->properties;
}
Genome * Solution::getGenome() {
return this->genome;
}
/*string Solution::toString() {
return this->toString->toString(this->genome);
}*/
<commit_msg>[Solution]: Deleted dead code<commit_after><|endoftext|>
|
<commit_before>/*
MIT License
Copyright (c) 2019 ZhuQian
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 "parallel.h"
#include <vector>
NARUKAMI_BEGIN
class ParallelForLoop
{
public:
const std::function<void(size_t)> func_1D;
const std::function<void(Point2i)> func_2D;
const size_t max_iteration_count;
const size_t chunk_size;
size_t next_iteration_index;
int active_worker;
ParallelForLoop *next; //next ParallelForLoop instance
const size_t num_x = -1;
public:
ParallelForLoop(std::function<void(size_t)> func, const size_t iteration_count, const size_t chunk_size) : func_1D(std::move(func)), max_iteration_count(iteration_count), chunk_size(chunk_size), active_worker(0), next_iteration_index(0) {}
ParallelForLoop(std::function<void(Point2i)> func, const Point2i &count) : func_2D(std::move(func)), max_iteration_count(count.x * count.y), chunk_size(1), active_worker(0), next_iteration_index(0), num_x(count.x) {}
};
bool is_finished(const ParallelForLoop &loop)
{
if (loop.next_iteration_index == loop.max_iteration_count && loop.active_worker == 0)
{
return true;
}
return false;
}
//threads pool
static std::vector<std::thread> threads;
//link list for ParallelForLoop instance;
static ParallelForLoop *work_list = nullptr;
static std::mutex work_list_mutex;
static std::condition_variable work_list_condition;
static bool shutdown_threads = false;
thread_local int thread_index = 0;
void thread_worker_func(int index)
{
thread_index = index;
// lock for the work list
std::unique_lock<std::mutex> lock(work_list_mutex);
while (!shutdown_threads)
{
if (work_list == nullptr)
{
//if no works to do,release lock and just sleep for other wakeup
work_list_condition.wait(lock);
}
else
{
ParallelForLoop &loop = *work_list;
//get the iteration range
size_t begin_index = loop.next_iteration_index;
size_t end_index = min(begin_index + loop.chunk_size, loop.max_iteration_count);
//update loop's next index
loop.next_iteration_index = end_index;
//switch to next loop
if (loop.next_iteration_index == loop.max_iteration_count)
{
work_list = loop.next;
}
//increase loop's active_worker
loop.active_worker++;
lock.unlock();
//--------------loop----------------------
for (size_t i = begin_index; i < end_index; ++i)
{
if (loop.func_1D)
{
loop.func_1D(i);
}
else if (loop.func_2D)
{
loop.func_2D(Point2i(i % loop.num_x, i / loop.num_x));
}
}
//--------------loop----------------------
lock.lock();
loop.active_worker--;
if (is_finished(loop))
{
//wake up threads
work_list_condition.notify_all();
}
}
}
}
void setup_threads(int num_core)
{
for (int i = 0; i < num_core; ++i)
{
threads.push_back(std::thread(thread_worker_func, i + 1));
}
}
void parallel_for(std::function<void(size_t)> func, const size_t count, const size_t chunk_size)
{
//if cpu's core eual one or count le chunk size
int num_core = num_system_core();
if (num_system_core() == 1 || count <= chunk_size)
{
for (size_t i = 0; i < count; ++i)
{
func(i);
}
return;
}
//check threads
if (threads.size() == 0)
{
setup_threads(num_core);
}
//create on stack
ParallelForLoop loop(func, count, chunk_size);
// lock for the work list
std::unique_lock<std::mutex> lock(work_list_mutex);
loop.next = work_list;
work_list = &loop;
lock.unlock();
//wake up threads
work_list_condition.notify_all();
lock.lock();
while (!is_finished(loop))
{
//get the iteration range
size_t begin_index = loop.next_iteration_index;
size_t end_index = min(begin_index + loop.chunk_size, loop.max_iteration_count);
//update loop's next index
loop.next_iteration_index = end_index;
//switch to next loop
if (loop.next_iteration_index == loop.max_iteration_count)
{
work_list = loop.next;
}
//increase loop's active_worker
loop.active_worker++;
lock.unlock();
//--------------loop----------------------
for (size_t i = begin_index; i < end_index; ++i)
{
loop.func_1D(i);
}
//--------------loop----------------------
lock.lock();
loop.active_worker--;
}
}
void parallel_for_2D(std::function<void(Point2i)> func, const Point2i &count)
{
//if cpu's core eual one or count le chunk size
int num_core = num_system_core();
if (num_system_core() == 1)
{
for (int y = 0; y < count.y; ++y)
{
for (int x = 0; x < count.x; ++x)
{
func(Point2i(x, y));
}
}
return;
}
//check threads
if (threads.size() == 0)
{
setup_threads(num_core);
}
//create on stack
ParallelForLoop loop(func, count);
// lock for the work list
std::unique_lock<std::mutex> lock(work_list_mutex);
loop.next = work_list;
work_list = &loop;
lock.unlock();
//wake up threads
work_list_condition.notify_all();
lock.lock();
while (!is_finished(loop))
{
//get the iteration range
size_t begin_index = loop.next_iteration_index;
size_t end_index = min(begin_index + loop.chunk_size, loop.max_iteration_count);
//update loop's next index
loop.next_iteration_index = end_index;
//switch to next loop
if (loop.next_iteration_index == loop.max_iteration_count)
{
work_list = loop.next;
}
//increase loop's active_worker
loop.active_worker++;
lock.unlock();
//--------------loop----------------------
for (size_t i = begin_index; i < end_index; ++i)
{
loop.func_2D(Point2i(i % loop.num_x, i / loop.num_x));
}
//--------------loop----------------------
lock.lock();
loop.active_worker--;
}
}
void parallel_for_clean()
{
if (threads.size() == 0)
{
return;
}
{
// lock for the work list
std::lock_guard<std::mutex> lock_guard(work_list_mutex);
shutdown_threads = true;
//wake up threads
work_list_condition.notify_all();
}
//wait threads
for (std::thread &t : threads)
{
t.join();
}
//clear
threads.erase(threads.begin(), threads.end());
shutdown_threads = false; //ready for next parallel_for
}
NARUKAMI_END<commit_msg>add report_thread_statistics into parallel_for func<commit_after>/*
MIT License
Copyright (c) 2019 ZhuQian
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 "parallel.h"
#include "core/stat.h"
#include <vector>
NARUKAMI_BEGIN
class ParallelForLoop
{
public:
const std::function<void(size_t)> func_1D;
const std::function<void(Point2i)> func_2D;
const size_t max_iteration_count;
const size_t chunk_size;
size_t next_iteration_index;
int active_worker;
ParallelForLoop *next; //next ParallelForLoop instance
const size_t num_x = -1;
public:
ParallelForLoop(std::function<void(size_t)> func, const size_t iteration_count, const size_t chunk_size) : func_1D(std::move(func)), max_iteration_count(iteration_count), chunk_size(chunk_size), active_worker(0), next_iteration_index(0) {}
ParallelForLoop(std::function<void(Point2i)> func, const Point2i &count) : func_2D(std::move(func)), max_iteration_count(count.x * count.y), chunk_size(1), active_worker(0), next_iteration_index(0), num_x(count.x) {}
};
bool is_finished(const ParallelForLoop &loop)
{
if (loop.next_iteration_index == loop.max_iteration_count && loop.active_worker == 0)
{
return true;
}
return false;
}
//threads pool
static std::vector<std::thread> threads;
//link list for ParallelForLoop instance;
static ParallelForLoop *work_list = nullptr;
static std::mutex work_list_mutex;
static std::condition_variable work_list_condition;
static bool shutdown_threads = false;
thread_local int thread_index = 0;
void thread_worker_func(int index)
{
thread_index = index;
// lock for the work list
std::unique_lock<std::mutex> lock(work_list_mutex);
while (!shutdown_threads)
{
if (work_list == nullptr)
{
//if no works to do,release lock and just sleep for other wakeup
work_list_condition.wait(lock);
}
else
{
ParallelForLoop &loop = *work_list;
//get the iteration range
size_t begin_index = loop.next_iteration_index;
size_t end_index = min(begin_index + loop.chunk_size, loop.max_iteration_count);
//update loop's next index
loop.next_iteration_index = end_index;
//switch to next loop
if (loop.next_iteration_index == loop.max_iteration_count)
{
work_list = loop.next;
}
//increase loop's active_worker
loop.active_worker++;
lock.unlock();
//--------------loop----------------------
for (size_t i = begin_index; i < end_index; ++i)
{
if (loop.func_1D)
{
loop.func_1D(i);
}
else if (loop.func_2D)
{
loop.func_2D(Point2i(i % loop.num_x, i / loop.num_x));
}
}
//--------------loop----------------------
lock.lock();
loop.active_worker--;
if (is_finished(loop))
{
//wake up threads
work_list_condition.notify_all();
}
}
}
//push thread data into stat
report_thread_statistics();
}
void setup_threads(int num_core)
{
for (int i = 0; i < num_core; ++i)
{
threads.push_back(std::thread(thread_worker_func, i + 1));
}
}
void parallel_for(std::function<void(size_t)> func, const size_t count, const size_t chunk_size)
{
//if cpu's core eual one or count le chunk size
int num_core = num_system_core();
if (num_system_core() == 1 || count <= chunk_size)
{
for (size_t i = 0; i < count; ++i)
{
func(i);
}
return;
}
//check threads
if (threads.size() == 0)
{
setup_threads(num_core);
}
//create on stack
ParallelForLoop loop(func, count, chunk_size);
// lock for the work list
std::unique_lock<std::mutex> lock(work_list_mutex);
loop.next = work_list;
work_list = &loop;
lock.unlock();
//wake up threads
work_list_condition.notify_all();
lock.lock();
while (!is_finished(loop))
{
//get the iteration range
size_t begin_index = loop.next_iteration_index;
size_t end_index = min(begin_index + loop.chunk_size, loop.max_iteration_count);
//update loop's next index
loop.next_iteration_index = end_index;
//switch to next loop
if (loop.next_iteration_index == loop.max_iteration_count)
{
work_list = loop.next;
}
//increase loop's active_worker
loop.active_worker++;
lock.unlock();
//--------------loop----------------------
for (size_t i = begin_index; i < end_index; ++i)
{
loop.func_1D(i);
}
//--------------loop----------------------
lock.lock();
loop.active_worker--;
}
}
void parallel_for_2D(std::function<void(Point2i)> func, const Point2i &count)
{
//if cpu's core eual one or count le chunk size
int num_core = num_system_core();
if (num_system_core() == 1)
{
for (int y = 0; y < count.y; ++y)
{
for (int x = 0; x < count.x; ++x)
{
func(Point2i(x, y));
}
}
return;
}
//check threads
if (threads.size() == 0)
{
setup_threads(num_core);
}
//create on stack
ParallelForLoop loop(func, count);
// lock for the work list
std::unique_lock<std::mutex> lock(work_list_mutex);
loop.next = work_list;
work_list = &loop;
lock.unlock();
//wake up threads
work_list_condition.notify_all();
lock.lock();
while (!is_finished(loop))
{
//get the iteration range
size_t begin_index = loop.next_iteration_index;
size_t end_index = min(begin_index + loop.chunk_size, loop.max_iteration_count);
//update loop's next index
loop.next_iteration_index = end_index;
//switch to next loop
if (loop.next_iteration_index == loop.max_iteration_count)
{
work_list = loop.next;
}
//increase loop's active_worker
loop.active_worker++;
lock.unlock();
//--------------loop----------------------
for (size_t i = begin_index; i < end_index; ++i)
{
loop.func_2D(Point2i(i % loop.num_x, i / loop.num_x));
}
//--------------loop----------------------
lock.lock();
loop.active_worker--;
}
}
void parallel_for_clean()
{
if (threads.size() == 0)
{
return;
}
{
// lock for the work list
std::lock_guard<std::mutex> lock_guard(work_list_mutex);
shutdown_threads = true;
//wake up threads
work_list_condition.notify_all();
}
//wait threads
for (std::thread &t : threads)
{
t.join();
}
//clear
threads.erase(threads.begin(), threads.end());
shutdown_threads = false; //ready for next parallel_for
}
NARUKAMI_END<|endoftext|>
|
<commit_before>// refactor of online2-wav-nnet3-latgen-faster.cc
#include "online2/online-nnet3-decoding.h"
#include "online2/online-nnet2-feature-pipeline.h"
#include "online2/onlinebin-util.h"
#include "online2/online-timing.h"
#include "online2/online-endpoint.h"
#include "fstext/fstext-lib.h"
#include "lat/lattice-functions.h"
#include "lat/word-align-lattice.h"
#include "nnet3/decodable-simple-looped.h"
#ifdef HAVE_CUDA
#include "cudamatrix/cu-device.h"
#endif
const int arate = 8000;
void ConfigFeatureInfo(kaldi::OnlineNnet2FeaturePipelineInfo& info,
std::string ivector_model_dir) {
// Configure inline to avoid absolute paths in ".conf" files
info.feature_type = "mfcc";
info.use_ivectors = true;
// ivector_extractor.conf
ReadKaldiObject(ivector_model_dir + "/final.mat",
&info.ivector_extractor_info.lda_mat);
ReadKaldiObject(ivector_model_dir + "/global_cmvn.stats",
&info.ivector_extractor_info.global_cmvn_stats);
ReadKaldiObject(ivector_model_dir + "/final.dubm",
&info.ivector_extractor_info.diag_ubm);
ReadKaldiObject(ivector_model_dir + "/final.ie",
&info.ivector_extractor_info.extractor);
info.ivector_extractor_info.num_gselect = 5;
info.ivector_extractor_info.min_post = 0.025;
info.ivector_extractor_info.posterior_scale = 0.1;
info.ivector_extractor_info.max_remembered_frames = 1000;
info.ivector_extractor_info.max_count = 100; // changed from 0.0 (?)
// XXX: Where do these come from?
info.ivector_extractor_info.greedy_ivector_extractor = true;
info.ivector_extractor_info.ivector_period = 10;
info.ivector_extractor_info.num_cg_iters = 15;
info.ivector_extractor_info.use_most_recent_ivector = true;
// splice.conf
info.ivector_extractor_info.splice_opts.left_context = 3;
info.ivector_extractor_info.splice_opts.right_context = 3;
// mfcc.conf
info.mfcc_opts.frame_opts.samp_freq = arate;
info.mfcc_opts.use_energy = false;
info.mfcc_opts.num_ceps = 40;
info.mfcc_opts.mel_opts.num_bins = 40;
info.mfcc_opts.mel_opts.low_freq = 40;
info.mfcc_opts.mel_opts.high_freq = -200;
info.ivector_extractor_info.Check();
}
void ConfigDecoding(kaldi::LatticeFasterDecoderConfig& config) {
config.lattice_beam = 6.0;
config.beam = 15.0;
config.max_active = 7000;
}
void ConfigEndpoint(kaldi::OnlineEndpointConfig& config) {
config.silence_phones = "1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20";
}
void usage() {
fprintf(stderr, "usage: k3 [nnet_dir hclg_path]\n");
}
int main(int argc, char *argv[]) {
using namespace kaldi;
using namespace fst;
setbuf(stdout, NULL);
std::string nnet_dir = "exp/tdnn_7b_chain_online";
std::string graph_dir = nnet_dir + "/graph_pp";
std::string fst_rxfilename = graph_dir + "/HCLG.fst";
if(argc == 3) {
nnet_dir = argv[1];
graph_dir = nnet_dir + "/graph_pp";
fst_rxfilename = argv[2];
}
else if(argc != 1) {
usage();
return EXIT_FAILURE;
}
#ifdef HAVE_CUDA
fprintf(stdout, "Cuda enabled\n");
CuDevice &cu_device = CuDevice::Instantiate();
cu_device.SetVerbose(true);
cu_device.SelectGpuId("yes");
fprintf(stdout, "active gpu: %d\n", cu_device.ActiveGpuId());
#endif
const std::string ivector_model_dir = nnet_dir + "/ivector_extractor";
const std::string nnet3_rxfilename = nnet_dir + "/final.mdl";
const std::string word_syms_rxfilename = graph_dir + "/words.txt";
const string word_boundary_filename = graph_dir + "/phones/word_boundary.int";
const string phone_syms_rxfilename = graph_dir + "/phones.txt";
WordBoundaryInfoNewOpts opts; // use default opts
WordBoundaryInfo word_boundary_info(opts, word_boundary_filename);
OnlineNnet2FeaturePipelineInfo feature_info;
ConfigFeatureInfo(feature_info, ivector_model_dir);
LatticeFasterDecoderConfig nnet3_decoding_config;
ConfigDecoding(nnet3_decoding_config);
OnlineEndpointConfig endpoint_config;
ConfigEndpoint(endpoint_config);
BaseFloat frame_shift = feature_info.FrameShiftInSeconds();
TransitionModel trans_model;
nnet3::AmNnetSimple am_nnet;
{
bool binary;
Input ki(nnet3_rxfilename, &binary);
trans_model.Read(ki.Stream(), binary);
am_nnet.Read(ki.Stream(), binary);
}
nnet3::NnetSimpleLoopedComputationOptions nnet_simple_looped_opts;
nnet_simple_looped_opts.acoustic_scale = 1.0; // changed from 0.1?
nnet3::DecodableNnetSimpleLoopedInfo de_nnet_simple_looped_info(nnet_simple_looped_opts, &am_nnet);
fst::Fst<fst::StdArc> *decode_fst = ReadFstKaldi(fst_rxfilename);
fst::SymbolTable *word_syms =
fst::SymbolTable::ReadText(word_syms_rxfilename);
fst::SymbolTable* phone_syms =
fst::SymbolTable::ReadText(phone_syms_rxfilename);
OnlineIvectorExtractorAdaptationState adaptation_state(feature_info.ivector_extractor_info);
OnlineNnet2FeaturePipeline feature_pipeline(feature_info);
feature_pipeline.SetAdaptationState(adaptation_state);
OnlineSilenceWeighting silence_weighting(
trans_model,
feature_info.silence_weighting_config);
SingleUtteranceNnet3Decoder decoder(nnet3_decoding_config,
trans_model,
de_nnet_simple_looped_info,
//am_nnet, // kaldi::nnet3::DecodableNnetSimpleLoopedInfo
*decode_fst,
&feature_pipeline);
char cmd[1024];
while(true) {
// Let the client decide what we should do...
fgets(cmd, sizeof(cmd), stdin);
if(strcmp(cmd,"stop\n") == 0) {
break;
}
else if(strcmp(cmd,"reset\n") == 0) {
feature_pipeline.~OnlineNnet2FeaturePipeline();
new (&feature_pipeline) OnlineNnet2FeaturePipeline(feature_info);
decoder.~SingleUtteranceNnet3Decoder();
new (&decoder) SingleUtteranceNnet3Decoder(nnet3_decoding_config,
trans_model,
de_nnet_simple_looped_info,
//am_nnet,
*decode_fst,
&feature_pipeline);
}
else if(strcmp(cmd,"push-chunk\n") == 0) {
// Get chunk length from python
int chunk_len;
fgets(cmd, sizeof(cmd), stdin);
sscanf(cmd, "%d\n", &chunk_len);
int16_t audio_chunk[chunk_len];
Vector<BaseFloat> wave_part = Vector<BaseFloat>(chunk_len);
fread(&audio_chunk, 2, chunk_len, stdin);
// We need to copy this into the `wave_part' Vector<BaseFloat> thing.
// From `gst-audio-source.cc' in gst-kaldi-nnet2
for (int i = 0; i < chunk_len ; ++i) {
(wave_part)(i) = static_cast<BaseFloat>(audio_chunk[i]);
}
feature_pipeline.AcceptWaveform(arate, wave_part);
std::vector<std::pair<int32, BaseFloat> > delta_weights;
if (silence_weighting.Active()) {
silence_weighting.ComputeCurrentTraceback(decoder.Decoder());
silence_weighting.GetDeltaWeights(feature_pipeline.NumFramesReady(),
&delta_weights);
feature_pipeline.IvectorFeature()->UpdateFrameWeights(delta_weights);
}
decoder.AdvanceDecoding();
fprintf(stdout, "ok\n");
}
else if(strcmp(cmd, "get-final\n") == 0) {
feature_pipeline.InputFinished(); // XXX: this is new: what does it do?
decoder.FinalizeDecoding();
Lattice final_lat;
decoder.GetBestPath(true, &final_lat);
CompactLattice clat;
ConvertLattice(final_lat, &clat);
// Compute prons alignment (see: kaldi/latbin/nbest-to-prons.cc)
CompactLattice aligned_clat;
std::vector<int32> words, times, lengths;
std::vector<std::vector<int32> > prons;
std::vector<std::vector<int32> > phone_lengths;
WordAlignLattice(clat, trans_model, word_boundary_info,
0, &aligned_clat);
CompactLatticeToWordProns(trans_model, aligned_clat, &words, ×,
&lengths, &prons, &phone_lengths);
for (int i = 0; i < words.size(); i++) {
if(words[i] == 0) {
// <eps> links - silence
continue;
}
fprintf(stdout, "word: %s / start: %f / duration: %f\n",
word_syms->Find(words[i]).c_str(),
times[i] * frame_shift,
lengths[i] * frame_shift);
// Print out the phonemes for this word
for(size_t j=0; j<phone_lengths[i].size(); j++) {
fprintf(stdout, "phone: %s / duration: %f\n",
phone_syms->Find(prons[i][j]).c_str(),
phone_lengths[i][j] * frame_shift);
}
}
fprintf(stdout, "done with words\n");
}
else {
fprintf(stderr, "unknown command %s\n", cmd);
}
}
}
<commit_msg>Decode last few frames after receiving "get-final"<commit_after>// refactor of online2-wav-nnet3-latgen-faster.cc
#include "online2/online-nnet3-decoding.h"
#include "online2/online-nnet2-feature-pipeline.h"
#include "online2/onlinebin-util.h"
#include "online2/online-timing.h"
#include "online2/online-endpoint.h"
#include "fstext/fstext-lib.h"
#include "lat/lattice-functions.h"
#include "lat/word-align-lattice.h"
#include "nnet3/decodable-simple-looped.h"
#ifdef HAVE_CUDA
#include "cudamatrix/cu-device.h"
#endif
const int arate = 8000;
void ConfigFeatureInfo(kaldi::OnlineNnet2FeaturePipelineInfo& info,
std::string ivector_model_dir) {
// Configure inline to avoid absolute paths in ".conf" files
info.feature_type = "mfcc";
info.use_ivectors = true;
// ivector_extractor.conf
ReadKaldiObject(ivector_model_dir + "/final.mat",
&info.ivector_extractor_info.lda_mat);
ReadKaldiObject(ivector_model_dir + "/global_cmvn.stats",
&info.ivector_extractor_info.global_cmvn_stats);
ReadKaldiObject(ivector_model_dir + "/final.dubm",
&info.ivector_extractor_info.diag_ubm);
ReadKaldiObject(ivector_model_dir + "/final.ie",
&info.ivector_extractor_info.extractor);
info.ivector_extractor_info.num_gselect = 5;
info.ivector_extractor_info.min_post = 0.025;
info.ivector_extractor_info.posterior_scale = 0.1;
info.ivector_extractor_info.max_remembered_frames = 1000;
info.ivector_extractor_info.max_count = 100; // changed from 0.0 (?)
// XXX: Where do these come from?
info.ivector_extractor_info.greedy_ivector_extractor = true;
info.ivector_extractor_info.ivector_period = 10;
info.ivector_extractor_info.num_cg_iters = 15;
info.ivector_extractor_info.use_most_recent_ivector = true;
// splice.conf
info.ivector_extractor_info.splice_opts.left_context = 3;
info.ivector_extractor_info.splice_opts.right_context = 3;
// mfcc.conf
info.mfcc_opts.frame_opts.samp_freq = arate;
info.mfcc_opts.use_energy = false;
info.mfcc_opts.num_ceps = 40;
info.mfcc_opts.mel_opts.num_bins = 40;
info.mfcc_opts.mel_opts.low_freq = 40;
info.mfcc_opts.mel_opts.high_freq = -200;
info.ivector_extractor_info.Check();
}
void ConfigDecoding(kaldi::LatticeFasterDecoderConfig& config) {
config.lattice_beam = 6.0;
config.beam = 15.0;
config.max_active = 7000;
}
void ConfigEndpoint(kaldi::OnlineEndpointConfig& config) {
config.silence_phones = "1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20";
}
void usage() {
fprintf(stderr, "usage: k3 [nnet_dir hclg_path]\n");
}
int main(int argc, char *argv[]) {
using namespace kaldi;
using namespace fst;
setbuf(stdout, NULL);
std::string nnet_dir = "exp/tdnn_7b_chain_online";
std::string graph_dir = nnet_dir + "/graph_pp";
std::string fst_rxfilename = graph_dir + "/HCLG.fst";
if(argc == 3) {
nnet_dir = argv[1];
graph_dir = nnet_dir + "/graph_pp";
fst_rxfilename = argv[2];
}
else if(argc != 1) {
usage();
return EXIT_FAILURE;
}
#ifdef HAVE_CUDA
fprintf(stdout, "Cuda enabled\n");
CuDevice &cu_device = CuDevice::Instantiate();
cu_device.SetVerbose(true);
cu_device.SelectGpuId("yes");
fprintf(stdout, "active gpu: %d\n", cu_device.ActiveGpuId());
#endif
const std::string ivector_model_dir = nnet_dir + "/ivector_extractor";
const std::string nnet3_rxfilename = nnet_dir + "/final.mdl";
const std::string word_syms_rxfilename = graph_dir + "/words.txt";
const string word_boundary_filename = graph_dir + "/phones/word_boundary.int";
const string phone_syms_rxfilename = graph_dir + "/phones.txt";
WordBoundaryInfoNewOpts opts; // use default opts
WordBoundaryInfo word_boundary_info(opts, word_boundary_filename);
OnlineNnet2FeaturePipelineInfo feature_info;
ConfigFeatureInfo(feature_info, ivector_model_dir);
LatticeFasterDecoderConfig nnet3_decoding_config;
ConfigDecoding(nnet3_decoding_config);
OnlineEndpointConfig endpoint_config;
ConfigEndpoint(endpoint_config);
BaseFloat frame_shift = feature_info.FrameShiftInSeconds();
TransitionModel trans_model;
nnet3::AmNnetSimple am_nnet;
{
bool binary;
Input ki(nnet3_rxfilename, &binary);
trans_model.Read(ki.Stream(), binary);
am_nnet.Read(ki.Stream(), binary);
}
nnet3::NnetSimpleLoopedComputationOptions nnet_simple_looped_opts;
nnet_simple_looped_opts.acoustic_scale = 1.0; // changed from 0.1?
nnet3::DecodableNnetSimpleLoopedInfo de_nnet_simple_looped_info(nnet_simple_looped_opts, &am_nnet);
fst::Fst<fst::StdArc> *decode_fst = ReadFstKaldi(fst_rxfilename);
fst::SymbolTable *word_syms =
fst::SymbolTable::ReadText(word_syms_rxfilename);
fst::SymbolTable* phone_syms =
fst::SymbolTable::ReadText(phone_syms_rxfilename);
OnlineIvectorExtractorAdaptationState adaptation_state(feature_info.ivector_extractor_info);
OnlineNnet2FeaturePipeline feature_pipeline(feature_info);
feature_pipeline.SetAdaptationState(adaptation_state);
OnlineSilenceWeighting silence_weighting(
trans_model,
feature_info.silence_weighting_config);
SingleUtteranceNnet3Decoder decoder(nnet3_decoding_config,
trans_model,
de_nnet_simple_looped_info,
//am_nnet, // kaldi::nnet3::DecodableNnetSimpleLoopedInfo
*decode_fst,
&feature_pipeline);
char cmd[1024];
while(true) {
// Let the client decide what we should do...
fgets(cmd, sizeof(cmd), stdin);
if(strcmp(cmd,"stop\n") == 0) {
break;
}
else if(strcmp(cmd,"reset\n") == 0) {
feature_pipeline.~OnlineNnet2FeaturePipeline();
new (&feature_pipeline) OnlineNnet2FeaturePipeline(feature_info);
decoder.~SingleUtteranceNnet3Decoder();
new (&decoder) SingleUtteranceNnet3Decoder(nnet3_decoding_config,
trans_model,
de_nnet_simple_looped_info,
//am_nnet,
*decode_fst,
&feature_pipeline);
}
else if(strcmp(cmd,"push-chunk\n") == 0) {
// Get chunk length from python
int chunk_len;
fgets(cmd, sizeof(cmd), stdin);
sscanf(cmd, "%d\n", &chunk_len);
int16_t audio_chunk[chunk_len];
Vector<BaseFloat> wave_part = Vector<BaseFloat>(chunk_len);
fread(&audio_chunk, 2, chunk_len, stdin);
// We need to copy this into the `wave_part' Vector<BaseFloat> thing.
// From `gst-audio-source.cc' in gst-kaldi-nnet2
for (int i = 0; i < chunk_len ; ++i) {
(wave_part)(i) = static_cast<BaseFloat>(audio_chunk[i]);
}
feature_pipeline.AcceptWaveform(arate, wave_part);
std::vector<std::pair<int32, BaseFloat> > delta_weights;
if (silence_weighting.Active()) {
silence_weighting.ComputeCurrentTraceback(decoder.Decoder());
silence_weighting.GetDeltaWeights(feature_pipeline.NumFramesReady(),
&delta_weights);
feature_pipeline.IvectorFeature()->UpdateFrameWeights(delta_weights);
}
decoder.AdvanceDecoding();
fprintf(stdout, "ok\n");
}
else if(strcmp(cmd, "get-final\n") == 0) {
feature_pipeline.InputFinished(); // Computes last few frames of input
decoder.AdvanceDecoding(); // Decodes remaining frames
decoder.FinalizeDecoding();
Lattice final_lat;
decoder.GetBestPath(true, &final_lat);
CompactLattice clat;
ConvertLattice(final_lat, &clat);
// Compute prons alignment (see: kaldi/latbin/nbest-to-prons.cc)
CompactLattice aligned_clat;
std::vector<int32> words, times, lengths;
std::vector<std::vector<int32> > prons;
std::vector<std::vector<int32> > phone_lengths;
WordAlignLattice(clat, trans_model, word_boundary_info,
0, &aligned_clat);
CompactLatticeToWordProns(trans_model, aligned_clat, &words, ×,
&lengths, &prons, &phone_lengths);
for (int i = 0; i < words.size(); i++) {
if(words[i] == 0) {
// <eps> links - silence
continue;
}
fprintf(stdout, "word: %s / start: %f / duration: %f\n",
word_syms->Find(words[i]).c_str(),
times[i] * frame_shift,
lengths[i] * frame_shift);
// Print out the phonemes for this word
for(size_t j=0; j<phone_lengths[i].size(); j++) {
fprintf(stdout, "phone: %s / duration: %f\n",
phone_syms->Find(prons[i][j]).c_str(),
phone_lengths[i][j] * frame_shift);
}
}
fprintf(stdout, "done with words\n");
}
else {
fprintf(stderr, "unknown command %s\n", cmd);
}
}
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/multiphysics_sys.h"
// GRINS
#include "grins/composite_function.h"
#include "grins/assembly_context.h"
// libMesh
#include "libmesh/getpot.h"
namespace GRINS
{
MultiphysicsSystem::MultiphysicsSystem( libMesh::EquationSystems& es,
const std::string& name,
const unsigned int number )
: FEMSystem(es, name, number),
_use_numerical_jacobians_only(false)
{
return;
}
MultiphysicsSystem::~MultiphysicsSystem()
{
return;
}
void MultiphysicsSystem::attach_physics_list( PhysicsList physics_list )
{
_physics_list = physics_list;
return;
}
void MultiphysicsSystem::read_input_options( const GetPot& input )
{
// Read options for MultiphysicsSystem first
this->verify_analytic_jacobians = input("linear-nonlinear-solver/verify_analytic_jacobians", 0.0 );
this->print_solution_norms = input("screen-options/print_solution_norms", false );
this->print_solutions = input("screen-options/print_solutions", false );
this->print_residual_norms = input("screen-options/print_residual_norms", false );
// backwards compatibility with old config files.
/*! \todo Remove old print_residual nomenclature */
this->print_residuals = input("screen-options/print_residual", false );
if (this->print_residuals)
libmesh_deprecated();
this->print_residuals = input("screen-options/print_residuals", this->print_residuals );
this->print_jacobian_norms = input("screen-options/print_jacobian_norms", false );
this->print_jacobians = input("screen-options/print_jacobians", false );
this->print_element_solutions = input("screen-options/print_element_solutions", false );
this->print_element_residuals = input("screen-options/print_element_residuals", false );
this->print_element_jacobians = input("screen-options/print_element_jacobians", false );
_use_numerical_jacobians_only = input("linear-nonlinear-solver/use_numerical_jacobians_only", false );
numerical_jacobian_h =
input("linear-nonlinear-solver/numerical_jacobian_h",
numerical_jacobian_h);
}
void MultiphysicsSystem::init_data()
{
// Need this to be true because of our overloading of the
// mass_residual function.
// This is data in FEMSystem. MUST be set before FEMSystem::init_data.
use_fixed_solution = true;
// Initalize all the variables. We pass this pointer for the system.
/* NOTE: We CANNOT fuse this loop with the others. This loop
MUST complete first. */
/*! \todo Figure out how to tell compilers not to fuse this loop when
they want to be aggressive. */
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->init_variables( this );
}
// Now set time_evolving variables
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->set_time_evolving_vars( this );
}
// Set whether the problem we're solving is steady or not
// Since the variable is static, just call one Physics class
{
(_physics_list.begin()->second)->set_is_steady((this->time_solver)->is_steady());
}
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Initialize builtin BC's for each physics
(physics_iter->second)->init_bcs( this );
}
// Next, call parent init_data function to intialize everything.
libMesh::FEMSystem::init_data();
// After solution has been initialized we can project initial
// conditions to it
CompositeFunction<libMesh::Number> ic_function;
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Initialize builtin IC's for each physics
(physics_iter->second)->init_ics( this, ic_function );
}
if (ic_function.n_subfunctions())
{
this->project_solution(&ic_function);
}
return;
}
libMesh::AutoPtr<libMesh::DiffContext> MultiphysicsSystem::build_context()
{
AssemblyContext* context = new AssemblyContext(*this);
libMesh::AutoPtr<libMesh::DiffContext> ap(context);
libMesh::DifferentiablePhysics* phys = libMesh::FEMSystem::get_physics();
libmesh_assert(phys);
// If we are solving a moving mesh problem, tell that to the Context
context->set_mesh_system(phys->get_mesh_system());
context->set_mesh_x_var(phys->get_mesh_x_var());
context->set_mesh_y_var(phys->get_mesh_y_var());
context->set_mesh_z_var(phys->get_mesh_z_var());
ap->set_deltat_pointer( &deltat );
// If we are solving the adjoint problem, tell that to the Context
ap->is_adjoint() = this->get_time_solver().is_adjoint();
return ap;
}
void MultiphysicsSystem::register_postprocessing_vars( const GetPot& input,
PostProcessedQuantities<libMesh::Real>& postprocessing )
{
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->register_postprocessing_vars( input, postprocessing );
}
return;
}
void MultiphysicsSystem::init_context( libMesh::DiffContext& context )
{
AssemblyContext& c = libMesh::libmesh_cast_ref<AssemblyContext&>(context);
//Loop over each physics to initialize relevant variable structures for assembling system
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->init_context( c );
}
return;
}
bool MultiphysicsSystem::_general_residual( bool request_jacobian,
libMesh::DiffContext& context,
ResFuncType resfunc,
CacheFuncType cachefunc)
{
AssemblyContext& c = libMesh::libmesh_cast_ref<AssemblyContext&>(context);
bool compute_jacobian = true;
if( !request_jacobian || _use_numerical_jacobians_only ) compute_jacobian = false;
CachedValues cache;
// Now compute cache for this element
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// boost::shared_ptr gets confused by operator->*
((*(physics_iter->second)).*cachefunc)( c, cache );
}
// Loop over each physics and compute their contributions
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Only compute if physics is active on current subdomain or globally
if( (physics_iter->second)->enabled_on_elem( &c.get_elem() ) )
{
((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );
}
}
// TODO: Need to think about the implications of this because there might be some
// TODO: jacobian terms we don't want to compute for efficiency reasons
return compute_jacobian;
}
bool MultiphysicsSystem::element_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::element_time_derivative,
&GRINS::Physics::compute_element_time_derivative_cache);
}
bool MultiphysicsSystem::side_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::side_time_derivative,
&GRINS::Physics::compute_side_time_derivative_cache);
}
bool MultiphysicsSystem::nonlocal_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_time_derivative,
&GRINS::Physics::compute_nonlocal_time_derivative_cache);
}
bool MultiphysicsSystem::element_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::element_constraint,
&GRINS::Physics::compute_element_constraint_cache);
}
bool MultiphysicsSystem::side_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::side_constraint,
&GRINS::Physics::compute_side_constraint_cache);
}
bool MultiphysicsSystem::nonlocal_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_constraint,
&GRINS::Physics::compute_nonlocal_constraint_cache);
}
bool MultiphysicsSystem::mass_residual( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::mass_residual,
&GRINS::Physics::compute_mass_residual_cache);
}
bool MultiphysicsSystem::nonlocal_mass_residual( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_mass_residual,
&GRINS::Physics::compute_nonlocal_mass_residual_cache);
}
std::tr1::shared_ptr<Physics> MultiphysicsSystem::get_physics( const std::string physics_name )
{
if( _physics_list.find( physics_name ) == _physics_list.end() )
{
std::cerr << "Error: Could not find physics " << physics_name << std::endl;
libmesh_error();
}
return _physics_list[physics_name];
}
bool MultiphysicsSystem::has_physics( const std::string physics_name ) const
{
bool has_physics = false;
if( _physics_list.find(physics_name) != _physics_list.end() )
has_physics = true;
return has_physics;
}
void MultiphysicsSystem::compute_postprocessed_quantity( unsigned int quantity_index,
const AssemblyContext& context,
const libMesh::Point& point,
libMesh::Real& value )
{
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->compute_postprocessed_quantity( quantity_index, context, point, value );
}
return;
}
#ifdef GRINS_USE_GRVY_TIMERS
void MultiphysicsSystem::attach_grvy_timer( GRVY::GRVY_Timer_Class* grvy_timer )
{
_timer = grvy_timer;
// Attach timers to each physics
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->attach_grvy_timer( grvy_timer );
}
return;
}
#endif
} // namespace GRINS
<commit_msg>Only call Physics for postprocessing if it's active on subdomain<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/multiphysics_sys.h"
// GRINS
#include "grins/composite_function.h"
#include "grins/assembly_context.h"
// libMesh
#include "libmesh/getpot.h"
namespace GRINS
{
MultiphysicsSystem::MultiphysicsSystem( libMesh::EquationSystems& es,
const std::string& name,
const unsigned int number )
: FEMSystem(es, name, number),
_use_numerical_jacobians_only(false)
{
return;
}
MultiphysicsSystem::~MultiphysicsSystem()
{
return;
}
void MultiphysicsSystem::attach_physics_list( PhysicsList physics_list )
{
_physics_list = physics_list;
return;
}
void MultiphysicsSystem::read_input_options( const GetPot& input )
{
// Read options for MultiphysicsSystem first
this->verify_analytic_jacobians = input("linear-nonlinear-solver/verify_analytic_jacobians", 0.0 );
this->print_solution_norms = input("screen-options/print_solution_norms", false );
this->print_solutions = input("screen-options/print_solutions", false );
this->print_residual_norms = input("screen-options/print_residual_norms", false );
// backwards compatibility with old config files.
/*! \todo Remove old print_residual nomenclature */
this->print_residuals = input("screen-options/print_residual", false );
if (this->print_residuals)
libmesh_deprecated();
this->print_residuals = input("screen-options/print_residuals", this->print_residuals );
this->print_jacobian_norms = input("screen-options/print_jacobian_norms", false );
this->print_jacobians = input("screen-options/print_jacobians", false );
this->print_element_solutions = input("screen-options/print_element_solutions", false );
this->print_element_residuals = input("screen-options/print_element_residuals", false );
this->print_element_jacobians = input("screen-options/print_element_jacobians", false );
_use_numerical_jacobians_only = input("linear-nonlinear-solver/use_numerical_jacobians_only", false );
numerical_jacobian_h =
input("linear-nonlinear-solver/numerical_jacobian_h",
numerical_jacobian_h);
}
void MultiphysicsSystem::init_data()
{
// Need this to be true because of our overloading of the
// mass_residual function.
// This is data in FEMSystem. MUST be set before FEMSystem::init_data.
use_fixed_solution = true;
// Initalize all the variables. We pass this pointer for the system.
/* NOTE: We CANNOT fuse this loop with the others. This loop
MUST complete first. */
/*! \todo Figure out how to tell compilers not to fuse this loop when
they want to be aggressive. */
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->init_variables( this );
}
// Now set time_evolving variables
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->set_time_evolving_vars( this );
}
// Set whether the problem we're solving is steady or not
// Since the variable is static, just call one Physics class
{
(_physics_list.begin()->second)->set_is_steady((this->time_solver)->is_steady());
}
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Initialize builtin BC's for each physics
(physics_iter->second)->init_bcs( this );
}
// Next, call parent init_data function to intialize everything.
libMesh::FEMSystem::init_data();
// After solution has been initialized we can project initial
// conditions to it
CompositeFunction<libMesh::Number> ic_function;
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Initialize builtin IC's for each physics
(physics_iter->second)->init_ics( this, ic_function );
}
if (ic_function.n_subfunctions())
{
this->project_solution(&ic_function);
}
return;
}
libMesh::AutoPtr<libMesh::DiffContext> MultiphysicsSystem::build_context()
{
AssemblyContext* context = new AssemblyContext(*this);
libMesh::AutoPtr<libMesh::DiffContext> ap(context);
libMesh::DifferentiablePhysics* phys = libMesh::FEMSystem::get_physics();
libmesh_assert(phys);
// If we are solving a moving mesh problem, tell that to the Context
context->set_mesh_system(phys->get_mesh_system());
context->set_mesh_x_var(phys->get_mesh_x_var());
context->set_mesh_y_var(phys->get_mesh_y_var());
context->set_mesh_z_var(phys->get_mesh_z_var());
ap->set_deltat_pointer( &deltat );
// If we are solving the adjoint problem, tell that to the Context
ap->is_adjoint() = this->get_time_solver().is_adjoint();
return ap;
}
void MultiphysicsSystem::register_postprocessing_vars( const GetPot& input,
PostProcessedQuantities<libMesh::Real>& postprocessing )
{
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->register_postprocessing_vars( input, postprocessing );
}
return;
}
void MultiphysicsSystem::init_context( libMesh::DiffContext& context )
{
AssemblyContext& c = libMesh::libmesh_cast_ref<AssemblyContext&>(context);
//Loop over each physics to initialize relevant variable structures for assembling system
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->init_context( c );
}
return;
}
bool MultiphysicsSystem::_general_residual( bool request_jacobian,
libMesh::DiffContext& context,
ResFuncType resfunc,
CacheFuncType cachefunc)
{
AssemblyContext& c = libMesh::libmesh_cast_ref<AssemblyContext&>(context);
bool compute_jacobian = true;
if( !request_jacobian || _use_numerical_jacobians_only ) compute_jacobian = false;
CachedValues cache;
// Now compute cache for this element
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// boost::shared_ptr gets confused by operator->*
((*(physics_iter->second)).*cachefunc)( c, cache );
}
// Loop over each physics and compute their contributions
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Only compute if physics is active on current subdomain or globally
if( (physics_iter->second)->enabled_on_elem( &c.get_elem() ) )
{
((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );
}
}
// TODO: Need to think about the implications of this because there might be some
// TODO: jacobian terms we don't want to compute for efficiency reasons
return compute_jacobian;
}
bool MultiphysicsSystem::element_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::element_time_derivative,
&GRINS::Physics::compute_element_time_derivative_cache);
}
bool MultiphysicsSystem::side_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::side_time_derivative,
&GRINS::Physics::compute_side_time_derivative_cache);
}
bool MultiphysicsSystem::nonlocal_time_derivative( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_time_derivative,
&GRINS::Physics::compute_nonlocal_time_derivative_cache);
}
bool MultiphysicsSystem::element_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::element_constraint,
&GRINS::Physics::compute_element_constraint_cache);
}
bool MultiphysicsSystem::side_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::side_constraint,
&GRINS::Physics::compute_side_constraint_cache);
}
bool MultiphysicsSystem::nonlocal_constraint( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_constraint,
&GRINS::Physics::compute_nonlocal_constraint_cache);
}
bool MultiphysicsSystem::mass_residual( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::mass_residual,
&GRINS::Physics::compute_mass_residual_cache);
}
bool MultiphysicsSystem::nonlocal_mass_residual( bool request_jacobian,
libMesh::DiffContext& context )
{
return this->_general_residual
(request_jacobian,
context,
&GRINS::Physics::nonlocal_mass_residual,
&GRINS::Physics::compute_nonlocal_mass_residual_cache);
}
std::tr1::shared_ptr<Physics> MultiphysicsSystem::get_physics( const std::string physics_name )
{
if( _physics_list.find( physics_name ) == _physics_list.end() )
{
std::cerr << "Error: Could not find physics " << physics_name << std::endl;
libmesh_error();
}
return _physics_list[physics_name];
}
bool MultiphysicsSystem::has_physics( const std::string physics_name ) const
{
bool has_physics = false;
if( _physics_list.find(physics_name) != _physics_list.end() )
has_physics = true;
return has_physics;
}
void MultiphysicsSystem::compute_postprocessed_quantity( unsigned int quantity_index,
const AssemblyContext& context,
const libMesh::Point& point,
libMesh::Real& value )
{
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
// Only compute if physics is active on current subdomain or globally
if( (physics_iter->second)->enabled_on_elem( &context.get_elem() ) )
{
(physics_iter->second)->compute_postprocessed_quantity( quantity_index, context, point, value );
}
}
return;
}
#ifdef GRINS_USE_GRVY_TIMERS
void MultiphysicsSystem::attach_grvy_timer( GRVY::GRVY_Timer_Class* grvy_timer )
{
_timer = grvy_timer;
// Attach timers to each physics
for( PhysicsListIter physics_iter = _physics_list.begin();
physics_iter != _physics_list.end();
physics_iter++ )
{
(physics_iter->second)->attach_grvy_timer( grvy_timer );
}
return;
}
#endif
} // namespace GRINS
<|endoftext|>
|
<commit_before>/* Copyright (c) 2013-2015 Jeffrey Pfau
*
* 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 "AudioProcessor.h"
#ifdef BUILD_SDL
#include "AudioProcessorSDL.h"
#endif
#ifdef BUILD_QT_MULTIMEDIA
#include "AudioProcessorQt.h"
#endif
extern "C" {
#include "gba/supervisor/thread.h"
}
using namespace QGBA;
#ifndef BUILD_SDL
AudioProcessor::Driver AudioProcessor::s_driver = AudioProcessor::Driver::QT_MULTIMEDIA;
#else
AudioProcessor::Driver AudioProcessor::s_driver = AudioProcessor::Driver::SDL;
#endif
AudioProcessor* AudioProcessor::create() {
switch (s_driver) {
#ifdef BUILD_SDL
case Driver::SDL:
return new AudioProcessorSDL();
#endif
#ifdef BUILD_QT_MULTIMEDIA
case Driver::QT_MULTIMEDIA:
return new AudioProcessorQt();
#endif
default:
#ifdef BUILD_QT_MULTIMEDIA
return new AudioProcessorQt();
#else
return new AudioProcessorSDL();
#endif
}
}
AudioProcessor::AudioProcessor(QObject* parent)
: QObject(parent)
, m_context(nullptr)
, m_samples(GBA_AUDIO_SAMPLES)
{
}
void AudioProcessor::setInput(GBAThread* input) {
m_context = input;
}
void AudioProcessor::setBufferSamples(int samples) {
m_samples = samples;
}
<commit_msg>Qt: Switch default AudioProcessor to SDL<commit_after>/* Copyright (c) 2013-2015 Jeffrey Pfau
*
* 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 "AudioProcessor.h"
#ifdef BUILD_SDL
#include "AudioProcessorSDL.h"
#endif
#ifdef BUILD_QT_MULTIMEDIA
#include "AudioProcessorQt.h"
#endif
extern "C" {
#include "gba/supervisor/thread.h"
}
using namespace QGBA;
#ifndef BUILD_SDL
AudioProcessor::Driver AudioProcessor::s_driver = AudioProcessor::Driver::QT_MULTIMEDIA;
#else
AudioProcessor::Driver AudioProcessor::s_driver = AudioProcessor::Driver::SDL;
#endif
AudioProcessor* AudioProcessor::create() {
switch (s_driver) {
#ifdef BUILD_SDL
case Driver::SDL:
return new AudioProcessorSDL();
#endif
#ifdef BUILD_QT_MULTIMEDIA
case Driver::QT_MULTIMEDIA:
return new AudioProcessorQt();
#endif
default:
#ifdef BUILD_SDL
return new AudioProcessorSDL();
#else
return new AudioProcessorQt();
#endif
}
}
AudioProcessor::AudioProcessor(QObject* parent)
: QObject(parent)
, m_context(nullptr)
, m_samples(GBA_AUDIO_SAMPLES)
{
}
void AudioProcessor::setInput(GBAThread* input) {
m_context = input;
}
void AudioProcessor::setBufferSamples(int samples) {
m_samples = samples;
}
<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "LibMTDevEventSource.h"
#include "LinuxMTHelper.h"
#include "TouchEvent.h"
#include "Player.h"
#include "AVGNode.h"
#include "TouchStatus.h"
#include "../base/Logger.h"
#include "../base/Point.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"
#include <linux/input.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <set>
extern "C" {
#include <mtdev.h>
#include <mtdev-mapping.h>
}
using namespace std;
namespace avg {
LibMTDevEventSource::LibMTDevEventSource()
: m_LastID(0),
m_pMTDevice(0)
{
}
LibMTDevEventSource::~LibMTDevEventSource()
{
if (m_pMTDevice) {
mtdev_close(m_pMTDevice);
delete m_pMTDevice;
}
}
void LibMTDevEventSource::start()
{
string sDevice = "/dev/input/event3";
m_DeviceFD = ::open(sDevice.c_str(), O_RDONLY | O_NONBLOCK);
if (m_DeviceFD == -1) {
throw Exception(AVG_ERR_MT_INIT,
string("Linux multitouch event source: Could not open device file '")+
sDevice+"'. "+strerror(errno)+".");
}
m_pMTDevice = new mtdev;
int err = mtdev_open(m_pMTDevice, m_DeviceFD);
if (err == -1) {
throw Exception(AVG_ERR_MT_INIT,
string("Linux multitouch event source: Could not open mtdev '")+
sDevice+"'. "+strerror(errno)+".");
}
input_absinfo* pAbsInfo;
pAbsInfo = &(m_pMTDevice->caps.abs[MTDEV_POSITION_X]);
m_Dimensions.tl.x = pAbsInfo->minimum;
m_Dimensions.br.x = pAbsInfo->maximum;
pAbsInfo = &(m_pMTDevice->caps.abs[MTDEV_POSITION_Y]);
m_Dimensions.tl.y = pAbsInfo->minimum;
m_Dimensions.br.y = pAbsInfo->maximum;
MultitouchEventSource::start();
AVG_TRACE(Logger::CONFIG, "Linux MTDev Multitouch event source created.");
}
std::vector<EventPtr> LibMTDevEventSource::pollEvents()
{
struct input_event events[64];
int numEvents = mtdev_get(m_pMTDevice, m_DeviceFD, events, 64);
if (numEvents < 0) {
cerr << "numEvents: " << numEvents << endl;
}
/*
if (numEvents > 0) {
cerr << "---- read ----" << endl;
}
*/
static int curSlot = 0;
set<int> changedIDs;
for (int i = 0; i < numEvents; ++i) {
input_event event = events[i];
if (event.type == EV_ABS && event.code == ABS_MT_SLOT) {
cerr << ">> slot " << event.value << endl;
curSlot = event.value;
} else {
TouchData* pTouch;
switch (event.code) {
case ABS_MT_TRACKING_ID:
// cerr << ">> ABS_MT_TRACKING_ID: " << event.value << endl;
pTouch = &(m_Slots[curSlot]);
if (event.value == -1) {
TouchStatusPtr pTouchStatus = getTouchStatus(pTouch->id);
// cerr << "up " << pTouch->id << endl;
if (pTouchStatus) {
// cerr << " --> remove" << endl;
TouchEventPtr pOldEvent = pTouchStatus->getLastEvent();
TouchEventPtr pUpEvent =
boost::dynamic_pointer_cast<TouchEvent>(
pOldEvent->cloneAs(Event::CURSORUP));
pTouchStatus->updateEvent(pUpEvent);
}
pTouch->id = -1;
} else {
pTouch->id = event.value;
}
break;
case ABS_MT_POSITION_X:
// cerr << ">> ABS_MT_POSITION_X: " << event.value << endl;
pTouch = &(m_Slots[curSlot]);
pTouch->pos.x = event.value;
break;
case ABS_MT_POSITION_Y:
// cerr << ">> ABS_MT_POSITION_Y: " << event.value << endl;
pTouch = &(m_Slots[curSlot]);
pTouch->pos.y = event.value;
break;
default:
break;
}
// cerr << ">> new id: " << curSlot << endl;
changedIDs.insert(curSlot);
}
}
for (set<int>::iterator it = changedIDs.begin(); it != changedIDs.end(); ++it) {
map<int, TouchData>::iterator it2 = m_Slots.find(*it);
if (it2 != m_Slots.end()) {
const TouchData& touch = it2->second;
// cerr << "slot: " << *it << ", id: " << touch.id << ", pos: " << touch.pos
// << endl;
// AVG_ASSERT(touch.pos.x != 0);
if (touch.id != -1) {
TouchStatusPtr pTouchStatus = getTouchStatus(touch.id);
if (!pTouchStatus) {
// cerr << "down" << endl;
// Down
m_LastID++;
TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSORDOWN,
touch.pos);
addTouchStatus((long)touch.id, pEvent);
} else {
// cerr << "move" << endl;
// Move
TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION, touch.pos);
pTouchStatus->updateEvent(pEvent);
}
}
}
}
/*
static int numContacts = 0;
static int tmpID;
static IntPoint tmpPos;
struct input_event event[64];
char * pReadPos = (char*)(void*)&event;
ssize_t numBytes = 0;
ssize_t newBytes = -1;
while (newBytes != 0) {
newBytes = read(m_DeviceFD, pReadPos+numBytes, sizeof(input_event));
if (newBytes == -1) {
newBytes = 0;
}
numBytes += newBytes;
}
AVG_ASSERT(numBytes%sizeof(input_event) == 0);
if (numBytes > 0) {
cerr << "---- read ----" << endl;
}
for (unsigned i = 0; i < numBytes/sizeof(input_event); ++i) {
switch (event[i].type) {
case EV_ABS:
cerr << "EV_ABS " << mtCodeToString(event[i].code) << endl;
switch (event[i].code) {
case ABS_MT_TRACKING_ID:
numContacts++;
tmpID = event[i].value;
break;
case ABS_MT_POSITION_X:
tmpPos.x = event[i].value;
break;
case ABS_MT_POSITION_Y:
tmpPos.y = event[i].value;
break;
default:
break;
}
break;
case EV_SYN:
cerr << "EV_SYN " << synCodeToString(event[i].code) << endl;
switch (event[i].code) {
case SYN_MT_REPORT:
{
cerr << "id: " << tmpID << ", pos: " << tmpPos << endl;
TouchStatusPtr pTouchStatus = getTouchStatus(tmpID);
if (!pTouchStatus) {
// Down
m_LastID++;
TouchEventPtr pEvent = createEvent(m_LastID,
Event::CURSORDOWN, tmpPos);
addTouchStatus((long)tmpID, pEvent);
} else {
// Move
TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION,
tmpPos);
pTouchStatus->updateEvent(pEvent);
}
}
break;
case SYN_REPORT:
cerr << "SYN_REPORT" << endl;
break;
default:
break;
}
break;
default:
// cerr << "Unexpected type " << eventTypeToString(event[i].type) << endl;
break;
}
}
*/
return MultitouchEventSource::pollEvents();
}
TouchEventPtr LibMTDevEventSource::createEvent(int id, Event::Type type, IntPoint pos)
{
DPoint size = getWindowSize();
DPoint normPos = DPoint(double(pos.x-m_Dimensions.tl.x)/m_Dimensions.width(),
double(pos.y-m_Dimensions.tl.y)/m_Dimensions.height());
IntPoint screenPos(int(normPos.x*size.x+0.5), int(normPos.y*size.y+0.5));
return TouchEventPtr(new TouchEvent(id, type, screenPos, Event::TOUCH, DPoint(0,0),
0, 20, 1, DPoint(5,0), DPoint(0,5)));
}
}
<commit_msg>Added AVG_LINUX_MULTITOUCH_DEVICE environment variable.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "LibMTDevEventSource.h"
#include "LinuxMTHelper.h"
#include "TouchEvent.h"
#include "Player.h"
#include "AVGNode.h"
#include "TouchStatus.h"
#include "../base/Logger.h"
#include "../base/Point.h"
#include "../base/ObjectCounter.h"
#include "../base/Exception.h"
#include "../base/OSHelper.h"
#include <linux/input.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <set>
extern "C" {
#include <mtdev.h>
#include <mtdev-mapping.h>
}
using namespace std;
namespace avg {
LibMTDevEventSource::LibMTDevEventSource()
: m_LastID(0),
m_pMTDevice(0)
{
}
LibMTDevEventSource::~LibMTDevEventSource()
{
if (m_pMTDevice) {
mtdev_close(m_pMTDevice);
delete m_pMTDevice;
}
}
void LibMTDevEventSource::start()
{
string sDevice("/dev/input/event3");
getEnv("AVG_LINUX_MULTITOUCH_DEVICE", sDevice);
m_DeviceFD = ::open(sDevice.c_str(), O_RDONLY | O_NONBLOCK);
if (m_DeviceFD == -1) {
throw Exception(AVG_ERR_MT_INIT,
string("Linux multitouch event source: Could not open device file '")+
sDevice+"'. "+strerror(errno)+".");
}
m_pMTDevice = new mtdev;
int err = mtdev_open(m_pMTDevice, m_DeviceFD);
if (err == -1) {
throw Exception(AVG_ERR_MT_INIT,
string("Linux multitouch event source: Could not open mtdev '")+
sDevice+"'. "+strerror(errno)+".");
}
input_absinfo* pAbsInfo;
pAbsInfo = &(m_pMTDevice->caps.abs[MTDEV_POSITION_X]);
m_Dimensions.tl.x = pAbsInfo->minimum;
m_Dimensions.br.x = pAbsInfo->maximum;
pAbsInfo = &(m_pMTDevice->caps.abs[MTDEV_POSITION_Y]);
m_Dimensions.tl.y = pAbsInfo->minimum;
m_Dimensions.br.y = pAbsInfo->maximum;
MultitouchEventSource::start();
AVG_TRACE(Logger::CONFIG, "Linux MTDev Multitouch event source created.");
}
std::vector<EventPtr> LibMTDevEventSource::pollEvents()
{
struct input_event events[64];
int numEvents = mtdev_get(m_pMTDevice, m_DeviceFD, events, 64);
if (numEvents < 0) {
cerr << "numEvents: " << numEvents << endl;
}
/*
if (numEvents > 0) {
cerr << "---- read ----" << endl;
}
*/
static int curSlot = 0;
set<int> changedIDs;
for (int i = 0; i < numEvents; ++i) {
input_event event = events[i];
if (event.type == EV_ABS && event.code == ABS_MT_SLOT) {
cerr << ">> slot " << event.value << endl;
curSlot = event.value;
} else {
TouchData* pTouch;
switch (event.code) {
case ABS_MT_TRACKING_ID:
// cerr << ">> ABS_MT_TRACKING_ID: " << event.value << endl;
pTouch = &(m_Slots[curSlot]);
if (event.value == -1) {
TouchStatusPtr pTouchStatus = getTouchStatus(pTouch->id);
// cerr << "up " << pTouch->id << endl;
if (pTouchStatus) {
// cerr << " --> remove" << endl;
TouchEventPtr pOldEvent = pTouchStatus->getLastEvent();
TouchEventPtr pUpEvent =
boost::dynamic_pointer_cast<TouchEvent>(
pOldEvent->cloneAs(Event::CURSORUP));
pTouchStatus->updateEvent(pUpEvent);
}
pTouch->id = -1;
} else {
pTouch->id = event.value;
}
break;
case ABS_MT_POSITION_X:
// cerr << ">> ABS_MT_POSITION_X: " << event.value << endl;
pTouch = &(m_Slots[curSlot]);
pTouch->pos.x = event.value;
break;
case ABS_MT_POSITION_Y:
// cerr << ">> ABS_MT_POSITION_Y: " << event.value << endl;
pTouch = &(m_Slots[curSlot]);
pTouch->pos.y = event.value;
break;
default:
break;
}
// cerr << ">> new id: " << curSlot << endl;
changedIDs.insert(curSlot);
}
}
for (set<int>::iterator it = changedIDs.begin(); it != changedIDs.end(); ++it) {
map<int, TouchData>::iterator it2 = m_Slots.find(*it);
if (it2 != m_Slots.end()) {
const TouchData& touch = it2->second;
// cerr << "slot: " << *it << ", id: " << touch.id << ", pos: " << touch.pos
// << endl;
// AVG_ASSERT(touch.pos.x != 0);
if (touch.id != -1) {
TouchStatusPtr pTouchStatus = getTouchStatus(touch.id);
if (!pTouchStatus) {
// cerr << "down" << endl;
// Down
m_LastID++;
TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSORDOWN,
touch.pos);
addTouchStatus((long)touch.id, pEvent);
} else {
// cerr << "move" << endl;
// Move
TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION, touch.pos);
pTouchStatus->updateEvent(pEvent);
}
}
}
}
/*
static int numContacts = 0;
static int tmpID;
static IntPoint tmpPos;
struct input_event event[64];
char * pReadPos = (char*)(void*)&event;
ssize_t numBytes = 0;
ssize_t newBytes = -1;
while (newBytes != 0) {
newBytes = read(m_DeviceFD, pReadPos+numBytes, sizeof(input_event));
if (newBytes == -1) {
newBytes = 0;
}
numBytes += newBytes;
}
AVG_ASSERT(numBytes%sizeof(input_event) == 0);
if (numBytes > 0) {
cerr << "---- read ----" << endl;
}
for (unsigned i = 0; i < numBytes/sizeof(input_event); ++i) {
switch (event[i].type) {
case EV_ABS:
cerr << "EV_ABS " << mtCodeToString(event[i].code) << endl;
switch (event[i].code) {
case ABS_MT_TRACKING_ID:
numContacts++;
tmpID = event[i].value;
break;
case ABS_MT_POSITION_X:
tmpPos.x = event[i].value;
break;
case ABS_MT_POSITION_Y:
tmpPos.y = event[i].value;
break;
default:
break;
}
break;
case EV_SYN:
cerr << "EV_SYN " << synCodeToString(event[i].code) << endl;
switch (event[i].code) {
case SYN_MT_REPORT:
{
cerr << "id: " << tmpID << ", pos: " << tmpPos << endl;
TouchStatusPtr pTouchStatus = getTouchStatus(tmpID);
if (!pTouchStatus) {
// Down
m_LastID++;
TouchEventPtr pEvent = createEvent(m_LastID,
Event::CURSORDOWN, tmpPos);
addTouchStatus((long)tmpID, pEvent);
} else {
// Move
TouchEventPtr pEvent = createEvent(0, Event::CURSORMOTION,
tmpPos);
pTouchStatus->updateEvent(pEvent);
}
}
break;
case SYN_REPORT:
cerr << "SYN_REPORT" << endl;
break;
default:
break;
}
break;
default:
// cerr << "Unexpected type " << eventTypeToString(event[i].type) << endl;
break;
}
}
*/
return MultitouchEventSource::pollEvents();
}
TouchEventPtr LibMTDevEventSource::createEvent(int id, Event::Type type, IntPoint pos)
{
DPoint size = getWindowSize();
DPoint normPos = DPoint(double(pos.x-m_Dimensions.tl.x)/m_Dimensions.width(),
double(pos.y-m_Dimensions.tl.y)/m_Dimensions.height());
IntPoint screenPos(int(normPos.x*size.x+0.5), int(normPos.y*size.y+0.5));
return TouchEventPtr(new TouchEvent(id, type, screenPos, Event::TOUCH, DPoint(0,0),
0, 20, 1, DPoint(5,0), DPoint(0,5)));
}
}
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen
// =============================================================================
//
// Main driver function for the HMMWV 9-body model, using rigid tire-terrain
// contact.
//
// If using the Irrlicht interface, river inputs are obtained from the keyboard.
//
// The global reference frame has Z up, X towards the back of the vehicle, and
// Y pointing to the right.
//
// =============================================================================
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "HMMWV9.h"
#include "HMMWV9_Vehicle.h"
#include "HMMWV9_FuncDriver.h"
#include "HMMWV9_RigidTerrain.h"
// If Irrlicht support is available...
#if IRRLICHT_ENABLED
// ...include additional headers
# include "unit_IRRLICHT/ChIrrApp.h"
# include "subsys/driver/ChIrrGuiDriver.h"
// ...and specify whether the demo should actually use Irrlicht
# define USE_IRRLICHT
#endif
using namespace chrono;
using namespace hmmwv9;
// =============================================================================
// Initial vehicle position
ChVector<> initLoc(40, 0, 1.7); // sprung mass height at design = 49.68 in
ChQuaternion<> initRot(1,0,0,0); // forward is in the negative global x-direction
// Rigid terrain dimensions
double terrainHeight = 0;
double terrainLength = 100.0; // size in X direction
double terrainWidth = 100.0; // size in Y directoin
// Simulation step size
double step_size = 0.001;
// Rendering FPS
int FPS = 50;
#ifdef USE_IRRLICHT
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0, 1.0);
#else
double tend = 20.0;
const std::string out_dir = "../HMMWV9";
const std::string pov_dir = out_dir + "/POVRAY";
#endif
// =============================================================================
int main(int argc, char* argv[])
{
SetChronoDataPath(CHRONO_DATA_DIR);
// ---------------------
// Create the subsystems
// ---------------------
// Create the HMMWV vehicle
HMMWV9_Vehicle vehicle(false,
hmmwv9::MESH,
hmmwv9::MESH);
vehicle.Initialize(ChCoordsys<>(initLoc, initRot));
// Create the ground
HMMWV9_RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8);
//terrain.AddMovingObstacles(10);
terrain.AddFixedObstacles();
#ifdef USE_IRRLICHT
irr::ChIrrApp application(&vehicle,
L"HMMWV 9-body demo",
irr::core::dimension2d<irr::u32>(1000, 800),
false,
true);
// make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up)
std::string mtexturedir = GetChronoDataFile("skybox/");
std::string str_lf = mtexturedir + "sky_lf.jpg";
std::string str_up = mtexturedir + "sky_up.jpg";
std::string str_dn = mtexturedir + "sky_dn.jpg";
irr::video::ITexture* map_skybox_side =
application.GetVideoDriver()->getTexture(str_lf.c_str());
irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
application.GetVideoDriver()->getTexture(str_up.c_str()),
application.GetVideoDriver()->getTexture(str_dn.c_str()),
map_skybox_side,
map_skybox_side,
map_skybox_side,
map_skybox_side);
mbox->setRotation( irr::core::vector3df(90,0,0));
application.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f),
irr::core::vector3df(30.f, 50.f, 100.f),
250, 130);
application.SetTimestep(step_size);
ChIrrGuiDriver driver(application, vehicle, trackPoint, 6, 0.5);
// Set the time response for steering and throttle keyboard inputs.
// NOTE: this is not exact, since we do not render quite at the specified FPS.
double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1)
double throttle_time = 1.0; // time to go from 0 to +1
driver.SetSteeringDelta(1 / (steering_time * FPS));
driver.SetThrottleDelta(1 / (throttle_time * FPS));
// Set up the assets for rendering
application.AssetBindAll();
application.AssetUpdateAll();
#else
HMMWV9_FuncDriver driver;
#endif
// ---------------
// Simulation loop
// ---------------
#ifdef USE_IRRLICHT
ChRealtimeStepTimer realtime_timer;
// Refresh 3D view only every N simulation steps:
int simul_substeps_num = (int) std::ceil((1 / step_size) / FPS);
int simul_substep = 0;
while (application.GetDevice()->run())
{
// Render scene
if (simul_substep == 0) {
application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));
driver.DrawAll();
application.GetVideoDriver()->endScene();
}
// Update subsystems
double time = vehicle.GetChTime();
driver.Update(time);
vehicle.Update(time, driver.getThrottle(), driver.getSteering());
// Advance simulation for one timestep.
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
vehicle.Advance(step);
++simul_substep;
if (simul_substep >= simul_substeps_num)
simul_substep = 0;
}
application.GetDevice()->drop();
#else
int out_steps = (int) std::ceil((1 / step_size) / FPS);
double time = 0;
int frame = 0;
int out_frame = 0;
if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
HMMWV9_Vehicle::ExportMeshPovray(out_dir);
HMMWV9_WheelLeft::ExportMeshPovray(out_dir);
HMMWV9_WheelRight::ExportMeshPovray(out_dir);
char filename[100];
while (time < tend)
{
if (frame % out_steps == 0) {
// Output render data
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), out_frame + 1);
utils::WriteShapesPovray(&m_system, filename);
std::cout << "Output frame: " << out_frame << std::endl;
std::cout << "Sim frame: " << frame << std::endl;
std::cout << "Time: " << time << std::endl;
std::cout << " throttle: " << driver.getThrottle() << " steering: " << driver.getSteering() << std::endl;
std::cout << std::endl;
out_frame++;
}
// Update subsystems
driver.Update(time);
vehicle.Update(time, driver.getThrottle(), driver.getSteering());
// Advance simulation for one timestep.
driver.Advance(step_size);
vehicle.DoStepDynamics(step_size);
time += step_size;
frame++;
}
#endif
return 0;
}
<commit_msg>Update the HMMWV9 main driver function to use tire modules.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen
// =============================================================================
//
// Main driver function for the HMMWV 9-body model, using rigid tire-terrain
// contact.
//
// If using the Irrlicht interface, river inputs are obtained from the keyboard.
//
// The global reference frame has Z up, X towards the back of the vehicle, and
// Y pointing to the right.
//
// =============================================================================
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "HMMWV9.h"
#include "HMMWV9_Vehicle.h"
#include "HMMWV9_FuncDriver.h"
#include "HMMWV9_RigidTire.h"
#include "HMMWV9_RigidTerrain.h"
// If Irrlicht support is available...
#if IRRLICHT_ENABLED
// ...include additional headers
# include "unit_IRRLICHT/ChIrrApp.h"
# include "subsys/driver/ChIrrGuiDriver.h"
// ...and specify whether the demo should actually use Irrlicht
# define USE_IRRLICHT
#endif
using namespace chrono;
using namespace hmmwv9;
// =============================================================================
// Initial vehicle position
ChVector<> initLoc(40, 0, 1.7); // sprung mass height at design = 49.68 in
ChQuaternion<> initRot(1,0,0,0); // forward is in the negative global x-direction
// Rigid terrain dimensions
double terrainHeight = 0;
double terrainLength = 100.0; // size in X direction
double terrainWidth = 100.0; // size in Y directoin
// Simulation step size
double step_size = 0.001;
// Rendering FPS
int FPS = 50;
#ifdef USE_IRRLICHT
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0, 1.0);
#else
double tend = 20.0;
const std::string out_dir = "../HMMWV9";
const std::string pov_dir = out_dir + "/POVRAY";
#endif
// =============================================================================
int main(int argc, char* argv[])
{
SetChronoDataPath(CHRONO_DATA_DIR);
// --------------------------
// Create the various modules
// --------------------------
// Create the HMMWV vehicle
HMMWV9_Vehicle vehicle(false,
hmmwv9::MESH,
hmmwv9::MESH);
vehicle.Initialize(ChCoordsys<>(initLoc, initRot));
// Create the tires
HMMWV9_RigidTire tire_front_right(0.7f);
HMMWV9_RigidTire tire_front_left(0.7f);
HMMWV9_RigidTire tire_rear_right(0.7f);
HMMWV9_RigidTire tire_rear_left(0.7f);
tire_front_right.Initialize(vehicle.GetWheelBody(FRONT_RIGHT));
tire_front_left.Initialize(vehicle.GetWheelBody(FRONT_LEFT));
tire_rear_right.Initialize(vehicle.GetWheelBody(REAR_RIGHT));
tire_rear_left.Initialize(vehicle.GetWheelBody(REAR_LEFT));
// Create the ground
HMMWV9_RigidTerrain terrain(vehicle, terrainHeight, terrainLength, terrainWidth, 0.8);
//terrain.AddMovingObstacles(10);
terrain.AddFixedObstacles();
#ifdef USE_IRRLICHT
irr::ChIrrApp application(&vehicle,
L"HMMWV 9-body demo",
irr::core::dimension2d<irr::u32>(1000, 800),
false,
true);
// make a skybox that has Z pointing up (default application.AddTypicalSky() makes Y up)
std::string mtexturedir = GetChronoDataFile("skybox/");
std::string str_lf = mtexturedir + "sky_lf.jpg";
std::string str_up = mtexturedir + "sky_up.jpg";
std::string str_dn = mtexturedir + "sky_dn.jpg";
irr::video::ITexture* map_skybox_side =
application.GetVideoDriver()->getTexture(str_lf.c_str());
irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
application.GetVideoDriver()->getTexture(str_up.c_str()),
application.GetVideoDriver()->getTexture(str_dn.c_str()),
map_skybox_side,
map_skybox_side,
map_skybox_side,
map_skybox_side);
mbox->setRotation( irr::core::vector3df(90,0,0));
application.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f),
irr::core::vector3df(30.f, 50.f, 100.f),
250, 130);
application.SetTimestep(step_size);
ChIrrGuiDriver driver(application, vehicle, trackPoint, 6, 0.5);
// Set the time response for steering and throttle keyboard inputs.
// NOTE: this is not exact, since we do not render quite at the specified FPS.
double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1)
double throttle_time = 1.0; // time to go from 0 to +1
driver.SetSteeringDelta(1 / (steering_time * FPS));
driver.SetThrottleDelta(1 / (throttle_time * FPS));
// Set up the assets for rendering
application.AssetBindAll();
application.AssetUpdateAll();
#else
HMMWV9_FuncDriver driver;
#endif
// ---------------
// Simulation loop
// ---------------
#ifdef USE_IRRLICHT
ChRealtimeStepTimer realtime_timer;
// Refresh 3D view only every N simulation steps
int simul_substeps_num = (int) std::ceil((1 / step_size) / FPS);
int simul_substep = 0;
while (application.GetDevice()->run())
{
// Render scene
if (simul_substep == 0) {
application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));
driver.DrawAll();
application.GetVideoDriver()->endScene();
}
// Update modules (inter-module communication)
double time = vehicle.GetChTime();
driver.Update(time);
tire_front_right.Update(time, vehicle.GetWheelState(FRONT_RIGHT));
tire_front_left.Update(time, vehicle.GetWheelState(FRONT_LEFT));
tire_rear_right.Update(time, vehicle.GetWheelState(REAR_RIGHT));
tire_rear_left.Update(time, vehicle.GetWheelState(REAR_LEFT));
vehicle.Update(time, driver.getThrottle(), driver.getSteering());
// Advance simulation for one timestep for all modules
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
tire_front_right.Advance(step);
tire_front_left.Advance(step);
tire_rear_right.Advance(step);
tire_rear_left.Advance(step);
vehicle.Advance(step);
++simul_substep;
if (simul_substep >= simul_substeps_num)
simul_substep = 0;
}
application.GetDevice()->drop();
#else
int out_steps = (int) std::ceil((1 / step_size) / FPS);
double time = 0;
int frame = 0;
int out_frame = 0;
if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
HMMWV9_Vehicle::ExportMeshPovray(out_dir);
HMMWV9_WheelLeft::ExportMeshPovray(out_dir);
HMMWV9_WheelRight::ExportMeshPovray(out_dir);
char filename[100];
while (time < tend)
{
if (frame % out_steps == 0) {
// Output render data
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), out_frame + 1);
utils::WriteShapesPovray(&m_system, filename);
std::cout << "Output frame: " << out_frame << std::endl;
std::cout << "Sim frame: " << frame << std::endl;
std::cout << "Time: " << time << std::endl;
std::cout << " throttle: " << driver.getThrottle() << " steering: " << driver.getSteering() << std::endl;
std::cout << std::endl;
out_frame++;
}
// Update modules
driver.Update(time);
tire_front_right.Update(time, vehicle.GetWheelState(FRONT_RIGHT));
tire_front_left.Update(time, vehicle.GetWheelState(FRONT_LEFT));
tire_rear_right.Update(time, vehicle.GetWheelState(REAR_RIGHT));
tire_rear_left.Update(time, vehicle.GetWheelState(REAR_LEFT));
vehicle.Update(time, driver.getThrottle(), driver.getSteering());
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
tire_front_right.Advance(step);
tire_front_left.Advance(step);
tire_rear_right.Advance(step);
tire_rear_left.Advance(step);
vehicle.DoStepDynamics(step_size);
time += step_size;
frame++;
}
#endif
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016-2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* Copyright (c) 2013 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cpu/o3/regfile.hh"
#include "cpu/o3/free_list.hh"
#include "arch/generic/types.hh"
#include "cpu/o3/free_list.hh"
PhysRegFile::PhysRegFile(unsigned _numPhysicalIntRegs,
unsigned _numPhysicalFloatRegs,
unsigned _numPhysicalVecRegs,
unsigned _numPhysicalVecPredRegs,
unsigned _numPhysicalCCRegs,
VecMode vmode)
: intRegFile(_numPhysicalIntRegs),
floatRegFile(_numPhysicalFloatRegs),
vectorRegFile(_numPhysicalVecRegs),
vecPredRegFile(_numPhysicalVecPredRegs),
ccRegFile(_numPhysicalCCRegs),
numPhysicalIntRegs(_numPhysicalIntRegs),
numPhysicalFloatRegs(_numPhysicalFloatRegs),
numPhysicalVecRegs(_numPhysicalVecRegs),
numPhysicalVecElemRegs(_numPhysicalVecRegs *
NumVecElemPerVecReg),
numPhysicalVecPredRegs(_numPhysicalVecPredRegs),
numPhysicalCCRegs(_numPhysicalCCRegs),
totalNumRegs(_numPhysicalIntRegs
+ _numPhysicalFloatRegs
+ _numPhysicalVecRegs
+ _numPhysicalVecRegs * NumVecElemPerVecReg
+ _numPhysicalVecPredRegs
+ _numPhysicalCCRegs),
vecMode(vmode)
{
PhysRegIndex phys_reg;
PhysRegIndex flat_reg_idx = 0;
if (TheISA::NumCCRegs == 0 && _numPhysicalCCRegs != 0) {
// Just make this a warning and go ahead and allocate them
// anyway, to keep from having to add checks everywhere
warn("Non-zero number of physical CC regs specified, even though\n"
" ISA does not use them.\n");
}
// The initial batch of registers are the integer ones
for (phys_reg = 0; phys_reg < numPhysicalIntRegs; phys_reg++) {
intRegIds.emplace_back(IntRegClass, phys_reg, flat_reg_idx++);
}
// The next batch of the registers are the floating-point physical
// registers; put them onto the floating-point free list.
for (phys_reg = 0; phys_reg < numPhysicalFloatRegs; phys_reg++) {
floatRegIds.emplace_back(FloatRegClass, phys_reg, flat_reg_idx++);
}
// The next batch of the registers are the vector physical
// registers; put them onto the vector free list.
for (phys_reg = 0; phys_reg < numPhysicalVecRegs; phys_reg++) {
vectorRegFile[phys_reg].zero();
vecRegIds.emplace_back(VecRegClass, phys_reg, flat_reg_idx++);
}
// The next batch of the registers are the vector element physical
// registers; they refer to the same containers as the vector
// registers, just a different (and incompatible) way to access
// them; put them onto the vector free list.
for (phys_reg = 0; phys_reg < numPhysicalVecRegs; phys_reg++) {
for (ElemIndex eIdx = 0; eIdx < NumVecElemPerVecReg; eIdx++) {
vecElemIds.emplace_back(VecElemClass, phys_reg,
eIdx, flat_reg_idx++);
}
}
// The next batch of the registers are the predicate physical
// registers; put them onto the predicate free list.
for (phys_reg = 0; phys_reg < numPhysicalVecPredRegs; phys_reg++) {
vecPredRegIds.emplace_back(VecPredRegClass, phys_reg, flat_reg_idx++);
}
// The rest of the registers are the condition-code physical
// registers; put them onto the condition-code free list.
for (phys_reg = 0; phys_reg < numPhysicalCCRegs; phys_reg++) {
ccRegIds.emplace_back(CCRegClass, phys_reg, flat_reg_idx++);
}
// Misc regs have a fixed mapping but still need PhysRegIds.
for (phys_reg = 0; phys_reg < TheISA::NumMiscRegs; phys_reg++) {
miscRegIds.emplace_back(MiscRegClass, phys_reg, 0);
}
}
void
PhysRegFile::initFreeList(UnifiedFreeList *freeList)
{
// Initialize the free lists.
int reg_idx = 0;
// The initial batch of registers are the integer ones
for (reg_idx = 0; reg_idx < numPhysicalIntRegs; reg_idx++) {
assert(intRegIds[reg_idx].index() == reg_idx);
}
freeList->addRegs(intRegIds.begin(), intRegIds.end());
// The next batch of the registers are the floating-point physical
// registers; put them onto the floating-point free list.
for (reg_idx = 0; reg_idx < numPhysicalFloatRegs; reg_idx++) {
assert(floatRegIds[reg_idx].index() == reg_idx);
}
freeList->addRegs(floatRegIds.begin(), floatRegIds.end());
/* The next batch of the registers are the vector physical
* registers; put them onto the vector free list. */
for (reg_idx = 0; reg_idx < numPhysicalVecRegs; reg_idx++) {
assert(vecRegIds[reg_idx].index() == reg_idx);
for (ElemIndex elemIdx = 0; elemIdx < NumVecElemPerVecReg; elemIdx++) {
assert(vecElemIds[reg_idx * NumVecElemPerVecReg +
elemIdx].index() == reg_idx);
assert(vecElemIds[reg_idx * NumVecElemPerVecReg +
elemIdx].elemIndex() == elemIdx);
}
}
/* depending on the mode we add the vector registers as whole units or
* as different elements. */
if (vecMode == Enums::Full)
freeList->addRegs(vecRegIds.begin(), vecRegIds.end());
else
freeList->addRegs(vecElemIds.begin(), vecElemIds.end());
// The next batch of the registers are the predicate physical
// registers; put them onto the predicate free list.
for (reg_idx = 0; reg_idx < numPhysicalVecPredRegs; reg_idx++) {
assert(vecPredRegIds[reg_idx].index() == reg_idx);
}
freeList->addRegs(vecPredRegIds.begin(), vecPredRegIds.end());
// The rest of the registers are the condition-code physical
// registers; put them onto the condition-code free list.
for (reg_idx = 0; reg_idx < numPhysicalCCRegs; reg_idx++) {
assert(ccRegIds[reg_idx].index() == reg_idx);
}
freeList->addRegs(ccRegIds.begin(), ccRegIds.end());
}
auto
PhysRegFile::getRegElemIds(PhysRegIdPtr reg) -> IdRange
{
panic_if(!reg->isVectorPhysReg(),
"Trying to get elems of a %s register", reg->className());
auto idx = reg->index();
return std::make_pair(
vecElemIds.begin() + idx * NumVecElemPerVecReg,
vecElemIds.begin() + (idx+1) * NumVecElemPerVecReg);
}
auto
PhysRegFile::getRegIds(RegClass cls) -> IdRange
{
switch (cls)
{
case IntRegClass:
return std::make_pair(intRegIds.begin(), intRegIds.end());
case FloatRegClass:
return std::make_pair(floatRegIds.begin(), floatRegIds.end());
case VecRegClass:
return std::make_pair(vecRegIds.begin(), vecRegIds.end());
case VecElemClass:
return std::make_pair(vecElemIds.begin(), vecElemIds.end());
case VecPredRegClass:
return std::make_pair(vecPredRegIds.begin(), vecPredRegIds.end());
case CCRegClass:
return std::make_pair(ccRegIds.begin(), ccRegIds.end());
case MiscRegClass:
return std::make_pair(miscRegIds.begin(), miscRegIds.end());
}
/* There is no way to make an empty iterator */
return std::make_pair(PhysIds::iterator(),
PhysIds::iterator());
}
PhysRegIdPtr
PhysRegFile::getTrueId(PhysRegIdPtr reg)
{
switch (reg->classValue()) {
case VecRegClass:
return &vecRegIds[reg->index()];
case VecElemClass:
return &vecElemIds[reg->index() * NumVecElemPerVecReg +
reg->elemIndex()];
default:
panic_if(!reg->isVectorPhysElem(),
"Trying to get the register of a %s register", reg->className());
}
return nullptr;
}
<commit_msg>cpu: Get rid of auto return types in the PhysRegFile.<commit_after>/*
* Copyright (c) 2016-2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* Copyright (c) 2013 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cpu/o3/regfile.hh"
#include "cpu/o3/free_list.hh"
#include "arch/generic/types.hh"
#include "cpu/o3/free_list.hh"
PhysRegFile::PhysRegFile(unsigned _numPhysicalIntRegs,
unsigned _numPhysicalFloatRegs,
unsigned _numPhysicalVecRegs,
unsigned _numPhysicalVecPredRegs,
unsigned _numPhysicalCCRegs,
VecMode vmode)
: intRegFile(_numPhysicalIntRegs),
floatRegFile(_numPhysicalFloatRegs),
vectorRegFile(_numPhysicalVecRegs),
vecPredRegFile(_numPhysicalVecPredRegs),
ccRegFile(_numPhysicalCCRegs),
numPhysicalIntRegs(_numPhysicalIntRegs),
numPhysicalFloatRegs(_numPhysicalFloatRegs),
numPhysicalVecRegs(_numPhysicalVecRegs),
numPhysicalVecElemRegs(_numPhysicalVecRegs *
NumVecElemPerVecReg),
numPhysicalVecPredRegs(_numPhysicalVecPredRegs),
numPhysicalCCRegs(_numPhysicalCCRegs),
totalNumRegs(_numPhysicalIntRegs
+ _numPhysicalFloatRegs
+ _numPhysicalVecRegs
+ _numPhysicalVecRegs * NumVecElemPerVecReg
+ _numPhysicalVecPredRegs
+ _numPhysicalCCRegs),
vecMode(vmode)
{
PhysRegIndex phys_reg;
PhysRegIndex flat_reg_idx = 0;
if (TheISA::NumCCRegs == 0 && _numPhysicalCCRegs != 0) {
// Just make this a warning and go ahead and allocate them
// anyway, to keep from having to add checks everywhere
warn("Non-zero number of physical CC regs specified, even though\n"
" ISA does not use them.\n");
}
// The initial batch of registers are the integer ones
for (phys_reg = 0; phys_reg < numPhysicalIntRegs; phys_reg++) {
intRegIds.emplace_back(IntRegClass, phys_reg, flat_reg_idx++);
}
// The next batch of the registers are the floating-point physical
// registers; put them onto the floating-point free list.
for (phys_reg = 0; phys_reg < numPhysicalFloatRegs; phys_reg++) {
floatRegIds.emplace_back(FloatRegClass, phys_reg, flat_reg_idx++);
}
// The next batch of the registers are the vector physical
// registers; put them onto the vector free list.
for (phys_reg = 0; phys_reg < numPhysicalVecRegs; phys_reg++) {
vectorRegFile[phys_reg].zero();
vecRegIds.emplace_back(VecRegClass, phys_reg, flat_reg_idx++);
}
// The next batch of the registers are the vector element physical
// registers; they refer to the same containers as the vector
// registers, just a different (and incompatible) way to access
// them; put them onto the vector free list.
for (phys_reg = 0; phys_reg < numPhysicalVecRegs; phys_reg++) {
for (ElemIndex eIdx = 0; eIdx < NumVecElemPerVecReg; eIdx++) {
vecElemIds.emplace_back(VecElemClass, phys_reg,
eIdx, flat_reg_idx++);
}
}
// The next batch of the registers are the predicate physical
// registers; put them onto the predicate free list.
for (phys_reg = 0; phys_reg < numPhysicalVecPredRegs; phys_reg++) {
vecPredRegIds.emplace_back(VecPredRegClass, phys_reg, flat_reg_idx++);
}
// The rest of the registers are the condition-code physical
// registers; put them onto the condition-code free list.
for (phys_reg = 0; phys_reg < numPhysicalCCRegs; phys_reg++) {
ccRegIds.emplace_back(CCRegClass, phys_reg, flat_reg_idx++);
}
// Misc regs have a fixed mapping but still need PhysRegIds.
for (phys_reg = 0; phys_reg < TheISA::NumMiscRegs; phys_reg++) {
miscRegIds.emplace_back(MiscRegClass, phys_reg, 0);
}
}
void
PhysRegFile::initFreeList(UnifiedFreeList *freeList)
{
// Initialize the free lists.
int reg_idx = 0;
// The initial batch of registers are the integer ones
for (reg_idx = 0; reg_idx < numPhysicalIntRegs; reg_idx++) {
assert(intRegIds[reg_idx].index() == reg_idx);
}
freeList->addRegs(intRegIds.begin(), intRegIds.end());
// The next batch of the registers are the floating-point physical
// registers; put them onto the floating-point free list.
for (reg_idx = 0; reg_idx < numPhysicalFloatRegs; reg_idx++) {
assert(floatRegIds[reg_idx].index() == reg_idx);
}
freeList->addRegs(floatRegIds.begin(), floatRegIds.end());
/* The next batch of the registers are the vector physical
* registers; put them onto the vector free list. */
for (reg_idx = 0; reg_idx < numPhysicalVecRegs; reg_idx++) {
assert(vecRegIds[reg_idx].index() == reg_idx);
for (ElemIndex elemIdx = 0; elemIdx < NumVecElemPerVecReg; elemIdx++) {
assert(vecElemIds[reg_idx * NumVecElemPerVecReg +
elemIdx].index() == reg_idx);
assert(vecElemIds[reg_idx * NumVecElemPerVecReg +
elemIdx].elemIndex() == elemIdx);
}
}
/* depending on the mode we add the vector registers as whole units or
* as different elements. */
if (vecMode == Enums::Full)
freeList->addRegs(vecRegIds.begin(), vecRegIds.end());
else
freeList->addRegs(vecElemIds.begin(), vecElemIds.end());
// The next batch of the registers are the predicate physical
// registers; put them onto the predicate free list.
for (reg_idx = 0; reg_idx < numPhysicalVecPredRegs; reg_idx++) {
assert(vecPredRegIds[reg_idx].index() == reg_idx);
}
freeList->addRegs(vecPredRegIds.begin(), vecPredRegIds.end());
// The rest of the registers are the condition-code physical
// registers; put them onto the condition-code free list.
for (reg_idx = 0; reg_idx < numPhysicalCCRegs; reg_idx++) {
assert(ccRegIds[reg_idx].index() == reg_idx);
}
freeList->addRegs(ccRegIds.begin(), ccRegIds.end());
}
PhysRegFile::IdRange
PhysRegFile::getRegElemIds(PhysRegIdPtr reg)
{
panic_if(!reg->isVectorPhysReg(),
"Trying to get elems of a %s register", reg->className());
auto idx = reg->index();
return std::make_pair(
vecElemIds.begin() + idx * NumVecElemPerVecReg,
vecElemIds.begin() + (idx+1) * NumVecElemPerVecReg);
}
PhysRegFile::IdRange
PhysRegFile::getRegIds(RegClass cls)
{
switch (cls)
{
case IntRegClass:
return std::make_pair(intRegIds.begin(), intRegIds.end());
case FloatRegClass:
return std::make_pair(floatRegIds.begin(), floatRegIds.end());
case VecRegClass:
return std::make_pair(vecRegIds.begin(), vecRegIds.end());
case VecElemClass:
return std::make_pair(vecElemIds.begin(), vecElemIds.end());
case VecPredRegClass:
return std::make_pair(vecPredRegIds.begin(), vecPredRegIds.end());
case CCRegClass:
return std::make_pair(ccRegIds.begin(), ccRegIds.end());
case MiscRegClass:
return std::make_pair(miscRegIds.begin(), miscRegIds.end());
}
/* There is no way to make an empty iterator */
return std::make_pair(PhysIds::iterator(),
PhysIds::iterator());
}
PhysRegIdPtr
PhysRegFile::getTrueId(PhysRegIdPtr reg)
{
switch (reg->classValue()) {
case VecRegClass:
return &vecRegIds[reg->index()];
case VecElemClass:
return &vecElemIds[reg->index() * NumVecElemPerVecReg +
reg->elemIndex()];
default:
panic_if(!reg->isVectorPhysElem(),
"Trying to get the register of a %s register", reg->className());
}
return nullptr;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2006,2007,2008,2009,2010,2011,2012 Olly Betts
*
* 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 "length.h"
#include <algorithm> // for min
#include <cfloat> // for FLT_RADIX, DBL_MANT_DIG, DBL_MAX_EXP, DBL_MAX
#include <cmath> // for scalbn, frexp, HUGE_VAL
#include <functional> // for std::reference_wrapper
#include "io_utils.h" // for io::read and io::write
// The serialisation we use for doubles is inspired by a comp.lang.c post
// by Jens Moeller:
//
// http://groups.google.com/group/comp.lang.c/browse_thread/thread/6558d4653f6dea8b/75a529ec03148c98
//
// The clever part is that the mantissa is encoded as a base-256 number which
// means there's no rounding error provided both ends have FLT_RADIX as some
// power of two.
//
// FLT_RADIX == 2 seems to be ubiquitous on modern UNIX platforms, while
// some older platforms used FLT_RADIX == 16 (IBM machines for example).
// FLT_RADIX == 10 seems to be very rare (the only instance Google finds
// is for a cross-compiler to some TI calculators).
#if FLT_RADIX == 2
# define MAX_MANTISSA_BYTES ((DBL_MANT_DIG + 7 + 7) / 8)
# define MAX_EXP ((DBL_MAX_EXP + 1) / 8)
# define MAX_MANTISSA (1 << (DBL_MAX_EXP & 7))
#elif FLT_RADIX == 16
# define MAX_MANTISSA_BYTES ((DBL_MANT_DIG + 1 + 1) / 2)
# define MAX_EXP ((DBL_MAX_EXP + 1) / 2)
# define MAX_MANTISSA (1 << ((DBL_MAX_EXP & 1) * 4))
#else
# error FLT_RADIX is a value not currently handled (not 2 or 16)
// # define MAX_MANTISSA_BYTES (sizeof(double) + 1)
#endif
static int base256ify_double(double &v) {
int exp;
v = frexp(v, &exp);
// v is now in the range [0.5, 1.0)
--exp;
#if FLT_RADIX == 2
v = scalbn(v, (exp & 7) + 1);
#else
v = ldexp(v, (exp & 7) + 1);
#endif
// v is now in the range [1.0, 256.0)
exp >>= 3;
return exp;
}
std::string
serialise_double(double v)
{
/* First byte:
* bit 7 Negative flag
* bit 4..6 Mantissa length - 1
* bit 0..3 --- 0-13 -> Exponent + 7
* \- 14 -> Exponent given by next byte
* - 15 -> Exponent given by next 2 bytes
*
* Then optional medium (1 byte) or large exponent (2 bytes, lsb first)
*
* Then mantissa (0 iff value is 0)
*/
bool negative = (v < 0.0);
if (negative) v = -v;
int exp = base256ify_double(v);
std::string result;
if (exp <= 6 && exp >= -7) {
unsigned char b = static_cast<unsigned char>(exp + 7);
if (negative) b |= static_cast<unsigned char>(0x80);
result += char(b);
} else {
if (exp >= -128 && exp < 127) {
result += negative ? char(0x8e) : char(0x0e);
result += char(exp + 128);
} else {
if (exp < -32768 || exp > 32767) {
THROW(InternalError, "Insane exponent in floating point number");
}
result += negative ? char(0x8f) : char(0x0f);
result += char(unsigned(exp + 32768) & 0xff);
result += char(unsigned(exp + 32768) >> 8);
}
}
int maxbytes = std::min(MAX_MANTISSA_BYTES, 8);
size_t n = result.size();
do {
unsigned char byte = static_cast<unsigned char>(v);
result += char(byte);
v -= double(byte);
v *= 256.0;
} while (v != 0.0 && --maxbytes);
n = result.size() - n;
if (n > 1) {
assert(n <= 8);
result[0] = static_cast<unsigned char>(result[0] | ((n - 1) << 4));
}
return result;
}
double
unserialise_double(const char** p, const char* end)
{
if (end - *p < 2) {
THROW(SerialisationError, "Bad encoded double: insufficient data");
}
unsigned char first = *(*p)++;
if (first == 0 && *(*p) == 0) {
++*p;
return 0.0;
}
bool negative = (first & 0x80) != 0;
size_t mantissa_len = ((first >> 4) & 0x07) + 1;
int exp = first & 0x0f;
if (exp >= 14) {
int bigexp = static_cast<unsigned char>(*(*p)++);
if (exp == 15) {
if unlikely(*p == end) {
*p = NULL;
THROW(SerialisationError, "Bad encoded double: short large exponent");
}
exp = bigexp | (static_cast<unsigned char>(*(*p)++) << 8);
exp -= 32768;
} else {
exp = bigexp - 128;
}
} else {
exp -= 7;
}
if (size_t(end - *p) < mantissa_len) {
THROW(SerialisationError, "Bad encoded double: short mantissa");
}
double v = 0.0;
static double dbl_max_mantissa = DBL_MAX;
static int dbl_max_exp = base256ify_double(dbl_max_mantissa);
*p += mantissa_len;
if (exp > dbl_max_exp ||
(exp == dbl_max_exp &&
double(static_cast<unsigned char>((*p)[-1])) > dbl_max_mantissa)) {
// The mantissa check should be precise provided that FLT_RADIX
// is a power of 2.
v = HUGE_VAL;
} else {
const char *q = *p;
while (mantissa_len--) {
v *= 0.00390625; // 1/256
v += double(static_cast<unsigned char>(*--q));
}
#if FLT_RADIX == 2
if (exp) v = scalbn(v, exp * 8);
#elif FLT_RADIX == 16
if (exp) v = scalbn(v, exp * 2);
#else
if (exp) v = ldexp(v, exp * 8);
#endif
#if 0
if (v == 0.0) {
// FIXME: handle underflow
}
#endif
}
if (negative) v = -v;
return v;
}
std::string
serialise_length(unsigned long long len)
{
std::string result;
if (len < 255) {
result += static_cast<unsigned char>(len);
} else {
result += '\xff';
len -= 255;
while (true) {
unsigned char b = static_cast<unsigned char>(len & 0x7f);
len >>= 7;
if (!len) {
result += (b | static_cast<unsigned char>(0x80));
break;
}
result += b;
}
}
return result;
}
unsigned long long
unserialise_length(const char** p, const char* end, bool check_remaining)
{
const char *ptr = *p;
assert(ptr);
assert(ptr <= end);
if unlikely(ptr == end) {
// Out of data.
*p = NULL;
THROW(SerialisationError, "Bad encoded length: no data");
}
unsigned long long len = static_cast<unsigned char>(*ptr++);
if (len == 0xff) {
len = 0;
unsigned char ch;
unsigned shift = 0;
do {
if unlikely(ptr == end || shift > (sizeof(unsigned long long) * 8 / 7 * 7)) {
*p = NULL;
THROW(SerialisationError, "Bad encoded length: insufficient data");
}
ch = *ptr++;
len |= static_cast<unsigned long long>(ch & 0x7f) << shift;
shift += 7;
} while ((ch & 0x80) == 0);
len += 255;
}
if (check_remaining && len > static_cast<unsigned long long>(end - ptr)) {
THROW(SerialisationError, "Bad encoded length: length greater than data");
}
*p = ptr;
return len;
}
std::string
serialise_string(const std::string &input) {
std::string output;
output.append(serialise_length(input.size()));
output.append(input);
return output;
}
std::string
unserialise_string(const char** p, const char* end) {
const char *ptr = *p;
assert(ptr);
assert(ptr <= end);
std::string string;
unsigned long long length = unserialise_length(&ptr, end, true);
string.append(std::string(ptr, length));
ptr += length;
*p = ptr;
return string;
}
void
serialise_length(int fd, unsigned long long len)
{
ssize_t w;
auto length = serialise_length(len);
w = io::write(fd, length.data(), length.size());
if (w < 0) THROW(Error, "Cannot write to file [%d]", fd);
}
unsigned long long
unserialise_length(int fd, std::string &buffer, std::size_t& off)
{
ssize_t r;
if (buffer.size() - off < 10) {
char buf[1024];
r = io::read(fd, buf, sizeof(buf));
if (r < 0) THROW(Error, "Cannot read from file [%d]", fd);
buffer.append(buf, r);
}
auto start = buffer.data();
auto end = start + buffer.size();
start += off;
auto pos = start;
auto length = unserialise_length(&pos, end, false);
off += (pos - start);
return length;
}
void
serialise_string(int fd, const std::string &input)
{
serialise_length(fd, input.size());
ssize_t w = io::write(fd, input.data(), input.size());
if (w < 0) THROW(Error, "Cannot write to file [%d]", fd);
}
std::string
unserialise_string(int fd, std::string &buffer, std::size_t& off)
{
ssize_t length = unserialise_length(fd, buffer, off);
auto pos = buffer.data();
auto end = pos + buffer.size();
pos += off;
std::string str;
auto available = end - pos;
if (available >= length) {
str.append(pos, pos + length);
buffer.erase(0, off + length);
off = 0;
} else {
str.reserve(length);
str.append(pos, end);
str.resize(length);
ssize_t r = io::read(fd, &str[available], length - available);
if (r < 0) THROW(Error, "Cannot read from file [%d]", fd);
if (r != length - available) THROW(SerialisationError, "Invalid input: insufficient data");
buffer.clear();
off = 0;
}
if (off > 10 * 1024) {
buffer.erase(0, off);
off = 0;
}
return str;
}
std::string
serialise_strings(const std::vector<std::reference_wrapper<const std::string>>& strings)
{
std::string output;
for (const std::string& s : strings) {
output.append(serialise_string(s));
}
return output;
}
std::string
unserialise_string_at(size_t at, const char** p, const char* end)
{
const char *ptr = *p;
assert(ptr);
assert(ptr <= end);
std::string string;
unsigned long long length = 0;
++at;
do {
ptr += length;
if (ptr >= end) break;
length = unserialise_length(&ptr, end, true);
} while (--at);
if (at == 0) {
string.assign(ptr, length);
ptr += length;
*p = ptr;
}
return string;
}
<commit_msg>Length and double serializer optimizations<commit_after>/*
* Copyright (C) 2015-2018 dubalu.com LLC. All rights reserved.
* Copyright (C) 2006,2007,2008,2009,2010,2011,2012 Olly Betts
*
* 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 "length.h"
#include <algorithm> // for min
#include <cfloat> // for FLT_RADIX, DBL_MANT_DIG, DBL_MAX_EXP, DBL_MAX
#include <cmath> // for scalbn, frexp, HUGE_VAL
#include <functional> // for std::reference_wrapper
#include "io_utils.h" // for io::read and io::write
// The serialisation we use for doubles is inspired by a comp.lang.c post
// by Jens Moeller:
//
// http://groups.google.com/group/comp.lang.c/browse_thread/thread/6558d4653f6dea8b/75a529ec03148c98
//
// The clever part is that the mantissa is encoded as a base-256 number which
// means there's no rounding error provided both ends have FLT_RADIX as some
// power of two.
//
// FLT_RADIX == 2 seems to be ubiquitous on modern UNIX platforms, while
// some older platforms used FLT_RADIX == 16 (IBM machines for example).
// FLT_RADIX == 10 seems to be very rare (the only instance Google finds
// is for a cross-compiler to some TI calculators).
#if FLT_RADIX == 2
# define MAX_MANTISSA_BYTES ((DBL_MANT_DIG + 7 + 7) / 8)
# define MAX_EXP ((DBL_MAX_EXP + 1) / 8)
# define MAX_MANTISSA (1 << (DBL_MAX_EXP & 7))
#elif FLT_RADIX == 16
# define MAX_MANTISSA_BYTES ((DBL_MANT_DIG + 1 + 1) / 2)
# define MAX_EXP ((DBL_MAX_EXP + 1) / 2)
# define MAX_MANTISSA (1 << ((DBL_MAX_EXP & 1) * 4))
#else
# error FLT_RADIX is a value not currently handled (not 2 or 16)
// # define MAX_MANTISSA_BYTES (sizeof(double) + 1)
#endif
constexpr int max_mantissa_bytes = std::min(MAX_MANTISSA_BYTES, 8);
constexpr int max_length_size = sizeof(unsigned long long) * 8 / 7;
static int
base256ify_double(double &v)
{
int exp;
v = frexp(v, &exp);
// v is now in the range [0.5, 1.0)
--exp;
#if FLT_RADIX == 2
v = scalbn(v, (exp & 7) + 1);
#else
v = ldexp(v, (exp & 7) + 1);
#endif
// v is now in the range [1.0, 256.0)
exp >>= 3;
return exp;
}
std::string
serialise_double(double v)
{
/* First byte:
* bit 7 Negative flag
* bit 4..6 Mantissa length - 1
* bit 0..3 --- 0-13 -> Exponent + 7
* \- 14 -> Exponent given by next byte
* - 15 -> Exponent given by next 2 bytes
*
* Then optional medium (1 byte) or large exponent (2 bytes, lsb first)
*
* Then mantissa (0 iff value is 0)
*/
bool negative = (v < 0.0);
if (negative) v = -v;
int exp = base256ify_double(v);
std::string result;
result.reserve(3 + max_mantissa_bytes);
if (exp <= 6 && exp >= -7) {
unsigned char b = static_cast<unsigned char>(exp + 7);
if (negative) b |= static_cast<unsigned char>(0x80);
result.push_back(static_cast<char>(b));
} else {
if (exp >= -128 && exp < 127) {
result.push_back(negative ? static_cast<char>(0x8e) : static_cast<char>(0x0e));
result.push_back(static_cast<char>(exp + 128));
} else {
if (exp < -32768 || exp > 32767) {
THROW(InternalError, "Insane exponent in floating point number");
}
result.push_back(negative ? static_cast<char>(0x8f) : static_cast<char>(0x0f));
result.push_back(static_cast<char>(static_cast<unsigned>(exp + 32768) & 0xff));
result.push_back(static_cast<char>(static_cast<unsigned>(exp + 32768) >> 8));
}
}
size_t n = result.size();
int max_bytes = max_mantissa_bytes;
do {
unsigned char byte = static_cast<unsigned char>(v);
result.push_back(static_cast<char>(byte));
v -= static_cast<double>(byte);
v *= 256.0;
} while (v != 0.0 && --max_bytes);
n = result.size() - n;
if (n > 1) {
assert(n <= 8);
result[0] = static_cast<unsigned char>(result[0] | ((n - 1) << 4));
}
return result;
}
double
unserialise_double(const char** p, const char* end)
{
if (end - *p < 2) {
THROW(SerialisationError, "Bad encoded double: insufficient data");
}
unsigned char first = *(*p)++;
if (first == 0 && *(*p) == 0) {
++*p;
return 0.0;
}
bool negative = (first & 0x80) != 0;
size_t mantissa_len = ((first >> 4) & 0x07) + 1;
int exp = first & 0x0f;
if (exp >= 14) {
int bigexp = static_cast<unsigned char>(*(*p)++);
if (exp == 15) {
if unlikely(*p == end) {
*p = NULL;
THROW(SerialisationError, "Bad encoded double: short large exponent");
}
exp = bigexp | (static_cast<unsigned char>(*(*p)++) << 8);
exp -= 32768;
} else {
exp = bigexp - 128;
}
} else {
exp -= 7;
}
if (static_cast<std::size_t>(end - *p) < mantissa_len) {
THROW(SerialisationError, "Bad encoded double: short mantissa");
}
double v = 0.0;
static double dbl_max_mantissa = DBL_MAX;
static int dbl_max_exp = base256ify_double(dbl_max_mantissa);
*p += mantissa_len;
if (exp > dbl_max_exp ||
(exp == dbl_max_exp &&
static_cast<double>(static_cast<unsigned char>((*p)[-1])) > dbl_max_mantissa)) {
// The mantissa check should be precise provided that FLT_RADIX
// is a power of 2.
v = HUGE_VAL;
} else {
const char *q = *p;
while (mantissa_len--) {
v *= 0.00390625; // 1/256
v += static_cast<double>(static_cast<unsigned char>(*--q));
}
#if FLT_RADIX == 2
if (exp) v = scalbn(v, exp * 8);
#elif FLT_RADIX == 16
if (exp) v = scalbn(v, exp * 2);
#else
if (exp) v = ldexp(v, exp * 8);
#endif
#if 0
if (v == 0.0) {
// FIXME: handle underflow
}
#endif
}
if (negative) v = -v;
return v;
}
std::string
serialise_length(unsigned long long len)
{
std::string result;
result.reserve(max_length_size);
if (len < 255) {
result.push_back(static_cast<unsigned char>(len));
} else {
result.push_back('\xff');
len -= 255;
while (true) {
unsigned char b = static_cast<unsigned char>(len & 0x7f);
len >>= 7;
if (!len) {
result.push_back(b | static_cast<unsigned char>(0x80));
break;
}
result.push_back(b);
}
}
return result;
}
unsigned long long
unserialise_length(const char** p, const char* end, bool check_remaining)
{
const char *ptr = *p;
assert(ptr);
assert(ptr <= end);
if unlikely(ptr == end) {
// Out of data.
*p = NULL;
THROW(SerialisationError, "Bad encoded length: no data");
}
unsigned long long len = static_cast<unsigned char>(*ptr++);
if (len == 0xff) {
len = 0;
unsigned char ch;
unsigned shift = 0;
do {
if unlikely(ptr == end || shift > (max_length_size * 7)) {
*p = NULL;
THROW(SerialisationError, "Bad encoded length: insufficient data");
}
ch = *ptr++;
len |= static_cast<unsigned long long>(ch & 0x7f) << shift;
shift += 7;
} while ((ch & 0x80) == 0);
len += 255;
}
if (check_remaining && len > static_cast<unsigned long long>(end - ptr)) {
THROW(SerialisationError, "Bad encoded length: length greater than data");
}
*p = ptr;
return len;
}
std::string
serialise_string(const std::string &input) {
std::string output;
unsigned long long input_size = input.size();
output.reserve(max_length_size + input_size);
output.append(serialise_length(input_size));
output.append(input);
return output;
}
std::string
unserialise_string(const char** p, const char* end) {
const char *ptr = *p;
assert(ptr);
assert(ptr <= end);
std::string string;
unsigned long long length = unserialise_length(&ptr, end, true);
string.append(std::string(ptr, length));
ptr += length;
*p = ptr;
return string;
}
void
serialise_length(int fd, unsigned long long len)
{
ssize_t w;
auto length = serialise_length(len);
w = io::write(fd, length.data(), length.size());
if (w < 0) THROW(Error, "Cannot write to file [%d]", fd);
}
unsigned long long
unserialise_length(int fd, std::string &buffer, std::size_t& off)
{
ssize_t r;
if (buffer.size() - off < 10) {
char buf[1024];
r = io::read(fd, buf, sizeof(buf));
if (r < 0) THROW(Error, "Cannot read from file [%d]", fd);
buffer.append(buf, r);
}
auto start = buffer.data();
auto end = start + buffer.size();
start += off;
auto pos = start;
auto length = unserialise_length(&pos, end, false);
off += (pos - start);
return length;
}
void
serialise_string(int fd, const std::string &input)
{
serialise_length(fd, input.size());
ssize_t w = io::write(fd, input.data(), input.size());
if (w < 0) THROW(Error, "Cannot write to file [%d]", fd);
}
std::string
unserialise_string(int fd, std::string &buffer, std::size_t& off)
{
ssize_t length = unserialise_length(fd, buffer, off);
auto pos = buffer.data();
auto end = pos + buffer.size();
pos += off;
std::string str;
auto available = end - pos;
if (available >= length) {
str.append(pos, pos + length);
buffer.erase(0, off + length);
off = 0;
} else {
str.reserve(length);
str.append(pos, end);
str.resize(length);
ssize_t r = io::read(fd, &str[available], length - available);
if (r < 0) THROW(Error, "Cannot read from file [%d]", fd);
if (r != length - available) THROW(SerialisationError, "Invalid input: insufficient data");
buffer.clear();
off = 0;
}
if (off > 10 * 1024) {
buffer.erase(0, off);
off = 0;
}
return str;
}
std::string
serialise_strings(const std::vector<std::reference_wrapper<const std::string>>& strings)
{
std::string output;
for (const std::string& s : strings) {
output.append(serialise_string(s));
}
return output;
}
std::string
unserialise_string_at(size_t at, const char** p, const char* end)
{
const char *ptr = *p;
assert(ptr);
assert(ptr <= end);
std::string string;
unsigned long long length = 0;
++at;
do {
ptr += length;
if (ptr >= end) break;
length = unserialise_length(&ptr, end, true);
} while (--at);
if (at == 0) {
string.assign(ptr, length);
ptr += length;
*p = ptr;
}
return string;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <getopt.h>
#include <cstring>
#include <less/less/LessTokenizer.h>
#include <less/less/LessParser.h>
#include <less/css/CssWriter.h>
#include <less/css/CssPrettyWriter.h>
#include <less/stylesheet/Stylesheet.h>
#include <less/css/IOException.h>
#include <less/lessstylesheet/LessStylesheet.h>
using namespace std;
/**
* /main Less CSS compiler, implemented in C++.
*
*/
void usage () {
cout <<
"Usage: lessc [OPTION]... [FILE]\n"
"\n"
" FILE Less source file. If not given, source \
is read from stdin.\n"
" -h, --help Show this message and exit.\n"
" --version Print the program name and version.\n"
"\n"
" -o, --output=<FILE> Send output to FILE\n"
" -f, --format Format output CSS with newlines and \
indentation. By default the output is unformatted.\n"
"\n"
" -m, --source-map=[FILE] Generate a source map.\n"
" --source-map-rootpath=<PATH> PATH is prepended to the \
source file references in the source map. \n"
" --source-map-basepath=<PATH> PATH is removed from the \
source file references in the source map.\n"
" --rootpath=<PATH> Prefix PATH to urls and import \
statements in output. \n"
" -I, --include-path=<FILE> Specify paths to look for \
imported .less files.\n"
"\n"
"Example:\n"
" lessc in.less -o out.css\n"
"\n"
"Report bugs to: " PACKAGE_BUGREPORT "\n"
PACKAGE_NAME " home page: <" PACKAGE_URL ">\n";
}
void version () {
cout <<
PACKAGE_STRING "\n"
"Copyright 2012 Bram van der Kroef\n"
"License: MIT License\n";
}
/**
* Copy a given path to a new string and add a trailing slash if necessary.
*/
char* path_create(const char* path, size_t len) {
size_t newlen = len +
(path[len - 1] != '/' ? 1 : 0);
char* p = new char[newlen + 1];
std::strncpy(p, path, len);
p[newlen - 1] = '/';
p[newlen] = '\0';
return p;
}
void path_parse_list(const char* path, std::list<const char*>& paths) {
const char* start = path;
const char* end = path;
size_t len;
while((end = std::strchr(start, ':')) != NULL) {
len = (end - start);
// skip empty paths
if (len > 0)
paths.push_back(path_create(start, len));
start = end + 1;
}
len = std::strlen(start);
if (len > 0)
paths.push_back(path_create(start, len));
}
char* path_create_relative(const char* path, const char* relative) {
const char* p_root;
const char* r_root;
size_t desc_n;
char* ret, *ret_p;
// strip common directories
while ((p_root = strchr(path, '/')) != NULL &&
(r_root = strchr(relative, '/')) != NULL &&
p_root - path == r_root - relative &&
strncmp(path, relative, p_root - path) == 0) {
path = p_root + 1;
relative = r_root + 1;
}
// count how many folders to go up.
for (desc_n = 0; relative != NULL; desc_n++) {
relative = strchr(relative + 1, '/');
}
desc_n--;
ret = new char[strlen(path) + 3 * desc_n + 1];
ret_p = ret;
while (desc_n > 0) {
memcpy(ret_p, "../", 3);
ret_p += 3;
desc_n--;
}
strcpy(ret_p, path);
return ret;
}
bool parseInput(LessStylesheet &stylesheet,
istream &in,
const char* source,
std::list<const char*> &sources,
std::list<const char*> &includePaths) {
std::list<const char*>::iterator i;
LessTokenizer tokenizer(in, source);
LessParser parser(tokenizer, sources);
parser.includePaths = &includePaths;
try{
parser.parseStylesheet(stylesheet);
} catch(ParseException* e) {
cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " <<
e->getColumn() << " Parse Error: " << e->what() << endl;
return false;
} catch(exception* e) {
cerr << " Error: " << e->what() << endl;
return false;
}
return true;
}
bool processStylesheet (LessStylesheet &stylesheet,
Stylesheet &css) {
ProcessingContext context;
try{
stylesheet.process(css, context);
} catch(ParseException* e) {
cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " <<
e->getColumn() << " Parse Error: " << e->what() << endl;
return false;
} catch(ValueException* e) {
cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " <<
e->getColumn() << " Error: " << e->what() << endl;
return false;
} catch(exception* e) {
cerr << "Error: " << e->what() << endl;
return false;
}
return true;
}
void writeOutput(Stylesheet &css,
const char* output,
bool formatoutput,
const char* rootpath,
std::list<const char*> &sources,
const char* sourcemap_file,
const char* sourcemap_rootpath,
const char* sourcemap_basepath,
const char* sourcemap_url) {
ostream* out = &cout;
CssWriter* writer;
ostream* sourcemap_s = NULL;
SourceMapWriter* sourcemap = NULL;
char* tmp;
std::list<const char*> relative_sources;
std::list<const char*>::iterator it;
size_t bp_l = 0;
if (sourcemap_basepath != NULL)
bp_l = strlen(sourcemap_basepath);
if (strcmp(output, "-") != 0)
out = new ofstream(output);
if (sourcemap_file != NULL) {
if (strcmp(sourcemap_file, "-") == 0) {
if (strcmp(output, "-") == 0) {
throw new IOException("source-map option requires that \
a file name is specified for either the source map or the css \
output file.");
} else {
tmp = new char[strlen(output) + 5];
sprintf(tmp, "%s.map", output);
sourcemap_file = tmp;
}
}
for (it = sources.begin(); it != sources.end(); it++) {
if (sourcemap_basepath == NULL) {
relative_sources.push_back(path_create_relative(*it, sourcemap_file));
} else if (strncmp(*it, sourcemap_basepath, bp_l) == 0) {
relative_sources.push_back(*it + bp_l);
}
}
sourcemap_s = new ofstream(sourcemap_file);
sourcemap = new SourceMapWriter(*sourcemap_s,
sources,
relative_sources,
path_create_relative(output, sourcemap_file),
sourcemap_rootpath);
writer = formatoutput ? new CssPrettyWriter(*out, *sourcemap) :
new CssWriter(*out, *sourcemap);
} else {
writer = formatoutput ? new CssPrettyWriter(*out) :
new CssWriter(*out);
}
writer->rootpath = rootpath;
css.write(*writer);
if (sourcemap != NULL) {
if (sourcemap_url != NULL)
writer->writeSourceMapUrl(sourcemap_url);
else
writer->writeSourceMapUrl(path_create_relative(sourcemap_file, output));
sourcemap->close();
delete sourcemap;
if (sourcemap_s != NULL)
delete sourcemap_s;
}
delete writer;
*out << endl;
}
void writeDependencies(const char* output, const std::list<const char*> &sources) {
std::list<const char *>::const_iterator i;
cout << output << ": ";
for (i = sources.begin(); i != sources.end(); i++) {
if (i != sources.begin())
cout << ", ";
cout << (*i);
}
cout << endl;
}
int main(int argc, char * argv[]){
istream* in = &cin;
bool formatoutput = false;
char* source = NULL;
const char* output = "-";
LessStylesheet stylesheet;
std::list<const char*> sources;
Stylesheet css;
bool depends = false, lint = false;
const char* sourcemap_file = NULL;
const char* sourcemap_rootpath = NULL;
const char* sourcemap_basepath = NULL;
const char* sourcemap_url = NULL;
const char* rootpath = NULL;
std::list<const char*> includePaths;
static struct option long_options[] = {
{"version", no_argument, 0, 1},
{"help", no_argument, 0, 'h'},
{"output", required_argument, 0, 'o'},
{"format", no_argument, 0, 'f'},
{"source-map", optional_argument, 0, 'm'},
{"source-map-rootpath", required_argument, 0, 2},
{"source-map-basepath", required_argument, 0, 3},
{"source-map-url", required_argument, 0, 5},
{"include-path", required_argument, 0, 'I'},
{"rootpath", required_argument, 0, 4},
{"depends", no_argument, 0, 'M'},
{"lint", no_argument, 0, 'l'},
{0,0,0,0}
};
try {
int c, option_index;
while((c = getopt_long(argc, argv, ":o:hfv:m::I:Ml", long_options, &option_index)) != -1) {
switch (c) {
case 1:
version();
return EXIT_SUCCESS;
case 'h':
usage();
return EXIT_SUCCESS;
case 'o':
output = optarg;
break;
case 'f':
formatoutput = true;
break;
case 'm':
if (optarg)
sourcemap_file = optarg;
else
sourcemap_file = "-";
break;
case 2:
sourcemap_rootpath = path_create(optarg, std::strlen(optarg));
break;
case 3:
sourcemap_basepath = path_create(optarg, std::strlen(optarg));
break;
case 5:
sourcemap_url = optarg;
break;
case 'I':
path_parse_list(optarg, includePaths);
break;
case 4:
rootpath = path_create(optarg, std::strlen(optarg));
break;
case 'M':
depends = true;
break;
case 'l':
lint = true;
break;
default:
cerr << "Unrecognized option. " << endl;
usage();
return EXIT_FAILURE;
}
}
if (argc - optind >= 1) {
source = new char[std::strlen(argv[optind]) + 1];
std::strcpy(source, argv[optind]);
in = new ifstream(source);
if (in->fail() || in->bad())
throw new IOException("Error opening file.");
} else {
source = new char[2];
std::strcpy(source, "-");
}
sources.push_back(source);
if (parseInput(stylesheet, *in, source, sources, includePaths)) {
if (depends) {
writeDependencies(output, sources);
return EXIT_SUCCESS;
}
if (!processStylesheet(stylesheet, css))
return EXIT_FAILURE;
if (lint)
return EXIT_SUCCESS;
writeOutput(css,
output,
formatoutput,
rootpath,
sources,
sourcemap_file,
sourcemap_rootpath,
sourcemap_basepath,
sourcemap_url);
} else
return EXIT_FAILURE;
delete [] source;
} catch (IOException* e) {
cerr << " Error: " << e->what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Fixed bug that loses sourcemap sources.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <getopt.h>
#include <cstring>
#include <less/less/LessTokenizer.h>
#include <less/less/LessParser.h>
#include <less/css/CssWriter.h>
#include <less/css/CssPrettyWriter.h>
#include <less/stylesheet/Stylesheet.h>
#include <less/css/IOException.h>
#include <less/lessstylesheet/LessStylesheet.h>
using namespace std;
/**
* /main Less CSS compiler, implemented in C++.
*
*/
void usage () {
cout <<
"Usage: lessc [OPTION]... [FILE]\n"
"\n"
" FILE Less source file. If not given, source \
is read from stdin.\n"
" -h, --help Show this message and exit.\n"
" --version Print the program name and version.\n"
"\n"
" -o, --output=<FILE> Send output to FILE\n"
" -f, --format Format output CSS with newlines and \
indentation. By default the output is unformatted.\n"
"\n"
" -m, --source-map=[FILE] Generate a source map.\n"
" --source-map-rootpath=<PATH> PATH is prepended to the \
source file references in the source map. \n"
" --source-map-basepath=<PATH> PATH is removed from the \
source file references in the source map.\n"
" --rootpath=<PATH> Prefix PATH to urls and import \
statements in output. \n"
" -I, --include-path=<FILE> Specify paths to look for \
imported .less files.\n"
"\n"
"Example:\n"
" lessc in.less -o out.css\n"
"\n"
"Report bugs to: " PACKAGE_BUGREPORT "\n"
PACKAGE_NAME " home page: <" PACKAGE_URL ">\n";
}
void version () {
cout <<
PACKAGE_STRING "\n"
"Copyright 2012 Bram van der Kroef\n"
"License: MIT License\n";
}
/**
* Copy a given path to a new string and add a trailing slash if necessary.
*/
char* path_create(const char* path, size_t len) {
size_t newlen = len +
(path[len - 1] != '/' ? 1 : 0);
char* p = new char[newlen + 1];
std::strncpy(p, path, len);
p[newlen - 1] = '/';
p[newlen] = '\0';
return p;
}
void path_parse_list(const char* path, std::list<const char*>& paths) {
const char* start = path;
const char* end = path;
size_t len;
while((end = std::strchr(start, ':')) != NULL) {
len = (end - start);
// skip empty paths
if (len > 0)
paths.push_back(path_create(start, len));
start = end + 1;
}
len = std::strlen(start);
if (len > 0)
paths.push_back(path_create(start, len));
}
char* path_create_relative(const char* path, const char* relative) {
const char* p_root;
const char* r_root;
size_t desc_n;
char* ret, *ret_p;
// strip common directories
while ((p_root = strchr(path, '/')) != NULL &&
(r_root = strchr(relative, '/')) != NULL &&
p_root - path == r_root - relative &&
strncmp(path, relative, p_root - path) == 0) {
path = p_root + 1;
relative = r_root + 1;
}
// count how many folders to go up.
for (desc_n = 0; relative != NULL; desc_n++) {
relative = strchr(relative + 1, '/');
}
desc_n--;
ret = new char[strlen(path) + 3 * desc_n + 1];
ret_p = ret;
while (desc_n > 0) {
memcpy(ret_p, "../", 3);
ret_p += 3;
desc_n--;
}
strcpy(ret_p, path);
return ret;
}
bool parseInput(LessStylesheet &stylesheet,
istream &in,
const char* source,
std::list<const char*> &sources,
std::list<const char*> &includePaths) {
std::list<const char*>::iterator i;
LessTokenizer tokenizer(in, source);
LessParser parser(tokenizer, sources);
parser.includePaths = &includePaths;
try{
parser.parseStylesheet(stylesheet);
} catch(ParseException* e) {
cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " <<
e->getColumn() << " Parse Error: " << e->what() << endl;
return false;
} catch(exception* e) {
cerr << " Error: " << e->what() << endl;
return false;
}
return true;
}
bool processStylesheet (LessStylesheet &stylesheet,
Stylesheet &css) {
ProcessingContext context;
try{
stylesheet.process(css, context);
} catch(ParseException* e) {
cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " <<
e->getColumn() << " Parse Error: " << e->what() << endl;
return false;
} catch(ValueException* e) {
cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " <<
e->getColumn() << " Error: " << e->what() << endl;
return false;
} catch(exception* e) {
cerr << "Error: " << e->what() << endl;
return false;
}
return true;
}
void writeOutput(Stylesheet &css,
const char* output,
bool formatoutput,
const char* rootpath,
std::list<const char*> &sources,
const char* sourcemap_file,
const char* sourcemap_rootpath,
const char* sourcemap_basepath,
const char* sourcemap_url) {
ostream* out = &cout;
CssWriter* writer;
ostream* sourcemap_s = NULL;
SourceMapWriter* sourcemap = NULL;
char* tmp;
std::list<const char*> relative_sources;
std::list<const char*>::iterator it;
size_t bp_l = 0;
if (sourcemap_basepath != NULL)
bp_l = strlen(sourcemap_basepath);
if (strcmp(output, "-") != 0)
out = new ofstream(output);
if (sourcemap_file != NULL) {
if (strcmp(sourcemap_file, "-") == 0) {
if (strcmp(output, "-") == 0) {
throw new IOException("source-map option requires that \
a file name is specified for either the source map or the css \
output file.");
} else {
tmp = new char[strlen(output) + 5];
sprintf(tmp, "%s.map", output);
sourcemap_file = tmp;
}
}
for (it = sources.begin(); it != sources.end(); it++) {
if (sourcemap_basepath == NULL) {
relative_sources.push_back(path_create_relative(*it, sourcemap_file));
} else if (strncmp(*it, sourcemap_basepath, bp_l) == 0) {
relative_sources.push_back(*it + bp_l);
} else {
relative_sources.push_back(*it);
}
}
sourcemap_s = new ofstream(sourcemap_file);
sourcemap = new SourceMapWriter(*sourcemap_s,
sources,
relative_sources,
path_create_relative(output, sourcemap_file),
sourcemap_rootpath);
writer = formatoutput ? new CssPrettyWriter(*out, *sourcemap) :
new CssWriter(*out, *sourcemap);
} else {
writer = formatoutput ? new CssPrettyWriter(*out) :
new CssWriter(*out);
}
writer->rootpath = rootpath;
css.write(*writer);
if (sourcemap != NULL) {
if (sourcemap_url != NULL)
writer->writeSourceMapUrl(sourcemap_url);
else
writer->writeSourceMapUrl(path_create_relative(sourcemap_file, output));
sourcemap->close();
delete sourcemap;
if (sourcemap_s != NULL)
delete sourcemap_s;
}
delete writer;
*out << endl;
}
void writeDependencies(const char* output, const std::list<const char*> &sources) {
std::list<const char *>::const_iterator i;
cout << output << ": ";
for (i = sources.begin(); i != sources.end(); i++) {
if (i != sources.begin())
cout << ", ";
cout << (*i);
}
cout << endl;
}
int main(int argc, char * argv[]){
istream* in = &cin;
bool formatoutput = false;
char* source = NULL;
const char* output = "-";
LessStylesheet stylesheet;
std::list<const char*> sources;
Stylesheet css;
bool depends = false, lint = false;
const char* sourcemap_file = NULL;
const char* sourcemap_rootpath = NULL;
const char* sourcemap_basepath = NULL;
const char* sourcemap_url = NULL;
const char* rootpath = NULL;
std::list<const char*> includePaths;
static struct option long_options[] = {
{"version", no_argument, 0, 1},
{"help", no_argument, 0, 'h'},
{"output", required_argument, 0, 'o'},
{"format", no_argument, 0, 'f'},
{"source-map", optional_argument, 0, 'm'},
{"source-map-rootpath", required_argument, 0, 2},
{"source-map-basepath", required_argument, 0, 3},
{"source-map-url", required_argument, 0, 5},
{"include-path", required_argument, 0, 'I'},
{"rootpath", required_argument, 0, 4},
{"depends", no_argument, 0, 'M'},
{"lint", no_argument, 0, 'l'},
{0,0,0,0}
};
try {
int c, option_index;
while((c = getopt_long(argc, argv, ":o:hfv:m::I:Ml", long_options, &option_index)) != -1) {
switch (c) {
case 1:
version();
return EXIT_SUCCESS;
case 'h':
usage();
return EXIT_SUCCESS;
case 'o':
output = optarg;
break;
case 'f':
formatoutput = true;
break;
case 'm':
if (optarg)
sourcemap_file = optarg;
else
sourcemap_file = "-";
break;
case 2:
sourcemap_rootpath = path_create(optarg, std::strlen(optarg));
break;
case 3:
sourcemap_basepath = path_create(optarg, std::strlen(optarg));
break;
case 5:
sourcemap_url = optarg;
break;
case 'I':
path_parse_list(optarg, includePaths);
break;
case 4:
rootpath = path_create(optarg, std::strlen(optarg));
break;
case 'M':
depends = true;
break;
case 'l':
lint = true;
break;
default:
cerr << "Unrecognized option. " << endl;
usage();
return EXIT_FAILURE;
}
}
if (argc - optind >= 1) {
source = new char[std::strlen(argv[optind]) + 1];
std::strcpy(source, argv[optind]);
in = new ifstream(source);
if (in->fail() || in->bad())
throw new IOException("Error opening file.");
} else {
source = new char[2];
std::strcpy(source, "-");
}
sources.push_back(source);
if (parseInput(stylesheet, *in, source, sources, includePaths)) {
if (depends) {
writeDependencies(output, sources);
return EXIT_SUCCESS;
}
if (!processStylesheet(stylesheet, css))
return EXIT_FAILURE;
if (lint)
return EXIT_SUCCESS;
writeOutput(css,
output,
formatoutput,
rootpath,
sources,
sourcemap_file,
sourcemap_rootpath,
sourcemap_basepath,
sourcemap_url);
} else
return EXIT_FAILURE;
delete [] source;
} catch (IOException* e) {
cerr << " Error: " << e->what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <random>
#include <tuple>
#include <ctime>
#include <SDL.h>
#include <entityx/entityx.h>
#include <entityx/deps/Dependencies.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <lfwatch.h>
#include "util.h"
#include "interleavedbuffer.h"
#include "events/input_event.h"
#include "systems/movement_system.h"
#include "systems/input_system.h"
#include "systems/asteroid_system.h"
#include "components/position.h"
#include "components/velocity.h"
#include "components/appearance.h"
#include "components/controllable.h"
#include "level.h"
Level::Level() : shader_program(0), viewing(), quit(false) {}
Level::~Level(){
glDeleteProgram(shader_program);
}
void Level::receive(const InputEvent &input){
switch (input.event.type){
case SDL_KEYDOWN:
quit = input.event.key.keysym.sym == SDLK_ESCAPE;
break;
default:
break;
}
}
bool Level::should_quit(){
return quit;
}
void Level::configure(){
system_manager->add<MovementSystem>();
system_manager->add<AsteroidSystem>(10);
system_manager->add<InputSystem>();
system_manager->add<entityx::deps::Dependency<Asteroid, Position, Velocity>>();
shader_program = util::load_program({std::make_tuple(GL_VERTEX_SHADER, "../res/vertex.glsl"),
std::make_tuple(GL_FRAGMENT_SHADER, "../res/fragment.glsl")});
viewing = InterleavedBuffer<Layout::PACKED, glm::mat4>{2, GL_UNIFORM_BUFFER, GL_STATIC_DRAW};
assert(shader_program != -1);
event_manager->subscribe<InputEvent>(*this);
file_watcher.watch("../res", lfw::Notify::FILE_MODIFIED,
[this](const lfw::EventData &e){
if (e.fname == "vertex.glsl" || e.fname == "fragment.glsl"){
this->load_shader();
}
});
}
void Level::initialize(){
std::mt19937 mt_rand;
mt_rand.seed(std::time(0));
for (int i = 0; i < 10; ++i){
entityx::Entity e = entity_manager->create();
if (i == 0){
e.assign<Controllable>();
}
else {
e.assign<Position>(glm::vec2{static_cast<float>(mt_rand() % 8) - 4,
static_cast<float>(mt_rand() % 8) - 4});
e.assign<Velocity>(0.25f * glm::vec2{static_cast<float>(mt_rand() % 4) - 2,
static_cast<float>(mt_rand() % 4) - 2});
}
e.assign<Asteroid>();
}
viewing.map(GL_WRITE_ONLY);
viewing.write<0>(0) = glm::lookAt(glm::vec3{0.f, 0.f, 8.f}, glm::vec3{0.f, 0.f, 0.f},
glm::vec3{0.f, 1.f, 0.f});
viewing.write<0>(1) = glm::ortho(-5.f, 5.f, -5.f, 5.f, 1.f, 100.f);
viewing.unmap();
GLuint viewing_block = glGetUniformBlockIndex(shader_program, "Viewing");
glUniformBlockBinding(shader_program, viewing_block, 0);
viewing.bind_base(0);
glUseProgram(shader_program);
}
void Level::update(double dt){
file_watcher.update();
system_manager->update<InputSystem>(dt);
system_manager->update<MovementSystem>(dt);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
system_manager->update<AsteroidSystem>(dt);
}
void Level::load_shader(){
GLint shader = util::load_program({std::make_tuple(GL_VERTEX_SHADER, "../res/vertex.glsl"),
std::make_tuple(GL_FRAGMENT_SHADER, "../res/fragment.glsl")});
if (shader == -1){
std::cerr << "Error compiling reloaded shader, cancelling...\n";
}
else {
glUseProgram(shader);
glDeleteProgram(shader_program);
shader_program = shader;
}
}
<commit_msg>Also respond to window X button<commit_after>#include <random>
#include <tuple>
#include <ctime>
#include <SDL.h>
#include <entityx/entityx.h>
#include <entityx/deps/Dependencies.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <lfwatch.h>
#include "util.h"
#include "interleavedbuffer.h"
#include "events/input_event.h"
#include "systems/movement_system.h"
#include "systems/input_system.h"
#include "systems/asteroid_system.h"
#include "components/position.h"
#include "components/velocity.h"
#include "components/appearance.h"
#include "components/controllable.h"
#include "level.h"
Level::Level() : shader_program(0), viewing(), quit(false) {}
Level::~Level(){
glDeleteProgram(shader_program);
}
void Level::receive(const InputEvent &input){
switch (input.event.type){
case SDL_QUIT:
quit = true;
break;
case SDL_KEYDOWN:
quit = input.event.key.keysym.sym == SDLK_ESCAPE;
break;
default:
break;
}
}
bool Level::should_quit(){
return quit;
}
void Level::configure(){
system_manager->add<MovementSystem>();
system_manager->add<AsteroidSystem>(10);
system_manager->add<InputSystem>();
system_manager->add<entityx::deps::Dependency<Asteroid, Position, Velocity>>();
shader_program = util::load_program({std::make_tuple(GL_VERTEX_SHADER, "../res/vertex.glsl"),
std::make_tuple(GL_FRAGMENT_SHADER, "../res/fragment.glsl")});
viewing = InterleavedBuffer<Layout::PACKED, glm::mat4>{2, GL_UNIFORM_BUFFER, GL_STATIC_DRAW};
assert(shader_program != -1);
event_manager->subscribe<InputEvent>(*this);
file_watcher.watch("../res", lfw::Notify::FILE_MODIFIED,
[this](const lfw::EventData &e){
if (e.fname == "vertex.glsl" || e.fname == "fragment.glsl"){
this->load_shader();
}
});
}
void Level::initialize(){
std::mt19937 mt_rand;
mt_rand.seed(std::time(0));
for (int i = 0; i < 10; ++i){
entityx::Entity e = entity_manager->create();
if (i == 0){
e.assign<Controllable>();
}
else {
e.assign<Position>(glm::vec2{static_cast<float>(mt_rand() % 8) - 4,
static_cast<float>(mt_rand() % 8) - 4});
e.assign<Velocity>(0.25f * glm::vec2{static_cast<float>(mt_rand() % 4) - 2,
static_cast<float>(mt_rand() % 4) - 2});
}
e.assign<Asteroid>();
}
viewing.map(GL_WRITE_ONLY);
viewing.write<0>(0) = glm::lookAt(glm::vec3{0.f, 0.f, 8.f}, glm::vec3{0.f, 0.f, 0.f},
glm::vec3{0.f, 1.f, 0.f});
viewing.write<0>(1) = glm::ortho(-5.f, 5.f, -5.f, 5.f, 1.f, 100.f);
viewing.unmap();
GLuint viewing_block = glGetUniformBlockIndex(shader_program, "Viewing");
glUniformBlockBinding(shader_program, viewing_block, 0);
viewing.bind_base(0);
glUseProgram(shader_program);
}
void Level::update(double dt){
file_watcher.update();
system_manager->update<InputSystem>(dt);
system_manager->update<MovementSystem>(dt);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
system_manager->update<AsteroidSystem>(dt);
}
void Level::load_shader(){
GLint shader = util::load_program({std::make_tuple(GL_VERTEX_SHADER, "../res/vertex.glsl"),
std::make_tuple(GL_FRAGMENT_SHADER, "../res/fragment.glsl")});
if (shader == -1){
std::cerr << "Error compiling reloaded shader, cancelling...\n";
}
else {
glUseProgram(shader);
glDeleteProgram(shader_program);
shader_program = shader;
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
**
** This file is part of chemkit. For more information see
** <http://www.chemkit.org>.
**
** chemkit is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** chemkit 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 chemkit. If not, see <http://www.gnu.org/licenses/>.
**
******************************************************************************/
#include "smilesgraph.h"
#include <algorithm>
#include <chemkit/atom.h>
#include <chemkit/bond.h>
#include <chemkit/molecule.h>
namespace {
// Returns true if the element is a member of the organic subset.
bool isOrganicElement(const chemkit::Atom *atom)
{
switch(atom->atomicNumber()){
case chemkit::Atom::Boron:
case chemkit::Atom::Carbon:
case chemkit::Atom::Nitrogen:
case chemkit::Atom::Oxygen:
case chemkit::Atom::Phosphorus:
case chemkit::Atom::Sulfur:
case chemkit::Atom::Chlorine:
case chemkit::Atom::Bromine:
case chemkit::Atom::Iodine:
return true;
default:
return false;
}
}
bool isOrganicAtom(const chemkit::Atom *atom)
{
return isOrganicElement(atom) && atom->formalCharge() == 0;
}
bool isPlanarAtom(const chemkit::Atom *atom)
{
if(atom->is(chemkit::Atom::Carbon) && atom->neighborCount() != 3){
return false;
}
else if(atom->is(chemkit::Atom::Oxygen) && atom->neighborCount() != 2){
return false;
}
else if(atom->is(chemkit::Atom::Sulfur) && atom->neighborCount() != 2){
return false;
}
return true;
}
// Returns true if the atom is a member of the aromatic subset.
bool isAromaticElement(const chemkit::Atom *atom)
{
switch(atom->atomicNumber()){
case chemkit::Atom::Boron:
case chemkit::Atom::Carbon:
case chemkit::Atom::Nitrogen:
case chemkit::Atom::Oxygen:
case chemkit::Atom::Phosphorus:
case chemkit::Atom::Sulfur:
case chemkit::Atom::Arsenic:
case chemkit::Atom::Selenium:
return true;
default:
return false;
}
}
bool isAromaticRing(const chemkit::Ring *ring)
{
foreach(const chemkit::Atom *atom, ring->atoms()){
if(!isAromaticElement(atom)){
return false;
}
else if(!isPlanarAtom(atom)){
return false;
}
foreach(const chemkit::Bond *bond, atom->bonds()){
if(ring->contains(bond)){
continue;
}
if(bond->order() == chemkit::Bond::Double && !bond->otherAtom(atom)->isInRing()){
return false;
}
}
}
return true;
}
bool isAromaticAtom(const chemkit::Atom *atom)
{
if(!isAromaticElement(atom)){
return false;
}
foreach(const chemkit::Ring *ring, atom->rings()){
if(isAromaticRing(ring)){
return true;
}
}
return false;
}
bool isIsotope(const chemkit::Atom *atom)
{
if(atom->is(chemkit::Atom::Hydrogen))
return atom->massNumber() != 1;
else
return atom->massNumber() != atom->atomicNumber() * 2;
}
// Returns true if the atom is an implicit hydrogen atom.
bool isImplicitHydrogen(const chemkit::Atom *atom)
{
return atom->isTerminalHydrogen() &&
atom->massNumber() == 1 &&
!atom->isBondedTo(chemkit::Atom::Hydrogen);
}
} // end anonymous namespace
// === SmilesGraphNode ===================================================== //
SmilesGraphNode::SmilesGraphNode(const chemkit::Atom *atom)
: m_atom(atom),
m_hydrogenCount(0),
m_parent(0),
m_bondOrder(0)
{
}
void SmilesGraphNode::setParent(SmilesGraphNode *parent, int bondOrder)
{
m_parent = parent;
m_bondOrder = bondOrder;
parent->m_children.append(this);
}
SmilesGraphNode* SmilesGraphNode::parent() const
{
return m_parent;
}
int SmilesGraphNode::childCount() const
{
return m_children.size();
}
QList<SmilesGraphNode *> SmilesGraphNode::children() const
{
return m_children;
}
void SmilesGraphNode::setHydrogenCount(int hydrogenCount)
{
m_hydrogenCount = hydrogenCount;
}
int SmilesGraphNode::hydrogenCount() const
{
return m_hydrogenCount;
}
void SmilesGraphNode::addRing(int ringNumber, int bondOrder)
{
m_rings.append(ringNumber);
m_ringBondOrders.append(bondOrder);
}
std::string SmilesGraphNode::toString(bool kekulize) const
{
std::stringstream string;
if(m_bondOrder == 0){
// do nothing
}
else if(!kekulize && isAromaticAtom(m_atom) && isAromaticAtom(m_parent->atom())){
// do nothing
}
else if(m_bondOrder == chemkit::Bond::Double){
string << "=";
}
else if(m_bondOrder == chemkit::Bond::Triple){
string << "#";
}
else if(m_bondOrder == chemkit::Bond::Quadruple){
string << "$";
}
if(!kekulize && isAromaticAtom(m_atom)){
if(m_atom->is(chemkit::Atom::Nitrogen) && m_atom->neighborCount(chemkit::Atom::Hydrogen) == 1){
string << "[nH]";
}
else{
string << QString(m_atom->symbol().c_str()).toLower().toStdString();
}
}
else if(isOrganicAtom(m_atom)){
string << m_atom->symbol().c_str();
}
else{
string << "[";
// mass number
if(isIsotope(m_atom)){
string << m_atom->massNumber();
}
string << m_atom->symbol().c_str();
if(m_hydrogenCount > 0){
string << "H";
if(m_hydrogenCount > 1){
string << m_hydrogenCount;
}
}
int charge = m_atom->formalCharge();
if(charge > 0){
string << "+";
}
else if(charge < 0){
string << "-";
}
if(qAbs(charge) > 1){
string << qAbs(charge);
}
string << "]";
}
for(int i = 0; i < m_rings.size(); i++){
int ringNumber = m_rings[i];
int bondOrder = m_ringBondOrders[i];
if(isAromaticAtom(m_atom)){
}
else if(bondOrder == chemkit::Bond::Double)
string << "=";
else if(bondOrder == chemkit::Bond::Triple)
string << "#";
if(ringNumber > 9){
string << "%";
}
string << ringNumber;
}
return string.str();
}
void SmilesGraphNode::write(std::stringstream &string, bool kekulize) const
{
string << toString(kekulize);
if(childCount() == 1){
m_children[0]->write(string, kekulize);
}
else if(childCount() > 1){
QList<SmilesGraphNode *> children = m_children;
const SmilesGraphNode *firstChild = children.takeFirst();
foreach(SmilesGraphNode *child, children){
string << "(";
child->write(string, kekulize);
string << ")";
}
firstChild->write(string, kekulize);
}
}
// === SmilesGraph ========================================================= //
SmilesGraph::SmilesGraph(const chemkit::Molecule *molecule)
{
QSet<const chemkit::Atom *> visitedAtoms;
QSet<const chemkit::Ring *> visitedRings;
QHash<const chemkit::Atom *, int> ringClosingAtoms;
QSet<const chemkit::Bond *> ringBonds;
while(visitedAtoms.size() != molecule->size()){
const chemkit::Atom *rootAtom = 0;
foreach(const chemkit::Atom *atom, molecule->atoms()){
if(visitedAtoms.contains(atom)){
continue;
}
if(!isImplicitHydrogen(atom)){
rootAtom = atom;
break;
}
}
SmilesGraphNode *rootNode = new SmilesGraphNode(rootAtom);
m_rootNodes.append(rootNode);
visitedAtoms.insert(rootAtom);
QQueue<SmilesGraphNode *> queue;
queue.enqueue(rootNode);
while(!queue.isEmpty()){
SmilesGraphNode *parentNode = queue.dequeue();
const chemkit::Atom *atom = parentNode->atom();
int hydrogenCount = 0;
foreach(const chemkit::Ring *ring, atom->rings()){
if(visitedRings.contains(ring)){
continue;
}
const chemkit::Atom *ringClosingAtom = 0;
foreach(const chemkit::Atom *neighbor, atom->neighbors()){
if(!ring->contains(neighbor)){
continue;
}
ringClosingAtom = neighbor;
}
int ringNumber;
for(int i = 1;; i++){
if(!ringClosingAtoms.values().contains(i)){
ringNumber = i;
break;
}
}
const chemkit::Bond *bond = atom->bondTo(ringClosingAtom);
ringClosingAtoms.insertMulti(ringClosingAtom, ringNumber);
ringBonds.insert(bond);
parentNode->addRing(ringNumber, bond->order());
visitedRings.insert(ring);
}
foreach(const chemkit::Atom *neighbor, atom->neighbors()){
if(visitedAtoms.contains(neighbor)){
continue;
}
else if(isImplicitHydrogen(neighbor)){
hydrogenCount++;
visitedAtoms.insert(neighbor);
continue;
}
const chemkit::Bond *bond = atom->bondTo(neighbor);
if(ringBonds.contains(bond)){
continue;
}
SmilesGraphNode *node = new SmilesGraphNode(neighbor);
visitedAtoms.insert(neighbor);
node->setParent(parentNode, bond->order());
if(ringClosingAtoms.contains(neighbor)){
foreach(int ring, ringClosingAtoms.values(neighbor)){
node->addRing(ring, 0);
}
ringClosingAtoms.remove(neighbor);
}
queue.enqueue(node);
}
parentNode->setHydrogenCount(hydrogenCount);
}
}
}
std::string SmilesGraph::toString(bool kekulize) const
{
if(m_rootNodes.isEmpty()){
return std::string();
}
else if(m_rootNodes.size() == 1){
std::stringstream stream;
m_rootNodes.first()->write(stream, kekulize);
return stream.str();
}
else{
std::stringstream stream;
foreach(const SmilesGraphNode *rootNode, m_rootNodes){
rootNode->write(stream, kekulize);
stream << ".";
}
// remove trailing '.'
std::string string = stream.str();
string.erase(string.end()-1);
return string;
}
}
<commit_msg>Fix bug in SmilesGraph class in the smiles plugin<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
**
** This file is part of chemkit. For more information see
** <http://www.chemkit.org>.
**
** chemkit is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** chemkit 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 chemkit. If not, see <http://www.gnu.org/licenses/>.
**
******************************************************************************/
#include "smilesgraph.h"
#include <algorithm>
#include <chemkit/atom.h>
#include <chemkit/bond.h>
#include <chemkit/molecule.h>
namespace {
// Returns true if the element is a member of the organic subset.
bool isOrganicElement(const chemkit::Atom *atom)
{
switch(atom->atomicNumber()){
case chemkit::Atom::Boron:
case chemkit::Atom::Carbon:
case chemkit::Atom::Nitrogen:
case chemkit::Atom::Oxygen:
case chemkit::Atom::Phosphorus:
case chemkit::Atom::Sulfur:
case chemkit::Atom::Chlorine:
case chemkit::Atom::Bromine:
case chemkit::Atom::Iodine:
return true;
default:
return false;
}
}
bool isOrganicAtom(const chemkit::Atom *atom)
{
return isOrganicElement(atom) && atom->formalCharge() == 0;
}
bool isPlanarAtom(const chemkit::Atom *atom)
{
if(atom->is(chemkit::Atom::Carbon) && atom->neighborCount() != 3){
return false;
}
else if(atom->is(chemkit::Atom::Oxygen) && atom->neighborCount() != 2){
return false;
}
else if(atom->is(chemkit::Atom::Sulfur) && atom->neighborCount() != 2){
return false;
}
return true;
}
// Returns true if the atom is a member of the aromatic subset.
bool isAromaticElement(const chemkit::Atom *atom)
{
switch(atom->atomicNumber()){
case chemkit::Atom::Boron:
case chemkit::Atom::Carbon:
case chemkit::Atom::Nitrogen:
case chemkit::Atom::Oxygen:
case chemkit::Atom::Phosphorus:
case chemkit::Atom::Sulfur:
case chemkit::Atom::Arsenic:
case chemkit::Atom::Selenium:
return true;
default:
return false;
}
}
bool isAromaticRing(const chemkit::Ring *ring)
{
foreach(const chemkit::Atom *atom, ring->atoms()){
if(!isAromaticElement(atom)){
return false;
}
else if(!isPlanarAtom(atom)){
return false;
}
foreach(const chemkit::Bond *bond, atom->bonds()){
if(ring->contains(bond)){
continue;
}
if(bond->order() == chemkit::Bond::Double && !bond->otherAtom(atom)->isInRing()){
return false;
}
}
}
return true;
}
bool isAromaticAtom(const chemkit::Atom *atom)
{
if(!isAromaticElement(atom)){
return false;
}
foreach(const chemkit::Ring *ring, atom->rings()){
if(isAromaticRing(ring)){
return true;
}
}
return false;
}
bool isIsotope(const chemkit::Atom *atom)
{
if(atom->is(chemkit::Atom::Hydrogen))
return atom->massNumber() != 1;
else
return atom->massNumber() != atom->atomicNumber() * 2;
}
// Returns true if the atom is an implicit hydrogen atom.
bool isImplicitHydrogen(const chemkit::Atom *atom)
{
return atom->isTerminalHydrogen() &&
atom->massNumber() == 1 &&
!atom->isBondedTo(chemkit::Atom::Hydrogen);
}
} // end anonymous namespace
// === SmilesGraphNode ===================================================== //
SmilesGraphNode::SmilesGraphNode(const chemkit::Atom *atom)
: m_atom(atom),
m_hydrogenCount(0),
m_parent(0),
m_bondOrder(0)
{
}
void SmilesGraphNode::setParent(SmilesGraphNode *parent, int bondOrder)
{
m_parent = parent;
m_bondOrder = bondOrder;
parent->m_children.append(this);
}
SmilesGraphNode* SmilesGraphNode::parent() const
{
return m_parent;
}
int SmilesGraphNode::childCount() const
{
return m_children.size();
}
QList<SmilesGraphNode *> SmilesGraphNode::children() const
{
return m_children;
}
void SmilesGraphNode::setHydrogenCount(int hydrogenCount)
{
m_hydrogenCount = hydrogenCount;
}
int SmilesGraphNode::hydrogenCount() const
{
return m_hydrogenCount;
}
void SmilesGraphNode::addRing(int ringNumber, int bondOrder)
{
m_rings.append(ringNumber);
m_ringBondOrders.append(bondOrder);
}
std::string SmilesGraphNode::toString(bool kekulize) const
{
std::stringstream string;
if(m_bondOrder == 0){
// do nothing
}
else if(!kekulize && isAromaticAtom(m_atom) && isAromaticAtom(m_parent->atom())){
// do nothing
}
else if(m_bondOrder == chemkit::Bond::Double){
string << "=";
}
else if(m_bondOrder == chemkit::Bond::Triple){
string << "#";
}
else if(m_bondOrder == chemkit::Bond::Quadruple){
string << "$";
}
if(!kekulize && isAromaticAtom(m_atom)){
if(m_atom->is(chemkit::Atom::Nitrogen) && m_atom->neighborCount(chemkit::Atom::Hydrogen) == 1){
string << "[nH]";
}
else{
string << QString(m_atom->symbol().c_str()).toLower().toStdString();
}
}
else if(isOrganicAtom(m_atom)){
string << m_atom->symbol().c_str();
}
else{
string << "[";
// mass number
if(isIsotope(m_atom)){
string << m_atom->massNumber();
}
string << m_atom->symbol().c_str();
if(m_hydrogenCount > 0){
string << "H";
if(m_hydrogenCount > 1){
string << m_hydrogenCount;
}
}
int charge = m_atom->formalCharge();
if(charge > 0){
string << "+";
}
else if(charge < 0){
string << "-";
}
if(qAbs(charge) > 1){
string << qAbs(charge);
}
string << "]";
}
for(int i = 0; i < m_rings.size(); i++){
int ringNumber = m_rings[i];
int bondOrder = m_ringBondOrders[i];
if(isAromaticAtom(m_atom)){
}
else if(bondOrder == chemkit::Bond::Double)
string << "=";
else if(bondOrder == chemkit::Bond::Triple)
string << "#";
if(ringNumber > 9){
string << "%";
}
string << ringNumber;
}
return string.str();
}
void SmilesGraphNode::write(std::stringstream &string, bool kekulize) const
{
string << toString(kekulize);
if(childCount() == 1){
m_children[0]->write(string, kekulize);
}
else if(childCount() > 1){
QList<SmilesGraphNode *> children = m_children;
const SmilesGraphNode *firstChild = children.takeFirst();
foreach(SmilesGraphNode *child, children){
string << "(";
child->write(string, kekulize);
string << ")";
}
firstChild->write(string, kekulize);
}
}
// === SmilesGraph ========================================================= //
SmilesGraph::SmilesGraph(const chemkit::Molecule *molecule)
{
QSet<const chemkit::Atom *> visitedAtoms;
QSet<const chemkit::Ring *> visitedRings;
QHash<const chemkit::Atom *, int> ringClosingAtoms;
QSet<const chemkit::Bond *> ringBonds;
// neighbor count for each atom without implicit hydrogens
std::vector<int> neighborCounts(molecule->size());
for(int i = 0; i < molecule->size(); i++){
const chemkit::Atom *atom = molecule->atom(i);
int neighborCount = 0;
foreach(const chemkit::Atom *neighbor, atom->neighbors()){
if(!isImplicitHydrogen(neighbor)){
neighborCount++;
}
}
neighborCounts[i] = neighborCount;
}
while(visitedAtoms.size() != molecule->size()){
const chemkit::Atom *rootAtom = 0;
foreach(const chemkit::Atom *atom, molecule->atoms()){
if(visitedAtoms.contains(atom)){
continue;
}
if(!isImplicitHydrogen(atom)){
rootAtom = atom;
break;
}
}
SmilesGraphNode *rootNode = new SmilesGraphNode(rootAtom);
m_rootNodes.append(rootNode);
visitedAtoms.insert(rootAtom);
int ringNumber = 1;
QQueue<SmilesGraphNode *> queue;
queue.enqueue(rootNode);
while(!queue.isEmpty()){
SmilesGraphNode *parentNode = queue.dequeue();
const chemkit::Atom *atom = parentNode->atom();
int hydrogenCount = 0;
foreach(const chemkit::Ring *ring, atom->rings()){
if(visitedRings.contains(ring)){
continue;
}
if(neighborCounts[atom->index()] <= 1){
break;
}
const chemkit::Atom *ringClosingAtom = 0;
foreach(const chemkit::Atom *neighbor, atom->neighbors()){
if(!ring->contains(neighbor)){
continue;
}
else if(ringBonds.contains(atom->bondTo(neighbor))){
continue;
}
else if(neighborCounts[neighbor->index()] <= 1){
continue;
}
ringClosingAtom = neighbor;
}
if(!ringClosingAtom){
continue;
}
const chemkit::Bond *bond = atom->bondTo(ringClosingAtom);
ringClosingAtoms.insertMulti(ringClosingAtom, ringNumber);
ringBonds.insert(bond);
parentNode->addRing(ringNumber, bond->order());
neighborCounts[bond->atom1()->index()]--;
neighborCounts[bond->atom2()->index()]--;
visitedRings.insert(ring);
ringNumber++;
}
foreach(const chemkit::Atom *neighbor, atom->neighbors()){
if(visitedAtoms.contains(neighbor)){
continue;
}
else if(isImplicitHydrogen(neighbor)){
hydrogenCount++;
visitedAtoms.insert(neighbor);
continue;
}
const chemkit::Bond *bond = atom->bondTo(neighbor);
if(ringBonds.contains(bond)){
continue;
}
SmilesGraphNode *node = new SmilesGraphNode(neighbor);
visitedAtoms.insert(neighbor);
node->setParent(parentNode, bond->order());
if(ringClosingAtoms.contains(neighbor)){
foreach(int ring, ringClosingAtoms.values(neighbor)){
node->addRing(ring, 0);
}
ringClosingAtoms.remove(neighbor);
}
queue.enqueue(node);
}
parentNode->setHydrogenCount(hydrogenCount);
}
}
}
std::string SmilesGraph::toString(bool kekulize) const
{
if(m_rootNodes.isEmpty()){
return std::string();
}
else if(m_rootNodes.size() == 1){
std::stringstream stream;
m_rootNodes.first()->write(stream, kekulize);
return stream.str();
}
else{
std::stringstream stream;
foreach(const SmilesGraphNode *rootNode, m_rootNodes){
rootNode->write(stream, kekulize);
stream << ".";
}
// remove trailing '.'
std::string string = stream.str();
string.erase(string.end()-1);
return string;
}
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#define WITH_D3D
#include "../rwbase.h"
#include "../rwerror.h"
#include "../rwplg.h"
#include "../rwpipeline.h"
#include "../rwobjects.h"
#include "../rwanim.h"
#include "../rwengine.h"
#include "../rwrender.h"
#include "../rwplugins.h"
#include "rwd3d.h"
#include "rwd3d9.h"
namespace rw {
namespace d3d9 {
using namespace d3d;
static void *matfx_env_amb_VS;
static void *matfx_env_amb_dir_VS;
static void *matfx_env_all_VS;
static void *matfx_env_PS;
static void *matfx_env_tex_PS;
enum
{
VSLOC_texMat = VSLOC_afterLights,
PSLOC_shininess = 1,
PSLOC_colorClamp = 2
};
void
matfxRender_Default(InstanceDataHeader *header, InstanceData *inst, int32 lightBits)
{
Material *m = inst->material;
// Pick a shader
if((lightBits & VSLIGHT_MASK) == 0)
setVertexShader(default_amb_VS);
else if((lightBits & VSLIGHT_MASK) == VSLIGHT_DIRECT)
setVertexShader(default_amb_dir_VS);
else
setVertexShader(default_all_VS);
SetRenderState(VERTEXALPHA, inst->vertexAlpha || m->color.alpha != 255);
if(inst->material->texture){
d3d::setTexture(0, m->texture);
setPixelShader(default_tex_PS);
}else
setPixelShader(default_PS);
drawInst(header, inst);
}
static Frame *lastEnvFrame;
static RawMatrix normal2texcoord = {
{ 0.5f, 0.0f, 0.0f }, 0.0f,
{ 0.0f, -0.5f, 0.0f }, 0.0f,
{ 0.0f, 0.0f, 1.0f }, 0.0f,
{ 0.5f, 0.5f, 0.0f }, 1.0f
};
void
uploadEnvMatrix(Frame *frame)
{
Matrix invMat;
if(frame == nil)
frame = engine->currentCamera->getFrame();
// cache the matrix across multiple meshes
if(frame == lastEnvFrame)
return;
lastEnvFrame = frame;
RawMatrix envMtx, invMtx;
Matrix::invert(&invMat, frame->getLTM());
convMatrix(&invMtx, &invMat);
RawMatrix::mult(&envMtx, &invMtx, &normal2texcoord);
d3ddevice->SetVertexShaderConstantF(VSLOC_texMat, (float*)&envMtx, 4);
}
void
matfxRender_EnvMap(InstanceDataHeader *header, InstanceData *inst, int32 lightBits, MatFX::Env *env)
{
Material *m = inst->material;
if(env->tex == nil || env->coefficient == 0.0f){
matfxRender_Default(header, inst, lightBits);
return;
}
d3d::setTexture(1, env->tex);
uploadEnvMatrix(env->frame);
d3ddevice->SetPixelShaderConstantF(PSLOC_shininess, &env->coefficient, 1);
SetRenderState(SRCBLEND, BLENDONE);
static float zero[4];
static float one[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
d3ddevice->SetPixelShaderConstantF(PSLOC_shininess, &env->coefficient, 1);
// This clamps the vertex color below. With it we can achieve both PC and PS2 style matfx
if(MatFX::modulateEnvMap)
d3ddevice->SetPixelShaderConstantF(PSLOC_colorClamp, zero, 1);
else
d3ddevice->SetPixelShaderConstantF(PSLOC_colorClamp, one, 1);
// Pick a shader
if((lightBits & VSLIGHT_MASK) == 0)
setVertexShader(matfx_env_amb_VS);
else if((lightBits & VSLIGHT_MASK) == VSLIGHT_DIRECT)
setVertexShader(matfx_env_amb_dir_VS);
else
setVertexShader(matfx_env_all_VS);
bool32 texAlpha = PLUGINOFFSET(D3dRaster, env->tex->raster, nativeRasterOffset)->hasAlpha;
if(inst->material->texture){
d3d::setTexture(0, m->texture);
setPixelShader(matfx_env_tex_PS);
}else
setPixelShader(matfx_env_PS);
SetRenderState(VERTEXALPHA, texAlpha || inst->vertexAlpha || m->color.alpha != 255);
drawInst(header, inst);
SetRenderState(SRCBLEND, BLENDSRCALPHA);
}
void
matfxRenderCB_Shader(Atomic *atomic, InstanceDataHeader *header)
{
int vsBits;
d3ddevice->SetStreamSource(0, (IDirect3DVertexBuffer9*)header->vertexStream[0].vertexBuffer,
0, header->vertexStream[0].stride);
d3ddevice->SetIndices((IDirect3DIndexBuffer9*)header->indexBuffer);
d3ddevice->SetVertexDeclaration((IDirect3DVertexDeclaration9*)header->vertexDeclaration);
lastEnvFrame = nil;
vsBits = lightingCB_Shader(atomic);
uploadMatrices(atomic->getFrame()->getLTM());
d3ddevice->SetVertexShaderConstantF(VSLOC_fogData, (float*)&d3dShaderState.fogData, 1);
d3ddevice->SetPixelShaderConstantF(PSLOC_fogColor, (float*)&d3dShaderState.fogColor, 1);
bool normals = !!(atomic->geometry->flags & Geometry::NORMALS);
float surfProps[4];
surfProps[3] = atomic->geometry->flags&Geometry::PRELIT ? 1.0f : 0.0f;
InstanceData *inst = header->inst;
for(uint32 i = 0; i < header->numMeshes; i++){
Material *m = inst->material;
rw::RGBAf col;
convColor(&col, &inst->material->color);
d3ddevice->SetVertexShaderConstantF(VSLOC_matColor, (float*)&col, 1);
surfProps[0] = m->surfaceProps.ambient;
surfProps[1] = m->surfaceProps.specular;
surfProps[2] = m->surfaceProps.diffuse;
d3ddevice->SetVertexShaderConstantF(VSLOC_surfProps, surfProps, 1);
MatFX *matfx = MatFX::get(m);
if(matfx == nil)
matfxRender_Default(header, inst, vsBits);
else switch(matfx->type){
case MatFX::ENVMAP:
if(normals)
matfxRender_EnvMap(header, inst, vsBits, &matfx->fx[0].env);
else
matfxRender_Default(header, inst, vsBits);
break;
case MatFX::NOTHING:
case MatFX::BUMPMAP:
case MatFX::BUMPENVMAP:
case MatFX::DUAL:
case MatFX::UVTRANSFORM:
case MatFX::DUALUVTRANSFORM:
// not supported yet
matfxRender_Default(header, inst, vsBits);
break;
}
inst++;
}
d3d::setTexture(1, nil);
setVertexShader(nil);
setPixelShader(nil);
}
#define VS_NAME g_vs20_main
#define PS_NAME g_ps20_main
void
createMatFXShaders(void)
{
{
static
#include "shaders/matfx_env_amb_VS.h"
matfx_env_amb_VS = createVertexShader((void*)VS_NAME);
assert(matfx_env_amb_VS);
}
{
static
#include "shaders/matfx_env_amb_dir_VS.h"
matfx_env_amb_dir_VS = createVertexShader((void*)VS_NAME);
assert(matfx_env_amb_dir_VS);
}
{
static
#include "shaders/matfx_env_all_VS.h"
matfx_env_all_VS = createVertexShader((void*)VS_NAME);
assert(matfx_env_all_VS);
}
{
static
#include "shaders/matfx_env_PS.h"
matfx_env_PS = createPixelShader((void*)PS_NAME);
assert(matfx_env_PS);
}
{
static
#include "shaders/matfx_env_tex_PS.h"
matfx_env_tex_PS = createPixelShader((void*)PS_NAME);
assert(matfx_env_tex_PS);
}
}
void
destroyMatFXShaders(void)
{
destroyVertexShader(matfx_env_PS);
matfx_env_PS = nil;
destroyVertexShader(matfx_env_tex_PS);
matfx_env_tex_PS = nil;
}
static void*
matfxOpen(void *o, int32, int32)
{
createMatFXShaders();
matFXGlobals.pipelines[PLATFORM_D3D9] = makeMatFXPipeline();
return o;
}
static void*
matfxClose(void *o, int32, int32)
{
destroyMatFXShaders();
return o;
}
void
initMatFX(void)
{
Driver::registerPlugin(PLATFORM_D3D9, 0, ID_MATFX,
matfxOpen, matfxClose);
}
ObjPipeline*
makeMatFXPipeline(void)
{
ObjPipeline *pipe = new ObjPipeline(PLATFORM_D3D9);
pipe->instanceCB = defaultInstanceCB;
pipe->uninstanceCB = defaultUninstanceCB;
pipe->renderCB = matfxRenderCB_Shader;
pipe->pluginID = ID_MATFX;
pipe->pluginData = 0;
return pipe;
}
}
}
<commit_msg>more silly bugs<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#define WITH_D3D
#include "../rwbase.h"
#include "../rwerror.h"
#include "../rwplg.h"
#include "../rwpipeline.h"
#include "../rwobjects.h"
#include "../rwanim.h"
#include "../rwengine.h"
#include "../rwrender.h"
#include "../rwplugins.h"
#include "rwd3d.h"
#include "rwd3d9.h"
namespace rw {
namespace d3d9 {
using namespace d3d;
static void *matfx_env_amb_VS;
static void *matfx_env_amb_dir_VS;
static void *matfx_env_all_VS;
static void *matfx_env_PS;
static void *matfx_env_tex_PS;
enum
{
VSLOC_texMat = VSLOC_afterLights,
PSLOC_shininess = 1,
PSLOC_colorClamp = 2
};
void
matfxRender_Default(InstanceDataHeader *header, InstanceData *inst, int32 lightBits)
{
Material *m = inst->material;
// Pick a shader
if((lightBits & VSLIGHT_MASK) == 0)
setVertexShader(default_amb_VS);
else if((lightBits & VSLIGHT_MASK) == VSLIGHT_DIRECT)
setVertexShader(default_amb_dir_VS);
else
setVertexShader(default_all_VS);
SetRenderState(VERTEXALPHA, inst->vertexAlpha || m->color.alpha != 255);
if(inst->material->texture){
d3d::setTexture(0, m->texture);
setPixelShader(default_tex_PS);
}else
setPixelShader(default_PS);
drawInst(header, inst);
}
static Frame *lastEnvFrame;
static RawMatrix normal2texcoord = {
{ 0.5f, 0.0f, 0.0f }, 0.0f,
{ 0.0f, -0.5f, 0.0f }, 0.0f,
{ 0.0f, 0.0f, 1.0f }, 0.0f,
{ 0.5f, 0.5f, 0.0f }, 1.0f
};
void
uploadEnvMatrix(Frame *frame)
{
Matrix invMat;
if(frame == nil)
frame = engine->currentCamera->getFrame();
// cache the matrix across multiple meshes
if(frame == lastEnvFrame)
return;
lastEnvFrame = frame;
RawMatrix envMtx, invMtx;
Matrix::invert(&invMat, frame->getLTM());
convMatrix(&invMtx, &invMat);
RawMatrix::mult(&envMtx, &invMtx, &normal2texcoord);
d3ddevice->SetVertexShaderConstantF(VSLOC_texMat, (float*)&envMtx, 4);
}
void
matfxRender_EnvMap(InstanceDataHeader *header, InstanceData *inst, int32 lightBits, MatFX::Env *env)
{
Material *m = inst->material;
if(env->tex == nil || env->coefficient == 0.0f){
matfxRender_Default(header, inst, lightBits);
return;
}
d3d::setTexture(1, env->tex);
uploadEnvMatrix(env->frame);
d3ddevice->SetPixelShaderConstantF(PSLOC_shininess, &env->coefficient, 1);
SetRenderState(SRCBLEND, BLENDONE);
static float zero[4];
static float one[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
d3ddevice->SetPixelShaderConstantF(PSLOC_shininess, &env->coefficient, 1);
// This clamps the vertex color below. With it we can achieve both PC and PS2 style matfx
if(MatFX::modulateEnvMap)
d3ddevice->SetPixelShaderConstantF(PSLOC_colorClamp, zero, 1);
else
d3ddevice->SetPixelShaderConstantF(PSLOC_colorClamp, one, 1);
// Pick a shader
if((lightBits & VSLIGHT_MASK) == 0)
setVertexShader(matfx_env_amb_VS);
else if((lightBits & VSLIGHT_MASK) == VSLIGHT_DIRECT)
setVertexShader(matfx_env_amb_dir_VS);
else
setVertexShader(matfx_env_all_VS);
bool32 texAlpha = PLUGINOFFSET(D3dRaster, env->tex->raster, nativeRasterOffset)->hasAlpha;
if(inst->material->texture){
d3d::setTexture(0, m->texture);
setPixelShader(matfx_env_tex_PS);
}else
setPixelShader(matfx_env_PS);
SetRenderState(VERTEXALPHA, texAlpha || inst->vertexAlpha || m->color.alpha != 255);
drawInst(header, inst);
SetRenderState(SRCBLEND, BLENDSRCALPHA);
}
void
matfxRenderCB_Shader(Atomic *atomic, InstanceDataHeader *header)
{
int vsBits;
d3ddevice->SetStreamSource(0, (IDirect3DVertexBuffer9*)header->vertexStream[0].vertexBuffer,
0, header->vertexStream[0].stride);
d3ddevice->SetIndices((IDirect3DIndexBuffer9*)header->indexBuffer);
d3ddevice->SetVertexDeclaration((IDirect3DVertexDeclaration9*)header->vertexDeclaration);
lastEnvFrame = nil;
vsBits = lightingCB_Shader(atomic);
uploadMatrices(atomic->getFrame()->getLTM());
d3ddevice->SetVertexShaderConstantF(VSLOC_fogData, (float*)&d3dShaderState.fogData, 1);
d3ddevice->SetPixelShaderConstantF(PSLOC_fogColor, (float*)&d3dShaderState.fogColor, 1);
bool normals = !!(atomic->geometry->flags & Geometry::NORMALS);
float surfProps[4];
surfProps[3] = atomic->geometry->flags&Geometry::PRELIT ? 1.0f : 0.0f;
InstanceData *inst = header->inst;
for(uint32 i = 0; i < header->numMeshes; i++){
Material *m = inst->material;
rw::RGBAf col;
convColor(&col, &inst->material->color);
d3ddevice->SetVertexShaderConstantF(VSLOC_matColor, (float*)&col, 1);
surfProps[0] = m->surfaceProps.ambient;
surfProps[1] = m->surfaceProps.specular;
surfProps[2] = m->surfaceProps.diffuse;
d3ddevice->SetVertexShaderConstantF(VSLOC_surfProps, surfProps, 1);
MatFX *matfx = MatFX::get(m);
if(matfx == nil)
matfxRender_Default(header, inst, vsBits);
else switch(matfx->type){
case MatFX::ENVMAP:
if(normals)
matfxRender_EnvMap(header, inst, vsBits, &matfx->fx[0].env);
else
matfxRender_Default(header, inst, vsBits);
break;
case MatFX::NOTHING:
case MatFX::BUMPMAP:
case MatFX::BUMPENVMAP:
case MatFX::DUAL:
case MatFX::UVTRANSFORM:
case MatFX::DUALUVTRANSFORM:
// not supported yet
matfxRender_Default(header, inst, vsBits);
break;
}
inst++;
}
d3d::setTexture(1, nil);
setVertexShader(nil);
setPixelShader(nil);
}
#define VS_NAME g_vs20_main
#define PS_NAME g_ps20_main
void
createMatFXShaders(void)
{
{
static
#include "shaders/matfx_env_amb_VS.h"
matfx_env_amb_VS = createVertexShader((void*)VS_NAME);
assert(matfx_env_amb_VS);
}
{
static
#include "shaders/matfx_env_amb_dir_VS.h"
matfx_env_amb_dir_VS = createVertexShader((void*)VS_NAME);
assert(matfx_env_amb_dir_VS);
}
{
static
#include "shaders/matfx_env_all_VS.h"
matfx_env_all_VS = createVertexShader((void*)VS_NAME);
assert(matfx_env_all_VS);
}
{
static
#include "shaders/matfx_env_PS.h"
matfx_env_PS = createPixelShader((void*)PS_NAME);
assert(matfx_env_PS);
}
{
static
#include "shaders/matfx_env_tex_PS.h"
matfx_env_tex_PS = createPixelShader((void*)PS_NAME);
assert(matfx_env_tex_PS);
}
}
void
destroyMatFXShaders(void)
{
destroyVertexShader(matfx_env_amb_VS);
matfx_env_amb_VS = nil;
destroyVertexShader(matfx_env_amb_dir_VS);
matfx_env_amb_dir_VS = nil;
destroyVertexShader(matfx_env_all_VS);
matfx_env_all_VS = nil;
destroyPixelShader(matfx_env_PS);
matfx_env_PS = nil;
destroyPixelShader(matfx_env_tex_PS);
matfx_env_tex_PS = nil;
}
static void*
matfxOpen(void *o, int32, int32)
{
createMatFXShaders();
matFXGlobals.pipelines[PLATFORM_D3D9] = makeMatFXPipeline();
return o;
}
static void*
matfxClose(void *o, int32, int32)
{
destroyMatFXShaders();
return o;
}
void
initMatFX(void)
{
Driver::registerPlugin(PLATFORM_D3D9, 0, ID_MATFX,
matfxOpen, matfxClose);
}
ObjPipeline*
makeMatFXPipeline(void)
{
ObjPipeline *pipe = new ObjPipeline(PLATFORM_D3D9);
pipe->instanceCB = defaultInstanceCB;
pipe->uninstanceCB = defaultUninstanceCB;
pipe->renderCB = matfxRenderCB_Shader;
pipe->pluginID = ID_MATFX;
pipe->pluginData = 0;
return pipe;
}
}
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreVolumeMeshBuilder.h"
#include "OgreHardwareBufferManager.h"
#include "OgreManualObject.h"
#include "OgreMeshManager.h"
namespace Ogre {
namespace Volume {
bool operator==(Vertex const& a, Vertex const& b)
{
return a.x == b.x &&
a.y == b.y &&
a.z == b.z &&
a.nX == b.nX &&
a.nY == b.nY &&
a.nZ == b.nZ;
}
//-----------------------------------------------------------------------
bool operator<(const Vertex& a, const Vertex& b)
{
return memcmp(&a, &b, sizeof(Ogre::Volume::Vertex)) < 0;
}
//-----------------------------------------------------------------------
const unsigned short MeshBuilder::MAIN_BINDING = 0;
//-----------------------------------------------------------------------
MeshBuilder::MeshBuilder(void) : mBoxInit(false)
{
}
//-----------------------------------------------------------------------
size_t MeshBuilder::generateBuffers(RenderOperation &operation)
{
// Early out if nothing to do.
if (mIndices.size() == 0)
{
return 0;
}
// Prepare vertex buffer
operation.operationType = RenderOperation::OT_TRIANGLE_LIST;
operation.vertexData = OGRE_NEW VertexData();
operation.vertexData->vertexCount = mVertices.size();
operation.vertexData->vertexStart = 0;
VertexDeclaration *decl = operation.vertexData->vertexDeclaration;
VertexBufferBinding *bind = operation.vertexData->vertexBufferBinding;
size_t offset = 0;
// Add vertex-positions to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_POSITION);
offset += VertexElement::getTypeSize(VET_FLOAT3);
// Add vertex-normals to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL);
offset += VertexElement::getTypeSize(VET_FLOAT3);
HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(MAIN_BINDING),
operation.vertexData->vertexCount,
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
bind->setBinding(0, vbuf);
float* vertices = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
VecVertex::const_iterator endVertices = mVertices.end();
for (VecVertex::const_iterator iter = mVertices.begin(); iter != endVertices; ++iter)
{
*vertices++ = (float)iter->x;
*vertices++ = (float)iter->y;
*vertices++ = (float)iter->z;
*vertices++ = (float)iter->nX;
*vertices++ = (float)iter->nY;
*vertices++ = (float)iter->nZ;
}
vbuf->unlock();
// Get Indexarray
operation.indexData = OGRE_NEW IndexData();
operation.indexData->indexCount = mIndices.size();
operation.indexData->indexStart = 0;
VecIndices::const_iterator endIndices = mIndices.end();
if (operation.indexData->indexCount > USHRT_MAX)
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_32BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned int* indices = static_cast<unsigned int*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = *iter;
}
}
else
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_16BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned short* indices = static_cast<unsigned short*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = *iter;
}
}
operation.indexData->indexBuffer->unlock();
return mIndices.size() / 3;
}
//-----------------------------------------------------------------------
AxisAlignedBox MeshBuilder::getBoundingBox(void)
{
return mBox;
}
//-----------------------------------------------------------------------
Entity* MeshBuilder::generateWithManualObject(SceneManager *sceneManager, const String &name, const String &material)
{
ManualObject* manual = sceneManager->createManualObject();
manual->begin(material, RenderOperation::OT_TRIANGLE_LIST);
for (VecVertex::const_iterator iter = mVertices.begin(); iter != mVertices.end(); ++iter)
{
manual->position(Vector3(iter->x, iter->y, iter->z));
manual->normal(Vector3(iter->nX, iter->nY, iter->nZ));
}
for (VecIndices::const_iterator iter = mIndices.begin(); iter != mIndices.end(); ++iter)
{
manual->index(*iter);
}
manual->end();
StringUtil::StrStreamType meshName;
meshName << name << "ManualObject";
MeshManager::getSingleton().remove(meshName.str());
manual->convertToMesh(meshName.str());
return sceneManager->createEntity(name, meshName.str());
}
//-----------------------------------------------------------------------
void MeshBuilder::executeCallback(MeshBuilderCallback *callback) const
{
callback->getTriangles(mVertices, mIndices);
}
}
}<commit_msg>Volume Rendering: setting the camera to manual in the CSG sample<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreVolumeMeshBuilder.h"
#include <limits.h>
#include "OgreHardwareBufferManager.h"
#include "OgreManualObject.h"
#include "OgreMeshManager.h"
namespace Ogre {
namespace Volume {
bool operator==(Vertex const& a, Vertex const& b)
{
return a.x == b.x &&
a.y == b.y &&
a.z == b.z &&
a.nX == b.nX &&
a.nY == b.nY &&
a.nZ == b.nZ;
}
//-----------------------------------------------------------------------
bool operator<(const Vertex& a, const Vertex& b)
{
return memcmp(&a, &b, sizeof(Ogre::Volume::Vertex)) < 0;
}
//-----------------------------------------------------------------------
const unsigned short MeshBuilder::MAIN_BINDING = 0;
//-----------------------------------------------------------------------
MeshBuilder::MeshBuilder(void) : mBoxInit(false)
{
}
//-----------------------------------------------------------------------
size_t MeshBuilder::generateBuffers(RenderOperation &operation)
{
// Early out if nothing to do.
if (mIndices.size() == 0)
{
return 0;
}
// Prepare vertex buffer
operation.operationType = RenderOperation::OT_TRIANGLE_LIST;
operation.vertexData = OGRE_NEW VertexData();
operation.vertexData->vertexCount = mVertices.size();
operation.vertexData->vertexStart = 0;
VertexDeclaration *decl = operation.vertexData->vertexDeclaration;
VertexBufferBinding *bind = operation.vertexData->vertexBufferBinding;
size_t offset = 0;
// Add vertex-positions to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_POSITION);
offset += VertexElement::getTypeSize(VET_FLOAT3);
// Add vertex-normals to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL);
offset += VertexElement::getTypeSize(VET_FLOAT3);
HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(MAIN_BINDING),
operation.vertexData->vertexCount,
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
bind->setBinding(0, vbuf);
float* vertices = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
VecVertex::const_iterator endVertices = mVertices.end();
for (VecVertex::const_iterator iter = mVertices.begin(); iter != endVertices; ++iter)
{
*vertices++ = (float)iter->x;
*vertices++ = (float)iter->y;
*vertices++ = (float)iter->z;
*vertices++ = (float)iter->nX;
*vertices++ = (float)iter->nY;
*vertices++ = (float)iter->nZ;
}
vbuf->unlock();
// Get Indexarray
operation.indexData = OGRE_NEW IndexData();
operation.indexData->indexCount = mIndices.size();
operation.indexData->indexStart = 0;
VecIndices::const_iterator endIndices = mIndices.end();
if (operation.indexData->indexCount > USHRT_MAX)
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_32BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned int* indices = static_cast<unsigned int*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = *iter;
}
}
else
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_16BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned short* indices = static_cast<unsigned short*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = *iter;
}
}
operation.indexData->indexBuffer->unlock();
return mIndices.size() / 3;
}
//-----------------------------------------------------------------------
AxisAlignedBox MeshBuilder::getBoundingBox(void)
{
return mBox;
}
//-----------------------------------------------------------------------
Entity* MeshBuilder::generateWithManualObject(SceneManager *sceneManager, const String &name, const String &material)
{
ManualObject* manual = sceneManager->createManualObject();
manual->begin(material, RenderOperation::OT_TRIANGLE_LIST);
for (VecVertex::const_iterator iter = mVertices.begin(); iter != mVertices.end(); ++iter)
{
manual->position(Vector3(iter->x, iter->y, iter->z));
manual->normal(Vector3(iter->nX, iter->nY, iter->nZ));
}
for (VecIndices::const_iterator iter = mIndices.begin(); iter != mIndices.end(); ++iter)
{
manual->index(*iter);
}
manual->end();
StringUtil::StrStreamType meshName;
meshName << name << "ManualObject";
MeshManager::getSingleton().remove(meshName.str());
manual->convertToMesh(meshName.str());
return sceneManager->createEntity(name, meshName.str());
}
//-----------------------------------------------------------------------
void MeshBuilder::executeCallback(MeshBuilderCallback *callback) const
{
callback->getTriangles(mVertices, mIndices);
}
}
}<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "SupervisorFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
static bool DONE = false;
static int CLIENT_PID = false;
static void StopHandler(int) {
LOG_TOPIC(INFO, Logger::STARTUP) << "received SIGINT for supervisor";
kill(CLIENT_PID, SIGTERM);
DONE = true;
}
SupervisorFeature::SupervisorFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Supervisor"), _supervisor(false), _clientPid(0) {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Daemon");
startsAfter("Logger");
startsAfter("WorkMonitor");
}
void SupervisorFeature::collectOptions(
std::shared_ptr<ProgramOptions> options) {
options->addHiddenOption("--supervisor",
"background the server, starts a supervisor",
new BooleanParameter(&_supervisor));
}
void SupervisorFeature::validateOptions(
std::shared_ptr<ProgramOptions> options) {
if (_supervisor) {
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// force daemon mode
daemon->setDaemon(true);
// revalidate options
daemon->validateOptions(options);
} catch (...) {
LOG(FATAL) << "daemon mode not available, cannot start supervisor";
FATAL_ERROR_EXIT();
}
}
}
void SupervisorFeature::daemonize() {
static time_t const MIN_TIME_ALIVE_IN_SEC = 30;
if (!_supervisor) {
return;
}
time_t startTime = time(0);
time_t t;
bool done = false;
int result = EXIT_SUCCESS;
// will be reseted in SchedulerFeature
ArangoGlobalContext::CONTEXT->unmaskStandardSignals();
LoggerFeature* logger = nullptr;
try {
logger = ApplicationServer::getFeature<LoggerFeature>("Logger");
} catch (...) {
LOG_TOPIC(FATAL, Logger::STARTUP)
<< "unknown feature 'Logger', giving up";
FATAL_ERROR_EXIT();
}
logger->setSupervisor(true);
logger->prepare();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "starting supervisor loop";
while (!done) {
logger->setSupervisor(false);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor will now try to fork a new child process";
// fork of the server
_clientPid = fork();
if (_clientPid < 0) {
LOG_TOPIC(FATAL, Logger::STARTUP) << "fork failed, giving up";
FATAL_ERROR_EXIT();
}
// parent (supervisor)
if (0 < _clientPid) {
signal(SIGINT, StopHandler);
signal(SIGTERM, StopHandler);
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor has forked a child process with pid " << _clientPid;
TRI_SetProcessTitle("arangodb [supervisor]");
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within parent";
CLIENT_PID = _clientPid;
DONE = false;
int status;
int res = waitpid(_clientPid, &status, 0);
bool horrible = true;
LOG_TOPIC(DEBUG, Logger::STARTUP) << "waitpid woke up with return value "
<< res << " and status " << status
<< " and DONE = " << (DONE ? "true" : "false");
if (DONE) {
// signal handler for SIGINT or SIGTERM was invoked
done = true;
horrible = false;
}
else {
TRI_ASSERT(horrible);
if (WIFEXITED(status)) {
// give information about cause of death
if (WEXITSTATUS(status) == 0) {
LOG_TOPIC(INFO, Logger::STARTUP) << "child " << _clientPid
<< " died of natural causes";
done = true;
horrible = false;
} else {
t = time(0) - startTime;
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child " << _clientPid
<< " died a horrible death, exit status " << WEXITSTATUS(status);
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child only survived for " << t
<< " seconds, this will not work - please fix the error "
"first";
done = true;
} else {
done = false;
}
}
} else if (WIFSIGNALED(status)) {
switch (WTERMSIG(status)) {
case 2: // SIGINT
case 9: // SIGKILL
case 15: // SIGTERM
LOG_TOPIC(INFO, Logger::STARTUP)
<< "child " << _clientPid
<< " died of natural causes, exit status " << WTERMSIG(status);
done = true;
horrible = false;
break;
default:
TRI_ASSERT(horrible);
t = time(0) - startTime;
LOG_TOPIC(ERR, Logger::STARTUP) << "child " << _clientPid
<< " died a horrible death, signal "
<< WTERMSIG(status);
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child only survived for " << t
<< " seconds, this will not work - please fix the "
"error first";
done = true;
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
LOG_TOPIC(WARN, Logger::STARTUP) << "child process "
<< _clientPid
<< " produced a core dump";
}
#endif
} else {
done = false;
}
break;
}
} else {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child " << _clientPid
<< " died a horrible death, unknown cause";
done = false;
}
}
if (horrible) {
result = EXIT_FAILURE;
} else {
result = EXIT_SUCCESS;
}
}
// child - run the normal boot sequence
else {
Logger::shutdown();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within child";
TRI_SetProcessTitle("arangodb [server]");
#ifdef TRI_HAVE_PRCTL
// force child to stop if supervisor dies
prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);
#endif
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// disable daemon mode
daemon->setDaemon(false);
} catch (...) {
}
return;
}
}
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: finished";
Logger::flush();
Logger::shutdown();
exit(result);
}
<commit_msg>add more state logging to the supervisor<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "SupervisorFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
static bool DONE = false;
static int CLIENT_PID = false;
static void StopHandler(int) {
LOG_TOPIC(INFO, Logger::STARTUP) << "received SIGINT for supervisor; commanding client [" << CLIENT_PID << "] to shut down.";
int rc = kill(CLIENT_PID, SIGTERM);
if (rc < 0) {
LOG_TOPIC(ERR, Logger::STARTUP) << "commanding client [" << CLIENT_PID << "] to shut down failed: [" << errno << "] " << strerror(errno);
}
DONE = true;
}
SupervisorFeature::SupervisorFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Supervisor"), _supervisor(false), _clientPid(0) {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Daemon");
startsAfter("Logger");
startsAfter("WorkMonitor");
}
void SupervisorFeature::collectOptions(
std::shared_ptr<ProgramOptions> options) {
options->addHiddenOption("--supervisor",
"background the server, starts a supervisor",
new BooleanParameter(&_supervisor));
}
void SupervisorFeature::validateOptions(
std::shared_ptr<ProgramOptions> options) {
if (_supervisor) {
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// force daemon mode
daemon->setDaemon(true);
// revalidate options
daemon->validateOptions(options);
} catch (...) {
LOG(FATAL) << "daemon mode not available, cannot start supervisor";
FATAL_ERROR_EXIT();
}
}
}
void SupervisorFeature::daemonize() {
static time_t const MIN_TIME_ALIVE_IN_SEC = 30;
if (!_supervisor) {
return;
}
time_t startTime = time(0);
time_t t;
bool done = false;
int result = EXIT_SUCCESS;
// will be reseted in SchedulerFeature
ArangoGlobalContext::CONTEXT->unmaskStandardSignals();
LoggerFeature* logger = nullptr;
try {
logger = ApplicationServer::getFeature<LoggerFeature>("Logger");
} catch (...) {
LOG_TOPIC(FATAL, Logger::STARTUP)
<< "unknown feature 'Logger', giving up";
FATAL_ERROR_EXIT();
}
logger->setSupervisor(true);
logger->prepare();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "starting supervisor loop";
while (!done) {
logger->setSupervisor(false);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor will now try to fork a new child process";
// fork of the server
_clientPid = fork();
if (_clientPid < 0) {
LOG_TOPIC(FATAL, Logger::STARTUP) << "fork failed, giving up";
FATAL_ERROR_EXIT();
}
// parent (supervisor)
if (0 < _clientPid) {
signal(SIGINT, StopHandler);
signal(SIGTERM, StopHandler);
LOG_TOPIC(INFO, Logger::STARTUP) << "supervisor has forked a child process with pid " << _clientPid;
TRI_SetProcessTitle("arangodb [supervisor]");
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within parent";
CLIENT_PID = _clientPid;
DONE = false;
int status;
int res = waitpid(_clientPid, &status, 0);
bool horrible = true;
LOG_TOPIC(INFO, Logger::STARTUP) << "waitpid woke up with return value "
<< res << " and status " << status
<< " and DONE = " << (DONE ? "true" : "false");
if (DONE) {
// signal handler for SIGINT or SIGTERM was invoked
done = true;
horrible = false;
}
else {
TRI_ASSERT(horrible);
if (WIFEXITED(status)) {
// give information about cause of death
if (WEXITSTATUS(status) == 0) {
LOG_TOPIC(INFO, Logger::STARTUP) << "child " << _clientPid
<< " died of natural causes";
done = true;
horrible = false;
} else {
t = time(0) - startTime;
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child " << _clientPid
<< " died a horrible death, exit status " << WEXITSTATUS(status);
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child only survived for " << t
<< " seconds, this will not work - please fix the error "
"first";
done = true;
} else {
done = false;
}
}
} else if (WIFSIGNALED(status)) {
switch (WTERMSIG(status)) {
case 2: // SIGINT
case 9: // SIGKILL
case 15: // SIGTERM
LOG_TOPIC(INFO, Logger::STARTUP)
<< "child " << _clientPid
<< " died of natural causes, exit status " << WTERMSIG(status);
done = true;
horrible = false;
break;
default:
TRI_ASSERT(horrible);
t = time(0) - startTime;
LOG_TOPIC(ERR, Logger::STARTUP) << "child " << _clientPid
<< " died a horrible death, signal "
<< WTERMSIG(status);
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child only survived for " << t
<< " seconds, this will not work - please fix the "
"error first";
done = true;
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
LOG_TOPIC(WARN, Logger::STARTUP) << "child process "
<< _clientPid
<< " produced a core dump";
}
#endif
} else {
done = false;
}
break;
}
} else {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child " << _clientPid
<< " died a horrible death, unknown cause";
done = false;
}
}
if (horrible) {
result = EXIT_FAILURE;
} else {
result = EXIT_SUCCESS;
}
}
// child - run the normal boot sequence
else {
Logger::shutdown();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within child";
TRI_SetProcessTitle("arangodb [server]");
#ifdef TRI_HAVE_PRCTL
// force child to stop if supervisor dies
prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);
#endif
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// disable daemon mode
daemon->setDaemon(false);
} catch (...) {
}
return;
}
}
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: finished";
Logger::flush();
Logger::shutdown();
exit(result);
}
<|endoftext|>
|
<commit_before>#include "NavSystem.h"
#include <Game/GameLevel.h>
#include <Game/ECS/GameWorld.h>
#include <Game/ECS/Components/ActionQueueComponent.h>
#include <Game/ECS/Components/SceneComponent.h>
#include <AI/Navigation/NavigationComponent.h>
#include <DetourCommon.h>
namespace DEM::AI
{
//???set height limit to check? agent height is good, must distinguish between different floors.
//otherwise false equalities may happen!
static inline bool dtVequal2D(const float* p0, const float* p1)
{
static const float thr = dtSqr(1.0f / 16384.0f);
const float d = dtVdist2DSqr(p0, p1);
return d < thr;
}
//---------------------------------------------------------------------
static void UpdatePosition(const vector3& Position, CNavigationComponent& Navigation, bool& Replan)
{
const bool PositionChanged = !dtVequal2D(Navigation.Corridor.getPos(), Position.v);
//???!!!movePosition etc only if not idle?
if (PositionChanged)
{
if (Navigation.Mode == ENavigationMode::Offmesh)
{
// Not moving along the navmesh surface
//!!!if traversing offmesh, must check its poly validity! see (!PositionChanged) below, the same is done!
}
else
{
// Try to move along the navmesh surface to the new position
if (Navigation.Corridor.movePosition(Position.v, Navigation.pNavQuery, Navigation.pNavFilter))
{
if (dtVequal2D(Position.v, Navigation.Corridor.getPos()))
{
Navigation.Mode = ENavigationMode::Surface;
}
else
{
// Moved too far or off the navmesh surface
const float Extents[3] = { 0.f, pActor->Height, 0.f };
dtPolyRef Ref = 0;
float Nearest[3];
Navigation.pNavQuery->findNearestPoly(Position.v, Extents, Navigation.pNavFilter, &Ref, Nearest);
if (Ref && dtVequal2D(Position.v, Nearest))
{
// We are on the navmesh, but our corridor needs rebuilding
Navigation.Mode = ENavigationMode::Surface;
Navigation.Corridor.reset(Ref, Position.v);
Replan = true;
}
else
{
Navigation.Mode = ENavigationMode::Recovery;
}
}
}
else
{
// Invalid starting poly or args
Navigation.Mode = ENavigationMode::Recovery;
}
//!!!and/or trigger an offmesh connection here!
//if triggered offmesh, finish current edge traversal!
//!!!if corridor pos != agent pos, need to set invalid state and recovery!
}
}
else
{
// Position is the same, but poly might become invalid
if (!Navigation.pNavQuery->isValidPolyRef(Navigation.Corridor.getFirstPoly(), Navigation.pNavFilter))
{
// find another poly under the feet, it may be valid
//???use fixPathStart or do as above?
if (Navigation.State == ENavigationState::Idle)
{
//???end edge traversal? must ensure that offmesh connection will be processed correctly!
Navigation.Corridor.reset(0, Position.v);
}
else
{
Navigation.Mode = ENavigationMode::Recovery;
}
}
}
// if valid and not idle (and position changed?) (and not replanning?), check current edge traversal end
///////////////////////////////
if (Navigation.State == ENavigationState::Idle)
{
if (PositionChanged)
{
// reset poly
// single-poly corridor: Corridor.reset(Corridor.getFirstPoly(), Corridor.getPos());
}
}
else
{
//!!!instead of this condition detect entering offmesh connection!
if (Navigation.Mode == ENavigationMode::Offmesh)
{
//???!!!always call moveOverOffmeshConnectionat start? then wait reaching offmesh connection end
// if started or ended offmesh traversal and this side is "done", moveOverOffmeshConnection
}
else
{
// FIXME: if moved too far AND starting poly changed, better to replan (or check return false?)
Navigation.Corridor.movePosition(Position.v, Navigation.pNavQuery, Navigation.pNavFilter);
// else movePosition, if failed update position poly
}
// check if edge traversal sub-action is done, finalize it
// detect both normal path edge and offmesh connection arrivals
// DT:
// if not on offmesh
// if curr poly invalid, find nearest poly and navmesh point in a target recovery radius
// if not found, reset corridor and drop navigation task
// else remember new destination point (in corridor is enough?) and replan
}
// set position validity flag (real == corridor, in other words real is on navmesh)
}
//---------------------------------------------------------------------
static void UpdateDestination(const vector3& Destination, CNavigationComponent& Navigation, bool& Replan)
{
const bool TargetChanged = !dtVequal(Navigation.Destination.v, Destination.v);
// FIXME: poly validity check still must happen!
//if (Navigation.State != ENavigationState::Idle && !TargetChanged) return;
Navigation.Destination = Destination;
// FIXME: if moved too far AND target poly changed, better to replan (or check return false?)
// if not idle, moveTargetPosition
// else set requested, no replan
// update dest poly if needed
// if dest is invalid, fix to navmesh and chande desired destination, may need replan
// DT:
// if not idle and not on offmesh
// if target poly invalid, find nearest poly in a recovery radius
// if on found poly, corridor.fixPathStart and replan
// else reset corridor to zero poly and go into invalid state
}
//---------------------------------------------------------------------
void ProcessNavigation(DEM::Game::CGameWorld& World)
{
World.ForEachEntityWith<CNavigationComponent, DEM::Game::CActionQueueComponent, const DEM::Game::CSceneComponent>(
[](auto EntityID, auto& Entity,
CNavigationComponent& Navigation,
DEM::Game::CActionQueueComponent* pActions,
const DEM::Game::CSceneComponent* pSceneComponent)
{
if (!pSceneComponent->RootNode) return;
//!!!Set idle: change state, reset intermediate data, handle breaking in the middle of the offmesh connection
//???can avoid recalculating straight path edges every frame? do on traversal end or pos changed or corridor invalid?
if (auto pNavigateAction = pActions->FindActive<Navigate>())
{
//!!!TODO:
// update time since last replan and other timers, if based on elapsed time
// NB: in Detour replan time increases only when on navmesh (not offmesh, not invalid)
bool Replan = false;
const auto& Position = pSceneComponent->RootNode->GetWorldPosition();
UpdatePosition(Position, Navigation, Replan);
UpdateDestination(pNavigateAction->_Destination, Navigation, Replan);
// if actor is already at the new destination, finish Navigate action (success), set idle and exit
// if navigation failed, finish Navigate action (failure), set idle and exit
//???if position is invalid and recovery point not found, finish Navigate action (failure), set idle and exit?
// validate corridor CHECK_LOOKAHEAD polys ahead, if failed replan
// if following path not waiting anything, and end is near and it's not target, replan
if (Replan)
{
//request replanning
}
// if state is REQUEST
// initSlicedFindPath + updateSlicedFindPath(few iterations) for quickpath
// finalizeSlicedFindPath[Partial if replan]
// if finalized and not empty, set corridor to partial or full path, partial requires target adjusting
// else reset corridor to the current position (will wait for full path)
// if full path, set state VALID
// else run async request and set state WAIT_ASYNC_PATH
//!!!async queue runs outside here! or could manage async request inside the agent itself, but multithreading
// then will be enabled only if the current function will be dispatched across different threads. Also total
// balancing prevents async request to be managed here!!! Need external!
// if WAIT_ASYNC_PATH (may check only if was not just set!)
// get request state
// if failed, retry REQUEST if target is valid or set FAILED if not
// else if done
// get result, fail if empty or not retrieved or curr end != new start
// if has curr path, merge with new and remove trackbacks
// set corridor to partial or full path, partial requires target adjusting (FAILED if fail)
// set state VALID
// if on navmesh and has target
// optimizePathTopology if it is the time and/or necessary events happened
// findCorners / findStraightPath
// optimizePathVisibility if it is the time and/or necessary events happened
// if in trigger range of an offmesh connection, moveOverOffmeshConnection and set OFFMESH state
// create sub-action for current edge traversal
//==============
// if corridor is invalid, trim and fix or even do full replanning
// if we are on the navmesh and are nearing corridor end poly which is not target poly and replan time has come, replan
// if replan flag is set after all above, we will do replanning this frame
// replanning:
// try calc quick path
// if found, use quick path and build remaining part in parallel
// else find from scratch
// if quick path was not full:
// if no async request, run one
// else check its status
// if failed, all navigation is failed
// else if done, get result and merge into a quick path and fix curr dest to the final one, setCorridor
// clear request info
// if following full path (no planning awaited):
// optimizePathTopology periodicaly (???better on some changes?)
// <process offmesh traversal - where and how?>
}
else if (Navigation.State != ENavigationState::Idle)
{
// set idle
}
});
}
//---------------------------------------------------------------------
}
<commit_msg>Nav from position update logic<commit_after>#include "NavSystem.h"
#include <Game/GameLevel.h>
#include <Game/ECS/GameWorld.h>
#include <Game/ECS/Components/ActionQueueComponent.h>
#include <Game/ECS/Components/SceneComponent.h>
#include <AI/Navigation/NavigationComponent.h>
#include <DetourCommon.h>
namespace DEM::AI
{
//???set height limit to check? agent height is good, must distinguish between different floors.
//otherwise false equalities may happen!
static inline bool dtVequal2D(const float* p0, const float* p1, float thr = 1.0f / (16384.0f * 16384.0f))
{
return dtVdist2DSqr(p0, p1) < thr;
}
//---------------------------------------------------------------------
static void UpdatePosition(const vector3& Position, CNavigationComponent& Navigation, bool& Replan)
{
const bool PositionChanged = !dtVequal2D(Navigation.Corridor.getPos(), Position.v);
if (PositionChanged && Navigation.Mode != ENavigationMode::Offmesh && Navigation.State != ENavigationState::Idle)
{
// Agent moves along the navmesh surface or recovers to it, adjust the corridor
if (Navigation.Corridor.movePosition(Position.v, Navigation.pNavQuery, Navigation.pNavFilter))
{
if (dtVequal2D(Position.v, Navigation.Corridor.getPos()))
{
// TODO: finish recovery, if was active. Preserve sub-action, if exists.
Navigation.Mode = ENavigationMode::Surface;
return;
}
}
}
else
{
// Agent is idle or moves along the offmesh connection, check the current poly validity
if (Navigation.pNavQuery->isValidPolyRef(Navigation.Corridor.getFirstPoly(), Navigation.pNavFilter)) return;
// If offmesh connection became invalid, cancel its traversal and fail navigation task
if (Navigation.Mode == ENavigationMode::Offmesh)
{
// TODO: fail navigation, cancel traversal sub-action, its system will handle cancelling from the middle
Navigation.Mode == ENavigationMode::Recovery;
return;
}
}
// Our current poly is unknown or invalid, find the nearist valid one
const float RecoveryRadius = std::min(pActor->Radius * 2.f, 20.f);
const float RecoveryExtents[3] = { RecoveryRadius, pActor->Height, RecoveryRadius };
dtPolyRef NearestRef = 0;
float NearestPos[3];
Navigation.pNavQuery->findNearestPoly(Position.v, RecoveryExtents, Navigation.pNavFilter, &NearestRef, NearestPos);
if (!NearestRef)
{
// No poly found in a recovery radius, agent can't recover and needs external position change
// TODO: fail navigation, cancel traversal sub-action, its system will handle cancelling from the middle
Navigation.Mode == ENavigationMode::Recovery;
Navigation.Corridor.reset(0, Position.v);
return;
}
// Check if our new location is far enough from the navmesh to enable recovery mode
if (!dtVequal2D(Position.v, NearestPos, pActor->Radius * 0.1f))
{
// TODO: must cancel current traversal sub-action even without replanning, if was not already recovering
Navigation.Mode == ENavigationMode::Recovery;
}
else
{
// TODO: finish recovery, if was active
Navigation.Mode == ENavigationMode::Surface;
}
if (Navigation.State == ENavigationState::Idle)
{
Navigation.Corridor.reset(NearestRef, NearestPos);
}
else
{
// TODO: if this doesn't work as intended, may implement the following logic:
// 1. Check if the nearest poly is one on our path (or only 1st poly in the corridor, or 1st and 2nd)
// 2. If yes, keep corridor without replanning and recover to the nearest pos
// 3. Else reset corridor to the new position and replan
// Also can recover to the corridor poly that is valid and most close to start.
// Must handle possible clipping through thin unwalkable areas.
// Make sure the first polygon is valid, but leave other valid
// polygons in the path so that replanner can adjust the path better.
Navigation.Corridor.fixPathStart(NearestRef, NearestPos);
Replan = true;
}
}
//---------------------------------------------------------------------
static void UpdateDestination(const vector3& Destination, CNavigationComponent& Navigation, bool& Replan)
{
const bool TargetChanged = !dtVequal(Navigation.Destination.v, Destination.v);
// FIXME: poly validity check still must happen!
//if (Navigation.State != ENavigationState::Idle && !TargetChanged) return;
Navigation.Destination = Destination;
// FIXME: if moved too far AND target poly changed, better to replan (or check return false?)
// if not idle, moveTargetPosition
// else set requested, no replan
// update dest poly if needed
// if dest is invalid, fix to navmesh and chande desired destination, may need replan
// DT:
// if not idle and not on offmesh
// if target poly invalid, find nearest poly in a recovery radius
// if on found poly, corridor.fixPathStart and replan
// else reset corridor to zero poly and go into invalid state
}
//---------------------------------------------------------------------
void ProcessNavigation(DEM::Game::CGameWorld& World)
{
World.ForEachEntityWith<CNavigationComponent, DEM::Game::CActionQueueComponent, const DEM::Game::CSceneComponent>(
[](auto EntityID, auto& Entity,
CNavigationComponent& Navigation,
DEM::Game::CActionQueueComponent* pActions,
const DEM::Game::CSceneComponent* pSceneComponent)
{
if (!pSceneComponent->RootNode) return;
//!!!Set idle: change state, reset intermediate data, handle breaking in the middle of the offmesh connection
//???can avoid recalculating straight path edges every frame? do on traversal end or pos changed or corridor invalid?
//!!!recovery subtask can use speed "as fast as possible" or "recovery" type, then character controller can
// resolve small length recovery as collision, immediately moving the character to the recovery destination.
if (auto pNavigateAction = pActions->FindActive<Navigate>())
{
//!!!TODO:
// update time since last replan and other timers, if based on elapsed time
// NB: in Detour replan time increases only when on navmesh (not offmesh, not invalid)
//???check traversal sub-action result before all other?
bool Replan = false;
const auto& Position = pSceneComponent->RootNode->GetWorldPosition();
UpdatePosition(Position, Navigation, Replan);
UpdateDestination(pNavigateAction->_Destination, Navigation, Replan);
// if actor is already at the new destination, finish Navigate action (success), set idle and exit
// if navigation failed, finish Navigate action (failure), set idle and exit
//???if position is invalid and recovery point not found, finish Navigate action (failure), set idle and exit?
// validate corridor CHECK_LOOKAHEAD polys ahead, if failed replan
// if following path not waiting anything, and end is near and it's not target, replan
if (Replan)
{
//???!!!cancel traversal sub-action?!
//request replanning
}
// if state is REQUEST
// initSlicedFindPath + updateSlicedFindPath(few iterations) for quickpath
// finalizeSlicedFindPath[Partial if replan]
// if finalized and not empty, set corridor to partial or full path, partial requires target adjusting
// else reset corridor to the current position (will wait for full path)
// if full path, set state VALID
// else run async request and set state WAIT_ASYNC_PATH
//!!!async queue runs outside here! or could manage async request inside the agent itself, but multithreading
// then will be enabled only if the current function will be dispatched across different threads. Also total
// balancing prevents async request to be managed here!!! Need external!
// if state is REQUEST
// ... see above
// _else_ if WAIT_ASYNC_PATH (may check only if was not just set!)
// get request state
// if failed, retry REQUEST if target is valid or set FAILED if not
// else if done
// get result, fail if empty or not retrieved or curr end != new start
// if has curr path, merge with new and remove trackbacks
// set corridor to partial or full path, partial requires target adjusting (FAILED if fail)
// set state VALID
// if on navmesh and has target
// optimizePathTopology if it is the time and/or necessary events happened
// findCorners / findStraightPath
// optimizePathVisibility if it is the time and/or necessary events happened
// if in trigger range of an offmesh connection, moveOverOffmeshConnection and set OFFMESH state
// create/update/check sub-action for current edge traversal
//==============
// if corridor is invalid, trim and fix or even do full replanning
// if we are on the navmesh and are nearing corridor end poly which is not target poly and replan time has come, replan
// if replan flag is set after all above, we will do replanning this frame
// replanning:
// try calc quick path
// if found, use quick path and build remaining part in parallel
// else find from scratch
// if quick path was not full:
// if no async request, run one
// else check its status
// if failed, all navigation is failed
// else if done, get result and merge into a quick path and fix curr dest to the final one, setCorridor
// clear request info
// if following full path (no planning awaited):
// optimizePathTopology periodicaly (???better on some changes?)
// <process offmesh traversal - where and how?>
}
else if (Navigation.State != ENavigationState::Idle)
{
// set idle
}
});
}
//---------------------------------------------------------------------
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: saldata.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: ihi $ $Date: 2008-01-14 16:15:21 $
*
* 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_vcl.hxx"
#include "saldata.hxx"
oslThreadKey SalData::s_aAutoReleaseKey = 0;
static void SAL_CALL releasePool( void* pPool )
{
if( pPool )
[(NSAutoreleasePool*)pPool release];
}
SalData::SalData()
:
mpTimerProc( NULL ),
mpFirstInstance( NULL ),
mpFirstObject( NULL ),
mpFirstVD( NULL ),
mpFirstPrinter( NULL ),
mpFontList( NULL ),
mxRGBSpace( CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB) ),
mxGraySpace( CGColorSpaceCreateWithName(kCGColorSpaceGenericGray) ),
maCursors( POINTER_COUNT, INVALID_CURSOR_PTR ),
mbIsScrollbarDoubleMax( false )
{
if( s_aAutoReleaseKey == 0 )
s_aAutoReleaseKey = osl_createThreadKey( releasePool );
}
SalData::~SalData()
{
CFRelease( mxRGBSpace );
CFRelease( mxGraySpace );
for( unsigned int i = 0; i < maCursors.size(); i++ )
{
NSCursor* pCurs = maCursors[i];
if( pCurs && pCurs != INVALID_CURSOR_PTR )
[pCurs release];
}
if( s_aAutoReleaseKey )
{
// release the last pool
NSAutoreleasePool* pPool = nil;
pPool = reinterpret_cast<NSAutoreleasePool*>( osl_getThreadKeyData( s_aAutoReleaseKey ) );
if( pPool )
{
osl_setThreadKeyData( s_aAutoReleaseKey, NULL );
[pPool release];
}
osl_destroyThreadKey( s_aAutoReleaseKey );
s_aAutoReleaseKey = NULL;
}
}
void SalData::ensureThreadAutoreleasePool()
{
NSAutoreleasePool* pPool = nil;
if( s_aAutoReleaseKey )
{
pPool = reinterpret_cast<NSAutoreleasePool*>( osl_getThreadKeyData( s_aAutoReleaseKey ) );
if( ! pPool )
{
pPool = [[NSAutoreleasePool alloc] init];
osl_setThreadKeyData( s_aAutoReleaseKey, pPool );
}
}
else
{
DBG_ERROR( "no autorelease key" );
}
}
void SalData::drainThreadAutoreleasePool()
{
NSAutoreleasePool* pPool = nil;
if( s_aAutoReleaseKey )
{
pPool = reinterpret_cast<NSAutoreleasePool*>( osl_getThreadKeyData( s_aAutoReleaseKey ) );
if( pPool )
{
// osl_setThreadKeyData( s_aAutoReleaseKey, NULL );
// [pPool release];
[pPool drain];
}
else
{
pPool = [[NSAutoreleasePool alloc] init];
osl_setThreadKeyData( s_aAutoReleaseKey, pPool );
}
}
else
{
DBG_ERROR( "no autorelease key" );
}
}
struct curs_ent
{
const char* pBaseName;
const NSPoint aHotSpot;
}
const aCursorTab[ POINTER_COUNT ] =
{
{ NULL, { 0, 0 } }, //POINTER_ARROW
{ "nullptr", { 16, 16 } }, //POINTER_NULL
{ "hourglass", { 15, 15 } }, //POINTER_WAIT
{ NULL, { 0, 0 } }, //POINTER_TEXT
{ "help", { 0, 0 } }, //POINTER_HELP
{ NULL, { 0, 0 } }, //POINTER_CROSS
{ NULL, { 0, 0 } }, //POINTER_MOVE
{ NULL, { 0, 0 } }, //POINTER_NSIZE
{ NULL, { 0, 0 } }, //POINTER_SSIZE
{ NULL, { 0, 0 } }, //POINTER_WSIZE
{ NULL, { 0, 0 } }, //POINTER_ESIZE
{ "nwsesize", { 15, 15 } }, //POINTER_NWSIZE
{ "neswsize", { 15, 15 } }, //POINTER_NESIZE
{ "neswsize", { 15, 15 } }, //POINTER_SWSIZE
{ "nwsesize", { 15, 15 } }, //POINTER_SESIZE
{ NULL, { 0, 0 } }, //POINTER_WINDOW_NSIZE
{ NULL, { 0, 0 } }, //POINTER_WINDOW_SSIZE
{ NULL, { 0, 0 } }, //POINTER_WINDOW_WSIZE
{ NULL, { 0, 0 } }, //POINTER_WINDOW_ESIZE
{ "nwsesize", { 15, 15 } }, //POINTER_WINDOW_NWSIZE
{ "neswsize", { 15, 15 } }, //POINTER_WINDOW_NESIZE
{ "neswsize", { 15, 15 } }, //POINTER_WINDOW_SWSIZE
{ "nwsesize", { 15, 15 } }, //POINTER_WINDOW_SESIZE
{ NULL, { 0, 0 } }, //POINTER_HSPLIT
{ NULL, { 0, 0 } }, //POINTER_VSPLIT
{ NULL, { 0, 0 } }, //POINTER_HSIZEBAR
{ NULL, { 0, 0 } }, //POINTER_VSIZEBAR
{ NULL, { 0, 0 } }, //POINTER_HAND
{ NULL, { 0, 0 } }, //POINTER_REFHAND
{ "pen", { 3, 27 } }, //POINTER_PEN
{ "magnify", { 12, 13 } }, //POINTER_MAGNIFY
{ "fill", { 10, 22 } }, //POINTER_FILL
{ "rotate", { 15, 15 } }, //POINTER_ROTATE
{ "hshear", { 15, 15 } }, //POINTER_HSHEAR
{ "vshear", { 15, 15 } }, //POINTER_VSHEAR
{ "mirror", { 14, 12 } }, //POINTER_MIRROR
{ "crook", { 15, 14 } }, //POINTER_CROOK
{ "crop", { 9, 9 } }, //POINTER_CROP
{ "movept", { 0, 0 } }, //POINTER_MOVEPOINT
{ "movebw", { 0, 0 } }, //POINTER_MOVEBEZIERWEIGHT
{ "movedata", { 0, 0 } }, //POINTER_MOVEDATA
{ "copydata", { 0, 0 } }, //POINTER_COPYDATA
{ "linkdata", { 0, 0 } }, //POINTER_LINKDATA
{ "movedlnk", { 0, 0 } }, //POINTER_MOVEDATALINK
{ "copydlnk", { 0, 0 } }, //POINTER_COPYDATALINK
{ "movef", { 8, 8 } }, //POINTER_MOVEFILE
{ "copyf", { 8, 8 } }, //POINTER_COPYFILE
{ "linkf", { 8, 8 } }, //POINTER_LINKFILE
{ "moveflnk", { 8, 8 } }, //POINTER_MOVEFILELINK
{ "copyflnk", { 8, 8 } }, //POINTER_COPYFILELINK
{ "movef2", { 7, 8 } }, //POINTER_MOVEFILES
{ "copyf2", { 7, 8 } }, //POINTER_COPYFILES
{ "notallow", { 15, 15 } }, //POINTER_NOTALLOWED
{ "dline", { 8, 8 } }, //POINTER_DRAW_LINE
{ "drect", { 8, 8 } }, //POINTER_DRAW_RECT
{ "dpolygon", { 8, 8 } }, //POINTER_DRAW_POLYGON
{ "dbezier", { 8, 8 } }, //POINTER_DRAW_BEZIER
{ "darc", { 8, 8 } }, //POINTER_DRAW_ARC
{ "dpie", { 8, 8 } }, //POINTER_DRAW_PIE
{ "dcirccut", { 8, 8 } }, //POINTER_DRAW_CIRCLECUT
{ "dellipse", { 8, 8 } }, //POINTER_DRAW_ELLIPSE
{ "dfree", { 8, 8 } }, //POINTER_DRAW_FREEHAND
{ "dconnect", { 8, 8 } }, //POINTER_DRAW_CONNECT
{ "dtext", { 8, 8 } }, //POINTER_DRAW_TEXT
{ "dcapt", { 8, 8 } }, //POINTER_DRAW_CAPTION
{ "chart", { 15, 16 } }, //POINTER_CHART
{ "detectiv", { 12, 13 } }, //POINTER_DETECTIVE
{ "pivotcol", { 7, 5 } }, //POINTER_PIVOT_COL
{ "pivotrow", { 8, 7 } }, //POINTER_PIVOT_ROW
{ "pivotfld", { 8, 7 } }, //POINTER_PIVOT_FIELD
{ "chain", { 0, 2 } }, //POINTER_CHAIN
{ "chainnot", { 2, 2 } }, //POINTER_CHAIN_NOTALLOWED
{ "timemove", { 16, 16 } }, //POINTER_TIMEEVENT_MOVE
{ "timesize", { 16, 17 } }, //POINTER_TIMEEVENT_SIZE
{ "asn", { 16, 12 } }, //POINTER_AUTOSCROLL_N
{ "ass", { 15, 19 } }, //POINTER_AUTOSCROLL_S
{ "asw", { 12, 15 } }, //POINTER_AUTOSCROLL_W
{ "ase", { 19, 16 } }, //POINTER_AUTOSCROLL_E
{ "asnw", { 10, 10 } }, //POINTER_AUTOSCROLL_NW
{ "asne", { 21, 10 } }, //POINTER_AUTOSCROLL_NE
{ "assw", { 21, 21 } }, //POINTER_AUTOSCROLL_SW
{ "asse", { 21, 21 } }, //POINTER_AUTOSCROLL_SE
{ "asns", { 15, 15 } }, //POINTER_AUTOSCROLL_NS
{ "aswe", { 15, 15 } }, //POINTER_AUTOSCROLL_WE
{ "asnswe", { 15, 15 } }, //POINTER_AUTOSCROLL_NSWE
{ "airbrush", { 5, 22 } }, //POINTER_AIRBRUSH
{ "vtext", { 15, 15 } }, //POINTER_TEXT_VERTICAL
{ "pivotdel", { 18, 15 } }, //POINTER_PIVOT_DELETE
{ "tblsels", { 15, 30 } }, //POINTER_TAB_SELECT_S
{ "tblsele", { 30, 16 } }, //POINTER_TAB_SELECT_E
{ "tblselse", { 30, 30 } }, //POINTER_TAB_SELECT_SE
{ "tblselw", { 1, 16 } }, //POINTER_TAB_SELECT_W
{ "tblselsw", { 1, 30 } }, //POINTER_TAB_SELECT_SW
{ "pntbrsh", { 9, 16 } } //POINTER_PAINTBRUSH
};
NSCursor* SalData::getCursor( PointerStyle i_eStyle )
{
if( i_eStyle >= POINTER_COUNT )
return nil;
NSCursor* pCurs = maCursors[ i_eStyle ];
if( pCurs == INVALID_CURSOR_PTR )
{
pCurs = nil;
if( aCursorTab[ i_eStyle ].pBaseName )
{
NSPoint aHotSpot = aCursorTab[ i_eStyle ].aHotSpot;
CFStringRef pCursorName =
CFStringCreateWithCStringNoCopy(
kCFAllocatorDefault,
aCursorTab[ i_eStyle ].pBaseName,
kCFStringEncodingASCII,
kCFAllocatorNull );
CFBundleRef hMain = CFBundleGetMainBundle();
CFURLRef hURL = CFBundleCopyResourceURL( hMain, pCursorName, CFSTR("png"), CFSTR("cursors") );
if( hURL )
{
pCurs = [[NSCursor alloc] initWithImage: [[NSImage alloc] initWithContentsOfURL: (NSURL*)hURL] hotSpot: aHotSpot];
CFRelease( hURL );
}
CFRelease( pCursorName );
}
maCursors[ i_eStyle ] = pCurs;
}
return pCurs;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.10.76); FILE MERGED 2008/03/28 15:44:04 rt 1.10.76.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: saldata.cxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include "saldata.hxx"
oslThreadKey SalData::s_aAutoReleaseKey = 0;
static void SAL_CALL releasePool( void* pPool )
{
if( pPool )
[(NSAutoreleasePool*)pPool release];
}
SalData::SalData()
:
mpTimerProc( NULL ),
mpFirstInstance( NULL ),
mpFirstObject( NULL ),
mpFirstVD( NULL ),
mpFirstPrinter( NULL ),
mpFontList( NULL ),
mxRGBSpace( CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB) ),
mxGraySpace( CGColorSpaceCreateWithName(kCGColorSpaceGenericGray) ),
maCursors( POINTER_COUNT, INVALID_CURSOR_PTR ),
mbIsScrollbarDoubleMax( false )
{
if( s_aAutoReleaseKey == 0 )
s_aAutoReleaseKey = osl_createThreadKey( releasePool );
}
SalData::~SalData()
{
CFRelease( mxRGBSpace );
CFRelease( mxGraySpace );
for( unsigned int i = 0; i < maCursors.size(); i++ )
{
NSCursor* pCurs = maCursors[i];
if( pCurs && pCurs != INVALID_CURSOR_PTR )
[pCurs release];
}
if( s_aAutoReleaseKey )
{
// release the last pool
NSAutoreleasePool* pPool = nil;
pPool = reinterpret_cast<NSAutoreleasePool*>( osl_getThreadKeyData( s_aAutoReleaseKey ) );
if( pPool )
{
osl_setThreadKeyData( s_aAutoReleaseKey, NULL );
[pPool release];
}
osl_destroyThreadKey( s_aAutoReleaseKey );
s_aAutoReleaseKey = NULL;
}
}
void SalData::ensureThreadAutoreleasePool()
{
NSAutoreleasePool* pPool = nil;
if( s_aAutoReleaseKey )
{
pPool = reinterpret_cast<NSAutoreleasePool*>( osl_getThreadKeyData( s_aAutoReleaseKey ) );
if( ! pPool )
{
pPool = [[NSAutoreleasePool alloc] init];
osl_setThreadKeyData( s_aAutoReleaseKey, pPool );
}
}
else
{
DBG_ERROR( "no autorelease key" );
}
}
void SalData::drainThreadAutoreleasePool()
{
NSAutoreleasePool* pPool = nil;
if( s_aAutoReleaseKey )
{
pPool = reinterpret_cast<NSAutoreleasePool*>( osl_getThreadKeyData( s_aAutoReleaseKey ) );
if( pPool )
{
// osl_setThreadKeyData( s_aAutoReleaseKey, NULL );
// [pPool release];
[pPool drain];
}
else
{
pPool = [[NSAutoreleasePool alloc] init];
osl_setThreadKeyData( s_aAutoReleaseKey, pPool );
}
}
else
{
DBG_ERROR( "no autorelease key" );
}
}
struct curs_ent
{
const char* pBaseName;
const NSPoint aHotSpot;
}
const aCursorTab[ POINTER_COUNT ] =
{
{ NULL, { 0, 0 } }, //POINTER_ARROW
{ "nullptr", { 16, 16 } }, //POINTER_NULL
{ "hourglass", { 15, 15 } }, //POINTER_WAIT
{ NULL, { 0, 0 } }, //POINTER_TEXT
{ "help", { 0, 0 } }, //POINTER_HELP
{ NULL, { 0, 0 } }, //POINTER_CROSS
{ NULL, { 0, 0 } }, //POINTER_MOVE
{ NULL, { 0, 0 } }, //POINTER_NSIZE
{ NULL, { 0, 0 } }, //POINTER_SSIZE
{ NULL, { 0, 0 } }, //POINTER_WSIZE
{ NULL, { 0, 0 } }, //POINTER_ESIZE
{ "nwsesize", { 15, 15 } }, //POINTER_NWSIZE
{ "neswsize", { 15, 15 } }, //POINTER_NESIZE
{ "neswsize", { 15, 15 } }, //POINTER_SWSIZE
{ "nwsesize", { 15, 15 } }, //POINTER_SESIZE
{ NULL, { 0, 0 } }, //POINTER_WINDOW_NSIZE
{ NULL, { 0, 0 } }, //POINTER_WINDOW_SSIZE
{ NULL, { 0, 0 } }, //POINTER_WINDOW_WSIZE
{ NULL, { 0, 0 } }, //POINTER_WINDOW_ESIZE
{ "nwsesize", { 15, 15 } }, //POINTER_WINDOW_NWSIZE
{ "neswsize", { 15, 15 } }, //POINTER_WINDOW_NESIZE
{ "neswsize", { 15, 15 } }, //POINTER_WINDOW_SWSIZE
{ "nwsesize", { 15, 15 } }, //POINTER_WINDOW_SESIZE
{ NULL, { 0, 0 } }, //POINTER_HSPLIT
{ NULL, { 0, 0 } }, //POINTER_VSPLIT
{ NULL, { 0, 0 } }, //POINTER_HSIZEBAR
{ NULL, { 0, 0 } }, //POINTER_VSIZEBAR
{ NULL, { 0, 0 } }, //POINTER_HAND
{ NULL, { 0, 0 } }, //POINTER_REFHAND
{ "pen", { 3, 27 } }, //POINTER_PEN
{ "magnify", { 12, 13 } }, //POINTER_MAGNIFY
{ "fill", { 10, 22 } }, //POINTER_FILL
{ "rotate", { 15, 15 } }, //POINTER_ROTATE
{ "hshear", { 15, 15 } }, //POINTER_HSHEAR
{ "vshear", { 15, 15 } }, //POINTER_VSHEAR
{ "mirror", { 14, 12 } }, //POINTER_MIRROR
{ "crook", { 15, 14 } }, //POINTER_CROOK
{ "crop", { 9, 9 } }, //POINTER_CROP
{ "movept", { 0, 0 } }, //POINTER_MOVEPOINT
{ "movebw", { 0, 0 } }, //POINTER_MOVEBEZIERWEIGHT
{ "movedata", { 0, 0 } }, //POINTER_MOVEDATA
{ "copydata", { 0, 0 } }, //POINTER_COPYDATA
{ "linkdata", { 0, 0 } }, //POINTER_LINKDATA
{ "movedlnk", { 0, 0 } }, //POINTER_MOVEDATALINK
{ "copydlnk", { 0, 0 } }, //POINTER_COPYDATALINK
{ "movef", { 8, 8 } }, //POINTER_MOVEFILE
{ "copyf", { 8, 8 } }, //POINTER_COPYFILE
{ "linkf", { 8, 8 } }, //POINTER_LINKFILE
{ "moveflnk", { 8, 8 } }, //POINTER_MOVEFILELINK
{ "copyflnk", { 8, 8 } }, //POINTER_COPYFILELINK
{ "movef2", { 7, 8 } }, //POINTER_MOVEFILES
{ "copyf2", { 7, 8 } }, //POINTER_COPYFILES
{ "notallow", { 15, 15 } }, //POINTER_NOTALLOWED
{ "dline", { 8, 8 } }, //POINTER_DRAW_LINE
{ "drect", { 8, 8 } }, //POINTER_DRAW_RECT
{ "dpolygon", { 8, 8 } }, //POINTER_DRAW_POLYGON
{ "dbezier", { 8, 8 } }, //POINTER_DRAW_BEZIER
{ "darc", { 8, 8 } }, //POINTER_DRAW_ARC
{ "dpie", { 8, 8 } }, //POINTER_DRAW_PIE
{ "dcirccut", { 8, 8 } }, //POINTER_DRAW_CIRCLECUT
{ "dellipse", { 8, 8 } }, //POINTER_DRAW_ELLIPSE
{ "dfree", { 8, 8 } }, //POINTER_DRAW_FREEHAND
{ "dconnect", { 8, 8 } }, //POINTER_DRAW_CONNECT
{ "dtext", { 8, 8 } }, //POINTER_DRAW_TEXT
{ "dcapt", { 8, 8 } }, //POINTER_DRAW_CAPTION
{ "chart", { 15, 16 } }, //POINTER_CHART
{ "detectiv", { 12, 13 } }, //POINTER_DETECTIVE
{ "pivotcol", { 7, 5 } }, //POINTER_PIVOT_COL
{ "pivotrow", { 8, 7 } }, //POINTER_PIVOT_ROW
{ "pivotfld", { 8, 7 } }, //POINTER_PIVOT_FIELD
{ "chain", { 0, 2 } }, //POINTER_CHAIN
{ "chainnot", { 2, 2 } }, //POINTER_CHAIN_NOTALLOWED
{ "timemove", { 16, 16 } }, //POINTER_TIMEEVENT_MOVE
{ "timesize", { 16, 17 } }, //POINTER_TIMEEVENT_SIZE
{ "asn", { 16, 12 } }, //POINTER_AUTOSCROLL_N
{ "ass", { 15, 19 } }, //POINTER_AUTOSCROLL_S
{ "asw", { 12, 15 } }, //POINTER_AUTOSCROLL_W
{ "ase", { 19, 16 } }, //POINTER_AUTOSCROLL_E
{ "asnw", { 10, 10 } }, //POINTER_AUTOSCROLL_NW
{ "asne", { 21, 10 } }, //POINTER_AUTOSCROLL_NE
{ "assw", { 21, 21 } }, //POINTER_AUTOSCROLL_SW
{ "asse", { 21, 21 } }, //POINTER_AUTOSCROLL_SE
{ "asns", { 15, 15 } }, //POINTER_AUTOSCROLL_NS
{ "aswe", { 15, 15 } }, //POINTER_AUTOSCROLL_WE
{ "asnswe", { 15, 15 } }, //POINTER_AUTOSCROLL_NSWE
{ "airbrush", { 5, 22 } }, //POINTER_AIRBRUSH
{ "vtext", { 15, 15 } }, //POINTER_TEXT_VERTICAL
{ "pivotdel", { 18, 15 } }, //POINTER_PIVOT_DELETE
{ "tblsels", { 15, 30 } }, //POINTER_TAB_SELECT_S
{ "tblsele", { 30, 16 } }, //POINTER_TAB_SELECT_E
{ "tblselse", { 30, 30 } }, //POINTER_TAB_SELECT_SE
{ "tblselw", { 1, 16 } }, //POINTER_TAB_SELECT_W
{ "tblselsw", { 1, 30 } }, //POINTER_TAB_SELECT_SW
{ "pntbrsh", { 9, 16 } } //POINTER_PAINTBRUSH
};
NSCursor* SalData::getCursor( PointerStyle i_eStyle )
{
if( i_eStyle >= POINTER_COUNT )
return nil;
NSCursor* pCurs = maCursors[ i_eStyle ];
if( pCurs == INVALID_CURSOR_PTR )
{
pCurs = nil;
if( aCursorTab[ i_eStyle ].pBaseName )
{
NSPoint aHotSpot = aCursorTab[ i_eStyle ].aHotSpot;
CFStringRef pCursorName =
CFStringCreateWithCStringNoCopy(
kCFAllocatorDefault,
aCursorTab[ i_eStyle ].pBaseName,
kCFStringEncodingASCII,
kCFAllocatorNull );
CFBundleRef hMain = CFBundleGetMainBundle();
CFURLRef hURL = CFBundleCopyResourceURL( hMain, pCursorName, CFSTR("png"), CFSTR("cursors") );
if( hURL )
{
pCurs = [[NSCursor alloc] initWithImage: [[NSImage alloc] initWithContentsOfURL: (NSURL*)hURL] hotSpot: aHotSpot];
CFRelease( hURL );
}
CFRelease( pCursorName );
}
maCursors[ i_eStyle ] = pCurs;
}
return pCurs;
}
<|endoftext|>
|
<commit_before>
#ifndef _CONF_H_
#define _CONF_H_
#include "utility.hpp"
#define VE_VERSION "r1.0.2-20150116"
#define VE_INFO "vdceye Manager r1.0.2 2015"
#ifdef WIN32
#define VE_NVR_CLIENT
#else
#define VE_NVR
#endif
/* NVR Client feature */
#ifdef VE_NVR_CLIENT
#define VE_RECORDER_MGR_CLIENT_SUPPORT
#endif
/* NVR feature */
#ifdef VE_NVR
#define VE_RECORDER_MGR_SERVER_SUPPORT
#endif
#define CONF_NAME_MAX 128
/* support Camera num */
#define CONF_MAP_MAX 4096
#define CONF_USER_PASSWORD_MAX 1024
#define CONF_PATH_MAX 1024
/* 0xFF FFFF to 0xFFFF FFFF is for status for the map */
#define CONF_MAP_INVALID_MIN 0xFFFFFF
#define CONF_KEY_STR_MAX 16
/* Support VMS(site, recorder) num */
#define CONF_VMS_NUM_MAX 128
#define CONF_VIEW_NUM_MAX 128
/* IP camera Group max num */
#define CONF_VGROUP_NUM_MAX 128
#define VSC_CONF_KEY "ConfVSCSystem"
#define VSC_CONF_LIC_KEY "ConfVSCLicense"
#define VSC_CONF_CHANNEL_KEY "ConfVSCDevice"
#define VSC_CONF_VIPC_KEY "ConfVSCVIPC"
#define VSC_CONF_VMS_KEY "ConfVSCVms"
#define VSC_CONF_VIEW_KEY "ConfVSCView"
#define VSC_CONF_VGROUP_KEY "ConfVSCVGroup"
#define VSC_CONF_HDFS_RECORD_KEY "ConfVSCHdfsRec"
#define VSC_CONF_EMAP_FILE_KEY "ConfVSCEmapFile"
#define VSC_CONF_EMAP_CONF_KEY "ConfVSCEmapConf"
#define VSC_CONF_PARAM_MAX 1024
#define VSC_CONF_PARAM_S_MAX 128
/* Max camera in one view */
#define VSC_CONF_VIEW_CH_MAX 256
/* Max camera in one Group */
#define VSC_CONF_VGROUP_CH_MAX 256
typedef enum
{
VSC_DEVICE_CAM = 1,
VSC_DEVICE_RECORDER,
VSC_DEVICE_LAST
} VSCDeviceType;
/* Device Type */
typedef enum
{
VSC_SUB_DEVICE_USB_CAM = 1,
VSC_SUB_DEVICE_FILE,
VSC_SUB_DEVICE_RTSP,
VSC_SUB_DEVICE_ONVIF,
VSC_SUB_DEVICE_ONVIF_RECODER,
VSC_SUB_DEVICE_LAST
} VSCDeviceSubType;
typedef enum
{
VSC_VMS_RECORDER = 1,
VSC_VMS_SITE,
VSC_VMS_VIRTUL_IPC,
VSC_VMS_LAST
} VSCVmsType;
typedef enum
{
VSC_SUB_VMS_PG = 1,
VSC_SUB_VMS_ZB,
VSC_SUB_VIPC_FILE,
VSC_SUB_VIPC_LIVE,
VSC_SUB_VMS_LAST
} VSCVmsSubType;
/* Control command */
typedef enum
{
LAYOUT_MODE_1 = 1,
LAYOUT_MODE_2X2,
LAYOUT_MODE_3X3,
LAYOUT_MODE_4X4,
LAYOUT_MODE_6,
LAYOUT_MODE_8,
LAYOUT_MODE_12p1,
LAYOUT_MODE_5x5,
LAYOUT_MODE_6x6,
LAYOUT_MODE_8x8,
LAYOUT_MODE_ONE,
LAYOUT_MODE_LAST
} VideoWallLayoutMode;
#pragma pack(push, 1 )
typedef struct __VSCConfSystemKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfSystemKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_KEY);
}
}VSCConfSystemKey;
typedef struct __VSCConfLicenseKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfLicenseKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_LIC_KEY);
}
}VSCConfLicenseKey;
typedef struct __VSCConfDeviceKey {
u32 nId;
s8 Key[CONF_KEY_STR_MAX];
__VSCConfDeviceKey(u32 id)
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_CHANNEL_KEY);
nId = id;
}
}VSCConfDeviceKey;
typedef struct __VSCConfVIPCKey {
u32 nId;
s8 Key[CONF_KEY_STR_MAX];
__VSCConfVIPCKey(u32 id)
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_VIPC_KEY);
nId = id;
}
}VSCConfVIPCKey;
typedef struct __VSCConfVmsKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfVmsKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_VMS_KEY);
}
}VSCConfVmsKey;
typedef struct __VSCConfViewKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfViewKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_VIEW_KEY);
}
}VSCConfViewKey;
/* Camera Group key */
typedef struct __VSCConfGroupKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfGroupKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_VGROUP_KEY);
}
}VSCConfVGroupKey;
/* HDFS Reocrd key */
typedef struct __VSCConfHdfsRecordKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfHdfsRecordKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_HDFS_RECORD_KEY);
}
}VSCConfHdfsRecordKey;
typedef struct __VSCConfData__ {
u32 DeviceMap[CONF_MAP_MAX];
u32 Language;
u32 DeviceNum;
u32 VIPCMap[CONF_MAP_MAX];
u32 VIPCNum;
}VSCConfData__;
typedef struct __VSCConfData {
union {
VSCConfData__ conf;
u8 whole[1024 * 128];
} data;
}VSCConfData;
typedef struct __VSCDeviceData__ {
u32 nId;
VSCDeviceType nType;
VSCDeviceSubType nSubType;
s8 Name[CONF_NAME_MAX];
s8 Param[VSC_CONF_PARAM_MAX];
s8 IP[VSC_CONF_PARAM_MAX];
s8 Port[VSC_CONF_PARAM_MAX];
s8 User[VSC_CONF_PARAM_MAX];
s8 Password[VSC_CONF_PARAM_MAX];
/* Camera Param */
s8 RtspLocation[VSC_CONF_PARAM_MAX];
s8 FileLocation[VSC_CONF_PARAM_MAX];
s8 OnvifAddress[VSC_CONF_PARAM_MAX];
s8 CameraIndex[VSC_CONF_PARAM_MAX];/* This is For USB Camera */
u32 UseProfileToken;/* 1 stand for use, 0 stand for do not use */
s8 OnvifProfileToken[VSC_CONF_PARAM_MAX];
/* Recording */
u32 Recording;/* 1 stand for recording, 0 stand for do record */
u32 GroupId;
u32 HdfsRecording;/* 1 stand for recording, 0 stand for do record */
}VSCDeviceData__;
typedef struct __VSCConfHdfsRecordData__ {
s8 NameNode[VSC_CONF_PARAM_MAX];
s8 Port[VSC_CONF_PARAM_MAX];
s8 User[VSC_CONF_PARAM_MAX];
s8 Password[VSC_CONF_PARAM_MAX];
int FileInterval;/* In Seconds */
}VSCConfHdfsRecordData__;
typedef struct __VSCVmsDataItem__ {
u32 nId;
VSCVmsType nType;
VSCVmsSubType nSubType;
s8 Name[CONF_NAME_MAX];
s8 Param[VSC_CONF_PARAM_MAX];
s8 IP[VSC_CONF_PARAM_MAX];
s8 Port[VSC_CONF_PARAM_MAX];
s8 User[VSC_CONF_PARAM_MAX];
s8 Password[VSC_CONF_PARAM_MAX];
s8 OnvifAddress[VSC_CONF_PARAM_MAX];
u32 GroupId;
u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCVmsDataItem;
typedef struct __VSCViewDataItem__ {
u32 nId;
s8 Name[CONF_NAME_MAX];
/* Map for this view */
u32 Map[VSC_CONF_VIEW_CH_MAX];
VideoWallLayoutMode Mode;
u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCViewDataItem;
/* IP Camera Group */
typedef struct __VSCVGroupDataItem__ {
u32 nId;
s8 Name[CONF_NAME_MAX];
/* Map for this group */
u32 Map[VSC_CONF_VGROUP_CH_MAX];
u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCVGroupDataItem;
typedef struct __VSCVIPCDataItem__ {
u32 nId;
VSCVmsType nType;
VSCVmsSubType nSubType;
s8 Name[CONF_NAME_MAX];
s8 Param[VSC_CONF_PARAM_S_MAX];
s32 nStreamId;
s8 IP[VSC_CONF_PARAM_S_MAX];
s8 Port[VSC_CONF_PARAM_S_MAX];
s8 User[VSC_CONF_PARAM_S_MAX];
s8 Password[VSC_CONF_PARAM_S_MAX];
s8 OnvifAddress[VSC_CONF_PARAM_S_MAX];
}VSCVIPCDataItem__;
typedef struct __VSCVmsData__ {
VSCVmsDataItem vms[CONF_VMS_NUM_MAX];
}VSCVmsData__;
typedef struct __VSCViewData__ {
VSCViewDataItem view[CONF_VIEW_NUM_MAX];
}VSCViewData__;
typedef struct __VSCVGroupData__ {
VSCVGroupDataItem group[CONF_VGROUP_NUM_MAX];
}VSCVGroupData__;
typedef struct __VSCDeviceData {
union {
VSCDeviceData__ conf;
u8 whole[1024 * 128];
} data;
}VSCDeviceData;
typedef struct __VSCVmsData {
union {
VSCVmsData__ conf;
u8 whole[1024 * 128];
} data;
}VSCVmsData;
typedef struct __VSCViewData {
union {
VSCViewData__ conf;
u8 whole[1024 * 128];
} data;
}VSCViewData;
typedef struct __VSCVGroupData {
union {
VSCVGroupData__ conf;
u8 whole[1024 * 128];
} data;
}VSCVGroupData;
typedef struct __VSCVIPCData {
union {
VSCVIPCDataItem__ conf;
u8 whole[1024 * 128];
} data;
}VSCVIPCData;
typedef struct __VSCHdfsRecordData {
union {
VSCConfHdfsRecordData__ conf;
u8 whole[1024 * 128];
} data;
}VSCHdfsRecordData;
inline void VSCVmsDataItemDefault(VSCVmsDataItem &item)
{
sprintf(item.Name, "Recorder");
strcpy(item.IP, "192.168.0.1");
strcpy(item.Port, "80");
strcpy(item.User, "admin");
strcpy(item.Password, "admin");
strcpy(item.Param, "none");
item.Used = 0;
item.nId = 0;
item.GroupId = 0;
}
inline void VSCViewDataItemDefault(VSCViewDataItem &item)
{
memset(&item, 0, sizeof(VSCViewDataItem));
sprintf(item.Name, "View");
item.Mode = LAYOUT_MODE_3X3;
}
inline void VSCVGroupDataItemDefault(VSCVGroupDataItem &item)
{
memset(&item, 0, sizeof(VSCVGroupDataItem));
sprintf(item.Name, "Group");
}
inline void VSCVIPCDataItemDefault(VSCVIPCDataItem__ &item)
{
sprintf(item.Name, "Virutal IPC");
strcpy(item.IP, "192.168.0.1");
strcpy(item.Port, "8000");
strcpy(item.User, "admin");
strcpy(item.Password, "admin");
item.nStreamId = 1;
}
inline void VSCHdfsRecordDataItemDefault(VSCConfHdfsRecordData__ &item)
{
strcpy(item.NameNode, "localhost");//default for hdd
strcpy(item.Port, "8020");//0 for hdd
strcpy(item.User, "admin");
strcpy(item.Password, "admin");
item.FileInterval = 30;/* 30s */
}
#pragma pack(pop)
#endif /* _CONF_H_ */
<commit_msg>add second for va<commit_after>
#ifndef _CONF_H_
#define _CONF_H_
#include "utility.hpp"
#define VE_VERSION "r1.0.2-20150116"
#define VE_INFO "vdceye Manager r1.0.2 2015"
#ifdef WIN32
#define VE_NVR_CLIENT
#else
#define VE_NVR
#endif
/* NVR Client feature */
#ifdef VE_NVR_CLIENT
#define VE_RECORDER_MGR_CLIENT_SUPPORT
#endif
/* NVR feature */
#ifdef VE_NVR
#define VE_RECORDER_MGR_SERVER_SUPPORT
#endif
#define CONF_NAME_MAX 128
/* support Camera num */
#define CONF_MAP_MAX 4096
#define CONF_USER_PASSWORD_MAX 1024
#define CONF_PATH_MAX 1024
/* 0xFF FFFF to 0xFFFF FFFF is for status for the map */
#define CONF_MAP_INVALID_MIN 0xFFFFFF
#define CONF_KEY_STR_MAX 16
/* Support VMS(site, recorder) num */
#define CONF_VMS_NUM_MAX 128
#define CONF_VIEW_NUM_MAX 128
/* IP camera Group max num */
#define CONF_VGROUP_NUM_MAX 128
#define VSC_CONF_KEY "ConfVSCSystem"
#define VSC_CONF_LIC_KEY "ConfVSCLicense"
#define VSC_CONF_CHANNEL_KEY "ConfVSCDevice"
#define VSC_CONF_VIPC_KEY "ConfVSCVIPC"
#define VSC_CONF_VMS_KEY "ConfVSCVms"
#define VSC_CONF_VIEW_KEY "ConfVSCView"
#define VSC_CONF_VGROUP_KEY "ConfVSCVGroup"
#define VSC_CONF_HDFS_RECORD_KEY "ConfVSCHdfsRec"
#define VSC_CONF_EMAP_FILE_KEY "ConfVSCEmapFile"
#define VSC_CONF_EMAP_CONF_KEY "ConfVSCEmapConf"
#define VSC_CONF_PARAM_MAX 1024
#define VSC_CONF_PARAM_S_MAX 128
/* Max camera in one view */
#define VSC_CONF_VIEW_CH_MAX 256
/* Max camera in one Group */
#define VSC_CONF_VGROUP_CH_MAX 256
typedef enum
{
VSC_DEVICE_CAM = 1,
VSC_DEVICE_RECORDER,
VSC_DEVICE_LAST
} VSCDeviceType;
/* Device Type */
typedef enum
{
VSC_SUB_DEVICE_USB_CAM = 1,
VSC_SUB_DEVICE_FILE,
VSC_SUB_DEVICE_RTSP,
VSC_SUB_DEVICE_ONVIF,
VSC_SUB_DEVICE_ONVIF_RECODER,
VSC_SUB_DEVICE_LAST
} VSCDeviceSubType;
typedef enum
{
VSC_VMS_RECORDER = 1,
VSC_VMS_SITE,
VSC_VMS_VIRTUL_IPC,
VSC_VMS_LAST
} VSCVmsType;
typedef enum
{
VSC_SUB_VMS_PG = 1,
VSC_SUB_VMS_ZB,
VSC_SUB_VIPC_FILE,
VSC_SUB_VIPC_LIVE,
VSC_SUB_VMS_LAST
} VSCVmsSubType;
/* Control command */
typedef enum
{
LAYOUT_MODE_1 = 1,
LAYOUT_MODE_2X2,
LAYOUT_MODE_3X3,
LAYOUT_MODE_4X4,
LAYOUT_MODE_6,
LAYOUT_MODE_8,
LAYOUT_MODE_12p1,
LAYOUT_MODE_5x5,
LAYOUT_MODE_6x6,
LAYOUT_MODE_8x8,
LAYOUT_MODE_ONE,
LAYOUT_MODE_LAST
} VideoWallLayoutMode;
#pragma pack(push, 1 )
typedef struct __VSCConfSystemKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfSystemKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_KEY);
}
}VSCConfSystemKey;
typedef struct __VSCConfLicenseKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfLicenseKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_LIC_KEY);
}
}VSCConfLicenseKey;
typedef struct __VSCConfDeviceKey {
u32 nId;
s8 Key[CONF_KEY_STR_MAX];
__VSCConfDeviceKey(u32 id)
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_CHANNEL_KEY);
nId = id;
}
}VSCConfDeviceKey;
typedef struct __VSCConfVIPCKey {
u32 nId;
s8 Key[CONF_KEY_STR_MAX];
__VSCConfVIPCKey(u32 id)
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_VIPC_KEY);
nId = id;
}
}VSCConfVIPCKey;
typedef struct __VSCConfVmsKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfVmsKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_VMS_KEY);
}
}VSCConfVmsKey;
typedef struct __VSCConfViewKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfViewKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_VIEW_KEY);
}
}VSCConfViewKey;
/* Camera Group key */
typedef struct __VSCConfGroupKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfGroupKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_VGROUP_KEY);
}
}VSCConfVGroupKey;
/* HDFS Reocrd key */
typedef struct __VSCConfHdfsRecordKey {
s8 Key[CONF_KEY_STR_MAX];
__VSCConfHdfsRecordKey()
{
memset(Key, 0, CONF_KEY_STR_MAX);
strcpy(Key, VSC_CONF_HDFS_RECORD_KEY);
}
}VSCConfHdfsRecordKey;
typedef struct __VSCConfData__ {
u32 DeviceMap[CONF_MAP_MAX];
u32 Language;
u32 DeviceNum;
u32 VIPCMap[CONF_MAP_MAX];
u32 VIPCNum;
}VSCConfData__;
typedef struct __VSCConfData {
union {
VSCConfData__ conf;
u8 whole[1024 * 128];
} data;
}VSCConfData;
typedef struct __VSCDeviceData__ {
u32 nId;
VSCDeviceType nType;
VSCDeviceSubType nSubType;
s8 Name[CONF_NAME_MAX];
s8 Param[VSC_CONF_PARAM_MAX];
s8 IP[VSC_CONF_PARAM_MAX];
s8 Port[VSC_CONF_PARAM_MAX];
s8 User[VSC_CONF_PARAM_MAX];
s8 Password[VSC_CONF_PARAM_MAX];
/* Camera Param */
s8 RtspLocation[VSC_CONF_PARAM_MAX];
s8 FileLocation[VSC_CONF_PARAM_MAX];
s8 OnvifAddress[VSC_CONF_PARAM_MAX];
s8 CameraIndex[VSC_CONF_PARAM_MAX];/* This is For USB Camera */
u32 UseProfileToken;/* 1 stand for use, 0 stand for do not use */
s8 OnvifProfileToken[VSC_CONF_PARAM_MAX];
/* Recording */
u32 Recording;/* 1 stand for recording, 0 stand for do record */
u32 GroupId;
u32 HdfsRecording;/* 1 stand for recording, 0 stand for do record */
/* Second stream, only for VA */
u32 UseProfileToken2;/* 1 stand for use, 0 stand for do not use */
s8 OnvifProfileToken2[VSC_CONF_PARAM_MAX];
}VSCDeviceData__;
typedef struct __VSCConfHdfsRecordData__ {
s8 NameNode[VSC_CONF_PARAM_MAX];
s8 Port[VSC_CONF_PARAM_MAX];
s8 User[VSC_CONF_PARAM_MAX];
s8 Password[VSC_CONF_PARAM_MAX];
int FileInterval;/* In Seconds */
}VSCConfHdfsRecordData__;
typedef struct __VSCVmsDataItem__ {
u32 nId;
VSCVmsType nType;
VSCVmsSubType nSubType;
s8 Name[CONF_NAME_MAX];
s8 Param[VSC_CONF_PARAM_MAX];
s8 IP[VSC_CONF_PARAM_MAX];
s8 Port[VSC_CONF_PARAM_MAX];
s8 User[VSC_CONF_PARAM_MAX];
s8 Password[VSC_CONF_PARAM_MAX];
s8 OnvifAddress[VSC_CONF_PARAM_MAX];
u32 GroupId;
u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCVmsDataItem;
typedef struct __VSCViewDataItem__ {
u32 nId;
s8 Name[CONF_NAME_MAX];
/* Map for this view */
u32 Map[VSC_CONF_VIEW_CH_MAX];
VideoWallLayoutMode Mode;
u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCViewDataItem;
/* IP Camera Group */
typedef struct __VSCVGroupDataItem__ {
u32 nId;
s8 Name[CONF_NAME_MAX];
/* Map for this group */
u32 Map[VSC_CONF_VGROUP_CH_MAX];
u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCVGroupDataItem;
typedef struct __VSCVIPCDataItem__ {
u32 nId;
VSCVmsType nType;
VSCVmsSubType nSubType;
s8 Name[CONF_NAME_MAX];
s8 Param[VSC_CONF_PARAM_S_MAX];
s32 nStreamId;
s8 IP[VSC_CONF_PARAM_S_MAX];
s8 Port[VSC_CONF_PARAM_S_MAX];
s8 User[VSC_CONF_PARAM_S_MAX];
s8 Password[VSC_CONF_PARAM_S_MAX];
s8 OnvifAddress[VSC_CONF_PARAM_S_MAX];
}VSCVIPCDataItem__;
typedef struct __VSCVmsData__ {
VSCVmsDataItem vms[CONF_VMS_NUM_MAX];
}VSCVmsData__;
typedef struct __VSCViewData__ {
VSCViewDataItem view[CONF_VIEW_NUM_MAX];
}VSCViewData__;
typedef struct __VSCVGroupData__ {
VSCVGroupDataItem group[CONF_VGROUP_NUM_MAX];
}VSCVGroupData__;
typedef struct __VSCDeviceData {
union {
VSCDeviceData__ conf;
u8 whole[1024 * 128];
} data;
}VSCDeviceData;
typedef struct __VSCVmsData {
union {
VSCVmsData__ conf;
u8 whole[1024 * 128];
} data;
}VSCVmsData;
typedef struct __VSCViewData {
union {
VSCViewData__ conf;
u8 whole[1024 * 128];
} data;
}VSCViewData;
typedef struct __VSCVGroupData {
union {
VSCVGroupData__ conf;
u8 whole[1024 * 128];
} data;
}VSCVGroupData;
typedef struct __VSCVIPCData {
union {
VSCVIPCDataItem__ conf;
u8 whole[1024 * 128];
} data;
}VSCVIPCData;
typedef struct __VSCHdfsRecordData {
union {
VSCConfHdfsRecordData__ conf;
u8 whole[1024 * 128];
} data;
}VSCHdfsRecordData;
inline void VSCVmsDataItemDefault(VSCVmsDataItem &item)
{
sprintf(item.Name, "Recorder");
strcpy(item.IP, "192.168.0.1");
strcpy(item.Port, "80");
strcpy(item.User, "admin");
strcpy(item.Password, "admin");
strcpy(item.Param, "none");
item.Used = 0;
item.nId = 0;
item.GroupId = 0;
}
inline void VSCViewDataItemDefault(VSCViewDataItem &item)
{
memset(&item, 0, sizeof(VSCViewDataItem));
sprintf(item.Name, "View");
item.Mode = LAYOUT_MODE_3X3;
}
inline void VSCVGroupDataItemDefault(VSCVGroupDataItem &item)
{
memset(&item, 0, sizeof(VSCVGroupDataItem));
sprintf(item.Name, "Group");
}
inline void VSCVIPCDataItemDefault(VSCVIPCDataItem__ &item)
{
sprintf(item.Name, "Virutal IPC");
strcpy(item.IP, "192.168.0.1");
strcpy(item.Port, "8000");
strcpy(item.User, "admin");
strcpy(item.Password, "admin");
item.nStreamId = 1;
}
inline void VSCHdfsRecordDataItemDefault(VSCConfHdfsRecordData__ &item)
{
strcpy(item.NameNode, "localhost");//default for hdd
strcpy(item.Port, "8020");//0 for hdd
strcpy(item.User, "admin");
strcpy(item.Password, "admin");
item.FileInterval = 30;/* 30s */
}
#pragma pack(pop)
#endif /* _CONF_H_ */
<|endoftext|>
|
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2009 Sandro Santilli <strk@keybit.net>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: original work
*
**********************************************************************/
#include "SingleSidedBufferResultMatcher.h"
#include <geos/geom/Geometry.h>
#include <geos/geom/BinaryOp.h>
#include <geos/operation/overlay/OverlayOp.h>
#include <geos/algorithm/distance/DiscreteHausdorffDistance.h>
#include <cmath>
namespace geos {
namespace xmltester {
double SingleSidedBufferResultMatcher::MIN_DISTANCE_TOLERANCE = 1.0e-8;
double SingleSidedBufferResultMatcher::MAX_HAUSDORFF_DISTANCE_FACTOR = 100;
bool
SingleSidedBufferResultMatcher::isBufferResultMatch(const geom::Geometry& actualBuffer,
const geom::Geometry& expectedBuffer,
double distance)
{
if (actualBuffer.isEmpty() && expectedBuffer.isEmpty())
return true;
if (! isBoundaryHausdorffDistanceInTolerance(actualBuffer,
expectedBuffer, distance))
{
std::cerr << "isBoundaryHasudorffDistanceInTolerance failed" << std::endl;
return false;
}
return true;
}
bool
SingleSidedBufferResultMatcher::isBoundaryHausdorffDistanceInTolerance(
const geom::Geometry& actualBuffer,
const geom::Geometry& expectedBuffer, double distance)
{
typedef std::auto_ptr<geom::Geometry> GeomPtr;
using geos::algorithm::distance::DiscreteHausdorffDistance;
GeomPtr actualBdy ( actualBuffer.clone() );
GeomPtr expectedBdy ( expectedBuffer.clone() );
DiscreteHausdorffDistance haus(*actualBdy, *expectedBdy);
haus.setDensifyFraction(0.25);
double maxDistanceFound = haus.orientedDistance();
double expectedDistanceTol = fabs(distance) / MAX_HAUSDORFF_DISTANCE_FACTOR;
if (expectedDistanceTol < MIN_DISTANCE_TOLERANCE)
{
expectedDistanceTol = MIN_DISTANCE_TOLERANCE;
}
if (maxDistanceFound > expectedDistanceTol)
{
std::cerr << "maxDistanceFound: " << maxDistanceFound << " tolerated " << expectedDistanceTol << std::endl;
return false;
}
return true;
}
} // namespace geos::xmltester
} // namespace geos
<commit_msg>Don't give a false success if one of the expected/obtained geometry is empty<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2009 Sandro Santilli <strk@keybit.net>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: original work
*
**********************************************************************/
#include "SingleSidedBufferResultMatcher.h"
#include <geos/geom/Geometry.h>
#include <geos/geom/BinaryOp.h>
#include <geos/operation/overlay/OverlayOp.h>
#include <geos/algorithm/distance/DiscreteHausdorffDistance.h>
#include <cmath>
namespace geos {
namespace xmltester {
double SingleSidedBufferResultMatcher::MIN_DISTANCE_TOLERANCE = 1.0e-8;
double SingleSidedBufferResultMatcher::MAX_HAUSDORFF_DISTANCE_FACTOR = 100;
bool
SingleSidedBufferResultMatcher::isBufferResultMatch(const geom::Geometry& actualBuffer,
const geom::Geometry& expectedBuffer,
double distance)
{
bool aEmpty = actualBuffer.isEmpty();
bool eEmpty = expectedBuffer.isEmpty();
// Both empty succeeds
if (aEmpty && eEmpty) return true;
// One empty and not the other is a failure
if (aEmpty || eEmpty)
{
std::cerr << "isBufferResultMatch failed (one empty and one not)" << std::endl;
return true;
}
if (! isBoundaryHausdorffDistanceInTolerance(actualBuffer,
expectedBuffer, distance))
{
std::cerr << "isBoundaryHasudorffDistanceInTolerance failed" << std::endl;
return false;
}
return true;
}
bool
SingleSidedBufferResultMatcher::isBoundaryHausdorffDistanceInTolerance(
const geom::Geometry& actualBuffer,
const geom::Geometry& expectedBuffer, double distance)
{
typedef std::auto_ptr<geom::Geometry> GeomPtr;
using geos::algorithm::distance::DiscreteHausdorffDistance;
GeomPtr actualBdy ( actualBuffer.clone() );
GeomPtr expectedBdy ( expectedBuffer.clone() );
DiscreteHausdorffDistance haus(*actualBdy, *expectedBdy);
haus.setDensifyFraction(0.25);
double maxDistanceFound = haus.orientedDistance();
double expectedDistanceTol = fabs(distance) / MAX_HAUSDORFF_DISTANCE_FACTOR;
if (expectedDistanceTol < MIN_DISTANCE_TOLERANCE)
{
expectedDistanceTol = MIN_DISTANCE_TOLERANCE;
}
if (maxDistanceFound > expectedDistanceTol)
{
std::cerr << "maxDistanceFound: " << maxDistanceFound << " tolerated " << expectedDistanceTol << std::endl;
return false;
}
return true;
}
} // namespace geos::xmltester
} // namespace geos
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: checklbx.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-10-12 12:07:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
// include ---------------------------------------------------------------
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#define _SVX_CHECKLBX_CXX
#include "dialogs.hrc"
#include "checklbx.hrc"
#include "checklbx.hxx"
#include "dialmgr.hxx"
// class SvxCheckListBox -------------------------------------------------
SvxCheckListBox::SvxCheckListBox( Window* pParent, WinBits nWinStyle ) :
SvTreeListBox( pParent, nWinStyle )
{
Init_Impl();
}
// -----------------------------------------------------------------------
SvxCheckListBox::SvxCheckListBox( Window* pParent, const ResId& rResId ) :
SvTreeListBox( pParent, rResId )
{
Init_Impl();
}
// -----------------------------------------------------------------------
SvxCheckListBox::~SvxCheckListBox()
{
delete pCheckButton;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::Init_Impl()
{
pCheckButton = new SvLBoxButtonData( this );
EnableCheckButton( pCheckButton );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::InsertEntry( const String& rStr, USHORT nPos )
{
SvTreeListBox::InsertEntry( rStr, NULL, FALSE, nPos );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::RemoveEntry( USHORT nPos )
{
if ( nPos < GetEntryCount() )
SvTreeListBox::GetModel()->Remove( GetEntry( nPos ) );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::SelectEntryPos( USHORT nPos, BOOL bSelect )
{
if ( nPos < GetEntryCount() )
Select( GetEntry( nPos ), bSelect );
}
// -----------------------------------------------------------------------
USHORT SvxCheckListBox::GetSelectEntryPos() const
{
SvLBoxEntry* pEntry = GetCurEntry();
if ( pEntry )
return (USHORT)GetModel()->GetAbsPos( pEntry );
return LISTBOX_ENTRY_NOTFOUND;
}
// -----------------------------------------------------------------------
String SvxCheckListBox::GetText( USHORT nPos ) const
{
SvLBoxEntry* pEntry = GetEntry( nPos );
if ( pEntry )
return GetEntryText( pEntry );
return String();
}
// -----------------------------------------------------------------------
USHORT SvxCheckListBox::GetCheckedEntryCount() const
{
USHORT nCheckCount = 0;
USHORT nCount = (USHORT)GetEntryCount();
for ( USHORT i = 0; i < nCount; ++i )
{
if ( IsChecked( i ) )
nCheckCount++;
}
return nCheckCount;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::CheckEntryPos( USHORT nPos, BOOL bCheck )
{
if ( nPos < GetEntryCount() )
SetCheckButtonState(
GetEntry( nPos ), bCheck ? SvButtonState( SV_BUTTON_CHECKED ) :
SvButtonState( SV_BUTTON_UNCHECKED ) );
}
// -----------------------------------------------------------------------
BOOL SvxCheckListBox::IsChecked( USHORT nPos ) const
{
if ( nPos < GetEntryCount() )
return (GetCheckButtonState( GetEntry( nPos ) ) == SV_BUTTON_CHECKED);
else
return FALSE;
}
// -----------------------------------------------------------------------
void* SvxCheckListBox::SetEntryData ( USHORT nPos, void* pNewData )
{
void* pOld = NULL;
if ( nPos < GetEntryCount() )
{
pOld = GetEntry( nPos )->GetUserData();
GetEntry( nPos )->SetUserData( pNewData );
}
return pOld;
}
// -----------------------------------------------------------------------
void* SvxCheckListBox::GetEntryData( USHORT nPos ) const
{
if ( nPos < GetEntryCount() )
return GetEntry( nPos )->GetUserData();
else
return NULL;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::ToggleCheckButton( SvLBoxEntry* pEntry )
{
if ( pEntry )
{
if ( !IsSelected( pEntry ) )
Select( pEntry );
else
CheckEntryPos( GetSelectEntryPos(), !IsChecked( GetSelectEntryPos() ) );
}
}
// -----------------------------------------------------------------------
void SvxCheckListBox::MouseButtonDown( const MouseEvent& rMEvt )
{
if ( rMEvt.IsLeft() )
{
Point aPnt = rMEvt.GetPosPixel();
SvLBoxEntry* pEntry = GetEntry( aPnt );
if ( pEntry )
{
BOOL bCheck = ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED );
SvLBoxItem* pItem = GetItem( pEntry, aPnt.X() );
if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXBUTTON )
{
SvTreeListBox::MouseButtonDown( rMEvt );
Select( pEntry, TRUE );
return;
}
else
{
ToggleCheckButton( pEntry );
SvTreeListBox::MouseButtonDown( rMEvt );
if ( bCheck != ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) )
CheckButtonHdl();
return;
}
}
}
SvTreeListBox::MouseButtonDown( rMEvt );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::KeyInput( const KeyEvent& rKEvt )
{
const KeyCode& rKey = rKEvt.GetKeyCode();
if ( rKey.GetCode() == KEY_RETURN || rKey.GetCode() == KEY_SPACE )
{
SvLBoxEntry* pEntry = GetCurEntry();
if ( pEntry )
{
BOOL bCheck = ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED );
ToggleCheckButton( pEntry );
if ( bCheck != ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) )
CheckButtonHdl();
}
}
else if ( GetEntryCount() )
SvTreeListBox::KeyInput( rKEvt );
}
// -----------------------------------------------------------------------
SvLBoxEntry* SvxCheckListBox::InsertEntry( const XubString& rText, SvLBoxEntry* pParent, BOOL bChildsOnDemand, ULONG nPos, void* pUserData )
{
return SvTreeListBox::InsertEntry( rText, pParent, bChildsOnDemand, nPos, pUserData );
}
// -----------------------------------------------------------------------
SvLBoxEntry* SvxCheckListBox::InsertEntry( const XubString& rText, const Image& rExpandedEntryBmp, const Image& rCollapsedEntryBmp, SvLBoxEntry* pParent, BOOL bChildsOnDemand, ULONG nPos, void* pUserData )
{
return SvTreeListBox::InsertEntry( rText, rExpandedEntryBmp, rCollapsedEntryBmp, pParent, bChildsOnDemand, nPos, pUserData );
}
<commit_msg>INTEGRATION: CWS jl49 (1.9.116); FILE MERGED 2006/12/12 09:03:30 sb 1.9.116.3: #i70481# Added TODO issue ID. 2006/12/04 13:46:48 sb 1.9.116.2: #i70481# Prepare for high-contrast images (not yet functional, has to be addressed by future issue). 2006/11/30 13:45:54 sb 1.9.116.1: #i70481# Extended SvLBoxButton.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: checklbx.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: ihi $ $Date: 2006-12-20 14:10:46 $
*
* 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_svx.hxx"
// include ---------------------------------------------------------------
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#define _SVX_CHECKLBX_CXX
#include "dialogs.hrc"
#include "checklbx.hrc"
#include "checklbx.hxx"
#include "dialmgr.hxx"
// class SvxCheckListBox -------------------------------------------------
SvxCheckListBox::SvxCheckListBox( Window* pParent, WinBits nWinStyle ) :
SvTreeListBox( pParent, nWinStyle )
{
Init_Impl();
}
// -----------------------------------------------------------------------
SvxCheckListBox::SvxCheckListBox( Window* pParent, const ResId& rResId ) :
SvTreeListBox( pParent, rResId )
{
Init_Impl();
}
// -----------------------------------------------------------------------
SvxCheckListBox::SvxCheckListBox( Window* pParent, const ResId& rResId,
const Image& rNormalStaticImage,
const Image& /*TODO#i72485# rHighContrastStaticImage*/ ) :
SvTreeListBox( pParent, rResId )
{
Init_Impl();
pCheckButton->aBmps[SV_BMP_STATICIMAGE] = rNormalStaticImage;
}
// -----------------------------------------------------------------------
SvxCheckListBox::~SvxCheckListBox()
{
delete pCheckButton;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::Init_Impl()
{
pCheckButton = new SvLBoxButtonData( this );
EnableCheckButton( pCheckButton );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::InsertEntry( const String& rStr, USHORT nPos,
void* pUserData,
SvLBoxButtonKind eButtonKind )
{
SvTreeListBox::InsertEntry( rStr, NULL, FALSE, nPos, pUserData,
eButtonKind );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::RemoveEntry( USHORT nPos )
{
if ( nPos < GetEntryCount() )
SvTreeListBox::GetModel()->Remove( GetEntry( nPos ) );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::SelectEntryPos( USHORT nPos, BOOL bSelect )
{
if ( nPos < GetEntryCount() )
Select( GetEntry( nPos ), bSelect );
}
// -----------------------------------------------------------------------
USHORT SvxCheckListBox::GetSelectEntryPos() const
{
SvLBoxEntry* pEntry = GetCurEntry();
if ( pEntry )
return (USHORT)GetModel()->GetAbsPos( pEntry );
return LISTBOX_ENTRY_NOTFOUND;
}
// -----------------------------------------------------------------------
String SvxCheckListBox::GetText( USHORT nPos ) const
{
SvLBoxEntry* pEntry = GetEntry( nPos );
if ( pEntry )
return GetEntryText( pEntry );
return String();
}
// -----------------------------------------------------------------------
USHORT SvxCheckListBox::GetCheckedEntryCount() const
{
USHORT nCheckCount = 0;
USHORT nCount = (USHORT)GetEntryCount();
for ( USHORT i = 0; i < nCount; ++i )
{
if ( IsChecked( i ) )
nCheckCount++;
}
return nCheckCount;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::CheckEntryPos( USHORT nPos, BOOL bCheck )
{
if ( nPos < GetEntryCount() )
SetCheckButtonState(
GetEntry( nPos ), bCheck ? SvButtonState( SV_BUTTON_CHECKED ) :
SvButtonState( SV_BUTTON_UNCHECKED ) );
}
// -----------------------------------------------------------------------
BOOL SvxCheckListBox::IsChecked( USHORT nPos ) const
{
if ( nPos < GetEntryCount() )
return (GetCheckButtonState( GetEntry( nPos ) ) == SV_BUTTON_CHECKED);
else
return FALSE;
}
// -----------------------------------------------------------------------
void* SvxCheckListBox::SetEntryData ( USHORT nPos, void* pNewData )
{
void* pOld = NULL;
if ( nPos < GetEntryCount() )
{
pOld = GetEntry( nPos )->GetUserData();
GetEntry( nPos )->SetUserData( pNewData );
}
return pOld;
}
// -----------------------------------------------------------------------
void* SvxCheckListBox::GetEntryData( USHORT nPos ) const
{
if ( nPos < GetEntryCount() )
return GetEntry( nPos )->GetUserData();
else
return NULL;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::ToggleCheckButton( SvLBoxEntry* pEntry )
{
if ( pEntry )
{
if ( !IsSelected( pEntry ) )
Select( pEntry );
else
CheckEntryPos( GetSelectEntryPos(), !IsChecked( GetSelectEntryPos() ) );
}
}
// -----------------------------------------------------------------------
void SvxCheckListBox::MouseButtonDown( const MouseEvent& rMEvt )
{
if ( rMEvt.IsLeft() )
{
Point aPnt = rMEvt.GetPosPixel();
SvLBoxEntry* pEntry = GetEntry( aPnt );
if ( pEntry )
{
BOOL bCheck = ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED );
SvLBoxItem* pItem = GetItem( pEntry, aPnt.X() );
if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXBUTTON )
{
SvTreeListBox::MouseButtonDown( rMEvt );
Select( pEntry, TRUE );
return;
}
else
{
ToggleCheckButton( pEntry );
SvTreeListBox::MouseButtonDown( rMEvt );
if ( bCheck != ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) )
CheckButtonHdl();
return;
}
}
}
SvTreeListBox::MouseButtonDown( rMEvt );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::KeyInput( const KeyEvent& rKEvt )
{
const KeyCode& rKey = rKEvt.GetKeyCode();
if ( rKey.GetCode() == KEY_RETURN || rKey.GetCode() == KEY_SPACE )
{
SvLBoxEntry* pEntry = GetCurEntry();
if ( pEntry )
{
BOOL bCheck = ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED );
ToggleCheckButton( pEntry );
if ( bCheck != ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) )
CheckButtonHdl();
}
}
else if ( GetEntryCount() )
SvTreeListBox::KeyInput( rKEvt );
}
// -----------------------------------------------------------------------
SvLBoxEntry* SvxCheckListBox::InsertEntry( const XubString& rText, SvLBoxEntry* pParent, BOOL bChildsOnDemand, ULONG nPos, void* pUserData, SvLBoxButtonKind eButtonKind )
{
return SvTreeListBox::InsertEntry( rText, pParent, bChildsOnDemand, nPos, pUserData, eButtonKind );
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: checklbx.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-06-19 15:02:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// include ---------------------------------------------------------------
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#define _SVX_CHECKLBX_CXX
#include "dialogs.hrc"
#include "checklbx.hrc"
#include "checklbx.hxx"
#include "dialmgr.hxx"
// class SvxCheckListBox -------------------------------------------------
SvxCheckListBox::SvxCheckListBox( Window* pParent, WinBits nWinStyle ) :
SvTreeListBox( pParent, nWinStyle )
{
Init_Impl();
}
// -----------------------------------------------------------------------
SvxCheckListBox::SvxCheckListBox( Window* pParent, const ResId& rResId ) :
SvTreeListBox( pParent, rResId )
{
Init_Impl();
}
// -----------------------------------------------------------------------
SvxCheckListBox::~SvxCheckListBox()
{
delete pCheckButton;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::Init_Impl()
{
pCheckButton = new SvLBoxButtonData( this );
EnableCheckButton( pCheckButton );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::InsertEntry( const String& rStr, USHORT nPos )
{
SvTreeListBox::InsertEntry( rStr, NULL, FALSE, nPos );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::RemoveEntry( USHORT nPos )
{
if ( nPos < GetEntryCount() )
SvTreeListBox::GetModel()->Remove( GetEntry( nPos ) );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::SelectEntryPos( USHORT nPos, BOOL bSelect )
{
if ( nPos < GetEntryCount() )
Select( GetEntry( nPos ), bSelect );
}
// -----------------------------------------------------------------------
USHORT SvxCheckListBox::GetSelectEntryPos() const
{
SvLBoxEntry* pEntry = GetCurEntry();
if ( pEntry )
return (USHORT)GetModel()->GetAbsPos( pEntry );
return LISTBOX_ENTRY_NOTFOUND;
}
// -----------------------------------------------------------------------
String SvxCheckListBox::GetText( USHORT nPos ) const
{
SvLBoxEntry* pEntry = GetEntry( nPos );
if ( pEntry )
return GetEntryText( pEntry );
return String();
}
// -----------------------------------------------------------------------
USHORT SvxCheckListBox::GetCheckedEntryCount() const
{
USHORT nCheckCount = 0;
USHORT nCount = (USHORT)GetEntryCount();
for ( USHORT i = 0; i < nCount; ++i )
{
if ( IsChecked( i ) )
nCheckCount++;
}
return nCheckCount;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::CheckEntryPos( USHORT nPos, BOOL bCheck )
{
if ( nPos < GetEntryCount() )
SetCheckButtonState(
GetEntry( nPos ), bCheck ? SvButtonState( SV_BUTTON_CHECKED ) :
SvButtonState( SV_BUTTON_UNCHECKED ) );
}
// -----------------------------------------------------------------------
BOOL SvxCheckListBox::IsChecked( USHORT nPos ) const
{
if ( nPos < GetEntryCount() )
return (GetCheckButtonState( GetEntry( nPos ) ) == SV_BUTTON_CHECKED);
else
return FALSE;
}
// -----------------------------------------------------------------------
void* SvxCheckListBox::SetEntryData ( USHORT nPos, void* pNewData )
{
void* pOld = NULL;
if ( nPos < GetEntryCount() )
{
pOld = GetEntry( nPos )->GetUserData();
GetEntry( nPos )->SetUserData( pNewData );
}
return pOld;
}
// -----------------------------------------------------------------------
void* SvxCheckListBox::GetEntryData( USHORT nPos ) const
{
if ( nPos < GetEntryCount() )
return GetEntry( nPos )->GetUserData();
else
return NULL;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::ToggleCheckButton( SvLBoxEntry* pEntry )
{
if ( pEntry )
{
if ( !IsSelected( pEntry ) )
Select( pEntry );
else
CheckEntryPos( GetSelectEntryPos(), !IsChecked( GetSelectEntryPos() ) );
}
}
// -----------------------------------------------------------------------
void SvxCheckListBox::MouseButtonDown( const MouseEvent& rMEvt )
{
if ( rMEvt.IsLeft() )
{
Point aPnt = rMEvt.GetPosPixel();
SvLBoxEntry* pEntry = GetEntry( aPnt );
if ( pEntry )
{
BOOL bCheck = ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED );
SvLBoxItem* pItem = GetItem( pEntry, aPnt.X() );
if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXBUTTON )
{
SvTreeListBox::MouseButtonDown( rMEvt );
Select( pEntry, TRUE );
return;
}
else
{
ToggleCheckButton( pEntry );
SvTreeListBox::MouseButtonDown( rMEvt );
if ( bCheck != ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) )
CheckButtonHdl();
return;
}
}
}
SvTreeListBox::MouseButtonDown( rMEvt );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::KeyInput( const KeyEvent& rKEvt )
{
const KeyCode& rKey = rKEvt.GetKeyCode();
if ( rKey.GetCode() == KEY_RETURN || rKey.GetCode() == KEY_SPACE )
{
SvLBoxEntry* pEntry = GetCurEntry();
if ( pEntry )
{
BOOL bCheck = ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED );
ToggleCheckButton( pEntry );
if ( bCheck != ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) )
CheckButtonHdl();
}
}
else if ( GetEntryCount() )
SvTreeListBox::KeyInput( rKEvt );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.116); FILE MERGED 2006/09/01 17:46:05 kaib 1.7.116.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: checklbx.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 04:11:54 $
*
* 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_svx.hxx"
// include ---------------------------------------------------------------
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#define _SVX_CHECKLBX_CXX
#include "dialogs.hrc"
#include "checklbx.hrc"
#include "checklbx.hxx"
#include "dialmgr.hxx"
// class SvxCheckListBox -------------------------------------------------
SvxCheckListBox::SvxCheckListBox( Window* pParent, WinBits nWinStyle ) :
SvTreeListBox( pParent, nWinStyle )
{
Init_Impl();
}
// -----------------------------------------------------------------------
SvxCheckListBox::SvxCheckListBox( Window* pParent, const ResId& rResId ) :
SvTreeListBox( pParent, rResId )
{
Init_Impl();
}
// -----------------------------------------------------------------------
SvxCheckListBox::~SvxCheckListBox()
{
delete pCheckButton;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::Init_Impl()
{
pCheckButton = new SvLBoxButtonData( this );
EnableCheckButton( pCheckButton );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::InsertEntry( const String& rStr, USHORT nPos )
{
SvTreeListBox::InsertEntry( rStr, NULL, FALSE, nPos );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::RemoveEntry( USHORT nPos )
{
if ( nPos < GetEntryCount() )
SvTreeListBox::GetModel()->Remove( GetEntry( nPos ) );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::SelectEntryPos( USHORT nPos, BOOL bSelect )
{
if ( nPos < GetEntryCount() )
Select( GetEntry( nPos ), bSelect );
}
// -----------------------------------------------------------------------
USHORT SvxCheckListBox::GetSelectEntryPos() const
{
SvLBoxEntry* pEntry = GetCurEntry();
if ( pEntry )
return (USHORT)GetModel()->GetAbsPos( pEntry );
return LISTBOX_ENTRY_NOTFOUND;
}
// -----------------------------------------------------------------------
String SvxCheckListBox::GetText( USHORT nPos ) const
{
SvLBoxEntry* pEntry = GetEntry( nPos );
if ( pEntry )
return GetEntryText( pEntry );
return String();
}
// -----------------------------------------------------------------------
USHORT SvxCheckListBox::GetCheckedEntryCount() const
{
USHORT nCheckCount = 0;
USHORT nCount = (USHORT)GetEntryCount();
for ( USHORT i = 0; i < nCount; ++i )
{
if ( IsChecked( i ) )
nCheckCount++;
}
return nCheckCount;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::CheckEntryPos( USHORT nPos, BOOL bCheck )
{
if ( nPos < GetEntryCount() )
SetCheckButtonState(
GetEntry( nPos ), bCheck ? SvButtonState( SV_BUTTON_CHECKED ) :
SvButtonState( SV_BUTTON_UNCHECKED ) );
}
// -----------------------------------------------------------------------
BOOL SvxCheckListBox::IsChecked( USHORT nPos ) const
{
if ( nPos < GetEntryCount() )
return (GetCheckButtonState( GetEntry( nPos ) ) == SV_BUTTON_CHECKED);
else
return FALSE;
}
// -----------------------------------------------------------------------
void* SvxCheckListBox::SetEntryData ( USHORT nPos, void* pNewData )
{
void* pOld = NULL;
if ( nPos < GetEntryCount() )
{
pOld = GetEntry( nPos )->GetUserData();
GetEntry( nPos )->SetUserData( pNewData );
}
return pOld;
}
// -----------------------------------------------------------------------
void* SvxCheckListBox::GetEntryData( USHORT nPos ) const
{
if ( nPos < GetEntryCount() )
return GetEntry( nPos )->GetUserData();
else
return NULL;
}
// -----------------------------------------------------------------------
void SvxCheckListBox::ToggleCheckButton( SvLBoxEntry* pEntry )
{
if ( pEntry )
{
if ( !IsSelected( pEntry ) )
Select( pEntry );
else
CheckEntryPos( GetSelectEntryPos(), !IsChecked( GetSelectEntryPos() ) );
}
}
// -----------------------------------------------------------------------
void SvxCheckListBox::MouseButtonDown( const MouseEvent& rMEvt )
{
if ( rMEvt.IsLeft() )
{
Point aPnt = rMEvt.GetPosPixel();
SvLBoxEntry* pEntry = GetEntry( aPnt );
if ( pEntry )
{
BOOL bCheck = ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED );
SvLBoxItem* pItem = GetItem( pEntry, aPnt.X() );
if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXBUTTON )
{
SvTreeListBox::MouseButtonDown( rMEvt );
Select( pEntry, TRUE );
return;
}
else
{
ToggleCheckButton( pEntry );
SvTreeListBox::MouseButtonDown( rMEvt );
if ( bCheck != ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) )
CheckButtonHdl();
return;
}
}
}
SvTreeListBox::MouseButtonDown( rMEvt );
}
// -----------------------------------------------------------------------
void SvxCheckListBox::KeyInput( const KeyEvent& rKEvt )
{
const KeyCode& rKey = rKEvt.GetKeyCode();
if ( rKey.GetCode() == KEY_RETURN || rKey.GetCode() == KEY_SPACE )
{
SvLBoxEntry* pEntry = GetCurEntry();
if ( pEntry )
{
BOOL bCheck = ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED );
ToggleCheckButton( pEntry );
if ( bCheck != ( GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ) )
CheckButtonHdl();
}
}
else if ( GetEntryCount() )
SvTreeListBox::KeyInput( rKEvt );
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: pagectrl.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2000-11-09 14:29:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// include ---------------------------------------------------------------
#pragma hdrstop
#define ITEMID_BOX 0
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#include "pageitem.hxx"
#include "pagectrl.hxx"
#include "boxitem.hxx"
#include <algorithm>
// struct PageWindow_Impl ------------------------------------------------
struct PageWindow_Impl
{
SvxBoxItem* pBorder;
Bitmap aBitmap;
FASTBOOL bBitmap;
PageWindow_Impl() : pBorder(0), bBitmap(FALSE) {}
};
// STATIC DATA -----------------------------------------------------------
#define CELL_WIDTH 1600L
#define CELL_HEIGHT 800L
// class SvxPageWindow ---------------------------------------------------
SvxPageWindow::SvxPageWindow( Window* pParent, const ResId& rId ) :
Window( pParent, rId ),
nTop ( 0 ),
nBottom ( 0 ),
nLeft ( 0 ),
nRight ( 0 ),
aColor ( COL_WHITE ),
nHdLeft ( 0 ),
nHdRight ( 0 ),
nHdDist ( 0 ),
nHdHeight ( 0 ),
aHdColor ( COL_WHITE ),
pHdBorder ( 0 ),
nFtLeft ( 0 ),
nFtRight ( 0 ),
nFtDist ( 0 ),
nFtHeight ( 0 ),
aFtColor ( COL_WHITE ),
pFtBorder ( 0 ),
bFooter ( FALSE ),
bHeader ( FALSE ),
bTable ( FALSE ),
bHorz ( FALSE ),
bVert ( FALSE ),
eUsage ( SVX_PAGE_ALL )
{
pImpl = new PageWindow_Impl;
// defaultmaessing in Twips rechnen
SetMapMode( MapMode( MAP_TWIP ) );
aWinSize = GetOutputSizePixel();
aWinSize.Height() -= 4;
aWinSize.Width() -= 4;
aWinSize = PixelToLogic( aWinSize );
aSolidLineColor = Color( COL_BLACK );
aDotLineColor = Color( COL_BLACK );
aGrayLineColor = Color( COL_GRAY );
aNormalFillColor = GetFillColor();
aDisabledFillColor = Color( COL_GRAY );
aGrayFillColor = Color( COL_LIGHTGRAY );
}
// -----------------------------------------------------------------------
SvxPageWindow::~SvxPageWindow()
{
delete pImpl;
delete pHdBorder;
delete pFtBorder;
}
// -----------------------------------------------------------------------
void __EXPORT SvxPageWindow::Paint( const Rectangle& rRect )
{
Fraction aXScale( aWinSize.Width(), std::max( aSize.Width() * 2 + aSize.Width() / 8, 1L ) );
Fraction aYScale( aWinSize.Height(), std::max( aSize.Height(), 1L ) );
MapMode aMapMode( GetMapMode() );
if ( aYScale < aXScale )
{
aMapMode.SetScaleX( aYScale );
aMapMode.SetScaleY( aYScale );
}
else
{
aMapMode.SetScaleX( aXScale );
aMapMode.SetScaleY( aXScale );
}
SetMapMode( aMapMode );
Size aSz( PixelToLogic( GetSizePixel() ) );
long nYPos = ( aSz.Height() - aSize.Height() ) / 2;
if ( eUsage == SVX_PAGE_ALL )
{
// alle Seiten gleich -> eine Seite malen
if ( aSize.Width() > aSize.Height() )
{
// Querformat in gleicher Gr"osse zeichnen
Fraction aX = aMapMode.GetScaleX();
Fraction aY = aMapMode.GetScaleY();
Fraction a2( 1.5 );
aX *= a2;
aY *= a2;
aMapMode.SetScaleX( aX );
aMapMode.SetScaleY( aY );
SetMapMode( aMapMode );
aSz = PixelToLogic( GetSizePixel() );
nYPos = ( aSz.Height() - aSize.Height() ) / 2;
long nXPos = ( aSz.Width() - aSize.Width() ) / 2;
DrawPage( Point( nXPos, nYPos ), TRUE, TRUE );
}
else
// Hochformat
DrawPage( Point( ( aSz.Width() - aSize.Width() ) / 2, nYPos ), TRUE, TRUE );
}
else
{
// Linke und rechte Seite unterschiedlich -> ggf. zwei Seiten malen
DrawPage( Point( 0, nYPos ), FALSE, (BOOL)( eUsage & SVX_PAGE_LEFT ) );
DrawPage( Point( aSize.Width() + aSize.Width() / 8, nYPos ), TRUE,
(BOOL)( eUsage & SVX_PAGE_RIGHT ) );
}
}
// -----------------------------------------------------------------------
void SvxPageWindow::DrawPage( const Point& rOrg, const BOOL bSecond, const BOOL bEnabled )
{
// Schatten
Size aTempSize = aSize;
if ( aTempSize.Height() > aTempSize.Width() )
// Beim Hochformat die H"ohe etwas verkleinern, damit der Schatten passt.
aTempSize.Height() -= PixelToLogic( Size( 0, 2 ) ).Height();
Point aShadowPt( rOrg );
aShadowPt += PixelToLogic( Point( 2, 2 ) );
SetLineColor( Color( COL_GRAY ) );
SetFillColor( Color( COL_GRAY ) );
DrawRect( Rectangle( aShadowPt, aTempSize ) );
// Seite
SetLineColor( Color( COL_BLACK ) );
if ( !bEnabled )
{
SetFillColor( Color( COL_GRAY ) );
DrawRect( Rectangle( rOrg, aTempSize ) );
return;
}
SetFillColor( Color( COL_WHITE ) );
DrawRect( Rectangle( rOrg, aTempSize ) );
// Border Top Bottom Left Right
Point aBegin( rOrg );
Point aEnd( rOrg );
long nL = nLeft;
long nR = nRight;
if ( eUsage == SVX_PAGE_MIRROR && !bSecond )
{
// f"ur gespiegelt drehen
nL = nRight;
nR = nLeft;
}
Rectangle aRect;
aRect.Left() = rOrg.X() + nL;
aRect.Right() = rOrg.X() + aTempSize.Width() - nR;
aRect.Top() = rOrg.Y() + nTop;
aRect.Bottom()= rOrg.Y() + aTempSize.Height() - nBottom;
Rectangle aHdRect( aRect );
Rectangle aFtRect( aRect );
if ( bHeader )
{
// ggf. Header anzeigen
aHdRect.Left() += nHdLeft;
aHdRect.Right() -= nHdRight;
aHdRect.Bottom() = aRect.Top() + nHdHeight;
aRect.Top() += nHdHeight + nHdDist;
SetFillColor( aHdColor );
DrawRect( aHdRect );
}
if ( bFooter )
{
// ggf. Footer anzeigen
aFtRect.Left() += nFtLeft;
aFtRect.Right() -= nFtRight;
aFtRect.Top() = aRect.Bottom() - nFtHeight;
aRect.Bottom() -= nFtHeight + nFtDist;
SetFillColor( aFtColor );
DrawRect( aFtRect );
}
// Body malen
SetFillColor( aColor );
if ( pImpl->bBitmap )
{
DrawRect( aRect );
Point aBmpPnt = aRect.TopLeft();
Size aBmpSiz = aRect.GetSize();
long nDeltaX = aBmpSiz.Width() / 15;
long nDeltaY = aBmpSiz.Height() / 15;
aBmpPnt.X() += nDeltaX;
aBmpPnt.Y() += nDeltaY;
aBmpSiz.Width() -= nDeltaX * 2;
aBmpSiz.Height() -= nDeltaY * 2;
DrawBitmap( aBmpPnt, aBmpSiz, pImpl->aBitmap );
}
else
DrawRect( aRect );
if ( bTable )
{
// Tabelle malen, ggf. zentrieren
SetLineColor( Color(COL_LIGHTGRAY) );
long nW = aRect.GetWidth(), nH = aRect.GetHeight();
long nTW = CELL_WIDTH * 3, nTH = CELL_HEIGHT * 3;
long nLeft = bHorz ? aRect.Left() + ((nW - nTW) / 2) : aRect.Left();
long nTop = bVert ? aRect.Top() + ((nH - nTH) / 2) : aRect.Top();
Rectangle aCellRect( Point( nLeft, nTop ), Size( CELL_WIDTH, CELL_HEIGHT ) );
for ( USHORT i = 0; i < 3; ++i )
{
aCellRect.Left() = nLeft;
aCellRect.Right() = nLeft + CELL_WIDTH;
if ( i > 0 )
aCellRect.Move( 0, CELL_HEIGHT );
for ( USHORT j = 0; j < 3; ++j )
{
if ( j > 0 )
aCellRect.Move( CELL_WIDTH, 0 );
DrawRect( aCellRect );
}
}
}
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetBorder( const SvxBoxItem& rNew )
{
delete pImpl->pBorder;
pImpl->pBorder = new SvxBoxItem( rNew );
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetBitmap( Bitmap* pBmp )
{
if ( pBmp )
{
pImpl->aBitmap = *pBmp;
pImpl->bBitmap = TRUE;
}
else
pImpl->bBitmap = FALSE;
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetHdBorder( const SvxBoxItem& rNew )
{
delete pHdBorder;
pHdBorder = new SvxBoxItem( rNew );
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetFtBorder( const SvxBoxItem& rNew )
{
delete pFtBorder;
pFtBorder = new SvxBoxItem( rNew );
}
<commit_msg>same type<commit_after>/*************************************************************************
*
* $RCSfile: pagectrl.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hjs $ $Date: 2000-11-09 18:26:22 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// include ---------------------------------------------------------------
#pragma hdrstop
#define ITEMID_BOX 0
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#include "pageitem.hxx"
#include "pagectrl.hxx"
#include "boxitem.hxx"
#include <algorithm>
// struct PageWindow_Impl ------------------------------------------------
struct PageWindow_Impl
{
SvxBoxItem* pBorder;
Bitmap aBitmap;
FASTBOOL bBitmap;
PageWindow_Impl() : pBorder(0), bBitmap(FALSE) {}
};
// STATIC DATA -----------------------------------------------------------
#define CELL_WIDTH 1600L
#define CELL_HEIGHT 800L
// class SvxPageWindow ---------------------------------------------------
SvxPageWindow::SvxPageWindow( Window* pParent, const ResId& rId ) :
Window( pParent, rId ),
nTop ( 0 ),
nBottom ( 0 ),
nLeft ( 0 ),
nRight ( 0 ),
aColor ( COL_WHITE ),
nHdLeft ( 0 ),
nHdRight ( 0 ),
nHdDist ( 0 ),
nHdHeight ( 0 ),
aHdColor ( COL_WHITE ),
pHdBorder ( 0 ),
nFtLeft ( 0 ),
nFtRight ( 0 ),
nFtDist ( 0 ),
nFtHeight ( 0 ),
aFtColor ( COL_WHITE ),
pFtBorder ( 0 ),
bFooter ( FALSE ),
bHeader ( FALSE ),
bTable ( FALSE ),
bHorz ( FALSE ),
bVert ( FALSE ),
eUsage ( SVX_PAGE_ALL )
{
pImpl = new PageWindow_Impl;
// defaultmaessing in Twips rechnen
SetMapMode( MapMode( MAP_TWIP ) );
aWinSize = GetOutputSizePixel();
aWinSize.Height() -= 4;
aWinSize.Width() -= 4;
aWinSize = PixelToLogic( aWinSize );
aSolidLineColor = Color( COL_BLACK );
aDotLineColor = Color( COL_BLACK );
aGrayLineColor = Color( COL_GRAY );
aNormalFillColor = GetFillColor();
aDisabledFillColor = Color( COL_GRAY );
aGrayFillColor = Color( COL_LIGHTGRAY );
}
// -----------------------------------------------------------------------
SvxPageWindow::~SvxPageWindow()
{
delete pImpl;
delete pHdBorder;
delete pFtBorder;
}
// -----------------------------------------------------------------------
void __EXPORT SvxPageWindow::Paint( const Rectangle& rRect )
{
Fraction aXScale( aWinSize.Width(), std::max( (long) (aSize.Width() * 2 + aSize.Width() / 8), 1L ) );
Fraction aYScale( aWinSize.Height(), std::max( aSize.Height(), 1L ) );
MapMode aMapMode( GetMapMode() );
if ( aYScale < aXScale )
{
aMapMode.SetScaleX( aYScale );
aMapMode.SetScaleY( aYScale );
}
else
{
aMapMode.SetScaleX( aXScale );
aMapMode.SetScaleY( aXScale );
}
SetMapMode( aMapMode );
Size aSz( PixelToLogic( GetSizePixel() ) );
long nYPos = ( aSz.Height() - aSize.Height() ) / 2;
if ( eUsage == SVX_PAGE_ALL )
{
// alle Seiten gleich -> eine Seite malen
if ( aSize.Width() > aSize.Height() )
{
// Querformat in gleicher Gr"osse zeichnen
Fraction aX = aMapMode.GetScaleX();
Fraction aY = aMapMode.GetScaleY();
Fraction a2( 1.5 );
aX *= a2;
aY *= a2;
aMapMode.SetScaleX( aX );
aMapMode.SetScaleY( aY );
SetMapMode( aMapMode );
aSz = PixelToLogic( GetSizePixel() );
nYPos = ( aSz.Height() - aSize.Height() ) / 2;
long nXPos = ( aSz.Width() - aSize.Width() ) / 2;
DrawPage( Point( nXPos, nYPos ), TRUE, TRUE );
}
else
// Hochformat
DrawPage( Point( ( aSz.Width() - aSize.Width() ) / 2, nYPos ), TRUE, TRUE );
}
else
{
// Linke und rechte Seite unterschiedlich -> ggf. zwei Seiten malen
DrawPage( Point( 0, nYPos ), FALSE, (BOOL)( eUsage & SVX_PAGE_LEFT ) );
DrawPage( Point( aSize.Width() + aSize.Width() / 8, nYPos ), TRUE,
(BOOL)( eUsage & SVX_PAGE_RIGHT ) );
}
}
// -----------------------------------------------------------------------
void SvxPageWindow::DrawPage( const Point& rOrg, const BOOL bSecond, const BOOL bEnabled )
{
// Schatten
Size aTempSize = aSize;
if ( aTempSize.Height() > aTempSize.Width() )
// Beim Hochformat die H"ohe etwas verkleinern, damit der Schatten passt.
aTempSize.Height() -= PixelToLogic( Size( 0, 2 ) ).Height();
Point aShadowPt( rOrg );
aShadowPt += PixelToLogic( Point( 2, 2 ) );
SetLineColor( Color( COL_GRAY ) );
SetFillColor( Color( COL_GRAY ) );
DrawRect( Rectangle( aShadowPt, aTempSize ) );
// Seite
SetLineColor( Color( COL_BLACK ) );
if ( !bEnabled )
{
SetFillColor( Color( COL_GRAY ) );
DrawRect( Rectangle( rOrg, aTempSize ) );
return;
}
SetFillColor( Color( COL_WHITE ) );
DrawRect( Rectangle( rOrg, aTempSize ) );
// Border Top Bottom Left Right
Point aBegin( rOrg );
Point aEnd( rOrg );
long nL = nLeft;
long nR = nRight;
if ( eUsage == SVX_PAGE_MIRROR && !bSecond )
{
// f"ur gespiegelt drehen
nL = nRight;
nR = nLeft;
}
Rectangle aRect;
aRect.Left() = rOrg.X() + nL;
aRect.Right() = rOrg.X() + aTempSize.Width() - nR;
aRect.Top() = rOrg.Y() + nTop;
aRect.Bottom()= rOrg.Y() + aTempSize.Height() - nBottom;
Rectangle aHdRect( aRect );
Rectangle aFtRect( aRect );
if ( bHeader )
{
// ggf. Header anzeigen
aHdRect.Left() += nHdLeft;
aHdRect.Right() -= nHdRight;
aHdRect.Bottom() = aRect.Top() + nHdHeight;
aRect.Top() += nHdHeight + nHdDist;
SetFillColor( aHdColor );
DrawRect( aHdRect );
}
if ( bFooter )
{
// ggf. Footer anzeigen
aFtRect.Left() += nFtLeft;
aFtRect.Right() -= nFtRight;
aFtRect.Top() = aRect.Bottom() - nFtHeight;
aRect.Bottom() -= nFtHeight + nFtDist;
SetFillColor( aFtColor );
DrawRect( aFtRect );
}
// Body malen
SetFillColor( aColor );
if ( pImpl->bBitmap )
{
DrawRect( aRect );
Point aBmpPnt = aRect.TopLeft();
Size aBmpSiz = aRect.GetSize();
long nDeltaX = aBmpSiz.Width() / 15;
long nDeltaY = aBmpSiz.Height() / 15;
aBmpPnt.X() += nDeltaX;
aBmpPnt.Y() += nDeltaY;
aBmpSiz.Width() -= nDeltaX * 2;
aBmpSiz.Height() -= nDeltaY * 2;
DrawBitmap( aBmpPnt, aBmpSiz, pImpl->aBitmap );
}
else
DrawRect( aRect );
if ( bTable )
{
// Tabelle malen, ggf. zentrieren
SetLineColor( Color(COL_LIGHTGRAY) );
long nW = aRect.GetWidth(), nH = aRect.GetHeight();
long nTW = CELL_WIDTH * 3, nTH = CELL_HEIGHT * 3;
long nLeft = bHorz ? aRect.Left() + ((nW - nTW) / 2) : aRect.Left();
long nTop = bVert ? aRect.Top() + ((nH - nTH) / 2) : aRect.Top();
Rectangle aCellRect( Point( nLeft, nTop ), Size( CELL_WIDTH, CELL_HEIGHT ) );
for ( USHORT i = 0; i < 3; ++i )
{
aCellRect.Left() = nLeft;
aCellRect.Right() = nLeft + CELL_WIDTH;
if ( i > 0 )
aCellRect.Move( 0, CELL_HEIGHT );
for ( USHORT j = 0; j < 3; ++j )
{
if ( j > 0 )
aCellRect.Move( CELL_WIDTH, 0 );
DrawRect( aCellRect );
}
}
}
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetBorder( const SvxBoxItem& rNew )
{
delete pImpl->pBorder;
pImpl->pBorder = new SvxBoxItem( rNew );
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetBitmap( Bitmap* pBmp )
{
if ( pBmp )
{
pImpl->aBitmap = *pBmp;
pImpl->bBitmap = TRUE;
}
else
pImpl->bBitmap = FALSE;
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetHdBorder( const SvxBoxItem& rNew )
{
delete pHdBorder;
pHdBorder = new SvxBoxItem( rNew );
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetFtBorder( const SvxBoxItem& rNew )
{
delete pFtBorder;
pFtBorder = new SvxBoxItem( rNew );
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 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 the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickdroparea_p.h"
#include "qquickdrag_p.h"
#include "qquickitem_p.h"
#include "qquickwindow.h"
#include <private/qqmlengine_p.h>
#ifndef QT_NO_DRAGANDDROP
QT_BEGIN_NAMESPACE
QQuickDropAreaDrag::QQuickDropAreaDrag(QQuickDropAreaPrivate *d, QObject *parent)
: QObject(parent)
, d(d)
{
}
QQuickDropAreaDrag::~QQuickDropAreaDrag()
{
}
class QQuickDropAreaPrivate : public QQuickItemPrivate
{
Q_DECLARE_PUBLIC(QQuickDropArea)
public:
QQuickDropAreaPrivate();
~QQuickDropAreaPrivate();
bool hasMatchingKey(const QStringList &keys) const;
QStringList getKeys(const QMimeData *mimeData) const;
QStringList keys;
QRegExp keyRegExp;
QPointF dragPosition;
QQuickDropAreaDrag *drag;
QPointer<QObject> source;
bool containsDrag;
};
QQuickDropAreaPrivate::QQuickDropAreaPrivate()
: drag(0)
, containsDrag(false)
{
}
QQuickDropAreaPrivate::~QQuickDropAreaPrivate()
{
delete drag;
}
/*!
\qmltype DropArea
\instantiates QQuickDropArea
\inqmlmodule QtQuick
\ingroup qtquick-input
\brief For specifying drag and drop handling in an area
A DropArea is an invisible item which receives events when other items are
dragged over it.
The \l Drag attached property can be used to notify the DropArea when an Item is
dragged over it.
The \l keys property can be used to filter drag events which don't include
a matching key.
The \l drag.source property is communicated to the source of a drag event as
the recipient of a drop on the drag target.
The \l delegate property provides a means to specify a component to be
instantiated for each active drag over a drag target.
*/
QQuickDropArea::QQuickDropArea(QQuickItem *parent)
: QQuickItem(*new QQuickDropAreaPrivate, parent)
{
setFlags(ItemAcceptsDrops);
}
QQuickDropArea::~QQuickDropArea()
{
}
/*!
\qmlproperty bool QtQuick::DropArea::containsDrag
This property identifies whether the DropArea currently contains any
dragged items.
*/
bool QQuickDropArea::containsDrag() const
{
Q_D(const QQuickDropArea);
return d->containsDrag;
}
/*!
\qmlproperty stringlist QtQuick::DropArea::keys
This property holds a list of drag keys a DropArea will accept.
If no keys are listed the DropArea will accept events from any drag source,
otherwise the drag source must have at least one compatible key.
\sa QtQuick::Drag::keys
*/
QStringList QQuickDropArea::keys() const
{
Q_D(const QQuickDropArea);
return d->keys;
}
void QQuickDropArea::setKeys(const QStringList &keys)
{
Q_D(QQuickDropArea);
if (d->keys != keys) {
d->keys = keys;
if (keys.isEmpty()) {
d->keyRegExp = QRegExp();
} else {
QString pattern = QLatin1Char('(') + QRegExp::escape(keys.first());
for (int i = 1; i < keys.count(); ++i)
pattern += QLatin1Char('|') + QRegExp::escape(keys.at(i));
pattern += QLatin1Char(')');
d->keyRegExp = QRegExp(pattern.replace(QLatin1String("\\*"), QLatin1String(".+")));
}
emit keysChanged();
}
}
QQuickDropAreaDrag *QQuickDropArea::drag()
{
Q_D(QQuickDropArea);
if (!d->drag)
d->drag = new QQuickDropAreaDrag(d);
return d->drag;
}
/*!
\qmlproperty Object QtQuick::DropArea::drag.source
This property holds the source of a drag.
*/
QObject *QQuickDropAreaDrag::source() const
{
return d->source;
}
/*!
\qmlpropertygroup QtQuick::DropArea::drag
\qmlproperty qreal QtQuick::DropArea::drag.x
\qmlproperty qreal QtQuick::DropArea::drag.y
These properties hold the coordinates of the last drag event.
*/
qreal QQuickDropAreaDrag::x() const
{
return d->dragPosition.x();
}
qreal QQuickDropAreaDrag::y() const
{
return d->dragPosition.y();
}
/*!
\qmlsignal QtQuick::DropArea::onPositionChanged(DragEvent drag)
This handler is called when the position of a drag has changed.
*/
void QQuickDropArea::dragMoveEvent(QDragMoveEvent *event)
{
Q_D(QQuickDropArea);
if (!d->containsDrag)
return;
d->dragPosition = event->pos();
if (d->drag)
emit d->drag->positionChanged();
event->accept();
QQuickDropEvent dragTargetEvent(d, event);
emit positionChanged(&dragTargetEvent);
}
bool QQuickDropAreaPrivate::hasMatchingKey(const QStringList &keys) const
{
if (keyRegExp.isEmpty())
return true;
QRegExp copy = keyRegExp;
foreach (const QString &key, keys) {
if (copy.exactMatch(key))
return true;
}
return false;
}
QStringList QQuickDropAreaPrivate::getKeys(const QMimeData *mimeData) const
{
if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(mimeData))
return dragMime->keys();
return mimeData->formats();
}
/*!
\qmlsignal QtQuick::DropArea::onEntered(DragEvent drag)
This handler is called when a \a drag enters the bounds of a DropArea.
*/
void QQuickDropArea::dragEnterEvent(QDragEnterEvent *event)
{
Q_D(QQuickDropArea);
const QMimeData *mimeData = event->mimeData();
if (!d->effectiveEnable || d->containsDrag || !mimeData || !d->hasMatchingKey(d->getKeys(mimeData)))
return;
d->dragPosition = event->pos();
event->accept();
QQuickDropEvent dragTargetEvent(d, event);
emit entered(&dragTargetEvent);
d->containsDrag = true;
if (QQuickDragMimeData *dragMime = qobject_cast<QQuickDragMimeData *>(const_cast<QMimeData *>(mimeData)))
d->source = dragMime->source();
else
d->source = event->source();
d->dragPosition = event->pos();
if (d->drag) {
emit d->drag->positionChanged();
emit d->drag->sourceChanged();
}
emit containsDragChanged();
}
/*!
\qmlsignal QtQuick::DropArea::onExited()
This handler is called when a drag exits the bounds of a DropArea.
*/
void QQuickDropArea::dragLeaveEvent(QDragLeaveEvent *)
{
Q_D(QQuickDropArea);
if (!d->containsDrag)
return;
emit exited();
d->containsDrag = false;
d->source = 0;
emit containsDragChanged();
if (d->drag)
emit d->drag->sourceChanged();
}
/*!
\qmlsignal QtQuick::DropArea::onDropped(DragEvent drop)
This handler is called when a drop event occurs within the bounds of a
a DropArea.
*/
void QQuickDropArea::dropEvent(QDropEvent *event)
{
Q_D(QQuickDropArea);
if (!d->containsDrag)
return;
QQuickDropEvent dragTargetEvent(d, event);
emit dropped(&dragTargetEvent);
d->containsDrag = false;
d->source = 0;
emit containsDragChanged();
if (d->drag)
emit d->drag->sourceChanged();
}
/*!
\qmltype DragEvent
\instantiates QQuickDropEvent
\inqmlmodule QtQuick
\ingroup qtquick-input-events
\brief Provides information about a drag event
The position of the drag event can be obtained from the \l x and \l y
properties, and the \l keys property identifies the drag keys of the event
\l {drag.source}{source}.
The existence of specific drag types can be determined using the \l hasColor,
\l hasHtml, \l hasText, and \l hasUrls properties.
The list of all supplied formats can be determined using the \l formats property.
Specific drag types can be obtained using the \l colorData, \l html, \l text,
and \l urls properties.
A string version of any available mimeType can be obtained using \l getDataAsString.
*/
/*!
\qmlproperty real QtQuick::DragEvent::x
This property holds the x coordinate of a drag event.
*/
/*!
\qmlproperty real QtQuick::DragEvent::y
This property holds the y coordinate of a drag event.
*/
/*!
\qmlproperty Object QtQuick::DragEvent::drag.source
This property holds the source of a drag event.
*/
/*!
\qmlproperty stringlist QtQuick::DragEvent::keys
This property holds a list of keys identifying the data type or source of a
drag event.
*/
/*!
\qmlproperty enumeration QtQuick::DragEvent::action
This property holds the action that the \l {drag.source}{source} is to perform on an accepted drop.
The drop action may be one of:
\list
\li Qt.CopyAction Copy the data to the target
\li Qt.MoveAction Move the data from the source to the target
\li Qt.LinkAction Create a link from the source to the target.
\li Qt.IgnoreAction Ignore the action (do nothing with the data).
\endlist
*/
/*!
\qmlproperty flags QtQuick::DragEvent::supportedActions
This property holds the set of \l {action}{actions} supported by the
drag source.
*/
/*!
\qmlproperty flags QtQuick::DragEvent::proposedAction
\since 5.2
This property holds the set of \l {action}{actions} proposed by the
drag source.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::accepted
This property holds whether the drag event was accepted by a handler.
The default value is true.
*/
/*!
\qmlmethod QtQuick::DragEvent::accept()
\qmlmethod QtQuick::DragEvent::accept(enumeration action)
Accepts the drag event.
If an \a action is specified it will overwrite the value of the \l action property.
*/
/*!
\qmlmethod QtQuick::DragEvent::acceptProposedAction()
\since 5.2
Accepts the drag event with the \l proposedAction.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::hasColor
\since 5.2
This property holds whether the drag event contains a color item.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::hasHtml
\since 5.2
This property holds whether the drag event contains a html item.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::hasText
\since 5.2
This property holds whether the drag event contains a text item.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::hasUrls
\since 5.2
This property holds whether the drag event contains one or more url items.
*/
/*!
\qmlproperty color QtQuick::DragEvent::colorData
\since 5.2
This property holds color data, if any.
*/
/*!
\qmlproperty string QtQuick::DragEvent::html
\since 5.2
This property holds html data, if any.
*/
/*!
\qmlproperty string QtQuick::DragEvent::text
\since 5.2
This property holds text data, if any.
*/
/*!
\qmlproperty urllist QtQuick::DragEvent::urls
\since 5.2
This property holds a list of urls, if any.
*/
/*!
\qmlproperty stringlist QtQuick::DragEvent::formats
\since 5.2
This property holds a list of mime type formats contained in the drag data.
*/
/*!
\qmlmethod string QtQuick::DragEvent::getDataAsString(string format)
\since 5.2
Returns the data for the given \a format converted to a string. \a format should be one contained in the \l formats property.
*/
QObject *QQuickDropEvent::source()
{
if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(event->mimeData()))
return dragMime->source();
else
return event->source();
}
QStringList QQuickDropEvent::keys() const
{
return d->getKeys(event->mimeData());
}
bool QQuickDropEvent::hasColor() const
{
return event->mimeData()->hasColor();
}
bool QQuickDropEvent::hasHtml() const
{
return event->mimeData()->hasHtml();
}
bool QQuickDropEvent::hasText() const
{
return event->mimeData()->hasText();
}
bool QQuickDropEvent::hasUrls() const
{
return event->mimeData()->hasUrls();
}
QVariant QQuickDropEvent::colorData() const
{
return event->mimeData()->colorData();
}
QString QQuickDropEvent::html() const
{
return event->mimeData()->html();
}
QString QQuickDropEvent::text() const
{
return event->mimeData()->text();
}
QList<QUrl> QQuickDropEvent::urls() const
{
return event->mimeData()->urls();
}
QStringList QQuickDropEvent::formats() const
{
return event->mimeData()->formats();
}
void QQuickDropEvent::getDataAsString(QQmlV4Function *args)
{
if (args->length() != 0) {
QV4::ExecutionEngine *v4 = args->v4engine();
QV4::Scope scope(v4);
QV4::ScopedValue v(scope, (*args)[0]);
QString format = v->toQString();
QString rv = QString::fromUtf8(event->mimeData()->data(format));
args->setReturnValue(v4->newString(rv)->asReturnedValue());
}
}
void QQuickDropEvent::acceptProposedAction(QQmlV4Function *)
{
event->acceptProposedAction();
}
void QQuickDropEvent::accept(QQmlV4Function *args)
{
Qt::DropAction action = event->dropAction();
if (args->length() >= 1) {
QV4::Scope scope(args->v4engine());
QV4::ScopedValue v(scope, (*args)[0]);
if (v->isInt32())
action = Qt::DropAction(v->integerValue());
}
// get action from arguments.
event->setDropAction(action);
event->accept();
}
QT_END_NAMESPACE
#endif // QT_NO_DRAGANDDROP
<commit_msg>Tidy up DropArea documentation.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 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 the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickdroparea_p.h"
#include "qquickdrag_p.h"
#include "qquickitem_p.h"
#include "qquickwindow.h"
#include <private/qqmlengine_p.h>
#ifndef QT_NO_DRAGANDDROP
QT_BEGIN_NAMESPACE
QQuickDropAreaDrag::QQuickDropAreaDrag(QQuickDropAreaPrivate *d, QObject *parent)
: QObject(parent)
, d(d)
{
}
QQuickDropAreaDrag::~QQuickDropAreaDrag()
{
}
class QQuickDropAreaPrivate : public QQuickItemPrivate
{
Q_DECLARE_PUBLIC(QQuickDropArea)
public:
QQuickDropAreaPrivate();
~QQuickDropAreaPrivate();
bool hasMatchingKey(const QStringList &keys) const;
QStringList getKeys(const QMimeData *mimeData) const;
QStringList keys;
QRegExp keyRegExp;
QPointF dragPosition;
QQuickDropAreaDrag *drag;
QPointer<QObject> source;
bool containsDrag;
};
QQuickDropAreaPrivate::QQuickDropAreaPrivate()
: drag(0)
, containsDrag(false)
{
}
QQuickDropAreaPrivate::~QQuickDropAreaPrivate()
{
delete drag;
}
/*!
\qmltype DropArea
\instantiates QQuickDropArea
\inqmlmodule QtQuick
\ingroup qtquick-input
\brief For specifying drag and drop handling in an area
A DropArea is an invisible item which receives events when other items are
dragged over it.
The \l Drag attached property can be used to notify the DropArea when an Item is
dragged over it.
The \l keys property can be used to filter drag events which don't include
a matching key.
The \l drag.source property is communicated to the source of a drag event as
the recipient of a drop on the drag target.
*/
QQuickDropArea::QQuickDropArea(QQuickItem *parent)
: QQuickItem(*new QQuickDropAreaPrivate, parent)
{
setFlags(ItemAcceptsDrops);
}
QQuickDropArea::~QQuickDropArea()
{
}
/*!
\qmlproperty bool QtQuick::DropArea::containsDrag
This property identifies whether the DropArea currently contains any
dragged items.
*/
bool QQuickDropArea::containsDrag() const
{
Q_D(const QQuickDropArea);
return d->containsDrag;
}
/*!
\qmlproperty stringlist QtQuick::DropArea::keys
This property holds a list of drag keys a DropArea will accept.
If no keys are listed the DropArea will accept events from any drag source,
otherwise the drag source must have at least one compatible key.
\sa QtQuick::Drag::keys
*/
QStringList QQuickDropArea::keys() const
{
Q_D(const QQuickDropArea);
return d->keys;
}
void QQuickDropArea::setKeys(const QStringList &keys)
{
Q_D(QQuickDropArea);
if (d->keys != keys) {
d->keys = keys;
if (keys.isEmpty()) {
d->keyRegExp = QRegExp();
} else {
QString pattern = QLatin1Char('(') + QRegExp::escape(keys.first());
for (int i = 1; i < keys.count(); ++i)
pattern += QLatin1Char('|') + QRegExp::escape(keys.at(i));
pattern += QLatin1Char(')');
d->keyRegExp = QRegExp(pattern.replace(QLatin1String("\\*"), QLatin1String(".+")));
}
emit keysChanged();
}
}
QQuickDropAreaDrag *QQuickDropArea::drag()
{
Q_D(QQuickDropArea);
if (!d->drag)
d->drag = new QQuickDropAreaDrag(d);
return d->drag;
}
/*!
\qmlproperty Object QtQuick::DropArea::drag.source
This property holds the source of a drag.
*/
QObject *QQuickDropAreaDrag::source() const
{
return d->source;
}
/*!
\qmlpropertygroup QtQuick::DropArea::drag
\qmlproperty qreal QtQuick::DropArea::drag.x
\qmlproperty qreal QtQuick::DropArea::drag.y
These properties hold the coordinates of the last drag event.
*/
qreal QQuickDropAreaDrag::x() const
{
return d->dragPosition.x();
}
qreal QQuickDropAreaDrag::y() const
{
return d->dragPosition.y();
}
/*!
\qmlsignal QtQuick::DropArea::onPositionChanged(DragEvent drag)
This handler is called when the position of a drag has changed.
*/
void QQuickDropArea::dragMoveEvent(QDragMoveEvent *event)
{
Q_D(QQuickDropArea);
if (!d->containsDrag)
return;
d->dragPosition = event->pos();
if (d->drag)
emit d->drag->positionChanged();
event->accept();
QQuickDropEvent dragTargetEvent(d, event);
emit positionChanged(&dragTargetEvent);
}
bool QQuickDropAreaPrivate::hasMatchingKey(const QStringList &keys) const
{
if (keyRegExp.isEmpty())
return true;
QRegExp copy = keyRegExp;
foreach (const QString &key, keys) {
if (copy.exactMatch(key))
return true;
}
return false;
}
QStringList QQuickDropAreaPrivate::getKeys(const QMimeData *mimeData) const
{
if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(mimeData))
return dragMime->keys();
return mimeData->formats();
}
/*!
\qmlsignal QtQuick::DropArea::onEntered(DragEvent drag)
This handler is called when a \a drag enters the bounds of a DropArea.
*/
void QQuickDropArea::dragEnterEvent(QDragEnterEvent *event)
{
Q_D(QQuickDropArea);
const QMimeData *mimeData = event->mimeData();
if (!d->effectiveEnable || d->containsDrag || !mimeData || !d->hasMatchingKey(d->getKeys(mimeData)))
return;
d->dragPosition = event->pos();
event->accept();
QQuickDropEvent dragTargetEvent(d, event);
emit entered(&dragTargetEvent);
d->containsDrag = true;
if (QQuickDragMimeData *dragMime = qobject_cast<QQuickDragMimeData *>(const_cast<QMimeData *>(mimeData)))
d->source = dragMime->source();
else
d->source = event->source();
d->dragPosition = event->pos();
if (d->drag) {
emit d->drag->positionChanged();
emit d->drag->sourceChanged();
}
emit containsDragChanged();
}
/*!
\qmlsignal QtQuick::DropArea::onExited()
This handler is called when a drag exits the bounds of a DropArea.
*/
void QQuickDropArea::dragLeaveEvent(QDragLeaveEvent *)
{
Q_D(QQuickDropArea);
if (!d->containsDrag)
return;
emit exited();
d->containsDrag = false;
d->source = 0;
emit containsDragChanged();
if (d->drag)
emit d->drag->sourceChanged();
}
/*!
\qmlsignal QtQuick::DropArea::onDropped(DragEvent drop)
This handler is called when a drop event occurs within the bounds of
a DropArea.
*/
void QQuickDropArea::dropEvent(QDropEvent *event)
{
Q_D(QQuickDropArea);
if (!d->containsDrag)
return;
QQuickDropEvent dragTargetEvent(d, event);
emit dropped(&dragTargetEvent);
d->containsDrag = false;
d->source = 0;
emit containsDragChanged();
if (d->drag)
emit d->drag->sourceChanged();
}
/*!
\qmltype DragEvent
\instantiates QQuickDropEvent
\inqmlmodule QtQuick
\ingroup qtquick-input-events
\brief Provides information about a drag event
The position of the drag event can be obtained from the \l x and \l y
properties, and the \l keys property identifies the drag keys of the event
\l {drag.source}{source}.
The existence of specific drag types can be determined using the \l hasColor,
\l hasHtml, \l hasText, and \l hasUrls properties.
The list of all supplied formats can be determined using the \l formats property.
Specific drag types can be obtained using the \l colorData, \l html, \l text,
and \l urls properties.
A string version of any available mimeType can be obtained using \l getDataAsString.
*/
/*!
\qmlproperty real QtQuick::DragEvent::x
This property holds the x coordinate of a drag event.
*/
/*!
\qmlproperty real QtQuick::DragEvent::y
This property holds the y coordinate of a drag event.
*/
/*!
\qmlproperty Object QtQuick::DragEvent::drag.source
This property holds the source of a drag event.
*/
/*!
\qmlproperty stringlist QtQuick::DragEvent::keys
This property holds a list of keys identifying the data type or source of a
drag event.
*/
/*!
\qmlproperty enumeration QtQuick::DragEvent::action
This property holds the action that the \l {drag.source}{source} is to perform on an accepted drop.
The drop action may be one of:
\list
\li Qt.CopyAction Copy the data to the target.
\li Qt.MoveAction Move the data from the source to the target.
\li Qt.LinkAction Create a link from the source to the target.
\li Qt.IgnoreAction Ignore the action (do nothing with the data).
\endlist
*/
/*!
\qmlproperty flags QtQuick::DragEvent::supportedActions
This property holds the set of \l {action}{actions} supported by the
drag source.
*/
/*!
\qmlproperty flags QtQuick::DragEvent::proposedAction
\since 5.2
This property holds the set of \l {action}{actions} proposed by the
drag source.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::accepted
This property holds whether the drag event was accepted by a handler.
The default value is true.
*/
/*!
\qmlmethod QtQuick::DragEvent::accept()
\qmlmethod QtQuick::DragEvent::accept(enumeration action)
Accepts the drag event.
If an \a action is specified it will overwrite the value of the \l action property.
*/
/*!
\qmlmethod QtQuick::DragEvent::acceptProposedAction()
\since 5.2
Accepts the drag event with the \l proposedAction.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::hasColor
\since 5.2
This property holds whether the drag event contains a color item.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::hasHtml
\since 5.2
This property holds whether the drag event contains a html item.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::hasText
\since 5.2
This property holds whether the drag event contains a text item.
*/
/*!
\qmlproperty bool QtQuick::DragEvent::hasUrls
\since 5.2
This property holds whether the drag event contains one or more url items.
*/
/*!
\qmlproperty color QtQuick::DragEvent::colorData
\since 5.2
This property holds color data, if any.
*/
/*!
\qmlproperty string QtQuick::DragEvent::html
\since 5.2
This property holds html data, if any.
*/
/*!
\qmlproperty string QtQuick::DragEvent::text
\since 5.2
This property holds text data, if any.
*/
/*!
\qmlproperty urllist QtQuick::DragEvent::urls
\since 5.2
This property holds a list of urls, if any.
*/
/*!
\qmlproperty stringlist QtQuick::DragEvent::formats
\since 5.2
This property holds a list of mime type formats contained in the drag data.
*/
/*!
\qmlmethod string QtQuick::DragEvent::getDataAsString(string format)
\since 5.2
Returns the data for the given \a format converted to a string. \a format should be one contained in the \l formats property.
*/
QObject *QQuickDropEvent::source()
{
if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(event->mimeData()))
return dragMime->source();
else
return event->source();
}
QStringList QQuickDropEvent::keys() const
{
return d->getKeys(event->mimeData());
}
bool QQuickDropEvent::hasColor() const
{
return event->mimeData()->hasColor();
}
bool QQuickDropEvent::hasHtml() const
{
return event->mimeData()->hasHtml();
}
bool QQuickDropEvent::hasText() const
{
return event->mimeData()->hasText();
}
bool QQuickDropEvent::hasUrls() const
{
return event->mimeData()->hasUrls();
}
QVariant QQuickDropEvent::colorData() const
{
return event->mimeData()->colorData();
}
QString QQuickDropEvent::html() const
{
return event->mimeData()->html();
}
QString QQuickDropEvent::text() const
{
return event->mimeData()->text();
}
QList<QUrl> QQuickDropEvent::urls() const
{
return event->mimeData()->urls();
}
QStringList QQuickDropEvent::formats() const
{
return event->mimeData()->formats();
}
void QQuickDropEvent::getDataAsString(QQmlV4Function *args)
{
if (args->length() != 0) {
QV4::ExecutionEngine *v4 = args->v4engine();
QV4::Scope scope(v4);
QV4::ScopedValue v(scope, (*args)[0]);
QString format = v->toQString();
QString rv = QString::fromUtf8(event->mimeData()->data(format));
args->setReturnValue(v4->newString(rv)->asReturnedValue());
}
}
void QQuickDropEvent::acceptProposedAction(QQmlV4Function *)
{
event->acceptProposedAction();
}
void QQuickDropEvent::accept(QQmlV4Function *args)
{
Qt::DropAction action = event->dropAction();
if (args->length() >= 1) {
QV4::Scope scope(args->v4engine());
QV4::ScopedValue v(scope, (*args)[0]);
if (v->isInt32())
action = Qt::DropAction(v->integerValue());
}
// get action from arguments.
event->setDropAction(action);
event->accept();
}
QT_END_NAMESPACE
#endif // QT_NO_DRAGANDDROP
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdio.h>
#include <string>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <vector>
#include <errno.h>
using namespace std;
class Shell_Base
{
protected:
int executed;
public:
Shell_Base()
{
executed = 0;
};
virtual void execute() = 0;
virtual int get_executed() = 0;
};
class Command : public Shell_Base
{
private:
vector<string> com;
public:
Command() : Shell_Base() {};
Command(vector<string> com) : Shell_Base()
{
this->com = com;
executed = 0;
};
void execute()
{
if (com.size() != 0)
{
int size = com.size() + 1;
char **args = new char*[size];
for (unsigned i = 0; i < com.size(); i++)
{
args[i] = (char*)com.at(i).c_str();
}
args[com.size()] = NULL;
string check = "exit";
if (args[0] == check.c_str())
{
executed = -1;
}
else
{
pid_t pid = fork();
if(pid < 0)
{perror("forking error");}
if(pid == 0)
{
// child
//cout << "child: " << pid << endl;
int s = execvp(args[0], args);
if (s == -1)
{perror("exec");}
exit(errno);
}
if (pid > 0)
{
// parent
int status;
wait(&status);
//cout << "status: " << status << endl;
executed = status;
//cout << "parent: " << pid << endl;
}
}
}
else
{
cout << "Error: Passed in an empty array." << endl;
}
// cout << "executed value: " << executed << endl;
};
int get_executed()
{
return executed;
};
void set_executed(int value)
{
executed = value;
};
};
class Operator : public Shell_Base
{
protected:
Shell_Base * l;
Shell_Base * r;
public:
Operator() : Shell_Base() {};
Operator(Shell_Base * l, Shell_Base * r) : Shell_Base()
{
this->l = l;
this->r = r;
};
int get_executed()
{
return executed;
}
virtual void execute() = 0;
virtual void set_left(Shell_Base * left) = 0;
virtual void set_right(Shell_Base * right) = 0;
};
class Or : public Operator
{
public:
Or() : Operator() {};
Or(Shell_Base * l, Shell_Base * r)
{
this->l = l;
this->r = r;
if (l != 0)
{
if (l->get_executed() > 0)
executed = 0;
else if (l->get_executed() == 0)
executed = 1;
}
else
{
// cout << "Error: no left child." << endl;
}
};
void execute()
{
if (r != 0)
{
if (executed == 0)
{
r->execute();
if (r->get_executed() != 0)
executed = 1;
}
}
else
{
// cout << "Error: no right child." << endl;
}
};
void set_left (Shell_Base * left)
{
l = left;
};
void set_right (Shell_Base * right)
{
r = right;
};
};
class And : public Operator
{
public:
And() : Operator() {};
And(Shell_Base* l, Shell_Base* r)
{
this->l = l;
this->r = r;
if (l != 0)
{
if (l->get_executed() > 0)
executed = 1;
else if (l->get_executed() == 0)
executed = 0;
}
else
{
// cout << "Error: no left child." << endl;
}
};
void set_left(Shell_Base * left)
{
l = left;
};
void set_right(Shell_Base * right)
{
r = right;
};
void execute()
{
if (r != 0)
{
if (executed == 0)
{
r->execute();
if (r->get_executed() != 0)
executed = 1;
}
}
else
{
// cout << "Error: no right child." << endl;
}
};
};
/*
class Hash : public Operator
{
public:
Hash() : Operator() {};
Hash(Shell_Base* l, Shell_Base* r) : Operator(l, r) {}; //right child will be ignored
void execute(); //exit after left child is executed
};
*/
class Semi : public Operator
{
public:
Semi() : Operator() {};
Semi(Shell_Base* l, Shell_Base* r)
{
this->l = l;
this->r = r;
executed = 0;
}
void set_left(Shell_Base * left)
{
l = left;
};
void set_right(Shell_Base * right)
{
r = right;
};
void execute()
{
if (r != 0)
{
r->execute();
if (r->get_executed() != 0)
executed = 1;
}
else
{
// cout << "Error: no right child." << endl;
}
};
};
<commit_msg>implemented first parts of test class<commit_after>#include <iostream>
#include <stdio.h>
#include <string>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <vector>
#include <errno.h>
using namespace std;
class Shell_Base
{
protected:
int executed;
public:
Shell_Base()
{
executed = 0;
};
virtual void execute() = 0;
virtual int get_executed() = 0;
};
class Command : public Shell_Base
{
private:
vector<string> com;
public:
Command() : Shell_Base() {};
Command(vector<string> com) : Shell_Base()
{
this->com = com;
executed = 0;
};
void execute()
{
if (com.size() != 0)
{
int size = com.size() + 1;
char **args = new char*[size];
for (unsigned i = 0; i < com.size(); i++)
{
args[i] = (char*)com.at(i).c_str();
}
args[com.size()] = NULL;
string check = "exit";
if (args[0] == check.c_str())
{
executed = -1;
}
else
{
pid_t pid = fork();
if(pid < 0)
{perror("forking error");}
if(pid == 0)
{
// child
//cout << "child: " << pid << endl;
int s = execvp(args[0], args);
if (s == -1)
{perror("exec");}
exit(errno);
}
if (pid > 0)
{
// parent
int status;
wait(&status);
//cout << "status: " << status << endl;
executed = status;
//cout << "parent: " << pid << endl;
}
}
}
else
{
cout << "Error: Passed in an empty array." << endl;
}
// cout << "executed value: " << executed << endl;
};
int get_executed()
{
return executed;
};
void set_executed(int value)
{
executed = value;
};
};
class Operator : public Shell_Base
{
protected:
Shell_Base * l;
Shell_Base * r;
public:
Operator() : Shell_Base() {};
Operator(Shell_Base * l, Shell_Base * r) : Shell_Base()
{
this->l = l;
this->r = r;
};
int get_executed()
{
return executed;
}
virtual void execute() = 0;
virtual void set_left(Shell_Base * left) = 0;
virtual void set_right(Shell_Base * right) = 0;
};
class Or : public Operator
{
public:
Or() : Operator() {};
Or(Shell_Base * l, Shell_Base * r)
{
this->l = l;
this->r = r;
if (l != 0)
{
if (l->get_executed() > 0)
executed = 0;
else if (l->get_executed() == 0)
executed = 1;
}
else
{
// cout << "Error: no left child." << endl;
}
};
void execute()
{
if (r != 0)
{
if (executed == 0)
{
r->execute();
if (r->get_executed() != 0)
executed = 1;
}
}
else
{
// cout << "Error: no right child." << endl;
}
};
void set_left (Shell_Base * left)
{
l = left;
};
void set_right (Shell_Base * right)
{
r = right;
};
};
class And : public Operator
{
public:
And() : Operator() {};
And(Shell_Base* l, Shell_Base* r)
{
this->l = l;
this->r = r;
if (l != 0)
{
if (l->get_executed() > 0)
executed = 1;
else if (l->get_executed() == 0)
executed = 0;
}
else
{
// cout << "Error: no left child." << endl;
}
};
void set_left(Shell_Base * left)
{
l = left;
};
void set_right(Shell_Base * right)
{
r = right;
};
void execute()
{
if (r != 0)
{
if (executed == 0)
{
r->execute();
if (r->get_executed() != 0)
executed = 1;
}
}
else
{
// cout << "Error: no right child." << endl;
}
};
};
/*
class Hash : public Operator
{
public:
Hash() : Operator() {};
Hash(Shell_Base* l, Shell_Base* r) : Operator(l, r) {}; //right child will be ignored
void execute(); //exit after left child is executed
};
*/
class Semi : public Operator
{
public:
Semi() : Operator() {};
Semi(Shell_Base* l, Shell_Base* r)
{
this->l = l;
this->r = r;
executed = 0;
}
void set_left(Shell_Base * left)
{
l = left;
};
void set_right(Shell_Base * right)
{
r = right;
};
void execute()
{
if (r != 0)
{
r->execute();
if (r->get_executed() != 0)
executed = 1;
}
else
{
// cout << "Error: no right child." << endl;
}
};
};
class Test : public Shell_Base
{
private:
vector<string> test_str;
public:
Test() : Shell_Base() {}
Test(vector<string> s) : Shell_Base()
{
this->test_str = s;
}
int get_executed()
{
return executed;
}
void execute()
{
}
};
<|endoftext|>
|
<commit_before>/**
* scoreboard.cpp
*
* The implementation of the scoreboard.h interface
*/
#include"scoreboard.h"
void Scoreboard::clearScoreboard() {
for(unsigned int i = 0; i < scores.size(); ++i) {
for(unsigned int j = 0; j < scores[i].size(); ++j) {
scores[i][j] = 0;
}
}
//Taylor, Forrest
int Scoreboard::getScore(int competitor, int period, int score)
{
if (competitor <= competitor_size && period <= period_size)
{
score = scores[competitor][period];
return score;
}
else
return -1;
}
<commit_msg>Added Keith/Hunter function<commit_after>/**
* scoreboard.cpp
*
* The implementation of the scoreboard.h interface
*/
#include"scoreboard.h"
void Scoreboard::clearScoreboard() {
for(unsigned int i = 0; i < scores.size(); ++i) {
for(unsigned int j = 0; j < scores[i].size(); ++j) {
scores[i][j] = 0;
}
}
/**
* Sets the score for a given competition and a given period
*
* If the given competitor or period is negative, then no changes take effect
* If the given competitor or period is greater than the current board size
* the size of the scoreboard is increased to address this new score
*
* @param competitor the competitor to set the score for
* @param period the period to set the score for
* @param score the score to set
*/
void scoreboard::setScore(int competitor, int period, int score) {
competitor--;
period--;
if (competitor < 0 || period < 0) {
return;
}
if (competitor >= scores.size()) {
for (int i = scores.size(); i < competitor; i++) {
scores.push_back(vector<int>);
}
}
if (period >= scores[competitor].size()) {
for (int i = scores[competitor].size(); i < period) {
scores[competitor].push_back(0);
}
}
scores[competitor][period] = score;
}
/**
* Gets the score for a given competitor and period
* @param competitor the competitor to get the score for
* @param period the period to get the score for
* @return the score
*/
int Scoreboard::getScore(int competitor, int period)
{
if (competitor <= competitor_size && period <= period_size)
{
return scores[competitor][period];
}
else
return -1;
}
<|endoftext|>
|
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/name.hpp>
#include <eosio/chain/chain_id_type.hpp>
#include <chainbase/chainbase.hpp>
#include <fc/container/flat_fwd.hpp>
#include <fc/io/varint.hpp>
#include <fc/io/enum_type.hpp>
#include <fc/crypto/sha224.hpp>
#include <fc/optional.hpp>
#include <fc/safe.hpp>
#include <fc/container/flat.hpp>
#include <fc/string.hpp>
#include <fc/io/raw.hpp>
#include <fc/static_variant.hpp>
#include <fc/smart_ref_fwd.hpp>
#include <fc/crypto/ripemd160.hpp>
#include <fc/fixed_string.hpp>
#include <fc/crypto/private_key.hpp>
#include <memory>
#include <vector>
#include <deque>
#include <cstdint>
#define OBJECT_CTOR1(NAME) \
NAME() = delete; \
public: \
template<typename Constructor, typename Allocator> \
NAME(Constructor&& c, chainbase::allocator<Allocator>) \
{ c(*this); }
#define OBJECT_CTOR2_MACRO(x, y, field) ,field(a)
#define OBJECT_CTOR2(NAME, FIELDS) \
NAME() = delete; \
public: \
template<typename Constructor, typename Allocator> \
NAME(Constructor&& c, chainbase::allocator<Allocator> a) \
: id(0) BOOST_PP_SEQ_FOR_EACH(OBJECT_CTOR2_MACRO, _, FIELDS) \
{ c(*this); }
#define OBJECT_CTOR(...) BOOST_PP_OVERLOAD(OBJECT_CTOR, __VA_ARGS__)(__VA_ARGS__)
#define _V(n, v) fc::mutable_variant_object(n, v)
namespace eosio { namespace chain {
using std::map;
using std::vector;
using std::unordered_map;
using std::string;
using std::deque;
using std::shared_ptr;
using std::weak_ptr;
using std::unique_ptr;
using std::set;
using std::pair;
using std::make_pair;
using std::enable_shared_from_this;
using std::tie;
using std::move;
using std::forward;
using std::to_string;
using std::all_of;
using fc::path;
using fc::smart_ref;
using fc::variant_object;
using fc::variant;
using fc::enum_type;
using fc::optional;
using fc::unsigned_int;
using fc::signed_int;
using fc::time_point_sec;
using fc::time_point;
using fc::safe;
using fc::flat_map;
using fc::flat_set;
using fc::static_variant;
using fc::ecc::range_proof_type;
using fc::ecc::range_proof_info;
using fc::ecc::commitment_type;
using public_key_type = fc::crypto::public_key;
using private_key_type = fc::crypto::private_key;
using signature_type = fc::crypto::signature;
struct void_t{};
using chainbase::allocator;
using shared_string = boost::interprocess::basic_string<char, std::char_traits<char>, allocator<char>>;
template<typename T>
using shared_vector = boost::interprocess::vector<T, allocator<T>>;
template<typename T>
using shared_set = boost::interprocess::set<T, std::less<T>, allocator<T>>;
using action_name = name;
using scope_name = name;
using account_name = name;
using permission_name = name;
using table_name = name;
/**
* List all object types from all namespaces here so they can
* be easily reflected and displayed in debug output. If a 3rd party
* wants to extend the core code then they will have to change the
* packed_object::type field from enum_type to uint16 to avoid
* warnings when converting packed_objects to/from json.
*/
enum object_type
{
null_object_type,
account_object_type,
account_sequence_object_type,
permission_object_type,
permission_usage_object_type,
permission_link_object_type,
key_value_object_type,
index64_object_type,
index128_object_type,
index256_object_type,
index_double_object_type,
index_long_double_object_type,
global_property_object_type,
dynamic_global_property_object_type,
block_summary_object_type,
transaction_object_type,
generated_transaction_object_type,
producer_object_type,
account_control_history_object_type, ///< Defined by history_plugin
public_key_history_object_type, ///< Defined by history_plugin
table_id_object_type,
resource_limits_object_type,
resource_usage_object_type,
resource_limits_state_object_type,
resource_limits_config_object_type,
account_history_object_type, ///< Defined by history_plugin
action_history_object_type, ///< Defined by history_plugin
reversible_block_object_type,
OBJECT_TYPE_COUNT ///< Sentry value which contains the number of different object types
};
class account_object;
class producer_object;
using block_id_type = fc::sha256;
using checksum_type = fc::sha256;
using checksum256_type = fc::sha256;
using checksum512_type = fc::sha512;
using checksum160_type = fc::ripemd160;
using transaction_id_type = checksum_type;
using digest_type = checksum_type;
using weight_type = uint16_t;
using block_num_type = uint32_t;
using share_type = int64_t;
using int128_t = __int128;
using uint128_t = unsigned __int128;
using bytes = vector<char>;
/**
* Extentions are prefixed with type and are a buffer that can be
* interpreted by code that is aware and ignored by unaware code.
*/
typedef vector<std::pair<uint16_t,vector<char>>> extensions_type;
} } // eosio::chain
FC_REFLECT_ENUM(eosio::chain::object_type,
(null_object_type)
(account_object_type)
(account_sequence_object_type)
(permission_object_type)
(permission_usage_object_type)
(permission_link_object_type)
(key_value_object_type)
(index64_object_type)
(index128_object_type)
(index256_object_type)
(index_double_object_type)
(index_long_double_object_type)
(global_property_object_type)
(dynamic_global_property_object_type)
(block_summary_object_type)
(transaction_object_type)
(generated_transaction_object_type)
(producer_object_type)
(account_control_history_object_type)
(public_key_history_object_type)
(table_id_object_type)
(resource_limits_object_type)
(resource_usage_object_type)
(resource_limits_state_object_type)
(resource_limits_config_object_type)
(account_history_object_type)
(action_history_object_type)
(reversible_block_object_type)
(OBJECT_TYPE_COUNT)
)
FC_REFLECT( eosio::chain::void_t, )
<commit_msg>revert change that broke upgrades without replay<commit_after>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/name.hpp>
#include <eosio/chain/chain_id_type.hpp>
#include <chainbase/chainbase.hpp>
#include <fc/container/flat_fwd.hpp>
#include <fc/io/varint.hpp>
#include <fc/io/enum_type.hpp>
#include <fc/crypto/sha224.hpp>
#include <fc/optional.hpp>
#include <fc/safe.hpp>
#include <fc/container/flat.hpp>
#include <fc/string.hpp>
#include <fc/io/raw.hpp>
#include <fc/static_variant.hpp>
#include <fc/smart_ref_fwd.hpp>
#include <fc/crypto/ripemd160.hpp>
#include <fc/fixed_string.hpp>
#include <fc/crypto/private_key.hpp>
#include <memory>
#include <vector>
#include <deque>
#include <cstdint>
#define OBJECT_CTOR1(NAME) \
NAME() = delete; \
public: \
template<typename Constructor, typename Allocator> \
NAME(Constructor&& c, chainbase::allocator<Allocator>) \
{ c(*this); }
#define OBJECT_CTOR2_MACRO(x, y, field) ,field(a)
#define OBJECT_CTOR2(NAME, FIELDS) \
NAME() = delete; \
public: \
template<typename Constructor, typename Allocator> \
NAME(Constructor&& c, chainbase::allocator<Allocator> a) \
: id(0) BOOST_PP_SEQ_FOR_EACH(OBJECT_CTOR2_MACRO, _, FIELDS) \
{ c(*this); }
#define OBJECT_CTOR(...) BOOST_PP_OVERLOAD(OBJECT_CTOR, __VA_ARGS__)(__VA_ARGS__)
#define _V(n, v) fc::mutable_variant_object(n, v)
namespace eosio { namespace chain {
using std::map;
using std::vector;
using std::unordered_map;
using std::string;
using std::deque;
using std::shared_ptr;
using std::weak_ptr;
using std::unique_ptr;
using std::set;
using std::pair;
using std::make_pair;
using std::enable_shared_from_this;
using std::tie;
using std::move;
using std::forward;
using std::to_string;
using std::all_of;
using fc::path;
using fc::smart_ref;
using fc::variant_object;
using fc::variant;
using fc::enum_type;
using fc::optional;
using fc::unsigned_int;
using fc::signed_int;
using fc::time_point_sec;
using fc::time_point;
using fc::safe;
using fc::flat_map;
using fc::flat_set;
using fc::static_variant;
using fc::ecc::range_proof_type;
using fc::ecc::range_proof_info;
using fc::ecc::commitment_type;
using public_key_type = fc::crypto::public_key;
using private_key_type = fc::crypto::private_key;
using signature_type = fc::crypto::signature;
struct void_t{};
using chainbase::allocator;
using shared_string = boost::interprocess::basic_string<char, std::char_traits<char>, allocator<char>>;
template<typename T>
using shared_vector = boost::interprocess::vector<T, allocator<T>>;
template<typename T>
using shared_set = boost::interprocess::set<T, std::less<T>, allocator<T>>;
using action_name = name;
using scope_name = name;
using account_name = name;
using permission_name = name;
using table_name = name;
/**
* List all object types from all namespaces here so they can
* be easily reflected and displayed in debug output. If a 3rd party
* wants to extend the core code then they will have to change the
* packed_object::type field from enum_type to uint16 to avoid
* warnings when converting packed_objects to/from json.
*
* UNUSED_ enums can be taken for new purposes but otherwise the offsets
* in this enumeration are potentially shared_memory breaking
*/
enum object_type
{
null_object_type = 0,
account_object_type,
account_sequence_object_type,
permission_object_type,
permission_usage_object_type,
permission_link_object_type,
UNUSED_action_code_object_type,
key_value_object_type,
index64_object_type,
index128_object_type,
index256_object_type,
index_double_object_type,
index_long_double_object_type,
global_property_object_type,
dynamic_global_property_object_type,
block_summary_object_type,
transaction_object_type,
generated_transaction_object_type,
producer_object_type,
UNUSED_chain_property_object_type,
account_control_history_object_type, ///< Defined by history_plugin
UNUSED_account_transaction_history_object_type,
UNUSED_transaction_history_object_type,
public_key_history_object_type, ///< Defined by history_plugin
UNUSED_balance_object_type,
UNUSED_staked_balance_object_type,
UNUSED_producer_votes_object_type,
UNUSED_producer_schedule_object_type,
UNUSED_proxy_vote_object_type,
UNUSED_scope_sequence_object_type,
table_id_object_type,
resource_limits_object_type,
resource_usage_object_type,
resource_limits_state_object_type,
resource_limits_config_object_type,
account_history_object_type, ///< Defined by history_plugin
action_history_object_type, ///< Defined by history_plugin
reversible_block_object_type,
OBJECT_TYPE_COUNT ///< Sentry value which contains the number of different object types
};
class account_object;
class producer_object;
using block_id_type = fc::sha256;
using checksum_type = fc::sha256;
using checksum256_type = fc::sha256;
using checksum512_type = fc::sha512;
using checksum160_type = fc::ripemd160;
using transaction_id_type = checksum_type;
using digest_type = checksum_type;
using weight_type = uint16_t;
using block_num_type = uint32_t;
using share_type = int64_t;
using int128_t = __int128;
using uint128_t = unsigned __int128;
using bytes = vector<char>;
/**
* Extentions are prefixed with type and are a buffer that can be
* interpreted by code that is aware and ignored by unaware code.
*/
typedef vector<std::pair<uint16_t,vector<char>>> extensions_type;
} } // eosio::chain
FC_REFLECT( eosio::chain::void_t, )
<|endoftext|>
|
<commit_before>
#include "sync.h"
#include "net.h"
#include "key.h"
#include "util.h"
#include "base58.h"
#include "protocol.h"
#include "spork.h"
#include "main.h"
#include "masternode-budget.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
class CSporkMessage;
class CSporkManager;
CSporkManager sporkManager;
std::map<uint256, CSporkMessage> mapSporks;
std::map<int, CSporkMessage> mapSporksActive;
void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if(fLiteMode) return; //disable all darksend/masternode related functionality
if (strCommand == "spork")
{
//LogPrintf("ProcessSpork::spork\n");
CDataStream vMsg(vRecv);
CSporkMessage spork;
vRecv >> spork;
if(chainActive.Tip() == NULL) return;
uint256 hash = spork.GetHash();
if(mapSporksActive.count(spork.nSporkID)) {
if(mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned){
if(fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
return;
} else {
if(fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
}
}
LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);
if(!sporkManager.CheckSignature(spork)){
LogPrintf("spork - invalid signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
mapSporks[hash] = spork;
mapSporksActive[spork.nSporkID] = spork;
sporkManager.Relay(spork);
//does a task if needed
ExecuteSpork(spork.nSporkID, spork.nValue);
}
if (strCommand == "getsporks")
{
std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();
while(it != mapSporksActive.end()) {
pfrom->PushMessage("spork", it->second);
it++;
}
}
}
// grab the spork, otherwise say it's off
bool IsSporkActive(int nSporkID)
{
int64_t r = -1;
if(mapSporksActive.count(nSporkID)){
r = mapSporksActive[nSporkID].nValue;
} else {
if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if(r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
if(r == -1) r = 4070908800; //return 2099-1-1 by default
return r < GetTime();
}
// grab the value of the spork on the network, or the default
int GetSporkValue(int nSporkID)
{
int r = 0;
if(mapSporksActive.count(nSporkID)){
r = mapSporksActive[nSporkID].nValue;
} else {
if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if(r == 0) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
return r;
}
void ExecuteSpork(int nSporkID, int nValue)
{
if(nSporkID == SPORK_11_RESET_BUDGET && nValue == 1){
budget.Clear();
}
//correct fork via spork technology
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) {
LogPrintf("Spork::ExecuteSpork -- Reconcider Last %d Blocks\n", nValue);
CValidationState state;
{
LOCK(cs_main);
DisconnectBlocksAndReprocess(nValue);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
}
}
bool CSporkManager::CheckSignature(CSporkMessage& spork)
{
//note: need to investigate why this is failing
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CPubKey pubkey(ParseHex(Params().SporkKey()));
std::string errorMessage = "";
if(!darkSendSigner.VerifyMessage(pubkey, spork.vchSig, strMessage, errorMessage)){
return false;
}
return true;
}
bool CSporkManager::Sign(CSporkMessage& spork)
{
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CKey key2;
CPubKey pubkey2;
std::string errorMessage = "";
if(!darkSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2))
{
LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage);
return false;
}
if(!darkSendSigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) {
LogPrintf("CMasternodePayments::Sign - Sign message failed");
return false;
}
if(!darkSendSigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePayments::Sign - Verify message failed");
return false;
}
return true;
}
bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)
{
CSporkMessage msg;
msg.nSporkID = nSporkID;
msg.nValue = nValue;
msg.nTimeSigned = GetTime();
if(Sign(msg)){
Relay(msg);
mapSporks[msg.GetHash()] = msg;
mapSporksActive[nSporkID] = msg;
return true;
}
return false;
}
void CSporkManager::Relay(CSporkMessage& msg)
{
CInv inv(MSG_SPORK, msg.GetHash());
RelayInv(inv);
}
bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
CSporkMessage msg;
// Test signing successful, proceed
strMasterPrivKey = strPrivKey;
Sign(msg);
if(CheckSignature(msg)){
LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n");
return true;
} else {
return false;
}
}
int CSporkManager::GetSporkIDByName(std::string strName)
{
if(strName == "SPORK_2_INSTANTX") return SPORK_2_INSTANTX;
if(strName == "SPORK_3_INSTANTX_BLOCK_FILTERING") return SPORK_3_INSTANTX_BLOCK_FILTERING;
if(strName == "SPORK_5_MAX_VALUE") return SPORK_5_MAX_VALUE;
if(strName == "SPORK_7_MASTERNODE_SCANNING") return SPORK_7_MASTERNODE_SCANNING;
if(strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;
if(strName == "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT;
if(strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;
if(strName == "SPORK_11_RESET_BUDGET") return SPORK_11_RESET_BUDGET;
if(strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS;
if(strName == "SPORK_13_ENABLE_SUPERBLOCKS") return SPORK_13_ENABLE_SUPERBLOCKS;
return -1;
}
std::string CSporkManager::GetSporkNameByID(int id)
{
if(id == SPORK_2_INSTANTX) return "SPORK_2_INSTANTX";
if(id == SPORK_3_INSTANTX_BLOCK_FILTERING) return "SPORK_3_INSTANTX_BLOCK_FILTERING";
if(id == SPORK_5_MAX_VALUE) return "SPORK_5_MAX_VALUE";
if(id == SPORK_7_MASTERNODE_SCANNING) return "SPORK_7_MASTERNODE_SCANNING";
if(id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT";
if(id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT";
if(id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES";
if(id == SPORK_11_RESET_BUDGET) return "SPORK_11_RESET_BUDGET";
if(id == SPORK_12_RECONSIDER_BLOCKS) return "SPORK_12_RECONSIDER_BLOCKS";
if(id == SPORK_13_ENABLE_SUPERBLOCKS) return "SPORK_13_ENABLE_SUPERBLOCKS";
return "Unknown";
}
<commit_msg>Reprocess before disconnect for rescan<commit_after>
#include "sync.h"
#include "net.h"
#include "key.h"
#include "util.h"
#include "base58.h"
#include "protocol.h"
#include "spork.h"
#include "main.h"
#include "masternode-budget.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
class CSporkMessage;
class CSporkManager;
CSporkManager sporkManager;
std::map<uint256, CSporkMessage> mapSporks;
std::map<int, CSporkMessage> mapSporksActive;
void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if(fLiteMode) return; //disable all darksend/masternode related functionality
if (strCommand == "spork")
{
//LogPrintf("ProcessSpork::spork\n");
CDataStream vMsg(vRecv);
CSporkMessage spork;
vRecv >> spork;
if(chainActive.Tip() == NULL) return;
uint256 hash = spork.GetHash();
if(mapSporksActive.count(spork.nSporkID)) {
if(mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned){
if(fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
return;
} else {
if(fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
}
}
LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);
if(!sporkManager.CheckSignature(spork)){
LogPrintf("spork - invalid signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
mapSporks[hash] = spork;
mapSporksActive[spork.nSporkID] = spork;
sporkManager.Relay(spork);
//does a task if needed
ExecuteSpork(spork.nSporkID, spork.nValue);
}
if (strCommand == "getsporks")
{
std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();
while(it != mapSporksActive.end()) {
pfrom->PushMessage("spork", it->second);
it++;
}
}
}
// grab the spork, otherwise say it's off
bool IsSporkActive(int nSporkID)
{
int64_t r = -1;
if(mapSporksActive.count(nSporkID)){
r = mapSporksActive[nSporkID].nValue;
} else {
if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if(r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
if(r == -1) r = 4070908800; //return 2099-1-1 by default
return r < GetTime();
}
// grab the value of the spork on the network, or the default
int GetSporkValue(int nSporkID)
{
int r = 0;
if(mapSporksActive.count(nSporkID)){
r = mapSporksActive[nSporkID].nValue;
} else {
if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;
if(r == 0) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
}
return r;
}
void ExecuteSpork(int nSporkID, int nValue)
{
if(nSporkID == SPORK_11_RESET_BUDGET && nValue == 1){
budget.Clear();
}
//correct fork via spork technology
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) {
LogPrintf("Spork::ExecuteSpork -- Reconcider Last %d Blocks\n", nValue);
CBlockIndex* pindexPrev = chainActive.Tip();
int count = 0;
for (unsigned int i = 1; pindexPrev && pindexPrev->nHeight > 0; i++) {
count++;
if(count >= nValue) return;
CValidationState state;
{
LOCK(cs_main);
LogPrintf("Spork::ExecuteSpork -- Reconcider %s\n", pindexPrev->phashBlock->ToString());
ReconsiderBlock(state, pindexPrev);
}
if (pindexPrev->pprev == NULL) { assert(pindexPrev); break; }
pindexPrev = pindexPrev->pprev;
}
CValidationState state;
{
LOCK(cs_main);
DisconnectBlocksAndReprocess(nValue);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
}
}
bool CSporkManager::CheckSignature(CSporkMessage& spork)
{
//note: need to investigate why this is failing
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CPubKey pubkey(ParseHex(Params().SporkKey()));
std::string errorMessage = "";
if(!darkSendSigner.VerifyMessage(pubkey, spork.vchSig, strMessage, errorMessage)){
return false;
}
return true;
}
bool CSporkManager::Sign(CSporkMessage& spork)
{
std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
CKey key2;
CPubKey pubkey2;
std::string errorMessage = "";
if(!darkSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2))
{
LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage);
return false;
}
if(!darkSendSigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) {
LogPrintf("CMasternodePayments::Sign - Sign message failed");
return false;
}
if(!darkSendSigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePayments::Sign - Verify message failed");
return false;
}
return true;
}
bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)
{
CSporkMessage msg;
msg.nSporkID = nSporkID;
msg.nValue = nValue;
msg.nTimeSigned = GetTime();
if(Sign(msg)){
Relay(msg);
mapSporks[msg.GetHash()] = msg;
mapSporksActive[nSporkID] = msg;
return true;
}
return false;
}
void CSporkManager::Relay(CSporkMessage& msg)
{
CInv inv(MSG_SPORK, msg.GetHash());
RelayInv(inv);
}
bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
CSporkMessage msg;
// Test signing successful, proceed
strMasterPrivKey = strPrivKey;
Sign(msg);
if(CheckSignature(msg)){
LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n");
return true;
} else {
return false;
}
}
int CSporkManager::GetSporkIDByName(std::string strName)
{
if(strName == "SPORK_2_INSTANTX") return SPORK_2_INSTANTX;
if(strName == "SPORK_3_INSTANTX_BLOCK_FILTERING") return SPORK_3_INSTANTX_BLOCK_FILTERING;
if(strName == "SPORK_5_MAX_VALUE") return SPORK_5_MAX_VALUE;
if(strName == "SPORK_7_MASTERNODE_SCANNING") return SPORK_7_MASTERNODE_SCANNING;
if(strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;
if(strName == "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT;
if(strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;
if(strName == "SPORK_11_RESET_BUDGET") return SPORK_11_RESET_BUDGET;
if(strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS;
if(strName == "SPORK_13_ENABLE_SUPERBLOCKS") return SPORK_13_ENABLE_SUPERBLOCKS;
return -1;
}
std::string CSporkManager::GetSporkNameByID(int id)
{
if(id == SPORK_2_INSTANTX) return "SPORK_2_INSTANTX";
if(id == SPORK_3_INSTANTX_BLOCK_FILTERING) return "SPORK_3_INSTANTX_BLOCK_FILTERING";
if(id == SPORK_5_MAX_VALUE) return "SPORK_5_MAX_VALUE";
if(id == SPORK_7_MASTERNODE_SCANNING) return "SPORK_7_MASTERNODE_SCANNING";
if(id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT";
if(id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT";
if(id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES";
if(id == SPORK_11_RESET_BUDGET) return "SPORK_11_RESET_BUDGET";
if(id == SPORK_12_RECONSIDER_BLOCKS) return "SPORK_12_RECONSIDER_BLOCKS";
if(id == SPORK_13_ENABLE_SUPERBLOCKS) return "SPORK_13_ENABLE_SUPERBLOCKS";
return "Unknown";
}
<|endoftext|>
|
<commit_before>#include "runtime_internal.h"
#ifdef BITS_64
#define WIN32API
#else
#define WIN32API __stdcall
#endif
extern "C" {
WIN32API void *LoadLibrary(const char *);
WIN32API void *GetProcAddress(void *, const char *);
WEAK void *halide_get_symbol(const char *name) {
return GetProcAddress(NULL, name);
}
WEAK void *halide_load_library(const char *name) {
return LoadLibrary(name);
}
WEAK void *halide_get_library_symbol(void *lib, const char *name) {
return GetProcAddress(lib, name);
}
}
<commit_msg>Fix missing LoadLibrary symbol on windows.<commit_after>#include "runtime_internal.h"
#ifdef BITS_64
#define WIN32API
#else
#define WIN32API __stdcall
#endif
extern "C" {
WIN32API void *LoadLibraryA(const char *);
WIN32API void *GetProcAddress(void *, const char *);
WEAK void *halide_get_symbol(const char *name) {
return GetProcAddress(NULL, name);
}
WEAK void *halide_load_library(const char *name) {
return LoadLibraryA(name);
}
WEAK void *halide_get_library_symbol(void *lib, const char *name) {
return GetProcAddress(lib, name);
}
}
<|endoftext|>
|
<commit_before><commit_msg>guard against self-assignment<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: viewimp.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: mib $ $Date: 2002-04-05 12:16:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _VIEWIMP_HXX
#define _VIEWIMP_HXX
#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SV_COLOR_HXX //autogen
#include <vcl/color.hxx>
#endif
#include "swtypes.hxx"
#include "swrect.hxx"
class ViewShell;
class SwFlyFrm;
class SwViewOption;
class SwRegionRects;
class SwScrollAreas;
class SwScrollColumn;
class SwFrm;
class SwLayAction;
class SwLayIdle;
class SwDrawView;
class SdrPageView;
class SwPageFrm;
class SwRegionRects;
class ExtOutputDevice;
class SdrPaintInfoRec;
struct SdrPaintProcRec;
#ifdef ACCESSIBLE_LAYOUT
class SwAccessibleMap;
#endif
class SwViewImp
{
friend class ViewShell;
friend class SwLayAction; //Lay- und IdleAction tragen sich ein und aus.
friend class SwLayIdle;
ViewShell *pSh; //Falls jemand einen Imp durchreicht und doch
//mal eine ViewShell braucht hier die
//Rueckwaertsverkettung.
SwDrawView *pDrawView; //Unsere DrawView
SdrPageView *pSdrPageView; //Genau eine Seite fuer unsere DrawView
SwPageFrm *pFirstVisPage;//Zeigt immer auf die erste sichtbare Seite.
SwRegionRects *pRegion; //Sammler fuer Paintrects aus der LayAction.
SwScrollAreas *pScrollRects; //Sammler fuer Scrollrects aus der LayAction.
SwScrollAreas *pScrolledArea;//Sammler der gescrollten Rechtecke.
SwLayAction *pLayAct; //Ist gesetzt wenn ein Action-Objekt existiert
//Wird vom SwLayAction-CTor ein- und vom DTor
//ausgetragen.
SwLayIdle *pIdleAct; //Analog zur SwLayAction fuer SwLayIdle.
#ifdef ACCESSIBLE_LAYOUT
SwAccessibleMap *pAccMap; // Accessible Wrappers
#endif
AutoTimer aScrollTimer; //Fuer das Aufraeumen nach dem Scrollen.
BOOL bFirstPageInvalid :1; //Pointer auf erste Seite ungueltig?
BOOL bNextScroll :1; //Scroll in der folgenden EndAction erlaubt?
BOOL bScroll :1; //Scroll in der aktuellen EndAction erlaubt?
BOOL bScrolled :1; //Wurde gescrolled? Dann im Idle aufraeumen.
BOOL bResetXorVisibility:1; //StartAction/EndAction
BOOL bShowHdlPaint :1; //LockPaint/UnlockPaint
BOOL bResetHdlHiddenPaint:1;// -- "" --
BOOL bPaintInScroll :1; //Paint (Update() im ScrollHdl der ViewShell
BOOL bSmoothUpdate :1; //Meber fuer SmoothScroll
BOOL bStopSmooth :1;
USHORT nRestoreActions ; //Die Anzahl der zu restaurierenden Actions (UNO)
SwRect aSmoothRect;
void SetFirstVisPage(); //Neue Ermittlung der ersten sichtbaren Seite
void ResetNextScroll() { bNextScroll = FALSE; }
void SetNextScroll() { bNextScroll = TRUE; }
void SetScroll() { bScroll = TRUE; }
void ResetScrolled() { bScrolled = FALSE; }
void SetScrolled() { bScrolled = TRUE; }
SwScrollAreas *GetScrollRects() { return pScrollRects; }
void FlushScrolledArea();
BOOL _FlushScrolledArea( SwRect& rRect );
BOOL FlushScrolledArea( SwRect& rRect )
{ if( !pScrolledArea ) return FALSE; return _FlushScrolledArea( rRect ); }
void _ScrolledRect( const SwRect& rRect, long nOffs );
void ScrolledRect( const SwRect& rRect, long nOffs )
{ if( pScrolledArea ) _ScrolledRect( rRect, nOffs ); }
void StartAction(); //Henkel Anzeigen und verstecken.
void EndAction(); //gerufen von ViewShell::ImplXXXAction
void LockPaint(); //dito, gerufen von ViewShell::ImplLockPaint
void UnlockPaint();
void PaintFlyChilds( SwFlyFrm *pFly, ExtOutputDevice& rOut,
const SdrPaintInfoRec& rInfoRec );
#ifdef ACCESSIBLE_LAYOUT
SwAccessibleMap *CreateAccessibleMap();
#endif
public:
SwViewImp( ViewShell * );
~SwViewImp();
void Init( const SwViewOption * ); //nur fuer ViewShell::Init()
const ViewShell *GetShell() const { return pSh; }
ViewShell *GetShell() { return pSh; }
Color GetRetoucheColor() const;
//Verwaltung zur ersten sichtbaren Seite
inline const SwPageFrm *GetFirstVisPage() const;
inline SwPageFrm *GetFirstVisPage();
void SetFirstVisPageInvalid() { bFirstPageInvalid = TRUE; }
//SS'en fuer Paint- und Scrollrects.
BOOL AddPaintRect( const SwRect &rRect );
void AddScrollRect( const SwFrm *pFrm, const SwRect &rRect, long nOffs );
void MoveScrollArea();
SwRegionRects *GetRegion() { return pRegion; }
void DelRegions(); //Loescht Scroll- und PaintRects
//Handler fuer das Refresh von gescrollten Bereichen (Korrektur des
//Alignments). Ruft das Refresh mit der ScrolledArea.
//RefreshScrolledArea kann z.B. beim Setzen des Crsr genutzt werden, es
//wird nur der Anteil des Rect refreshed, der mit der ScrolledArea
//ueberlappt. Das 'reingereichte Rechteck wird veraendert!
void RestartScrollTimer() { aScrollTimer.Start(); }
DECL_LINK( RefreshScrolledHdl, Timer * );
void _RefreshScrolledArea( const SwRect &rRect );
void RefreshScrolledArea( SwRect &rRect );
//Wird vom Layout ggf. waehrend einer Action gerufen, wenn der
//Verdacht besteht, dass es etwas drunter und drueber geht.
void ResetScroll() { bScroll = FALSE; }
BOOL IsNextScroll() const { return bNextScroll; }
BOOL IsScroll() const { return bScroll; }
BOOL IsScrolled() const { return bScrolled; }
BOOL IsPaintInScroll() const { return bPaintInScroll; }
// neues Interface fuer StarView Drawing
inline const BOOL HasDrawView() const { return 0 != pDrawView; }
SwDrawView* GetDrawView() { return pDrawView; }
const SwDrawView* GetDrawView() const { return pDrawView; }
SdrPageView*GetPageView() { return pSdrPageView; }
const SdrPageView*GetPageView() const { return pSdrPageView; }
void MakeDrawView();
void PaintLayer ( const BYTE nLayerID, const SwRect &rRect ) const;
//wird als Link an die DrawEngine uebergeben, entscheidet was wie
//gepaintet wird oder nicht.
DECL_LINK( PaintDispatcher, SdrPaintProcRec * );
// Interface Drawing
BOOL IsDragPossible( const Point &rPoint );
void NotifySizeChg( const Size &rNewSz );
//SS Fuer die Lay- bzw. IdleAction und verwandtes
BOOL IsAction() const { return pLayAct != 0; }
BOOL IsIdleAction() const { return pIdleAct != 0; }
SwLayAction &GetLayAction() { return *pLayAct; }
const SwLayAction &GetLayAction() const { return *pLayAct; }
SwLayIdle &GetIdleAction() { return *pIdleAct;}
const SwLayIdle &GetIdleAction() const { return *pIdleAct;}
//Wenn eine Aktion laueft wird diese gebeten zu pruefen ob es
//an der zeit ist den WaitCrsr einzuschalten.
void CheckWaitCrsr();
BOOL IsCalcLayoutProgress() const; //Fragt die LayAction wenn vorhanden.
//TRUE wenn eine LayAction laeuft, dort wird dann auch das Flag fuer
//ExpressionFields gesetzt.
BOOL IsUpdateExpFlds();
void SetRestoreActions(USHORT nSet){nRestoreActions = nSet;}
USHORT GetRestoreActions() const{return nRestoreActions;}
#ifdef ACCESSIBLE_LAYOUT
// Is this view accessible?
sal_Bool IsAccessible() const { return pAccMap != 0; }
inline SwAccessibleMap& GetAccessibleMap();
// Update (this) accessible view
void UpdateAccessible();
// Remove a frame from the accessible view
void DisposeAccessibleFrm( const SwFrm *pFrm,
sal_Bool bRecursive=sal_False );
// Move a frame's position in the accessible view
void MoveAccessibleFrm( const SwFrm *pFrm, const SwRect& rOldFrm );
// Add a frame in the accessible view
inline void AddAccessibleFrm( const SwFrm *pFrm );
// Invalidate accessible frame's frame's content
void InvalidateAccessibleFrmContent( const SwFrm *pFrm );
// Invalidate accessible frame's cursor position
void InvalidateAccessibleCursorPosition( const SwFrm *pFrm );
// Invalidate editable state for all accessible frames
void InvalidateAccessibleEditableState( sal_Bool bAllShells=sal_True );
// Invalidate opaque state for all accessible frames
void InvalidateAccessibleOpaqueState();
// Fire all accessible events that have been collected so far
void FireAccessibleEvents();
#endif
};
//Kann auf dem Stack angelegt werden, wenn etwas ausgegeben oder
//gescrolled wird. Handles und sontiges vom Drawing werden im CTor
//gehidet und im DTor wieder sichtbar gemacht.
//AW 06-Sep99: Hiding of handles is no longer necessary, removed
class SwSaveHdl
{
SwViewImp *pImp;
BOOL bXorVis;
public:
SwSaveHdl( SwViewImp *pImp );
~SwSaveHdl();
};
inline SwPageFrm *SwViewImp::GetFirstVisPage()
{
if ( bFirstPageInvalid )
SetFirstVisPage();
return pFirstVisPage;
}
inline const SwPageFrm *SwViewImp::GetFirstVisPage() const
{
if ( bFirstPageInvalid )
((SwViewImp*)this)->SetFirstVisPage();
return pFirstVisPage;
}
#ifdef ACCESSIBLE_LAYOUT
inline SwAccessibleMap& SwViewImp::GetAccessibleMap()
{
if( !pAccMap )
CreateAccessibleMap();
return *pAccMap;
}
inline void SwViewImp::AddAccessibleFrm( const SwFrm *pFrm )
{
SwRect aEmptyRect;
MoveAccessibleFrm( pFrm, aEmptyRect );
}
#endif
#endif //_VIEWIMP_HXX
<commit_msg>#95586# added XAccessibleRelation interface to text frames<commit_after>/*************************************************************************
*
* $RCSfile: viewimp.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: dvo $ $Date: 2002-04-26 13:22: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 _VIEWIMP_HXX
#define _VIEWIMP_HXX
#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SV_COLOR_HXX //autogen
#include <vcl/color.hxx>
#endif
#include "swtypes.hxx"
#include "swrect.hxx"
class ViewShell;
class SwFlyFrm;
class SwViewOption;
class SwRegionRects;
class SwScrollAreas;
class SwScrollColumn;
class SwFrm;
class SwLayAction;
class SwLayIdle;
class SwDrawView;
class SdrPageView;
class SwPageFrm;
class SwRegionRects;
class ExtOutputDevice;
class SdrPaintInfoRec;
struct SdrPaintProcRec;
#ifdef ACCESSIBLE_LAYOUT
class SwAccessibleMap;
#endif
class SwViewImp
{
friend class ViewShell;
friend class SwLayAction; //Lay- und IdleAction tragen sich ein und aus.
friend class SwLayIdle;
ViewShell *pSh; //Falls jemand einen Imp durchreicht und doch
//mal eine ViewShell braucht hier die
//Rueckwaertsverkettung.
SwDrawView *pDrawView; //Unsere DrawView
SdrPageView *pSdrPageView; //Genau eine Seite fuer unsere DrawView
SwPageFrm *pFirstVisPage;//Zeigt immer auf die erste sichtbare Seite.
SwRegionRects *pRegion; //Sammler fuer Paintrects aus der LayAction.
SwScrollAreas *pScrollRects; //Sammler fuer Scrollrects aus der LayAction.
SwScrollAreas *pScrolledArea;//Sammler der gescrollten Rechtecke.
SwLayAction *pLayAct; //Ist gesetzt wenn ein Action-Objekt existiert
//Wird vom SwLayAction-CTor ein- und vom DTor
//ausgetragen.
SwLayIdle *pIdleAct; //Analog zur SwLayAction fuer SwLayIdle.
#ifdef ACCESSIBLE_LAYOUT
SwAccessibleMap *pAccMap; // Accessible Wrappers
#endif
AutoTimer aScrollTimer; //Fuer das Aufraeumen nach dem Scrollen.
BOOL bFirstPageInvalid :1; //Pointer auf erste Seite ungueltig?
BOOL bNextScroll :1; //Scroll in der folgenden EndAction erlaubt?
BOOL bScroll :1; //Scroll in der aktuellen EndAction erlaubt?
BOOL bScrolled :1; //Wurde gescrolled? Dann im Idle aufraeumen.
BOOL bResetXorVisibility:1; //StartAction/EndAction
BOOL bShowHdlPaint :1; //LockPaint/UnlockPaint
BOOL bResetHdlHiddenPaint:1;// -- "" --
BOOL bPaintInScroll :1; //Paint (Update() im ScrollHdl der ViewShell
BOOL bSmoothUpdate :1; //Meber fuer SmoothScroll
BOOL bStopSmooth :1;
USHORT nRestoreActions ; //Die Anzahl der zu restaurierenden Actions (UNO)
SwRect aSmoothRect;
void SetFirstVisPage(); //Neue Ermittlung der ersten sichtbaren Seite
void ResetNextScroll() { bNextScroll = FALSE; }
void SetNextScroll() { bNextScroll = TRUE; }
void SetScroll() { bScroll = TRUE; }
void ResetScrolled() { bScrolled = FALSE; }
void SetScrolled() { bScrolled = TRUE; }
SwScrollAreas *GetScrollRects() { return pScrollRects; }
void FlushScrolledArea();
BOOL _FlushScrolledArea( SwRect& rRect );
BOOL FlushScrolledArea( SwRect& rRect )
{ if( !pScrolledArea ) return FALSE; return _FlushScrolledArea( rRect ); }
void _ScrolledRect( const SwRect& rRect, long nOffs );
void ScrolledRect( const SwRect& rRect, long nOffs )
{ if( pScrolledArea ) _ScrolledRect( rRect, nOffs ); }
void StartAction(); //Henkel Anzeigen und verstecken.
void EndAction(); //gerufen von ViewShell::ImplXXXAction
void LockPaint(); //dito, gerufen von ViewShell::ImplLockPaint
void UnlockPaint();
void PaintFlyChilds( SwFlyFrm *pFly, ExtOutputDevice& rOut,
const SdrPaintInfoRec& rInfoRec );
#ifdef ACCESSIBLE_LAYOUT
SwAccessibleMap *CreateAccessibleMap();
#endif
public:
SwViewImp( ViewShell * );
~SwViewImp();
void Init( const SwViewOption * ); //nur fuer ViewShell::Init()
const ViewShell *GetShell() const { return pSh; }
ViewShell *GetShell() { return pSh; }
Color GetRetoucheColor() const;
//Verwaltung zur ersten sichtbaren Seite
inline const SwPageFrm *GetFirstVisPage() const;
inline SwPageFrm *GetFirstVisPage();
void SetFirstVisPageInvalid() { bFirstPageInvalid = TRUE; }
//SS'en fuer Paint- und Scrollrects.
BOOL AddPaintRect( const SwRect &rRect );
void AddScrollRect( const SwFrm *pFrm, const SwRect &rRect, long nOffs );
void MoveScrollArea();
SwRegionRects *GetRegion() { return pRegion; }
void DelRegions(); //Loescht Scroll- und PaintRects
//Handler fuer das Refresh von gescrollten Bereichen (Korrektur des
//Alignments). Ruft das Refresh mit der ScrolledArea.
//RefreshScrolledArea kann z.B. beim Setzen des Crsr genutzt werden, es
//wird nur der Anteil des Rect refreshed, der mit der ScrolledArea
//ueberlappt. Das 'reingereichte Rechteck wird veraendert!
void RestartScrollTimer() { aScrollTimer.Start(); }
DECL_LINK( RefreshScrolledHdl, Timer * );
void _RefreshScrolledArea( const SwRect &rRect );
void RefreshScrolledArea( SwRect &rRect );
//Wird vom Layout ggf. waehrend einer Action gerufen, wenn der
//Verdacht besteht, dass es etwas drunter und drueber geht.
void ResetScroll() { bScroll = FALSE; }
BOOL IsNextScroll() const { return bNextScroll; }
BOOL IsScroll() const { return bScroll; }
BOOL IsScrolled() const { return bScrolled; }
BOOL IsPaintInScroll() const { return bPaintInScroll; }
// neues Interface fuer StarView Drawing
inline const BOOL HasDrawView() const { return 0 != pDrawView; }
SwDrawView* GetDrawView() { return pDrawView; }
const SwDrawView* GetDrawView() const { return pDrawView; }
SdrPageView*GetPageView() { return pSdrPageView; }
const SdrPageView*GetPageView() const { return pSdrPageView; }
void MakeDrawView();
void PaintLayer ( const BYTE nLayerID, const SwRect &rRect ) const;
//wird als Link an die DrawEngine uebergeben, entscheidet was wie
//gepaintet wird oder nicht.
DECL_LINK( PaintDispatcher, SdrPaintProcRec * );
// Interface Drawing
BOOL IsDragPossible( const Point &rPoint );
void NotifySizeChg( const Size &rNewSz );
//SS Fuer die Lay- bzw. IdleAction und verwandtes
BOOL IsAction() const { return pLayAct != 0; }
BOOL IsIdleAction() const { return pIdleAct != 0; }
SwLayAction &GetLayAction() { return *pLayAct; }
const SwLayAction &GetLayAction() const { return *pLayAct; }
SwLayIdle &GetIdleAction() { return *pIdleAct;}
const SwLayIdle &GetIdleAction() const { return *pIdleAct;}
//Wenn eine Aktion laueft wird diese gebeten zu pruefen ob es
//an der zeit ist den WaitCrsr einzuschalten.
void CheckWaitCrsr();
BOOL IsCalcLayoutProgress() const; //Fragt die LayAction wenn vorhanden.
//TRUE wenn eine LayAction laeuft, dort wird dann auch das Flag fuer
//ExpressionFields gesetzt.
BOOL IsUpdateExpFlds();
void SetRestoreActions(USHORT nSet){nRestoreActions = nSet;}
USHORT GetRestoreActions() const{return nRestoreActions;}
#ifdef ACCESSIBLE_LAYOUT
// Is this view accessible?
sal_Bool IsAccessible() const { return pAccMap != 0; }
inline SwAccessibleMap& GetAccessibleMap();
// Update (this) accessible view
void UpdateAccessible();
// Remove a frame from the accessible view
void DisposeAccessibleFrm( const SwFrm *pFrm,
sal_Bool bRecursive=sal_False );
// Move a frame's position in the accessible view
void MoveAccessibleFrm( const SwFrm *pFrm, const SwRect& rOldFrm );
// Add a frame in the accessible view
inline void AddAccessibleFrm( const SwFrm *pFrm );
// Invalidate accessible frame's frame's content
void InvalidateAccessibleFrmContent( const SwFrm *pFrm );
// Invalidate accessible frame's cursor position
void InvalidateAccessibleCursorPosition( const SwFrm *pFrm );
// Invalidate editable state for all accessible frames
void InvalidateAccessibleEditableState( sal_Bool bAllShells=sal_True );
// Invalidate opaque state for all accessible frames
void InvalidateAccessibleOpaqueState();
// Invalidate frame's relation set (for chained frames)
void InvalidateAccessibleRelationSet( const SwFlyFrm *pMaster,
const SwFlyFrm *pFollow );
// Fire all accessible events that have been collected so far
void FireAccessibleEvents();
#endif
};
//Kann auf dem Stack angelegt werden, wenn etwas ausgegeben oder
//gescrolled wird. Handles und sontiges vom Drawing werden im CTor
//gehidet und im DTor wieder sichtbar gemacht.
//AW 06-Sep99: Hiding of handles is no longer necessary, removed
class SwSaveHdl
{
SwViewImp *pImp;
BOOL bXorVis;
public:
SwSaveHdl( SwViewImp *pImp );
~SwSaveHdl();
};
inline SwPageFrm *SwViewImp::GetFirstVisPage()
{
if ( bFirstPageInvalid )
SetFirstVisPage();
return pFirstVisPage;
}
inline const SwPageFrm *SwViewImp::GetFirstVisPage() const
{
if ( bFirstPageInvalid )
((SwViewImp*)this)->SetFirstVisPage();
return pFirstVisPage;
}
#ifdef ACCESSIBLE_LAYOUT
inline SwAccessibleMap& SwViewImp::GetAccessibleMap()
{
if( !pAccMap )
CreateAccessibleMap();
return *pAccMap;
}
inline void SwViewImp::AddAccessibleFrm( const SwFrm *pFrm )
{
SwRect aEmptyRect;
MoveAccessibleFrm( pFrm, aEmptyRect );
}
#endif
#endif //_VIEWIMP_HXX
<|endoftext|>
|
<commit_before><commit_msg>sw: fix crash in sw_unoapi due to calling wrong SwTxtPortion ctor<commit_after><|endoftext|>
|
<commit_before>#include "utils.h"
/*
std::vector<double> BuiltTimepointsList(PlotDataMapRef &data)
{
{
std::vector<size_t> index_num( data.numeric.size(), 0);
std::vector<double> out;
bool loop = true;
const double MAX = std::numeric_limits<double>::max();
while(loop)
{
double min_time = MAX;
double prev_time = out.empty() ? -MAX : out.back();
loop = false;
size_t count = 0;
for(const auto& it: data.numeric)
{
const auto& plot = it.second;
out.reserve(plot.size());
size_t index = index_num[count];
while ( index < plot.size() && plot.at(index).x <= prev_time )
{
index++;
}
if( index >= plot.size() )
{
count++;
continue;
}
else{
loop = true;
}
index_num[count] = index;
double time_val = plot.at(index).x;
min_time = std::min( min_time, time_val);
count++;
}
if( min_time < MAX)
{
out.push_back( min_time );
}
}
return out;
}
}
*/
std::pair<std::vector<QString>, bool> MoveData(PlotDataMapRef &source, PlotDataMapRef &destination)
{
bool destination_updated = false;
std::vector<QString> added_curves;
for (auto& it : source.numeric)
{
const std::string& name = it.first;
if (it.second.size() > 0 && destination.numeric.count(name) == 0)
{
added_curves.push_back(QString::fromStdString(name));
}
}
for (auto& it : source.numeric)
{
const std::string& name = it.first;
auto& source_plot = it.second;
auto plot_with_same_name = destination.numeric.find(name);
// this is a new plot
if (plot_with_same_name == destination.numeric.end())
{
plot_with_same_name =
destination.numeric
.emplace(std::piecewise_construct, std::forward_as_tuple(name), std::forward_as_tuple(name))
.first;
}
auto& destination_plot = plot_with_same_name->second;
for (size_t i = 0; i < source_plot.size(); i++)
{
destination_plot.pushBack(source_plot.at(i));
destination_updated = true;
}
source_plot.clear();
}
for (auto& it : source.user_defined)
{
const std::string& name = it.first;
auto& source_plot = it.second;
auto plot_with_same_name = destination.user_defined.find(name);
// this is a new plot
if (plot_with_same_name == destination.user_defined.end())
{
plot_with_same_name =
destination.user_defined
.emplace(std::piecewise_construct, std::forward_as_tuple(name), std::forward_as_tuple(name))
.first;
}
auto& destination_plot = plot_with_same_name->second;
for (size_t i = 0; i < source_plot.size(); i++)
{
destination_plot.pushBack( std::move(source_plot.at(i)) );
destination_updated = true;
}
source_plot.clear();
}
return { added_curves, destination_updated };
}
<commit_msg>fix bug when datapoints are cleared<commit_after>#include "utils.h"
/*
std::vector<double> BuiltTimepointsList(PlotDataMapRef &data)
{
{
std::vector<size_t> index_num( data.numeric.size(), 0);
std::vector<double> out;
bool loop = true;
const double MAX = std::numeric_limits<double>::max();
while(loop)
{
double min_time = MAX;
double prev_time = out.empty() ? -MAX : out.back();
loop = false;
size_t count = 0;
for(const auto& it: data.numeric)
{
const auto& plot = it.second;
out.reserve(plot.size());
size_t index = index_num[count];
while ( index < plot.size() && plot.at(index).x <= prev_time )
{
index++;
}
if( index >= plot.size() )
{
count++;
continue;
}
else{
loop = true;
}
index_num[count] = index;
double time_val = plot.at(index).x;
min_time = std::min( min_time, time_val);
count++;
}
if( min_time < MAX)
{
out.push_back( min_time );
}
}
return out;
}
}
*/
std::pair<std::vector<QString>, bool> MoveData(PlotDataMapRef &source,
PlotDataMapRef &destination)
{
bool destination_updated = false;
std::vector<QString> added_curves;
for (auto& it : source.numeric)
{
const std::string& name = it.first;
auto& source_plot = it.second;
if(source_plot.size() == 0)
{
continue;
}
auto plot_with_same_name = destination.numeric.find(name);
// this is a new plot
if (plot_with_same_name == destination.numeric.end())
{
added_curves.push_back(QString::fromStdString(name));
plot_with_same_name =
destination.numeric
.emplace(std::piecewise_construct, std::forward_as_tuple(name), std::forward_as_tuple(name))
.first;
}
auto& destination_plot = plot_with_same_name->second;
for (size_t i = 0; i < source_plot.size(); i++)
{
destination_plot.pushBack(source_plot.at(i));
destination_updated = true;
}
source_plot.clear();
}
for (auto& it : source.user_defined)
{
const std::string& name = it.first;
auto& source_plot = it.second;
auto plot_with_same_name = destination.user_defined.find(name);
// this is a new plot
if (plot_with_same_name == destination.user_defined.end())
{
plot_with_same_name =
destination.user_defined
.emplace(std::piecewise_construct, std::forward_as_tuple(name), std::forward_as_tuple(name))
.first;
}
auto& destination_plot = plot_with_same_name->second;
for (size_t i = 0; i < source_plot.size(); i++)
{
destination_plot.pushBack( std::move(source_plot.at(i)) );
destination_updated = true;
}
source_plot.clear();
}
return { added_curves, destination_updated };
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 The Imaging Source Europe GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils.h"
#include "internal.h"
#include <algorithm>
#include <cstring>
#include <sys/ioctl.h>
#include <errno.h>
#include <limits>
#include <cmath>
#define IOCTL_RETRY 4
using namespace tcam;
std::string tcam::propertyType2String (TCAM_PROPERTY_TYPE type)
{
switch (type)
{
case TCAM_PROPERTY_TYPE_BOOLEAN: return "BOOLEAN";
case TCAM_PROPERTY_TYPE_INTEGER: return "INTEGER";
case TCAM_PROPERTY_TYPE_DOUBLE: return "DOUBLE";
case TCAM_PROPERTY_TYPE_STRING: return "STRING";
case TCAM_PROPERTY_TYPE_ENUMERATION: return "ENUMERATION";
case TCAM_PROPERTY_TYPE_BUTTON: return "BUTTON";
case TCAM_PROPERTY_TYPE_UNKNOWN:
default:
return "";
}
}
std::vector<std::string> tcam::split_string (const std::string& to_split, const std::string &delim)
{
std::vector<std::string> vec;
size_t beg = 0;
size_t end = 0;
while (end != std::string::npos)
{
end = to_split.find_first_of(delim, beg);
std::string s = to_split.substr(beg, end - beg);
vec.push_back(s);
beg = end + delim.size();
}
return vec;
}
int tcam::tcam_xioctl (int fd, int request, void *arg)
{
int ret = 0;
int tries= IOCTL_RETRY;
do
{
ret = ioctl(fd, request, arg);
// ret = v4l2_ioctl(fd, request, arg);
}
while (ret && tries-- &&
((errno == EINTR) || (errno == EAGAIN) || (errno == ETIMEDOUT)));
if (ret && (tries <= 0))
{
tcam_log(TCAM_LOG_ERROR,"ioctl (%i) retried %i times - giving up: %s)\n", request, IOCTL_RETRY, strerror(errno));
}
return (ret);
}
std::vector<double> tcam::create_steps_for_range (double min, double max)
{
std::vector<double> vec;
if (max <= min)
return vec;
vec.push_back(min);
// we do not want every framerate to have unnecessary decimals
// e.g. 1.345678 instead of 1.00000
double current_step = (int)min;
// 0.0 is not a valid framerate
if (current_step < 1.0)
current_step = 1.0;
while (current_step < max)
{
vec.push_back(current_step);
if (current_step < 20.0)
{
current_step += 1;
}
else if (current_step < 100.0)
{
current_step += 10.0;
}
else if (current_step < 1000.0)
{
current_step += 50.0;
}
else
{
current_step += 100.0;
}
}
if (vec.back() != max)
{
vec.push_back(max);
}
return vec;
}
uint64_t tcam::get_buffer_length (unsigned int width, unsigned int height, uint32_t fourcc)
{
if (width == 0 || height == 0 || fourcc == 0)
{
return 0;
}
uint64_t size = width * height * (img::get_bits_per_pixel(fourcc) / 8);
return size;
}
unsigned int tcam::tcam_get_required_buffer_size (const struct tcam_video_format* format)
{
if (format == nullptr)
{
return 0;
}
return get_buffer_length(format->width, format->height, format->fourcc);
}
uint32_t tcam::get_pitch_length (unsigned int width, uint32_t fourcc)
{
if (width == 0 || fourcc == 0)
{
return 0;
}
return width * (img::get_bits_per_pixel(fourcc) / 8);
}
bool tcam::is_buffer_complete (const struct tcam_image_buffer* buffer)
{
auto size = tcam::get_buffer_length(buffer->format.width,
buffer->format.height,
buffer->format.fourcc);
if (size != buffer->length)
{
return false;
}
return true;
}
tcam_image_size tcam::calculate_auto_center (const tcam_image_size& sensor, const tcam_image_size& image)
{
tcam_image_size ret = {};
if (image.width > sensor.width || image.height > sensor.height)
{
return ret;
}
ret.width = (sensor.width / 2) - (image.width /2);
ret.height = (sensor.height / 2) - (image.height / 2);
return ret;
}
std::shared_ptr<Property> tcam::find_property (std::vector<std::shared_ptr<Property>>& properties,
TCAM_PROPERTY_ID property_id)
{
for (auto& p : properties)
{
if (p->get_ID() == property_id)
{
return p;
}
}
return nullptr;
}
std::shared_ptr<Property> tcam::find_property (std::vector<std::shared_ptr<Property>>& properties,
const std::string& property_name)
{
auto f = [&property_name] (const std::shared_ptr<Property>& p)
{
if (p->get_name().compare(property_name) == 0)
return true;
return false;
};
auto iter = std::find_if(properties.begin(), properties.end(), f);
if (iter != properties.end())
{
return *iter;
}
return nullptr;
}
bool tcam::compare_double (double val1, double val2)
{
return std::fabs(val1 - val2) < std::numeric_limits<double>::epsilon();
}
bool tcam::are_equal (const tcam_image_size& s1,
const tcam_image_size& s2)
{
if (s1.height == s2.height
&& s1.width == s2.width)
{
return true;
}
return false;
}
bool tcam::are_equal (const struct tcam_resolution_description& res1,
const struct tcam_resolution_description& res2)
{
if (res1.type == res2.type
&& res1.framerate_count == res2.framerate_count
&& are_equal(res1.max_size, res2.max_size)
&& are_equal(res1.min_size,res2.min_size))
{
return true;
}
return false;
}
bool tcam::are_equal (const struct tcam_video_format_description& fmt1,
const struct tcam_video_format_description& fmt2)
{
if (fmt1.fourcc == fmt2.fourcc
&& fmt1.binning == fmt2.binning
&& fmt1.skipping == fmt2.skipping
&& fmt1.resolution_count == fmt2.resolution_count
&& strcmp(fmt1.description, fmt2.description) == 0)
{
return true;
}
return false;
}
bool tcam::is_smaller(const tcam_image_size &s1, const tcam_image_size &s2)
{
if (s1.height <= s2.height && s1.width <= s2.width)
{
return true;
}
return false;
};
TCAM_PROPERTY_ID tcam::generate_unique_property_id ()
{
static unsigned int id_to_use;
static unsigned int id_prefix = 0x199f0000;
TCAM_PROPERTY_ID new_id = id_prefix ^ id_to_use;
id_to_use++;
return new_id;
}
<commit_msg>Add error log for defective fourcc<commit_after>/*
* Copyright 2014 The Imaging Source Europe GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils.h"
#include "internal.h"
#include <algorithm>
#include <cstring>
#include <sys/ioctl.h>
#include <errno.h>
#include <limits>
#include <cmath>
#define IOCTL_RETRY 4
using namespace tcam;
std::string tcam::propertyType2String (TCAM_PROPERTY_TYPE type)
{
switch (type)
{
case TCAM_PROPERTY_TYPE_BOOLEAN: return "BOOLEAN";
case TCAM_PROPERTY_TYPE_INTEGER: return "INTEGER";
case TCAM_PROPERTY_TYPE_DOUBLE: return "DOUBLE";
case TCAM_PROPERTY_TYPE_STRING: return "STRING";
case TCAM_PROPERTY_TYPE_ENUMERATION: return "ENUMERATION";
case TCAM_PROPERTY_TYPE_BUTTON: return "BUTTON";
case TCAM_PROPERTY_TYPE_UNKNOWN:
default:
return "";
}
}
std::vector<std::string> tcam::split_string (const std::string& to_split, const std::string &delim)
{
std::vector<std::string> vec;
size_t beg = 0;
size_t end = 0;
while (end != std::string::npos)
{
end = to_split.find_first_of(delim, beg);
std::string s = to_split.substr(beg, end - beg);
vec.push_back(s);
beg = end + delim.size();
}
return vec;
}
int tcam::tcam_xioctl (int fd, int request, void *arg)
{
int ret = 0;
int tries= IOCTL_RETRY;
do
{
ret = ioctl(fd, request, arg);
// ret = v4l2_ioctl(fd, request, arg);
}
while (ret && tries-- &&
((errno == EINTR) || (errno == EAGAIN) || (errno == ETIMEDOUT)));
if (ret && (tries <= 0))
{
tcam_log(TCAM_LOG_ERROR,"ioctl (%i) retried %i times - giving up: %s)\n", request, IOCTL_RETRY, strerror(errno));
}
return (ret);
}
std::vector<double> tcam::create_steps_for_range (double min, double max)
{
std::vector<double> vec;
if (max <= min)
return vec;
vec.push_back(min);
// we do not want every framerate to have unnecessary decimals
// e.g. 1.345678 instead of 1.00000
double current_step = (int)min;
// 0.0 is not a valid framerate
if (current_step < 1.0)
current_step = 1.0;
while (current_step < max)
{
vec.push_back(current_step);
if (current_step < 20.0)
{
current_step += 1;
}
else if (current_step < 100.0)
{
current_step += 10.0;
}
else if (current_step < 1000.0)
{
current_step += 50.0;
}
else
{
current_step += 100.0;
}
}
if (vec.back() != max)
{
vec.push_back(max);
}
return vec;
}
uint64_t tcam::get_buffer_length (unsigned int width, unsigned int height, uint32_t fourcc)
{
if (width == 0 || height == 0 || fourcc == 0)
{
return 0;
}
if (!img::is_known_fcc(fourcc))
{
tcam_log(TCAM_LOG_ERROR, "Unknown fourcc %d", fourcc);
}
uint64_t size = width * height * (img::get_bits_per_pixel(fourcc) / 8);
return size;
}
unsigned int tcam::tcam_get_required_buffer_size (const struct tcam_video_format* format)
{
if (format == nullptr)
{
return 0;
}
return get_buffer_length(format->width, format->height, format->fourcc);
}
uint32_t tcam::get_pitch_length (unsigned int width, uint32_t fourcc)
{
if (width == 0 || fourcc == 0)
{
return 0;
}
return width * (img::get_bits_per_pixel(fourcc) / 8);
}
bool tcam::is_buffer_complete (const struct tcam_image_buffer* buffer)
{
auto size = tcam::get_buffer_length(buffer->format.width,
buffer->format.height,
buffer->format.fourcc);
if (size != buffer->length)
{
return false;
}
return true;
}
tcam_image_size tcam::calculate_auto_center (const tcam_image_size& sensor, const tcam_image_size& image)
{
tcam_image_size ret = {};
if (image.width > sensor.width || image.height > sensor.height)
{
return ret;
}
ret.width = (sensor.width / 2) - (image.width /2);
ret.height = (sensor.height / 2) - (image.height / 2);
return ret;
}
std::shared_ptr<Property> tcam::find_property (std::vector<std::shared_ptr<Property>>& properties,
TCAM_PROPERTY_ID property_id)
{
for (auto& p : properties)
{
if (p->get_ID() == property_id)
{
return p;
}
}
return nullptr;
}
std::shared_ptr<Property> tcam::find_property (std::vector<std::shared_ptr<Property>>& properties,
const std::string& property_name)
{
auto f = [&property_name] (const std::shared_ptr<Property>& p)
{
if (p->get_name().compare(property_name) == 0)
return true;
return false;
};
auto iter = std::find_if(properties.begin(), properties.end(), f);
if (iter != properties.end())
{
return *iter;
}
return nullptr;
}
bool tcam::compare_double (double val1, double val2)
{
return std::fabs(val1 - val2) < std::numeric_limits<double>::epsilon();
}
bool tcam::are_equal (const tcam_image_size& s1,
const tcam_image_size& s2)
{
if (s1.height == s2.height
&& s1.width == s2.width)
{
return true;
}
return false;
}
bool tcam::are_equal (const struct tcam_resolution_description& res1,
const struct tcam_resolution_description& res2)
{
if (res1.type == res2.type
&& res1.framerate_count == res2.framerate_count
&& are_equal(res1.max_size, res2.max_size)
&& are_equal(res1.min_size,res2.min_size))
{
return true;
}
return false;
}
bool tcam::are_equal (const struct tcam_video_format_description& fmt1,
const struct tcam_video_format_description& fmt2)
{
if (fmt1.fourcc == fmt2.fourcc
&& fmt1.binning == fmt2.binning
&& fmt1.skipping == fmt2.skipping
&& fmt1.resolution_count == fmt2.resolution_count
&& strcmp(fmt1.description, fmt2.description) == 0)
{
return true;
}
return false;
}
bool tcam::is_smaller(const tcam_image_size &s1, const tcam_image_size &s2)
{
if (s1.height <= s2.height && s1.width <= s2.width)
{
return true;
}
return false;
};
TCAM_PROPERTY_ID tcam::generate_unique_property_id ()
{
static unsigned int id_to_use;
static unsigned int id_prefix = 0x199f0000;
TCAM_PROPERTY_ID new_id = id_prefix ^ id_to_use;
id_to_use++;
return new_id;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: listsh.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:51:13 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#include "cmdid.h"
#include "uiparam.hxx"
#include "hintids.hxx"
#ifndef _SVX_SIZEITEM_HXX //autogen
#include <svx/sizeitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <svx/brshitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _SVX_SRCHITEM_HXX //autogen
#include <svx/srchitem.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
// --> FME 2005-01-04 #i35572#
#ifndef _NUMRULE_HXX
#include <numrule.hxx>
#endif
// <--
#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#include "wrtsh.hxx"
#include "swmodule.hxx"
#include "frmatr.hxx"
#include "helpid.h"
#include "globals.hrc"
#include "shells.hrc"
#include "uinums.hxx"
#include "listsh.hxx"
#include "poolfmt.hxx"
#include "view.hxx"
#include "edtwin.hxx"
#define SwListShell
#include "itemdef.hxx"
#include "swslots.hxx"
SFX_IMPL_INTERFACE(SwListShell, SwBaseShell, SW_RES(STR_SHELLNAME_LIST))
{
SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_NUM_TOOLBOX));
}
TYPEINIT1(SwListShell,SwBaseShell)
// --> FME 2005-01-04 #i35572# Functionality of Numbering/Bullet toolbar
// for outline numbered paragraphs should match the functions for outlines
// available in the navigator. Therefore the code in the following
// function is quite similar the the code in SwContentTree::ExecCommand.
void lcl_OutlineUpDownWithSubPoints( SwWrtShell& rSh, bool bMove, bool bUp )
{
const sal_uInt16 nActPos = rSh.GetOutlinePos();
if ( nActPos < USHRT_MAX && rSh.IsOutlineMovable( nActPos ) )
{
rSh.Push();
rSh.MakeOutlineSel( nActPos, nActPos, TRUE );
if ( bMove )
{
const sal_uInt16 nActLevel = rSh.GetOutlineLevel( nActPos );
sal_uInt16 nActEndPos = nActPos + 1;
sal_Int16 nDir = 0;
if ( !bUp )
{
// Move down with subpoints:
while ( nActEndPos < rSh.GetOutlineCnt() &&
rSh.GetOutlineLevel( nActEndPos ) > nActLevel )
++nActEndPos;
if ( nActEndPos < rSh.GetOutlineCnt() )
{
// The current subpoint which should be moved
// starts at nActPos and ends at nActEndPos - 1
--nActEndPos;
sal_uInt16 nDest = nActEndPos + 2;
while ( nDest < rSh.GetOutlineCnt() &&
rSh.GetOutlineLevel( nDest ) > nActLevel )
++nDest;
nDir = nDest - 1 - nActEndPos;
}
}
else
{
// Move up with subpoints:
if ( nActPos > 0 )
{
--nActEndPos;
sal_uInt16 nDest = nActPos - 1;
while ( nDest > 0 && rSh.GetOutlineLevel( nDest ) > nActLevel )
--nDest;
nDir = nDest - nActPos;
}
}
if ( nDir )
{
rSh.MoveOutlinePara( nDir );
rSh.GotoOutline( nActPos + nDir );
}
}
else
{
// Up/down with subpoints:
rSh.OutlineUpDown( bUp ? -1 : 1 );
}
rSh.ClearMark();
rSh.Pop( sal_False );
}
}
// <--
void SwListShell::Execute(SfxRequest &rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
USHORT nSlot = rReq.GetSlot();
SwWrtShell& rSh = GetShell();
// --> FME 2005-01-04 #i35572#
const SwNumRule* pCurRule = rSh.GetCurNumRule();
ASSERT( pCurRule, "SwListShell::Execute without NumRule" )
bool bOutline = pCurRule && pCurRule->IsOutlineRule();
// <--
switch (nSlot)
{
case FN_NUM_BULLET_DOWN:
{
SfxViewFrame * pFrame = GetView().GetViewFrame();
rReq.Done();
rSh.NumUpDown();
pFrame->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
}
break;
case FN_NUM_BULLET_NEXT:
rSh.GotoNextNum();
rReq.Done();
break;
case FN_NUM_BULLET_NONUM:
rSh.NoNum();
rReq.Done();
break;
case FN_NUM_BULLET_OFF:
{
rReq.Ignore();
SfxRequest aReq( GetView().GetViewFrame(), FN_NUM_BULLET_ON );
aReq.AppendItem( SfxBoolItem( FN_PARAM_1, FALSE ) );
aReq.Done();
rSh.DelNumRules();
break;
}
case FN_NUM_BULLET_OUTLINE_DOWN:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, false, false );
else
rSh.MoveNumParas(FALSE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEDOWN:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, true, false );
else
rSh.MoveNumParas(TRUE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEUP:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, true, true );
else
rSh.MoveNumParas(TRUE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_UP:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, false, true );
else
rSh.MoveNumParas(FALSE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_PREV:
rSh.GotoPrevNum();
rReq.Done();
break;
case FN_NUM_BULLET_UP:
rSh.NumUpDown(FALSE);
GetView().GetViewFrame()->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
rReq.Done();
break;
case FN_NUM_OR_NONUM:
{
BOOL bApi = rReq.IsAPI();
BOOL bDelete = !rSh.IsNoNum(!bApi);
if(pArgs )
bDelete = ((SfxBoolItem &)pArgs->Get(rReq.GetSlot())).GetValue();
rSh.NumOrNoNum( bDelete, !bApi );
rReq.AppendItem( SfxBoolItem( nSlot, bDelete ) );
rReq.Done();
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
}
void SwListShell::GetState(SfxItemSet &rSet)
{
SfxWhichIter aIter( rSet );
USHORT nWhich = aIter.FirstWhich();
BOOL bHasChildren;
SwWrtShell& rSh = GetShell();
BYTE nCurrentNumLevel = rSh.GetNumLevel( &bHasChildren );
BOOL bNoNumbering = nCurrentNumLevel == NO_NUMBERING;
BOOL bNoNumLevel = ! IsNum(nCurrentNumLevel);
nCurrentNumLevel = GetRealLevel(nCurrentNumLevel);
while ( nWhich )
{
switch( nWhich )
{
case FN_NUM_OR_NONUM:
rSet.Put(SfxBoolItem(nWhich, GetShell().IsNoNum(FALSE)));
break;
case FN_NUM_BULLET_OUTLINE_UP:
case FN_NUM_BULLET_UP:
if(!nCurrentNumLevel)
rSet.DisableItem(nWhich);
break;
case FN_NUM_BULLET_OUTLINE_DOWN :
{
sal_uInt8 nUpper, nLower;
rSh.GetCurrentOutlineLevels( nUpper, nLower );
if(nLower == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
}
break;
case FN_NUM_BULLET_DOWN:
if(nCurrentNumLevel == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
break;
}
nWhich = aIter.NextWhich();
}
}
SwListShell::SwListShell(SwView &rView) :
SwBaseShell(rView)
{
SetName(String::CreateFromAscii("List"));
SetHelpId(SW_LISTSHELL);
}
<commit_msg>INTEGRATION: CWS writercorehandoff (1.8.238); FILE MERGED 2005/09/13 18:20:39 tra 1.8.238.4: RESYNC: (1.9-1.10); FILE MERGED 2005/07/28 11:59:30 tra 1.8.238.3: RESYNC: (1.8-1.9); FILE MERGED 2005/06/07 14:16:00 fme 1.8.238.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005/06/06 09:29:59 tra 1.8.238.1: Unnecessary includes removed #i50348#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: listsh.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2006-08-14 17:54:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#include "cmdid.h"
#include "uiparam.hxx"
#include "hintids.hxx"
#ifndef _SVX_SIZEITEM_HXX //autogen
#include <svx/sizeitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <svx/brshitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _SVX_SRCHITEM_HXX //autogen
#include <svx/srchitem.hxx>
#endif
// --> FME 2005-01-04 #i35572#
#ifndef _NUMRULE_HXX
#include <numrule.hxx>
#endif
// <--
#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#include "wrtsh.hxx"
#include "swmodule.hxx"
#include "frmatr.hxx"
#include "helpid.h"
#include "globals.hrc"
#include "shells.hrc"
#include "uinums.hxx"
#include "listsh.hxx"
#include "poolfmt.hxx"
#include "view.hxx"
#include "edtwin.hxx"
#define SwListShell
#include "itemdef.hxx"
#include "swslots.hxx"
SFX_IMPL_INTERFACE(SwListShell, SwBaseShell, SW_RES(STR_SHELLNAME_LIST))
{
SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_NUM_TOOLBOX));
}
TYPEINIT1(SwListShell,SwBaseShell)
// --> FME 2005-01-04 #i35572# Functionality of Numbering/Bullet toolbar
// for outline numbered paragraphs should match the functions for outlines
// available in the navigator. Therefore the code in the following
// function is quite similar the the code in SwContentTree::ExecCommand.
void lcl_OutlineUpDownWithSubPoints( SwWrtShell& rSh, bool bMove, bool bUp )
{
const sal_uInt16 nActPos = rSh.GetOutlinePos();
if ( nActPos < USHRT_MAX && rSh.IsOutlineMovable( nActPos ) )
{
rSh.Push();
rSh.MakeOutlineSel( nActPos, nActPos, TRUE );
if ( bMove )
{
const sal_uInt16 nActLevel = rSh.GetOutlineLevel( nActPos );
sal_uInt16 nActEndPos = nActPos + 1;
sal_Int16 nDir = 0;
if ( !bUp )
{
// Move down with subpoints:
while ( nActEndPos < rSh.GetOutlineCnt() &&
rSh.GetOutlineLevel( nActEndPos ) > nActLevel )
++nActEndPos;
if ( nActEndPos < rSh.GetOutlineCnt() )
{
// The current subpoint which should be moved
// starts at nActPos and ends at nActEndPos - 1
--nActEndPos;
sal_uInt16 nDest = nActEndPos + 2;
while ( nDest < rSh.GetOutlineCnt() &&
rSh.GetOutlineLevel( nDest ) > nActLevel )
++nDest;
nDir = nDest - 1 - nActEndPos;
}
}
else
{
// Move up with subpoints:
if ( nActPos > 0 )
{
--nActEndPos;
sal_uInt16 nDest = nActPos - 1;
while ( nDest > 0 && rSh.GetOutlineLevel( nDest ) > nActLevel )
--nDest;
nDir = nDest - nActPos;
}
}
if ( nDir )
{
rSh.MoveOutlinePara( nDir );
rSh.GotoOutline( nActPos + nDir );
}
}
else
{
// Up/down with subpoints:
rSh.OutlineUpDown( bUp ? -1 : 1 );
}
rSh.ClearMark();
rSh.Pop( sal_False );
}
}
// <--
void SwListShell::Execute(SfxRequest &rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
USHORT nSlot = rReq.GetSlot();
SwWrtShell& rSh = GetShell();
// --> FME 2005-01-04 #i35572#
const SwNumRule* pCurRule = rSh.GetCurNumRule();
ASSERT( pCurRule, "SwListShell::Execute without NumRule" )
bool bOutline = pCurRule && pCurRule->IsOutlineRule();
// <--
switch (nSlot)
{
case FN_NUM_BULLET_DOWN:
{
SfxViewFrame * pFrame = GetView().GetViewFrame();
rReq.Done();
rSh.NumUpDown();
pFrame->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
}
break;
case FN_NUM_BULLET_NEXT:
rSh.GotoNextNum();
rReq.Done();
break;
case FN_NUM_BULLET_NONUM:
rSh.NoNum();
rReq.Done();
break;
case FN_NUM_BULLET_OFF:
{
rReq.Ignore();
SfxRequest aReq( GetView().GetViewFrame(), FN_NUM_BULLET_ON );
aReq.AppendItem( SfxBoolItem( FN_PARAM_1, FALSE ) );
aReq.Done();
rSh.DelNumRules();
break;
}
case FN_NUM_BULLET_OUTLINE_DOWN:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, false, false );
else
rSh.MoveNumParas(FALSE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEDOWN:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, true, false );
else
rSh.MoveNumParas(TRUE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEUP:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, true, true );
else
rSh.MoveNumParas(TRUE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_UP:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, false, true );
else
rSh.MoveNumParas(FALSE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_PREV:
rSh.GotoPrevNum();
rReq.Done();
break;
case FN_NUM_BULLET_UP:
rSh.NumUpDown(FALSE);
GetView().GetViewFrame()->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
rReq.Done();
break;
case FN_NUM_OR_NONUM:
{
BOOL bApi = rReq.IsAPI();
BOOL bDelete = !rSh.IsNoNum(!bApi);
if(pArgs )
bDelete = ((SfxBoolItem &)pArgs->Get(rReq.GetSlot())).GetValue();
rSh.NumOrNoNum( bDelete, !bApi );
rReq.AppendItem( SfxBoolItem( nSlot, bDelete ) );
rReq.Done();
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
}
void SwListShell::GetState(SfxItemSet &rSet)
{
SfxWhichIter aIter( rSet );
USHORT nWhich = aIter.FirstWhich();
BOOL bHasChildren;
SwWrtShell& rSh = GetShell();
BYTE nCurrentNumLevel = rSh.GetNumLevel( &bHasChildren );
BOOL bNoNumbering = nCurrentNumLevel == NO_NUMBERING;
BOOL bNoNumLevel = ! IsNum(nCurrentNumLevel);
nCurrentNumLevel = GetRealLevel(nCurrentNumLevel);
while ( nWhich )
{
switch( nWhich )
{
case FN_NUM_OR_NONUM:
rSet.Put(SfxBoolItem(nWhich, GetShell().IsNoNum(FALSE)));
break;
case FN_NUM_BULLET_OUTLINE_UP:
case FN_NUM_BULLET_UP:
if(!nCurrentNumLevel)
rSet.DisableItem(nWhich);
break;
case FN_NUM_BULLET_OUTLINE_DOWN :
{
sal_uInt8 nUpper, nLower;
rSh.GetCurrentOutlineLevels( nUpper, nLower );
if(nLower == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
}
break;
case FN_NUM_BULLET_DOWN:
if(nCurrentNumLevel == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
break;
}
nWhich = aIter.NextWhich();
}
}
SwListShell::SwListShell(SwView &rView) :
SwBaseShell(rView)
{
SetName(String::CreateFromAscii("List"));
SetHelpId(SW_LISTSHELL);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
*/
/** @file
* Disk Image Definitions
*/
#include <sys/types.h>
#include <sys/uio.h>
#include <errno.h>
#include <unistd.h>
#include <cstring>
#include <fstream>
#include <string>
#include "base/callback.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "dev/disk_image.hh"
#include "sim/sim_exit.hh"
#include "sim/byteswap.hh"
using namespace std;
////////////////////////////////////////////////////////////////////////
//
// Raw Disk image
//
RawDiskImage::RawDiskImage(const Params* p)
: DiskImage(p), disk_size(0)
{ open(p->image_file, p->read_only); }
RawDiskImage::~RawDiskImage()
{ close(); }
void
RawDiskImage::open(const string &filename, bool rd_only)
{
if (!filename.empty()) {
initialized = true;
readonly = rd_only;
file = filename;
ios::openmode mode = ios::in | ios::binary;
if (!readonly)
mode |= ios::out;
stream.open(file.c_str(), mode);
if (!stream.is_open())
panic("Error opening %s", filename);
}
}
void
RawDiskImage::close()
{
stream.close();
}
off_t
RawDiskImage::size() const
{
if (disk_size == 0) {
if (!stream.is_open())
panic("file not open!\n");
stream.seekg(0, ios::end);
disk_size = stream.tellg();
}
return disk_size / SectorSize;
}
off_t
RawDiskImage::read(uint8_t *data, off_t offset) const
{
if (!initialized)
panic("RawDiskImage not initialized");
if (!stream.is_open())
panic("file not open!\n");
if (stream.seekg(offset * SectorSize, ios::beg) < 0)
panic("Could not seek to location in file");
streampos pos = stream.tellg();
stream.read((char *)data, SectorSize);
DPRINTF(DiskImageRead, "read: offset=%d\n", (uint64_t)offset);
DDUMP(DiskImageRead, data, SectorSize);
return stream.tellg() - pos;
}
off_t
RawDiskImage::write(const uint8_t *data, off_t offset)
{
if (!initialized)
panic("RawDiskImage not initialized");
if (readonly)
panic("Cannot write to a read only disk image");
if (!stream.is_open())
panic("file not open!\n");
if (stream.seekp(offset * SectorSize, ios::beg) < 0)
panic("Could not seek to location in file");
DPRINTF(DiskImageWrite, "write: offset=%d\n", (uint64_t)offset);
DDUMP(DiskImageWrite, data, SectorSize);
streampos pos = stream.tellp();
stream.write((const char *)data, SectorSize);
return stream.tellp() - pos;
}
RawDiskImage *
RawDiskImageParams::create()
{
return new RawDiskImage(this);
}
////////////////////////////////////////////////////////////////////////
//
// Copy on Write Disk image
//
const int CowDiskImage::VersionMajor = 1;
const int CowDiskImage::VersionMinor = 0;
class CowDiskCallback : public Callback
{
private:
CowDiskImage *image;
public:
CowDiskCallback(CowDiskImage *i) : image(i) {}
void process() { image->save(); delete this; }
};
CowDiskImage::CowDiskImage(const Params *p)
: DiskImage(p), filename(p->image_file), child(p->child), table(NULL)
{
if (filename.empty()) {
init(p->table_size);
} else {
if (!open(filename)) {
assert(!p->read_only && "why have a non-existent read only file?");
init(p->table_size);
}
if (!p->read_only)
registerExitCallback(new CowDiskCallback(this));
}
}
CowDiskImage::~CowDiskImage()
{
SectorTable::iterator i = table->begin();
SectorTable::iterator end = table->end();
while (i != end) {
delete (*i).second;
++i;
}
}
void
SafeRead(ifstream &stream, void *data, int count)
{
stream.read((char *)data, count);
if (!stream.is_open())
panic("file not open");
if (stream.eof())
panic("premature end-of-file");
if (stream.bad() || stream.fail())
panic("error reading cowdisk image");
}
template<class T>
void
SafeRead(ifstream &stream, T &data)
{
SafeRead(stream, &data, sizeof(data));
}
template<class T>
void
SafeReadSwap(ifstream &stream, T &data)
{
SafeRead(stream, &data, sizeof(data));
data = letoh(data); //is this the proper byte order conversion?
}
bool
CowDiskImage::open(const string &file)
{
ifstream stream(file.c_str());
if (!stream.is_open())
return false;
if (stream.fail() || stream.bad())
panic("Error opening %s", file);
uint64_t magic;
SafeRead(stream, magic);
if (memcmp(&magic, "COWDISK!", sizeof(magic)) != 0)
panic("Could not open %s: Invalid magic", file);
uint32_t major, minor;
SafeReadSwap(stream, major);
SafeReadSwap(stream, minor);
if (major != VersionMajor && minor != VersionMinor)
panic("Could not open %s: invalid version %d.%d != %d.%d",
file, major, minor, VersionMajor, VersionMinor);
uint64_t sector_count;
SafeReadSwap(stream, sector_count);
table = new SectorTable(sector_count);
for (uint64_t i = 0; i < sector_count; i++) {
uint64_t offset;
SafeReadSwap(stream, offset);
Sector *sector = new Sector;
SafeRead(stream, sector, sizeof(Sector));
assert(table->find(offset) == table->end());
(*table)[offset] = sector;
}
stream.close();
initialized = true;
return true;
}
void
CowDiskImage::init(int hash_size)
{
table = new SectorTable(hash_size);
initialized = true;
}
void
SafeWrite(ofstream &stream, const void *data, int count)
{
stream.write((const char *)data, count);
if (!stream.is_open())
panic("file not open");
if (stream.eof())
panic("premature end-of-file");
if (stream.bad() || stream.fail())
panic("error reading cowdisk image");
}
template<class T>
void
SafeWrite(ofstream &stream, const T &data)
{
SafeWrite(stream, &data, sizeof(data));
}
template<class T>
void
SafeWriteSwap(ofstream &stream, const T &data)
{
T swappeddata = letoh(data); //is this the proper byte order conversion?
SafeWrite(stream, &swappeddata, sizeof(data));
}
void
CowDiskImage::save()
{
save(filename);
}
void
CowDiskImage::save(const string &file)
{
if (!initialized)
panic("RawDiskImage not initialized");
ofstream stream(file.c_str());
if (!stream.is_open() || stream.fail() || stream.bad())
panic("Error opening %s", file);
uint64_t magic;
memcpy(&magic, "COWDISK!", sizeof(magic));
SafeWrite(stream, magic);
SafeWriteSwap(stream, (uint32_t)VersionMajor);
SafeWriteSwap(stream, (uint32_t)VersionMinor);
SafeWriteSwap(stream, (uint64_t)table->size());
uint64_t size = table->size();
SectorTable::iterator iter = table->begin();
SectorTable::iterator end = table->end();
for (uint64_t i = 0; i < size; i++) {
if (iter == end)
panic("Incorrect Table Size during save of COW disk image");
SafeWriteSwap(stream, (uint64_t)(*iter).first);
SafeWrite(stream, (*iter).second->data, sizeof(Sector));
++iter;
}
stream.close();
}
void
CowDiskImage::writeback()
{
SectorTable::iterator i = table->begin();
SectorTable::iterator end = table->end();
while (i != end) {
child->write((*i).second->data, (*i).first);
++i;
}
}
off_t
CowDiskImage::size() const
{ return child->size(); }
off_t
CowDiskImage::read(uint8_t *data, off_t offset) const
{
if (!initialized)
panic("CowDiskImage not initialized");
if (offset > size())
panic("access out of bounds");
SectorTable::const_iterator i = table->find(offset);
if (i == table->end())
return child->read(data, offset);
else {
memcpy(data, (*i).second->data, SectorSize);
DPRINTF(DiskImageRead, "read: offset=%d\n", (uint64_t)offset);
DDUMP(DiskImageRead, data, SectorSize);
return SectorSize;
}
}
off_t
CowDiskImage::write(const uint8_t *data, off_t offset)
{
if (!initialized)
panic("RawDiskImage not initialized");
if (offset > size())
panic("access out of bounds");
SectorTable::iterator i = table->find(offset);
if (i == table->end()) {
Sector *sector = new Sector;
memcpy(sector, data, SectorSize);
table->insert(make_pair(offset, sector));
} else {
memcpy((*i).second->data, data, SectorSize);
}
DPRINTF(DiskImageWrite, "write: offset=%d\n", (uint64_t)offset);
DDUMP(DiskImageWrite, data, SectorSize);
return SectorSize;
}
void
CowDiskImage::serialize(ostream &os)
{
string cowFilename = name() + ".cow";
SERIALIZE_SCALAR(cowFilename);
save(Checkpoint::dir() + "/" + cowFilename);
}
void
CowDiskImage::unserialize(Checkpoint *cp, const string §ion)
{
string cowFilename;
UNSERIALIZE_SCALAR(cowFilename);
cowFilename = cp->cptDir + "/" + cowFilename;
open(cowFilename);
}
CowDiskImage *
CowDiskImageParams::create()
{
return new CowDiskImage(this);
}
<commit_msg>devices: Avoid using assert() to catch misconfiguration<commit_after>/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
*/
/** @file
* Disk Image Definitions
*/
#include <sys/types.h>
#include <sys/uio.h>
#include <errno.h>
#include <unistd.h>
#include <cstring>
#include <fstream>
#include <string>
#include "base/callback.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "dev/disk_image.hh"
#include "sim/sim_exit.hh"
#include "sim/byteswap.hh"
using namespace std;
////////////////////////////////////////////////////////////////////////
//
// Raw Disk image
//
RawDiskImage::RawDiskImage(const Params* p)
: DiskImage(p), disk_size(0)
{ open(p->image_file, p->read_only); }
RawDiskImage::~RawDiskImage()
{ close(); }
void
RawDiskImage::open(const string &filename, bool rd_only)
{
if (!filename.empty()) {
initialized = true;
readonly = rd_only;
file = filename;
ios::openmode mode = ios::in | ios::binary;
if (!readonly)
mode |= ios::out;
stream.open(file.c_str(), mode);
if (!stream.is_open())
panic("Error opening %s", filename);
}
}
void
RawDiskImage::close()
{
stream.close();
}
off_t
RawDiskImage::size() const
{
if (disk_size == 0) {
if (!stream.is_open())
panic("file not open!\n");
stream.seekg(0, ios::end);
disk_size = stream.tellg();
}
return disk_size / SectorSize;
}
off_t
RawDiskImage::read(uint8_t *data, off_t offset) const
{
if (!initialized)
panic("RawDiskImage not initialized");
if (!stream.is_open())
panic("file not open!\n");
if (stream.seekg(offset * SectorSize, ios::beg) < 0)
panic("Could not seek to location in file");
streampos pos = stream.tellg();
stream.read((char *)data, SectorSize);
DPRINTF(DiskImageRead, "read: offset=%d\n", (uint64_t)offset);
DDUMP(DiskImageRead, data, SectorSize);
return stream.tellg() - pos;
}
off_t
RawDiskImage::write(const uint8_t *data, off_t offset)
{
if (!initialized)
panic("RawDiskImage not initialized");
if (readonly)
panic("Cannot write to a read only disk image");
if (!stream.is_open())
panic("file not open!\n");
if (stream.seekp(offset * SectorSize, ios::beg) < 0)
panic("Could not seek to location in file");
DPRINTF(DiskImageWrite, "write: offset=%d\n", (uint64_t)offset);
DDUMP(DiskImageWrite, data, SectorSize);
streampos pos = stream.tellp();
stream.write((const char *)data, SectorSize);
return stream.tellp() - pos;
}
RawDiskImage *
RawDiskImageParams::create()
{
return new RawDiskImage(this);
}
////////////////////////////////////////////////////////////////////////
//
// Copy on Write Disk image
//
const int CowDiskImage::VersionMajor = 1;
const int CowDiskImage::VersionMinor = 0;
class CowDiskCallback : public Callback
{
private:
CowDiskImage *image;
public:
CowDiskCallback(CowDiskImage *i) : image(i) {}
void process() { image->save(); delete this; }
};
CowDiskImage::CowDiskImage(const Params *p)
: DiskImage(p), filename(p->image_file), child(p->child), table(NULL)
{
if (filename.empty()) {
init(p->table_size);
} else {
if (!open(filename)) {
if (p->read_only)
fatal("could not open read-only file");
init(p->table_size);
}
if (!p->read_only)
registerExitCallback(new CowDiskCallback(this));
}
}
CowDiskImage::~CowDiskImage()
{
SectorTable::iterator i = table->begin();
SectorTable::iterator end = table->end();
while (i != end) {
delete (*i).second;
++i;
}
}
void
SafeRead(ifstream &stream, void *data, int count)
{
stream.read((char *)data, count);
if (!stream.is_open())
panic("file not open");
if (stream.eof())
panic("premature end-of-file");
if (stream.bad() || stream.fail())
panic("error reading cowdisk image");
}
template<class T>
void
SafeRead(ifstream &stream, T &data)
{
SafeRead(stream, &data, sizeof(data));
}
template<class T>
void
SafeReadSwap(ifstream &stream, T &data)
{
SafeRead(stream, &data, sizeof(data));
data = letoh(data); //is this the proper byte order conversion?
}
bool
CowDiskImage::open(const string &file)
{
ifstream stream(file.c_str());
if (!stream.is_open())
return false;
if (stream.fail() || stream.bad())
panic("Error opening %s", file);
uint64_t magic;
SafeRead(stream, magic);
if (memcmp(&magic, "COWDISK!", sizeof(magic)) != 0)
panic("Could not open %s: Invalid magic", file);
uint32_t major, minor;
SafeReadSwap(stream, major);
SafeReadSwap(stream, minor);
if (major != VersionMajor && minor != VersionMinor)
panic("Could not open %s: invalid version %d.%d != %d.%d",
file, major, minor, VersionMajor, VersionMinor);
uint64_t sector_count;
SafeReadSwap(stream, sector_count);
table = new SectorTable(sector_count);
for (uint64_t i = 0; i < sector_count; i++) {
uint64_t offset;
SafeReadSwap(stream, offset);
Sector *sector = new Sector;
SafeRead(stream, sector, sizeof(Sector));
assert(table->find(offset) == table->end());
(*table)[offset] = sector;
}
stream.close();
initialized = true;
return true;
}
void
CowDiskImage::init(int hash_size)
{
table = new SectorTable(hash_size);
initialized = true;
}
void
SafeWrite(ofstream &stream, const void *data, int count)
{
stream.write((const char *)data, count);
if (!stream.is_open())
panic("file not open");
if (stream.eof())
panic("premature end-of-file");
if (stream.bad() || stream.fail())
panic("error reading cowdisk image");
}
template<class T>
void
SafeWrite(ofstream &stream, const T &data)
{
SafeWrite(stream, &data, sizeof(data));
}
template<class T>
void
SafeWriteSwap(ofstream &stream, const T &data)
{
T swappeddata = letoh(data); //is this the proper byte order conversion?
SafeWrite(stream, &swappeddata, sizeof(data));
}
void
CowDiskImage::save()
{
save(filename);
}
void
CowDiskImage::save(const string &file)
{
if (!initialized)
panic("RawDiskImage not initialized");
ofstream stream(file.c_str());
if (!stream.is_open() || stream.fail() || stream.bad())
panic("Error opening %s", file);
uint64_t magic;
memcpy(&magic, "COWDISK!", sizeof(magic));
SafeWrite(stream, magic);
SafeWriteSwap(stream, (uint32_t)VersionMajor);
SafeWriteSwap(stream, (uint32_t)VersionMinor);
SafeWriteSwap(stream, (uint64_t)table->size());
uint64_t size = table->size();
SectorTable::iterator iter = table->begin();
SectorTable::iterator end = table->end();
for (uint64_t i = 0; i < size; i++) {
if (iter == end)
panic("Incorrect Table Size during save of COW disk image");
SafeWriteSwap(stream, (uint64_t)(*iter).first);
SafeWrite(stream, (*iter).second->data, sizeof(Sector));
++iter;
}
stream.close();
}
void
CowDiskImage::writeback()
{
SectorTable::iterator i = table->begin();
SectorTable::iterator end = table->end();
while (i != end) {
child->write((*i).second->data, (*i).first);
++i;
}
}
off_t
CowDiskImage::size() const
{ return child->size(); }
off_t
CowDiskImage::read(uint8_t *data, off_t offset) const
{
if (!initialized)
panic("CowDiskImage not initialized");
if (offset > size())
panic("access out of bounds");
SectorTable::const_iterator i = table->find(offset);
if (i == table->end())
return child->read(data, offset);
else {
memcpy(data, (*i).second->data, SectorSize);
DPRINTF(DiskImageRead, "read: offset=%d\n", (uint64_t)offset);
DDUMP(DiskImageRead, data, SectorSize);
return SectorSize;
}
}
off_t
CowDiskImage::write(const uint8_t *data, off_t offset)
{
if (!initialized)
panic("RawDiskImage not initialized");
if (offset > size())
panic("access out of bounds");
SectorTable::iterator i = table->find(offset);
if (i == table->end()) {
Sector *sector = new Sector;
memcpy(sector, data, SectorSize);
table->insert(make_pair(offset, sector));
} else {
memcpy((*i).second->data, data, SectorSize);
}
DPRINTF(DiskImageWrite, "write: offset=%d\n", (uint64_t)offset);
DDUMP(DiskImageWrite, data, SectorSize);
return SectorSize;
}
void
CowDiskImage::serialize(ostream &os)
{
string cowFilename = name() + ".cow";
SERIALIZE_SCALAR(cowFilename);
save(Checkpoint::dir() + "/" + cowFilename);
}
void
CowDiskImage::unserialize(Checkpoint *cp, const string §ion)
{
string cowFilename;
UNSERIALIZE_SCALAR(cowFilename);
cowFilename = cp->cptDir + "/" + cowFilename;
open(cowFilename);
}
CowDiskImage *
CowDiskImageParams::create()
{
return new CowDiskImage(this);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Nathan Binkert
* Andreas Hansson
*/
#include "base/chunk_generator.hh"
#include "debug/DMA.hh"
#include "debug/Drain.hh"
#include "dev/dma_device.hh"
#include "sim/system.hh"
DmaPort::DmaPort(MemObject *dev, System *s)
: MasterPort(dev->name() + ".dma", dev), device(dev), sendEvent(this),
sys(s), masterId(s->getMasterId(dev->name())),
pendingCount(0), drainManager(NULL),
inRetry(false)
{ }
void
DmaPort::handleResp(PacketPtr pkt, Tick delay)
{
// should always see a response with a sender state
assert(pkt->isResponse());
// get the DMA sender state
DmaReqState *state = dynamic_cast<DmaReqState*>(pkt->senderState);
assert(state);
DPRINTF(DMA, "Received response %s for addr: %#x size: %d nb: %d," \
" tot: %d sched %d\n",
pkt->cmdString(), pkt->getAddr(), pkt->req->getSize(),
state->numBytes, state->totBytes,
state->completionEvent ?
state->completionEvent->scheduled() : 0);
assert(pendingCount != 0);
pendingCount--;
// update the number of bytes received based on the request rather
// than the packet as the latter could be rounded up to line sizes
state->numBytes += pkt->req->getSize();
assert(state->totBytes >= state->numBytes);
// if we have reached the total number of bytes for this DMA
// request, then signal the completion and delete the sate
if (state->totBytes == state->numBytes) {
if (state->completionEvent) {
delay += state->delay;
if (delay)
device->schedule(state->completionEvent, curTick() + delay);
else
state->completionEvent->process();
}
delete state;
}
// delete the request that we created and also the packet
delete pkt->req;
delete pkt;
// we might be drained at this point, if so signal the drain event
if (pendingCount == 0 && drainManager) {
drainManager->signalDrainDone();
drainManager = NULL;
}
}
bool
DmaPort::recvTimingResp(PacketPtr pkt)
{
// We shouldn't ever get a block in ownership state
assert(!(pkt->memInhibitAsserted() && !pkt->sharedAsserted()));
handleResp(pkt);
return true;
}
DmaDevice::DmaDevice(const Params *p)
: PioDevice(p), dmaPort(this, sys)
{ }
void
DmaDevice::init()
{
if (!dmaPort.isConnected())
panic("DMA port of %s not connected to anything!", name());
PioDevice::init();
}
unsigned int
DmaDevice::drain(DrainManager *dm)
{
unsigned int count = pioPort.drain(dm) + dmaPort.drain(dm);
if (count)
setDrainState(Drainable::Draining);
else
setDrainState(Drainable::Drained);
return count;
}
unsigned int
DmaPort::drain(DrainManager *dm)
{
if (pendingCount == 0)
return 0;
drainManager = dm;
DPRINTF(Drain, "DmaPort not drained\n");
return 1;
}
void
DmaPort::recvRetry()
{
assert(transmitList.size());
trySendTimingReq();
}
void
DmaPort::dmaAction(Packet::Command cmd, Addr addr, int size, Event *event,
uint8_t *data, Tick delay, Request::Flags flag)
{
// one DMA request sender state for every action, that is then
// split into many requests and packets based on the block size,
// i.e. cache line size
DmaReqState *reqState = new DmaReqState(event, size, delay);
DPRINTF(DMA, "Starting DMA for addr: %#x size: %d sched: %d\n", addr, size,
event ? event->scheduled() : -1);
for (ChunkGenerator gen(addr, size, peerBlockSize());
!gen.done(); gen.next()) {
Request *req = new Request(gen.addr(), gen.size(), flag, masterId);
PacketPtr pkt = new Packet(req, cmd);
// Increment the data pointer on a write
if (data)
pkt->dataStatic(data + gen.complete());
pkt->senderState = reqState;
DPRINTF(DMA, "--Queuing DMA for addr: %#x size: %d\n", gen.addr(),
gen.size());
queueDma(pkt);
}
// in zero time also initiate the sending of the packets we have
// just created, for atomic this involves actually completing all
// the requests
sendDma();
}
void
DmaPort::queueDma(PacketPtr pkt)
{
transmitList.push_back(pkt);
// remember that we have another packet pending, this will only be
// decremented once a response comes back
pendingCount++;
}
void
DmaPort::trySendTimingReq()
{
// send the first packet on the transmit list and schedule the
// following send if it is successful
PacketPtr pkt = transmitList.front();
DPRINTF(DMA, "Trying to send %s addr %#x\n", pkt->cmdString(),
pkt->getAddr());
inRetry = !sendTimingReq(pkt);
if (!inRetry) {
transmitList.pop_front();
DPRINTF(DMA, "-- Done\n");
// if there is more to do, then do so
if (!transmitList.empty())
// this should ultimately wait for as many cycles as the
// device needs to send the packet, but currently the port
// does not have any known width so simply wait a single
// cycle
device->schedule(sendEvent, device->clockEdge(Cycles(1)));
} else {
DPRINTF(DMA, "-- Failed, waiting for retry\n");
}
DPRINTF(DMA, "TransmitList: %d, inRetry: %d\n",
transmitList.size(), inRetry);
}
void
DmaPort::sendDma()
{
// some kind of selcetion between access methods
// more work is going to have to be done to make
// switching actually work
assert(transmitList.size());
Enums::MemoryMode state = sys->getMemoryMode();
if (state == Enums::timing) {
// if we are either waiting for a retry or are still waiting
// after sending the last packet, then do not proceed
if (inRetry || sendEvent.scheduled()) {
DPRINTF(DMA, "Can't send immediately, waiting to send\n");
return;
}
trySendTimingReq();
} else if (state == Enums::atomic) {
// send everything there is to send in zero time
while (!transmitList.empty()) {
PacketPtr pkt = transmitList.front();
transmitList.pop_front();
DPRINTF(DMA, "Sending DMA for addr: %#x size: %d\n",
pkt->req->getPaddr(), pkt->req->getSize());
Tick lat = sendAtomic(pkt);
handleResp(pkt, lat);
}
} else
panic("Unknown memory mode.");
}
BaseMasterPort &
DmaDevice::getMasterPort(const std::string &if_name, PortID idx)
{
if (if_name == "dma") {
return dmaPort;
}
return PioDevice::getMasterPort(if_name, idx);
}
<commit_msg>dev: Fix infinite recursion in DMA devices<commit_after>/*
* Copyright (c) 2012 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Nathan Binkert
* Andreas Hansson
*/
#include "base/chunk_generator.hh"
#include "debug/DMA.hh"
#include "debug/Drain.hh"
#include "dev/dma_device.hh"
#include "sim/system.hh"
DmaPort::DmaPort(MemObject *dev, System *s)
: MasterPort(dev->name() + ".dma", dev), device(dev), sendEvent(this),
sys(s), masterId(s->getMasterId(dev->name())),
pendingCount(0), drainManager(NULL),
inRetry(false)
{ }
void
DmaPort::handleResp(PacketPtr pkt, Tick delay)
{
// should always see a response with a sender state
assert(pkt->isResponse());
// get the DMA sender state
DmaReqState *state = dynamic_cast<DmaReqState*>(pkt->senderState);
assert(state);
DPRINTF(DMA, "Received response %s for addr: %#x size: %d nb: %d," \
" tot: %d sched %d\n",
pkt->cmdString(), pkt->getAddr(), pkt->req->getSize(),
state->numBytes, state->totBytes,
state->completionEvent ?
state->completionEvent->scheduled() : 0);
assert(pendingCount != 0);
pendingCount--;
// update the number of bytes received based on the request rather
// than the packet as the latter could be rounded up to line sizes
state->numBytes += pkt->req->getSize();
assert(state->totBytes >= state->numBytes);
// if we have reached the total number of bytes for this DMA
// request, then signal the completion and delete the sate
if (state->totBytes == state->numBytes) {
if (state->completionEvent) {
delay += state->delay;
device->schedule(state->completionEvent, curTick() + delay);
}
delete state;
}
// delete the request that we created and also the packet
delete pkt->req;
delete pkt;
// we might be drained at this point, if so signal the drain event
if (pendingCount == 0 && drainManager) {
drainManager->signalDrainDone();
drainManager = NULL;
}
}
bool
DmaPort::recvTimingResp(PacketPtr pkt)
{
// We shouldn't ever get a block in ownership state
assert(!(pkt->memInhibitAsserted() && !pkt->sharedAsserted()));
handleResp(pkt);
return true;
}
DmaDevice::DmaDevice(const Params *p)
: PioDevice(p), dmaPort(this, sys)
{ }
void
DmaDevice::init()
{
if (!dmaPort.isConnected())
panic("DMA port of %s not connected to anything!", name());
PioDevice::init();
}
unsigned int
DmaDevice::drain(DrainManager *dm)
{
unsigned int count = pioPort.drain(dm) + dmaPort.drain(dm);
if (count)
setDrainState(Drainable::Draining);
else
setDrainState(Drainable::Drained);
return count;
}
unsigned int
DmaPort::drain(DrainManager *dm)
{
if (pendingCount == 0)
return 0;
drainManager = dm;
DPRINTF(Drain, "DmaPort not drained\n");
return 1;
}
void
DmaPort::recvRetry()
{
assert(transmitList.size());
trySendTimingReq();
}
void
DmaPort::dmaAction(Packet::Command cmd, Addr addr, int size, Event *event,
uint8_t *data, Tick delay, Request::Flags flag)
{
// one DMA request sender state for every action, that is then
// split into many requests and packets based on the block size,
// i.e. cache line size
DmaReqState *reqState = new DmaReqState(event, size, delay);
DPRINTF(DMA, "Starting DMA for addr: %#x size: %d sched: %d\n", addr, size,
event ? event->scheduled() : -1);
for (ChunkGenerator gen(addr, size, peerBlockSize());
!gen.done(); gen.next()) {
Request *req = new Request(gen.addr(), gen.size(), flag, masterId);
PacketPtr pkt = new Packet(req, cmd);
// Increment the data pointer on a write
if (data)
pkt->dataStatic(data + gen.complete());
pkt->senderState = reqState;
DPRINTF(DMA, "--Queuing DMA for addr: %#x size: %d\n", gen.addr(),
gen.size());
queueDma(pkt);
}
// in zero time also initiate the sending of the packets we have
// just created, for atomic this involves actually completing all
// the requests
sendDma();
}
void
DmaPort::queueDma(PacketPtr pkt)
{
transmitList.push_back(pkt);
// remember that we have another packet pending, this will only be
// decremented once a response comes back
pendingCount++;
}
void
DmaPort::trySendTimingReq()
{
// send the first packet on the transmit list and schedule the
// following send if it is successful
PacketPtr pkt = transmitList.front();
DPRINTF(DMA, "Trying to send %s addr %#x\n", pkt->cmdString(),
pkt->getAddr());
inRetry = !sendTimingReq(pkt);
if (!inRetry) {
transmitList.pop_front();
DPRINTF(DMA, "-- Done\n");
// if there is more to do, then do so
if (!transmitList.empty())
// this should ultimately wait for as many cycles as the
// device needs to send the packet, but currently the port
// does not have any known width so simply wait a single
// cycle
device->schedule(sendEvent, device->clockEdge(Cycles(1)));
} else {
DPRINTF(DMA, "-- Failed, waiting for retry\n");
}
DPRINTF(DMA, "TransmitList: %d, inRetry: %d\n",
transmitList.size(), inRetry);
}
void
DmaPort::sendDma()
{
// some kind of selcetion between access methods
// more work is going to have to be done to make
// switching actually work
assert(transmitList.size());
Enums::MemoryMode state = sys->getMemoryMode();
if (state == Enums::timing) {
// if we are either waiting for a retry or are still waiting
// after sending the last packet, then do not proceed
if (inRetry || sendEvent.scheduled()) {
DPRINTF(DMA, "Can't send immediately, waiting to send\n");
return;
}
trySendTimingReq();
} else if (state == Enums::atomic) {
// send everything there is to send in zero time
while (!transmitList.empty()) {
PacketPtr pkt = transmitList.front();
transmitList.pop_front();
DPRINTF(DMA, "Sending DMA for addr: %#x size: %d\n",
pkt->req->getPaddr(), pkt->req->getSize());
Tick lat = sendAtomic(pkt);
handleResp(pkt, lat);
}
} else
panic("Unknown memory mode.");
}
BaseMasterPort &
DmaDevice::getMasterPort(const std::string &if_name, PortID idx)
{
if (if_name == "dma") {
return dmaPort;
}
return PioDevice::getMasterPort(if_name, idx);
}
<|endoftext|>
|
<commit_before>// Copyright 2011 Google Inc. 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 "disk_interface.h"
#include <algorithm>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef _WIN32
#include <windows.h>
#include <direct.h> // _mkdir
#endif
#include "util.h"
namespace {
string DirName(const string& path) {
#ifdef _WIN32
const char kPathSeparators[] = "\\/";
#else
const char kPathSeparators[] = "/";
#endif
string::size_type slash_pos = path.find_last_of(kPathSeparators);
if (slash_pos == string::npos)
return string(); // Nothing to do.
const char* const kEnd = kPathSeparators + strlen(kPathSeparators);
while (slash_pos > 0 &&
std::find(kPathSeparators, kEnd, path[slash_pos - 1]) != kEnd)
--slash_pos;
return path.substr(0, slash_pos);
}
int MakeDir(const string& path) {
#ifdef _WIN32
return _mkdir(path.c_str());
#else
return mkdir(path.c_str(), 0777);
#endif
}
TimeStamp TimeStampFromFileTime(const FILETIME& filetime) {
// FILETIME is in 100-nanosecond increments since the Windows epoch.
// We don't much care about epoch correctness but we do want the
// resulting value to fit in an integer.
uint64_t mtime = ((uint64_t)filetime.dwHighDateTime << 32) |
((uint64_t)filetime.dwLowDateTime);
mtime /= 1000000000LL / 100; // 100ns -> s.
mtime -= 12622770400LL; // 1600 epoch -> 2000 epoch (subtract 400 years).
return (TimeStamp)mtime;
}
TimeStamp StatSingleFile(const string& path, bool quiet) {
WIN32_FILE_ATTRIBUTE_DATA attrs;
if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &attrs)) {
DWORD err = GetLastError();
if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
return 0;
if (!quiet) {
Error("GetFileAttributesEx(%s): %s", path.c_str(),
GetLastErrorString().c_str());
}
return -1;
}
return TimeStampFromFileTime(attrs.ftLastWriteTime);
}
void StatAllFilesInDir(const string& dir, map<string, TimeStamp>* stamps) {
// FindExInfoBasic is 30% faster than FindExInfoStandard.
WIN32_FIND_DATAA ffd;
HANDLE hFind = FindFirstFileExA((dir + "\\*").c_str(), FindExInfoBasic, &ffd,
FindExSearchNameMatch, NULL, 0);
if (hFind == INVALID_HANDLE_VALUE) {
fprintf(stderr, "fail %s", dir.c_str());
exit(-1);
}
do {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
continue;
string lowername = ffd.cFileName;
transform(lowername.begin(), lowername.end(), lowername.begin(), ::tolower);
const FILETIME& filetime = ffd.ftLastWriteTime;
(*stamps).insert(make_pair(lowername, TimeStampFromFileTime(filetime)));
} while (FindNextFileA(hFind, &ffd));
FindClose(hFind);
}
} // namespace
// DiskInterface ---------------------------------------------------------------
bool DiskInterface::MakeDirs(const string& path) {
string dir = DirName(path);
if (dir.empty())
return true; // Reached root; assume it's there.
TimeStamp mtime = Stat(dir);
if (mtime < 0)
return false; // Error.
if (mtime > 0)
return true; // Exists already; we're done.
// Directory doesn't exist. Try creating its parent first.
bool success = MakeDirs(dir);
if (!success)
return false;
return MakeDir(dir);
}
// RealDiskInterface -----------------------------------------------------------
TimeStamp RealDiskInterface::Stat(const string& path) {
#ifdef _WIN32
// MSDN: "Naming Files, Paths, and Namespaces"
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
if (!path.empty() && path[0] != '\\' && path.size() > MAX_PATH) {
if (!quiet_) {
Error("Stat(%s): Filename longer than %i characters",
path.c_str(), MAX_PATH);
}
return -1;
}
if (!use_cache_)
return StatSingleFile(path, quiet_);
string dir = DirName(path);
string base(path.substr(dir.size() ? dir.size() + 1 : 0));
transform(dir.begin(), dir.end(), dir.begin(), ::tolower);
transform(base.begin(), base.end(), base.begin(), ::tolower);
Cache::iterator ci = cache_.find(dir);
if (ci == cache_.end()) {
DirCache* dc = new DirCache;
StatAllFilesInDir(dir.empty() ? "." : dir, dc);
ci = cache_.insert(make_pair(dir, dc)).first;
}
DirCache::iterator di = ci->second->find(base);
return di != ci->second->end() ? di->second : 0;
#else
struct stat st;
if (stat(path.c_str(), &st) < 0) {
if (errno == ENOENT || errno == ENOTDIR)
return 0;
if (!quiet_) {
Error("stat(%s): %s", path.c_str(), strerror(errno));
}
return -1;
}
return st.st_mtime;
#endif
}
bool RealDiskInterface::WriteFile(const string& path, const string& contents) {
FILE* fp = fopen(path.c_str(), "w");
if (fp == NULL) {
Error("WriteFile(%s): Unable to create file. %s",
path.c_str(), strerror(errno));
return false;
}
if (fwrite(contents.data(), 1, contents.length(), fp) < contents.length()) {
Error("WriteFile(%s): Unable to write to the file. %s",
path.c_str(), strerror(errno));
fclose(fp);
return false;
}
if (fclose(fp) == EOF) {
Error("WriteFile(%s): Unable to close the file. %s",
path.c_str(), strerror(errno));
return false;
}
return true;
}
bool RealDiskInterface::MakeDir(const string& path) {
if (::MakeDir(path) < 0) {
if (errno == EEXIST) {
return true;
}
Error("mkdir(%s): %s", path.c_str(), strerror(errno));
return false;
}
return true;
}
string RealDiskInterface::ReadFile(const string& path, string* err) {
string contents;
int ret = ::ReadFile(path, &contents, err);
if (ret == -ENOENT) {
// Swallow ENOENT.
err->clear();
}
return contents;
}
int RealDiskInterface::RemoveFile(const string& path) {
if (remove(path.c_str()) < 0) {
switch (errno) {
case ENOENT:
return 1;
default:
Error("remove(%s): %s", path.c_str(), strerror(errno));
return -1;
}
} else {
return 0;
}
}
<commit_msg>error checking<commit_after>// Copyright 2011 Google Inc. 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 "disk_interface.h"
#include <algorithm>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef _WIN32
#include <windows.h>
#include <direct.h> // _mkdir
#endif
#include "util.h"
namespace {
string DirName(const string& path) {
#ifdef _WIN32
const char kPathSeparators[] = "\\/";
#else
const char kPathSeparators[] = "/";
#endif
string::size_type slash_pos = path.find_last_of(kPathSeparators);
if (slash_pos == string::npos)
return string(); // Nothing to do.
const char* const kEnd = kPathSeparators + strlen(kPathSeparators);
while (slash_pos > 0 &&
std::find(kPathSeparators, kEnd, path[slash_pos - 1]) != kEnd)
--slash_pos;
return path.substr(0, slash_pos);
}
int MakeDir(const string& path) {
#ifdef _WIN32
return _mkdir(path.c_str());
#else
return mkdir(path.c_str(), 0777);
#endif
}
TimeStamp TimeStampFromFileTime(const FILETIME& filetime) {
// FILETIME is in 100-nanosecond increments since the Windows epoch.
// We don't much care about epoch correctness but we do want the
// resulting value to fit in an integer.
uint64_t mtime = ((uint64_t)filetime.dwHighDateTime << 32) |
((uint64_t)filetime.dwLowDateTime);
mtime /= 1000000000LL / 100; // 100ns -> s.
mtime -= 12622770400LL; // 1600 epoch -> 2000 epoch (subtract 400 years).
return (TimeStamp)mtime;
}
TimeStamp StatSingleFile(const string& path, bool quiet) {
WIN32_FILE_ATTRIBUTE_DATA attrs;
if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &attrs)) {
DWORD err = GetLastError();
if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
return 0;
if (!quiet) {
Error("GetFileAttributesEx(%s): %s", path.c_str(),
GetLastErrorString().c_str());
}
return -1;
}
return TimeStampFromFileTime(attrs.ftLastWriteTime);
}
void StatAllFilesInDir(const string& dir, map<string, TimeStamp>* stamps,
bool quiet) {
// FindExInfoBasic is 30% faster than FindExInfoStandard.
WIN32_FIND_DATAA ffd;
HANDLE hFind = FindFirstFileExA((dir + "\\*").c_str(), FindExInfoBasic, &ffd,
FindExSearchNameMatch, NULL, 0);
if (hFind == INVALID_HANDLE_VALUE) {
DWORD err = GetLastError();
if (err != ERROR_FILE_NOT_FOUND && err != ERROR_PATH_NOT_FOUND && !quiet) {
Error("FindFirstFileExA(%s): %s", dir.c_str(),
GetLastErrorString().c_str());
}
return;
}
do {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
continue;
string lowername = ffd.cFileName;
transform(lowername.begin(), lowername.end(), lowername.begin(), ::tolower);
stamps->insert(make_pair(lowername,
TimeStampFromFileTime(ffd.ftLastWriteTime)));
} while (FindNextFileA(hFind, &ffd));
FindClose(hFind);
}
} // namespace
// DiskInterface ---------------------------------------------------------------
bool DiskInterface::MakeDirs(const string& path) {
string dir = DirName(path);
if (dir.empty())
return true; // Reached root; assume it's there.
TimeStamp mtime = Stat(dir);
if (mtime < 0)
return false; // Error.
if (mtime > 0)
return true; // Exists already; we're done.
// Directory doesn't exist. Try creating its parent first.
bool success = MakeDirs(dir);
if (!success)
return false;
return MakeDir(dir);
}
// RealDiskInterface -----------------------------------------------------------
TimeStamp RealDiskInterface::Stat(const string& path) {
#ifdef _WIN32
// MSDN: "Naming Files, Paths, and Namespaces"
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
if (!path.empty() && path[0] != '\\' && path.size() > MAX_PATH) {
if (!quiet_) {
Error("Stat(%s): Filename longer than %i characters",
path.c_str(), MAX_PATH);
}
return -1;
}
if (!use_cache_)
return StatSingleFile(path, quiet_);
string dir = DirName(path);
string base(path.substr(dir.size() ? dir.size() + 1 : 0));
transform(dir.begin(), dir.end(), dir.begin(), ::tolower);
transform(base.begin(), base.end(), base.begin(), ::tolower);
Cache::iterator ci = cache_.find(dir);
if (ci == cache_.end()) {
DirCache* dc = new DirCache;
StatAllFilesInDir(dir.empty() ? "." : dir, dc, quiet_);
ci = cache_.insert(make_pair(dir, dc)).first;
}
DirCache::iterator di = ci->second->find(base);
return di != ci->second->end() ? di->second : 0;
#else
struct stat st;
if (stat(path.c_str(), &st) < 0) {
if (errno == ENOENT || errno == ENOTDIR)
return 0;
if (!quiet_) {
Error("stat(%s): %s", path.c_str(), strerror(errno));
}
return -1;
}
return st.st_mtime;
#endif
}
bool RealDiskInterface::WriteFile(const string& path, const string& contents) {
FILE* fp = fopen(path.c_str(), "w");
if (fp == NULL) {
Error("WriteFile(%s): Unable to create file. %s",
path.c_str(), strerror(errno));
return false;
}
if (fwrite(contents.data(), 1, contents.length(), fp) < contents.length()) {
Error("WriteFile(%s): Unable to write to the file. %s",
path.c_str(), strerror(errno));
fclose(fp);
return false;
}
if (fclose(fp) == EOF) {
Error("WriteFile(%s): Unable to close the file. %s",
path.c_str(), strerror(errno));
return false;
}
return true;
}
bool RealDiskInterface::MakeDir(const string& path) {
if (::MakeDir(path) < 0) {
if (errno == EEXIST) {
return true;
}
Error("mkdir(%s): %s", path.c_str(), strerror(errno));
return false;
}
return true;
}
string RealDiskInterface::ReadFile(const string& path, string* err) {
string contents;
int ret = ::ReadFile(path, &contents, err);
if (ret == -ENOENT) {
// Swallow ENOENT.
err->clear();
}
return contents;
}
int RealDiskInterface::RemoveFile(const string& path) {
if (remove(path.c_str()) < 0) {
switch (errno) {
case ENOENT:
return 1;
default:
Error("remove(%s): %s", path.c_str(), strerror(errno));
return -1;
}
} else {
return 0;
}
}
<|endoftext|>
|
<commit_before><commit_msg>Small cleanup<commit_after><|endoftext|>
|
<commit_before>#include <chrono>
#include <iostream>
#include <random>
#include "xcdat.hpp"
using namespace xcdat;
namespace {
constexpr int RUNS = 10;
class StopWatch {
public:
using hrc = std::chrono::high_resolution_clock;
StopWatch() : tp_{hrc::now()} {}
double sec() const {
const auto tp = hrc::now() - tp_;
return std::chrono::duration<double>(tp).count();
}
double milli_sec() const {
const auto tp = hrc::now() - tp_;
return std::chrono::duration<double, std::milli>(tp).count();
}
double micro_sec() const {
const auto tp = hrc::now() - tp_;
return std::chrono::duration<double, std::micro>(tp).count();
}
private:
hrc::time_point tp_;
};
size_t read_keys(const char* file_name, std::vector<std::string>& keys) {
std::ifstream ifs{file_name};
if (!ifs) {
return 0;
}
size_t size = 0;
for (std::string line; std::getline(ifs, line);) {
keys.push_back(line);
size += line.length() + 1; // with terminator
}
return size;
}
std::vector<std::string_view>
extract_views(const std::vector<std::string>& keys) {
std::vector<std::string_view> views(keys.size());
for (size_t i = 0; i < keys.size(); ++i) {
views[i] = keys[i];
}
return views;
};
void show_usage(std::ostream& os) {
os << "xcdat build <type> <key> <dict>\n";
os << "\t<type>\t'1' for DACs; '2' for FDACs.\n";
os << "\t<key> \tinput file of a set of keys.\n";
os << "\t<dict>\toutput file of the dictionary.\n";
os << "xcdat query <type> <dict> <limit>\n";
os << "\t<type> \t'1' for DACs; '2' for FDACs.\n";
os << "\t<dict> \tinput file of the dictionary.\n";
os << "\t<limit>\tlimit at lookup (default=10).\n";
os << "xcdat bench <type> <dict> <key>\n";
os << "\t<type>\t'1' for DACs; '2' for FDACs.\n";
os << "\t<dict>\tinput file of the dictionary.\n";
os << "\t<key> \tinput file of keys for benchmark.\n";
os.flush();
}
template<bool Fast>
int build(std::vector<std::string>& args) {
if (args.size() != 4) {
show_usage(std::cerr);
return 1;
}
std::vector<std::string> keys_buffer;
auto raw_size = read_keys(args[2].c_str(), keys_buffer);
if (raw_size == 0) {
std::cerr << "open error : " << args[2] << std::endl;
return 1;
}
auto keys = extract_views(keys_buffer);
Trie<Fast> trie;
try {
StopWatch sw;
trie = TrieBuilder::build<Fast>(keys);
std::cout << "constr. time: " << sw.sec() << " sec" << std::endl;
} catch (const xcdat::TrieBuilder::Exception& ex) {
std::cerr << ex.what() << std::endl;
return 1;
}
std::cout << "cmpr. ratio: "
<< static_cast<double>(trie.size_in_bytes()) / raw_size
<< std::endl;
trie.show_stat(std::cout);
{
std::ofstream ofs{args[3] + (Fast ? ".fdac" : ".dac")};
if (!ofs) {
std::cerr << "open error : " << args[3] << std::endl;
return 1;
}
trie.write(ofs);
}
return 0;
}
template<bool Fast>
int query(std::vector<std::string>& args) {
if (args.size() != 3 && args.size() != 4) {
show_usage(std::cerr);
return 1;
}
Trie<Fast> trie;
{
std::ifstream ifs(args[2]);
if (!ifs) {
std::cerr << "open error : " << args[2] << std::endl;
return 1;
}
trie = Trie<Fast>(ifs);
}
size_t limit = 10;
if (args.size() == 4) {
limit = std::stoull(args.back());
}
std::string query;
while (true){
std::cout << "> " << std::flush;
std::getline(std::cin, query);
if (query.empty()){
break;
}
std::cout << "Lookup" << std::endl;
auto id = trie.lookup(query);
if (id == Trie<Fast>::NOT_FOUND) {
std::cout << "not found" << std::endl;
} else {
std::cout << id << '\t' << query << std::endl;
}
std::cout << "Common Prefix Lookup" << std::endl;
{
size_t N = 0;
auto it = trie.make_prefix_iterator(query);
while (N < limit && it.next()) {
std::cout << it.id() << '\t' << it.key() << std::endl;
++N;
}
size_t M = 0;
while (it.next()) {
++M;
}
if (M != 0) {
std::cout << "and more..." << std::endl;
}
std::cout << N + M << " found" << std::endl;
}
std::cout << "Predictive Lookup" << std::endl;
{
size_t N = 0;
auto it = trie.make_predictive_iterator(query);
while (N < limit && it.next()) {
std::cout << it.id() << '\t' << it.key() << std::endl;
++N;
}
size_t M = 0;
while (it.next()) {
++M;
}
if (M != 0) {
std::cout << "and more..." << std::endl;
}
std::cout << N + M << " found" << std::endl;
}
}
return 0;
}
template<bool Fast>
int bench(std::vector<std::string>& args) {
if (args.size() != 4) {
show_usage(std::cerr);
return 1;
}
Trie<Fast> trie;
{
std::ifstream ifs(args[2]);
if (!ifs) {
std::cerr << "open error : " << args[2] << std::endl;
return 1;
}
trie = Trie<Fast>(ifs);
}
std::vector<std::string> keys_buffer;
if (read_keys(args[3].c_str(), keys_buffer) == 0) {
std::cerr << "open error : " << args[3] << std::endl;
return 1;
}
auto keys = extract_views(keys_buffer);
std::vector<id_type> ids(keys.size());
for (size_t i = 0; i < keys.size(); ++i) {
ids[i] = trie.lookup(keys[i]);
}
{
std::cout << "Lookup benchmark on " << RUNS << " runs" << std::endl;
StopWatch sw;
for (uint32_t r = 0; r < RUNS; ++r) {
for (size_t i = 0; i < keys.size(); ++i) {
if (trie.lookup(keys[i]) == Trie<Fast>::NOT_FOUND) {
std::cerr << "Failed to lookup " << keys_buffer[i] << std::endl;
return 1;
}
}
}
std::cout << sw.micro_sec() / RUNS / keys.size()
<< " us per str" << std::endl;
}
{
std::cout << "Access benchmark on " << RUNS << " runs" << std::endl;
StopWatch sw;
for (uint32_t r = 0; r < RUNS; ++r) {
for (auto id : ids) {
auto dec = trie.access(id);
if (dec.empty()) {
std::cerr << "Failed to access " << id << std::endl;
return 1;
}
}
}
std::cout << sw.micro_sec() / RUNS / ids.size()
<< " us per ID" << std::endl;
}
return 0;
}
} // namespace
int main(int argc, const char* argv[]) {
if (argc < 3) {
show_usage(std::cerr);
return 1;
}
std::vector<std::string> args;
for (int i = 1; i < argc; ++i) {
args.emplace_back(std::string{argv[i]});
}
bool is_fast;
if (args[1][0] == '1') {
is_fast = false;
} else if (args[1][0] == '2') {
is_fast = true;
} else {
show_usage(std::cerr);
return 1;
}
if (args[0] == "build") {
return is_fast ? build<true>(args) : build<false>(args);
} else if (args[0] == "query") {
return is_fast ? query<true>(args) : query<false>(args);
} else if (args[0] == "bench") {
return is_fast ? bench<true>(args) : bench<false>(args);
}
show_usage(std::cerr);
return 1;
}
<commit_msg>Modify args<commit_after>#include <chrono>
#include <iostream>
#include <random>
#include "xcdat.hpp"
using namespace xcdat;
namespace {
constexpr int RUNS = 10;
class StopWatch {
public:
using hrc = std::chrono::high_resolution_clock;
StopWatch() : tp_{hrc::now()} {}
double sec() const {
const auto tp = hrc::now() - tp_;
return std::chrono::duration<double>(tp).count();
}
double milli_sec() const {
const auto tp = hrc::now() - tp_;
return std::chrono::duration<double, std::milli>(tp).count();
}
double micro_sec() const {
const auto tp = hrc::now() - tp_;
return std::chrono::duration<double, std::micro>(tp).count();
}
private:
hrc::time_point tp_;
};
size_t read_keys(const char* file_name, std::vector<std::string>& keys) {
std::ifstream ifs{file_name};
if (!ifs) {
return 0;
}
size_t size = 0;
for (std::string line; std::getline(ifs, line);) {
keys.push_back(line);
size += line.length() + 1; // with terminator
}
return size;
}
std::vector<std::string_view>
extract_views(const std::vector<std::string>& keys) {
std::vector<std::string_view> views(keys.size());
for (size_t i = 0; i < keys.size(); ++i) {
views[i] = keys[i];
}
return views;
};
void show_usage(std::ostream& os) {
os << "xcdat build <type> <key> <dict>\n";
os << "\t<type>\t1: DACs, 2: FDACs\n";
os << "\t<key> \tInput file name of a set of keys (must be sorted)\n";
os << "\t<dict>\tOutput file name of the dictionary (optional)\n";
os << "\t \tIf omitted, <key>.dacs or <key>.fdacs is output\n";
os << "xcdat query <type> <dict> <limit>\n";
os << "\t<type> \t1: DACs, 2: FDACs\n";
os << "\t<dict> \tInput file name of the dictionary\n";
os << "\t<limit>\tLimit of #results (optional, default=10)\n";
os << "xcdat bench <type> <dict> <key>\n";
os << "\t<type>\t1: DACs, 2: FDACs\n";
os << "\t<dict>\tInput file name of the dictionary\n";
os << "\t<key> \tInput file name of keys for benchmark\n";
os.flush();
}
template<bool Fast>
int build(std::vector<std::string>& args) {
if (args.size() != 3 && args.size() != 4) {
show_usage(std::cerr);
return 1;
}
std::vector<std::string> keys_buffer;
auto raw_size = read_keys(args[2].c_str(), keys_buffer);
if (raw_size == 0) {
std::cerr << "open error : " << args[2] << std::endl;
return 1;
}
auto keys = extract_views(keys_buffer);
Trie<Fast> trie;
try {
StopWatch sw;
trie = TrieBuilder::build<Fast>(keys);
std::cout << "constr. time: " << sw.sec() << " sec" << std::endl;
} catch (const xcdat::TrieBuilder::Exception& ex) {
std::cerr << ex.what() << std::endl;
return 1;
}
std::cout << "cmpr. ratio: "
<< static_cast<double>(trie.size_in_bytes()) / raw_size
<< std::endl;
trie.show_stat(std::cout);
{
std::string out_name;
if (args.size() == 4) {
out_name = args[3];
} else {
out_name = args[2] + (Fast ? ".fdac" : ".dac");
}
std::ofstream ofs{out_name};
if (!ofs) {
std::cerr << "open error : " << out_name << std::endl;
return 1;
}
trie.write(ofs);
}
return 0;
}
template<bool Fast>
int query(std::vector<std::string>& args) {
if (args.size() != 3 && args.size() != 4) {
show_usage(std::cerr);
return 1;
}
Trie<Fast> trie;
{
std::ifstream ifs(args[2]);
if (!ifs) {
std::cerr << "open error : " << args[2] << std::endl;
return 1;
}
trie = Trie<Fast>(ifs);
}
size_t limit = 10;
if (args.size() == 4) {
limit = std::stoull(args.back());
}
std::string query;
while (true){
std::cout << "> " << std::flush;
std::getline(std::cin, query);
if (query.empty()){
break;
}
std::cout << "Lookup" << std::endl;
auto id = trie.lookup(query);
if (id == Trie<Fast>::NOT_FOUND) {
std::cout << "not found" << std::endl;
} else {
std::cout << id << '\t' << query << std::endl;
}
std::cout << "Common Prefix Lookup" << std::endl;
{
size_t N = 0;
auto it = trie.make_prefix_iterator(query);
while (N < limit && it.next()) {
std::cout << it.id() << '\t' << it.key() << std::endl;
++N;
}
size_t M = 0;
while (it.next()) {
++M;
}
if (M != 0) {
std::cout << "and more..." << std::endl;
}
std::cout << N + M << " found" << std::endl;
}
std::cout << "Predictive Lookup" << std::endl;
{
size_t N = 0;
auto it = trie.make_predictive_iterator(query);
while (N < limit && it.next()) {
std::cout << it.id() << '\t' << it.key() << std::endl;
++N;
}
size_t M = 0;
while (it.next()) {
++M;
}
if (M != 0) {
std::cout << "and more..." << std::endl;
}
std::cout << N + M << " found" << std::endl;
}
}
return 0;
}
template<bool Fast>
int bench(std::vector<std::string>& args) {
if (args.size() != 4) {
show_usage(std::cerr);
return 1;
}
Trie<Fast> trie;
{
std::ifstream ifs(args[2]);
if (!ifs) {
std::cerr << "open error : " << args[2] << std::endl;
return 1;
}
trie = Trie<Fast>(ifs);
}
std::vector<std::string> keys_buffer;
if (read_keys(args[3].c_str(), keys_buffer) == 0) {
std::cerr << "open error : " << args[3] << std::endl;
return 1;
}
auto keys = extract_views(keys_buffer);
std::vector<id_type> ids(keys.size());
std::cout << "Warm up" << std::endl;
for (size_t i = 0; i < keys.size(); ++i) {
ids[i] = trie.lookup(keys[i]);
if (ids[i] == Trie<Fast>::NOT_FOUND) {
std::cerr << "A non-registered key is included, "
<< keys_buffer[i] << std::endl;
return 1;
}
}
{
std::cout << "Lookup benchmark on " << RUNS << " runs" << std::endl;
StopWatch sw;
for (uint32_t r = 0; r < RUNS; ++r) {
for (size_t i = 0; i < keys.size(); ++i) {
if (trie.lookup(keys[i]) != ids[i]) {
std::cerr << "Critical lookup error ʅ( ՞ਊ՞)ʃ" << std::endl;
return 1;
}
}
}
std::cout << sw.micro_sec() / RUNS / keys.size()
<< " us per str" << std::endl;
}
{
std::cout << "Access benchmark on " << RUNS << " runs" << std::endl;
StopWatch sw;
for (uint32_t r = 0; r < RUNS; ++r) {
for (auto id : ids) {
auto dec = trie.access(id);
if (dec.empty()) {
std::cerr << "Critical access error ʅ( ՞ਊ՞)ʃ" << std::endl;
return 1;
}
}
}
std::cout << sw.micro_sec() / RUNS / ids.size()
<< " us per ID" << std::endl;
}
return 0;
}
} // namespace
int main(int argc, const char* argv[]) {
if (argc < 3) {
show_usage(std::cerr);
return 1;
}
std::vector<std::string> args;
for (int i = 1; i < argc; ++i) {
args.emplace_back(std::string{argv[i]});
}
bool is_fast;
if (args[1][0] == '1') {
is_fast = false;
} else if (args[1][0] == '2') {
is_fast = true;
} else {
show_usage(std::cerr);
return 1;
}
if (args[0] == "build") {
return is_fast ? build<true>(args) : build<false>(args);
} else if (args[0] == "query") {
return is_fast ? query<true>(args) : query<false>(args);
} else if (args[0] == "bench") {
return is_fast ? bench<true>(args) : bench<false>(args);
}
show_usage(std::cerr);
return 1;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: jumpmatrix.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2007-07-06 12:34:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_JUMPMATRIX_HXX
#define SC_JUMPMATRIX_HXX
#ifndef SC_TOKEN_HXX
#include "token.hxx"
#endif
#ifndef SC_MATRIX_HXX
#include "scmatrix.hxx"
#endif
#ifndef SC_ERRORCODES_HXX
#include "errorcodes.hxx"
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#include <vector>
typedef ::std::vector< ScToken*> ScTokenVec;
struct ScJumpMatrixEntry
{
double fBool; // 0:= false 1:= true also if no-path
// other values may contain error conditions like NAN and INF
short nStart; // start of path (actually start-1, see ScTokenIterator)
short nNext; // next after path
// jump path exists if nStart != nNext, else no path
short nStop; // optional stop of path (nPC < nStop)
void SetJump( double fBoolP, short nStartP, short nNextP, short nStopP )
{
fBool = fBoolP;
nStart = nStartP;
nNext = nNextP;
nStop = nStopP;
}
void GetJump( double& rBool, short& rStart, short& rNext, short& rStop )
{
rBool = fBool;
rStart = nStart;
rNext = nNext;
rStop = nStop;
}
};
class ScJumpMatrix
{
ScJumpMatrixEntry* pJump; // the jumps
ScMatrixRef pMat; // the results
ScTokenVec* pParams; // parameter stack
SCSIZE nCols;
SCSIZE nRows;
SCSIZE nCurCol;
SCSIZE nCurRow;
bool bStarted;
// not implemented, prevent usage
ScJumpMatrix( const ScJumpMatrix& );
ScJumpMatrix& operator=( const ScJumpMatrix& );
public:
ScJumpMatrix( SCSIZE nColsP, SCSIZE nRowsP )
: pJump( new ScJumpMatrixEntry[ nColsP * nRowsP ] )
, pMat( new ScMatrix( nColsP, nRowsP) )
, pParams( NULL )
, nCols( nColsP )
, nRows( nRowsP )
, nCurCol( 0 )
, nCurRow( 0 )
, bStarted( false )
{
// Initialize result matrix in case of
// a premature end of the interpreter
// due to errors.
pMat->FillDouble( CreateDoubleError(
NOTAVAILABLE), 0, 0, nCols-1,
nRows-1);
/*! pJump not initialized */
}
~ScJumpMatrix()
{
if ( pParams )
{
for ( ScTokenVec::iterator i =
pParams->begin(); i !=
pParams->end(); ++i )
{
(*i)->DecRef();
}
delete pParams;
}
delete [] pJump;
}
void GetDimensions( SCSIZE& rCols, SCSIZE& rRows ) const
{
rCols = nCols;
rRows = nRows;
}
void SetJump( SCSIZE nCol, SCSIZE nRow, double fBool,
short nStart, short nNext,
short nStop = SHRT_MAX )
{
pJump[ (ULONG)nCol * nRows + nRow ].
SetJump( fBool, nStart, nNext, nStop);
}
void GetJump( SCSIZE nCol, SCSIZE nRow, double& rBool,
short& rStart, short& rNext,
short& rStop ) const
{
pJump[ (ULONG)nCol * nRows + nRow ].
GetJump( rBool, rStart, rNext, rStop);
}
void SetAllJumps( double fBool,
short nStart, short nNext,
short nStop = SHRT_MAX )
{
ULONG n = (ULONG)nCols * nRows;
for ( ULONG j=0; j<n; ++j )
{
pJump[ j ].SetJump( fBool, nStart,
nNext, nStop);
}
}
void SetJumpParameters( ScTokenVec* p )
{ pParams = p; }
const ScTokenVec* GetJumpParameters() const { return pParams; }
ScMatrix* GetResultMatrix() const { return pMat; }
void GetPos( SCSIZE& rCol, SCSIZE& rRow ) const
{
rCol = nCurCol;
rRow = nCurRow;
}
bool Next( SCSIZE& rCol, SCSIZE& rRow )
{
if ( !bStarted )
{
bStarted = true;
nCurCol = nCurRow = 0;
}
else
{
if ( ++nCurRow >= nRows )
{
nCurRow = 0;
++nCurCol;
}
}
GetPos( rCol, rRow );
return nCurCol < nCols;
}
};
#endif // SC_JUMPMATRIX_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.240); FILE MERGED 2008/04/01 15:29:57 thb 1.5.240.3: #i85898# Stripping all external header guards 2008/04/01 12:36:05 thb 1.5.240.2: #i85898# Stripping all external header guards 2008/03/31 17:14:04 rt 1.5.240.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: jumpmatrix.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_JUMPMATRIX_HXX
#define SC_JUMPMATRIX_HXX
#include "token.hxx"
#include "scmatrix.hxx"
#include "errorcodes.hxx"
#include <tools/solar.h>
#include <vector>
typedef ::std::vector< ScToken*> ScTokenVec;
struct ScJumpMatrixEntry
{
double fBool; // 0:= false 1:= true also if no-path
// other values may contain error conditions like NAN and INF
short nStart; // start of path (actually start-1, see ScTokenIterator)
short nNext; // next after path
// jump path exists if nStart != nNext, else no path
short nStop; // optional stop of path (nPC < nStop)
void SetJump( double fBoolP, short nStartP, short nNextP, short nStopP )
{
fBool = fBoolP;
nStart = nStartP;
nNext = nNextP;
nStop = nStopP;
}
void GetJump( double& rBool, short& rStart, short& rNext, short& rStop )
{
rBool = fBool;
rStart = nStart;
rNext = nNext;
rStop = nStop;
}
};
class ScJumpMatrix
{
ScJumpMatrixEntry* pJump; // the jumps
ScMatrixRef pMat; // the results
ScTokenVec* pParams; // parameter stack
SCSIZE nCols;
SCSIZE nRows;
SCSIZE nCurCol;
SCSIZE nCurRow;
bool bStarted;
// not implemented, prevent usage
ScJumpMatrix( const ScJumpMatrix& );
ScJumpMatrix& operator=( const ScJumpMatrix& );
public:
ScJumpMatrix( SCSIZE nColsP, SCSIZE nRowsP )
: pJump( new ScJumpMatrixEntry[ nColsP * nRowsP ] )
, pMat( new ScMatrix( nColsP, nRowsP) )
, pParams( NULL )
, nCols( nColsP )
, nRows( nRowsP )
, nCurCol( 0 )
, nCurRow( 0 )
, bStarted( false )
{
// Initialize result matrix in case of
// a premature end of the interpreter
// due to errors.
pMat->FillDouble( CreateDoubleError(
NOTAVAILABLE), 0, 0, nCols-1,
nRows-1);
/*! pJump not initialized */
}
~ScJumpMatrix()
{
if ( pParams )
{
for ( ScTokenVec::iterator i =
pParams->begin(); i !=
pParams->end(); ++i )
{
(*i)->DecRef();
}
delete pParams;
}
delete [] pJump;
}
void GetDimensions( SCSIZE& rCols, SCSIZE& rRows ) const
{
rCols = nCols;
rRows = nRows;
}
void SetJump( SCSIZE nCol, SCSIZE nRow, double fBool,
short nStart, short nNext,
short nStop = SHRT_MAX )
{
pJump[ (ULONG)nCol * nRows + nRow ].
SetJump( fBool, nStart, nNext, nStop);
}
void GetJump( SCSIZE nCol, SCSIZE nRow, double& rBool,
short& rStart, short& rNext,
short& rStop ) const
{
pJump[ (ULONG)nCol * nRows + nRow ].
GetJump( rBool, rStart, rNext, rStop);
}
void SetAllJumps( double fBool,
short nStart, short nNext,
short nStop = SHRT_MAX )
{
ULONG n = (ULONG)nCols * nRows;
for ( ULONG j=0; j<n; ++j )
{
pJump[ j ].SetJump( fBool, nStart,
nNext, nStop);
}
}
void SetJumpParameters( ScTokenVec* p )
{ pParams = p; }
const ScTokenVec* GetJumpParameters() const { return pParams; }
ScMatrix* GetResultMatrix() const { return pMat; }
void GetPos( SCSIZE& rCol, SCSIZE& rRow ) const
{
rCol = nCurCol;
rRow = nCurRow;
}
bool Next( SCSIZE& rCol, SCSIZE& rRow )
{
if ( !bStarted )
{
bStarted = true;
nCurCol = nCurRow = 0;
}
else
{
if ( ++nCurRow >= nRows )
{
nCurRow = 0;
++nCurCol;
}
}
GetPos( rCol, rRow );
return nCurCol < nCols;
}
};
#endif // SC_JUMPMATRIX_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tokstack.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-10-21 12:01:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TOKSTACK_HXX
#define _TOKSTACK_HXX
#ifndef _INC_STRING
#include <string.h>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef SC_COMPILER_HXX
#include "compiler.hxx"
#endif
typedef OpCode DefTokenId;
// in PRODUCT version: ambiguity between OpCode (being USHORT) and UINT16
// Unfortunately a typedef is just a dumb alias and not a real type ...
//typedef UINT16 TokenId;
struct TokenId
{
UINT16 nId;
TokenId() {}
TokenId( UINT16 n ) : nId( n ) {}
TokenId( const TokenId& r ) : nId( r.nId ) {}
inline TokenId& operator =( const TokenId& r ) { nId = r.nId; return *this; }
inline TokenId& operator =( UINT16 n ) { nId = n; return *this; }
inline operator UINT16&() { return nId; }
inline operator const UINT16&() const { return nId; }
inline BOOL operator <( UINT16 n ) const { return nId < n; }
inline BOOL operator >( UINT16 n ) const { return nId > n; }
inline BOOL operator <=( UINT16 n ) const { return nId <= n; }
inline BOOL operator >=( UINT16 n ) const { return nId >= n; }
inline BOOL operator ==( UINT16 n ) const { return nId == n; }
inline BOOL operator !=( UINT16 n ) const { return nId != n; }
};
//------------------------------------------------------------------------
struct ComplRefData;
class TokenStack;
class ScToken;
enum E_TYPE
{
T_Id, // Id-Folge
T_Str, // String
T_D, // Double
T_RefC, // Cell Reference
T_RefA, // Area Reference
T_RN, // Range Name
T_Ext, // irgendwas Unbekanntes mit Funktionsnamen
T_Nlf, // token for natural language formula
T_Error // fuer Abfrage im Fehlerfall
};
class TokenPool
{
// !ACHTUNG!: externe Id-Basis ist 1, interne 0!
// Ausgabe Id = 0 -> Fehlerfall
private:
String** ppP_Str; // Pool fuer Strings
UINT16 nP_Str; // ...mit Groesse
UINT16 nP_StrAkt; // ...und Schreibmarke
double* pP_Dbl; // Pool fuer Doubles
UINT16 nP_Dbl;
UINT16 nP_DblAkt;
SingleRefData** ppP_RefTr; // Pool fuer Referenzen
UINT16 nP_RefTr;
UINT16 nP_RefTrAkt;
UINT16* pP_Id; // Pool fuer Id-Folgen
UINT16 nP_Id;
UINT16 nP_IdAkt;
UINT16 nP_IdLast; // letzter Folgen-Beginn
struct EXTCONT
{
DefTokenId eId;
String aText;
EXTCONT( const DefTokenId e, const String& r ) :
eId( e ), aText( r ){}
};
EXTCONT** ppP_Ext;
UINT16 nP_Ext;
UINT16 nP_ExtAkt;
struct NLFCONT
{
SingleRefData aRef;
NLFCONT( const SingleRefData& r ) : aRef( r ) {}
};
NLFCONT** ppP_Nlf;
UINT16 nP_Nlf;
UINT16 nP_NlfAkt;
UINT16* pElement; // Array mit Indizes fuer Elemente
E_TYPE* pType; // ...mit Typ-Info
UINT16* pSize; // ...mit Laengenangabe (Anz. UINT16)
UINT16 nElement;
UINT16 nElementAkt;
static const UINT16 nScTokenOff;// Offset fuer SC-Token
#ifdef DBG_UTIL
UINT16 nRek; // Rekursionszaehler
#endif
ScTokenArray* pScToken; // Tokenbastler
void GrowString( void );
void GrowDouble( void );
void GrowTripel( void );
void GrowId( void );
void GrowElement( void );
void GrowExt( void );
void GrowNlf( void );
void GetElement( const UINT16 nId );
void GetElementRek( const UINT16 nId );
public:
TokenPool( void );
~TokenPool();
inline TokenPool& operator <<( const TokenId nId );
inline TokenPool& operator <<( const DefTokenId eId );
inline TokenPool& operator <<( TokenStack& rStack );
void operator >>( TokenId& rId );
inline void operator >>( TokenStack& rStack );
inline const TokenId Store( void );
const TokenId Store( const double& rDouble );
// nur fuer Range-Names
const TokenId Store( const UINT16 nIndex );
inline const TokenId Store( const INT16 nWert );
const TokenId Store( const String& rString );
const TokenId Store( const SingleRefData& rTr );
const TokenId Store( const ComplRefData& rTr );
const TokenId Store( const DefTokenId eId, const String& rName );
// 4 externals (e.g. AddIns, Makros...)
const TokenId StoreNlf( const SingleRefData& rTr );
inline const TokenId LastId( void ) const;
inline const ScTokenArray* operator []( const TokenId nId );
void Reset( void );
inline E_TYPE GetType( const TokenId& nId ) const;
inline const SingleRefData* GetSRD( const TokenId& nId ) const;
BOOL IsSingleOp( const TokenId& nId, const DefTokenId eId ) const;
const String* GetExternal( const TokenId& nId ) const;
const String* GetString( const TokenId& nId ) const;
};
class TokenStack
// Stack fuer Token-Ids: Id 0 sollte reserviert bleiben als
// fehlerhafte Id, da z.B. Get() im Fehlerfall 0 liefert
{
private:
TokenId* pStack; // Stack als Array
UINT16 nPos; // Schreibmarke
UINT16 nSize; // Erster Index ausserhalb des Stacks
public:
TokenStack( UINT16 nNewSize = 1024 );
~TokenStack();
inline TokenStack& operator <<( const TokenId nNewId );
inline void operator >>( TokenId &rId );
inline void Reset( void );
inline const TokenId Get( void );
};
inline const TokenId TokenStack::Get( void )
{
DBG_ASSERT( nPos > 0,
"*TokenStack::Get(): Leer ist leer, ist leer, ist leer, ist..." );
register TokenId nRet;
if( nPos == 0 )
nRet = 0;
else
{
nPos--;
nRet = pStack[ nPos ];
}
return nRet;
}
inline TokenStack &TokenStack::operator <<( const TokenId nNewId )
{// Element auf Stack
DBG_ASSERT( nPos < nSize, "*TokenStack::<<(): Stackueberlauf" );
if( nPos < nSize )
{
pStack[ nPos ] = nNewId;
nPos++;
}
return *this;
}
inline void TokenStack::operator >>( TokenId& rId )
{// Element von Stack
DBG_ASSERT( nPos > 0,
"*TokenStack::>>(): Leer ist leer, ist leer, ist leer, ..." );
if( nPos > 0 )
{
nPos--;
rId = pStack[ nPos ];
}
}
inline void TokenStack::Reset( void )
{
nPos = 0;
}
inline TokenPool& TokenPool::operator <<( const TokenId nId )
{
// POST: nId's werden hintereinander im Pool unter einer neuen Id
// abgelegt. Vorgang wird mit >> oder Store() abgeschlossen
// nId -> ( UINT16 ) nId - 1;
DBG_ASSERT( ( UINT16 ) nId < nScTokenOff,
"-TokenPool::operator <<: TokenId im DefToken-Bereich!" );
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) nId ) - 1;
nP_IdAkt++;
return *this;
}
inline TokenPool& TokenPool::operator <<( const DefTokenId eId )
{
DBG_ASSERT( ( UINT32 ) eId + nScTokenOff < 0xFFFF,
"-TokenPool::operator<<: enmum zu gross!" );
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) eId ) + nScTokenOff;
nP_IdAkt++;
return *this;
}
inline TokenPool& TokenPool::operator <<( TokenStack& rStack )
{
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) rStack.Get() ) - 1;
nP_IdAkt++;
return *this;
}
inline void TokenPool::operator >>( TokenStack& rStack )
{
register TokenId nId;
*this >> nId;
rStack << nId;
}
inline const TokenId TokenPool::Store( void )
{
register TokenId nId;
*this >> nId;
return nId;
}
inline const TokenId TokenPool::Store( const INT16 nWert )
{
return Store( ( double ) nWert );
}
inline const TokenId TokenPool::LastId( void ) const
{
return ( TokenId ) nElementAkt; // stimmt, da Ausgabe mit Offset 1!
}
const inline ScTokenArray* TokenPool::operator []( const TokenId nId )
{
pScToken->Clear();
if( nId )
{//...nur wenn nId > 0!
#ifdef DBG_UTIL
nRek = 0;
#endif
GetElement( ( UINT16 ) nId - 1 );
}
return pScToken;
}
inline E_TYPE TokenPool::GetType( const TokenId& rId ) const
{
register E_TYPE nRet;
UINT16 nId = (UINT16) rId - 1;
if( nId < nElementAkt )
nRet = pType[ nId ] ;
else
nRet = T_Error;
return nRet;
}
inline const SingleRefData* TokenPool::GetSRD( const TokenId& rId ) const
{
register SingleRefData* pRet;
UINT16 nId = (UINT16) rId - 1;
if( nId < nElementAkt && pType[ nId ] == T_RefC )
pRet = ppP_RefTr[ pElement[ nId ] ];
else
pRet = NULL;
return pRet;
}
#endif
<commit_msg>INTEGRATION: CWS dr51 (1.8.274); FILE MERGED 2006/10/30 14:09:30 dr 1.8.274.1: #i70925# reduce function parameter count if no more tokens available on stack<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tokstack.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: ihi $ $Date: 2006-12-19 13:23:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TOKSTACK_HXX
#define _TOKSTACK_HXX
#ifndef _INC_STRING
#include <string.h>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef SC_COMPILER_HXX
#include "compiler.hxx"
#endif
typedef OpCode DefTokenId;
// in PRODUCT version: ambiguity between OpCode (being USHORT) and UINT16
// Unfortunately a typedef is just a dumb alias and not a real type ...
//typedef UINT16 TokenId;
struct TokenId
{
UINT16 nId;
TokenId() {}
TokenId( UINT16 n ) : nId( n ) {}
TokenId( const TokenId& r ) : nId( r.nId ) {}
inline TokenId& operator =( const TokenId& r ) { nId = r.nId; return *this; }
inline TokenId& operator =( UINT16 n ) { nId = n; return *this; }
inline operator UINT16&() { return nId; }
inline operator const UINT16&() const { return nId; }
inline BOOL operator <( UINT16 n ) const { return nId < n; }
inline BOOL operator >( UINT16 n ) const { return nId > n; }
inline BOOL operator <=( UINT16 n ) const { return nId <= n; }
inline BOOL operator >=( UINT16 n ) const { return nId >= n; }
inline BOOL operator ==( UINT16 n ) const { return nId == n; }
inline BOOL operator !=( UINT16 n ) const { return nId != n; }
};
//------------------------------------------------------------------------
struct ComplRefData;
class TokenStack;
class ScToken;
enum E_TYPE
{
T_Id, // Id-Folge
T_Str, // String
T_D, // Double
T_RefC, // Cell Reference
T_RefA, // Area Reference
T_RN, // Range Name
T_Ext, // irgendwas Unbekanntes mit Funktionsnamen
T_Nlf, // token for natural language formula
T_Error // fuer Abfrage im Fehlerfall
};
class TokenPool
{
// !ACHTUNG!: externe Id-Basis ist 1, interne 0!
// Ausgabe Id = 0 -> Fehlerfall
private:
String** ppP_Str; // Pool fuer Strings
UINT16 nP_Str; // ...mit Groesse
UINT16 nP_StrAkt; // ...und Schreibmarke
double* pP_Dbl; // Pool fuer Doubles
UINT16 nP_Dbl;
UINT16 nP_DblAkt;
SingleRefData** ppP_RefTr; // Pool fuer Referenzen
UINT16 nP_RefTr;
UINT16 nP_RefTrAkt;
UINT16* pP_Id; // Pool fuer Id-Folgen
UINT16 nP_Id;
UINT16 nP_IdAkt;
UINT16 nP_IdLast; // letzter Folgen-Beginn
struct EXTCONT
{
DefTokenId eId;
String aText;
EXTCONT( const DefTokenId e, const String& r ) :
eId( e ), aText( r ){}
};
EXTCONT** ppP_Ext;
UINT16 nP_Ext;
UINT16 nP_ExtAkt;
struct NLFCONT
{
SingleRefData aRef;
NLFCONT( const SingleRefData& r ) : aRef( r ) {}
};
NLFCONT** ppP_Nlf;
UINT16 nP_Nlf;
UINT16 nP_NlfAkt;
UINT16* pElement; // Array mit Indizes fuer Elemente
E_TYPE* pType; // ...mit Typ-Info
UINT16* pSize; // ...mit Laengenangabe (Anz. UINT16)
UINT16 nElement;
UINT16 nElementAkt;
static const UINT16 nScTokenOff;// Offset fuer SC-Token
#ifdef DBG_UTIL
UINT16 nRek; // Rekursionszaehler
#endif
ScTokenArray* pScToken; // Tokenbastler
void GrowString( void );
void GrowDouble( void );
void GrowTripel( void );
void GrowId( void );
void GrowElement( void );
void GrowExt( void );
void GrowNlf( void );
void GetElement( const UINT16 nId );
void GetElementRek( const UINT16 nId );
public:
TokenPool( void );
~TokenPool();
inline TokenPool& operator <<( const TokenId nId );
inline TokenPool& operator <<( const DefTokenId eId );
inline TokenPool& operator <<( TokenStack& rStack );
void operator >>( TokenId& rId );
inline void operator >>( TokenStack& rStack );
inline const TokenId Store( void );
const TokenId Store( const double& rDouble );
// nur fuer Range-Names
const TokenId Store( const UINT16 nIndex );
inline const TokenId Store( const INT16 nWert );
const TokenId Store( const String& rString );
const TokenId Store( const SingleRefData& rTr );
const TokenId Store( const ComplRefData& rTr );
const TokenId Store( const DefTokenId eId, const String& rName );
// 4 externals (e.g. AddIns, Makros...)
const TokenId StoreNlf( const SingleRefData& rTr );
inline const TokenId LastId( void ) const;
inline const ScTokenArray* operator []( const TokenId nId );
void Reset( void );
inline E_TYPE GetType( const TokenId& nId ) const;
inline const SingleRefData* GetSRD( const TokenId& nId ) const;
BOOL IsSingleOp( const TokenId& nId, const DefTokenId eId ) const;
const String* GetExternal( const TokenId& nId ) const;
const String* GetString( const TokenId& nId ) const;
};
class TokenStack
// Stack fuer Token-Ids: Id 0 sollte reserviert bleiben als
// fehlerhafte Id, da z.B. Get() im Fehlerfall 0 liefert
{
private:
TokenId* pStack; // Stack als Array
UINT16 nPos; // Schreibmarke
UINT16 nSize; // Erster Index ausserhalb des Stacks
public:
TokenStack( UINT16 nNewSize = 1024 );
~TokenStack();
inline TokenStack& operator <<( const TokenId nNewId );
inline void operator >>( TokenId &rId );
inline void Reset( void );
inline bool HasMoreTokens() const { return nPos > 0; }
inline const TokenId Get( void );
};
inline const TokenId TokenStack::Get( void )
{
DBG_ASSERT( nPos > 0,
"*TokenStack::Get(): Leer ist leer, ist leer, ist leer, ist..." );
register TokenId nRet;
if( nPos == 0 )
nRet = 0;
else
{
nPos--;
nRet = pStack[ nPos ];
}
return nRet;
}
inline TokenStack &TokenStack::operator <<( const TokenId nNewId )
{// Element auf Stack
DBG_ASSERT( nPos < nSize, "*TokenStack::<<(): Stackueberlauf" );
if( nPos < nSize )
{
pStack[ nPos ] = nNewId;
nPos++;
}
return *this;
}
inline void TokenStack::operator >>( TokenId& rId )
{// Element von Stack
DBG_ASSERT( nPos > 0,
"*TokenStack::>>(): Leer ist leer, ist leer, ist leer, ..." );
if( nPos > 0 )
{
nPos--;
rId = pStack[ nPos ];
}
}
inline void TokenStack::Reset( void )
{
nPos = 0;
}
inline TokenPool& TokenPool::operator <<( const TokenId nId )
{
// POST: nId's werden hintereinander im Pool unter einer neuen Id
// abgelegt. Vorgang wird mit >> oder Store() abgeschlossen
// nId -> ( UINT16 ) nId - 1;
DBG_ASSERT( ( UINT16 ) nId < nScTokenOff,
"-TokenPool::operator <<: TokenId im DefToken-Bereich!" );
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) nId ) - 1;
nP_IdAkt++;
return *this;
}
inline TokenPool& TokenPool::operator <<( const DefTokenId eId )
{
DBG_ASSERT( ( UINT32 ) eId + nScTokenOff < 0xFFFF,
"-TokenPool::operator<<: enmum zu gross!" );
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) eId ) + nScTokenOff;
nP_IdAkt++;
return *this;
}
inline TokenPool& TokenPool::operator <<( TokenStack& rStack )
{
if( nP_IdAkt >= nP_Id )
GrowId();
pP_Id[ nP_IdAkt ] = ( ( UINT16 ) rStack.Get() ) - 1;
nP_IdAkt++;
return *this;
}
inline void TokenPool::operator >>( TokenStack& rStack )
{
register TokenId nId;
*this >> nId;
rStack << nId;
}
inline const TokenId TokenPool::Store( void )
{
register TokenId nId;
*this >> nId;
return nId;
}
inline const TokenId TokenPool::Store( const INT16 nWert )
{
return Store( ( double ) nWert );
}
inline const TokenId TokenPool::LastId( void ) const
{
return ( TokenId ) nElementAkt; // stimmt, da Ausgabe mit Offset 1!
}
const inline ScTokenArray* TokenPool::operator []( const TokenId nId )
{
pScToken->Clear();
if( nId )
{//...nur wenn nId > 0!
#ifdef DBG_UTIL
nRek = 0;
#endif
GetElement( ( UINT16 ) nId - 1 );
}
return pScToken;
}
inline E_TYPE TokenPool::GetType( const TokenId& rId ) const
{
register E_TYPE nRet;
UINT16 nId = (UINT16) rId - 1;
if( nId < nElementAkt )
nRet = pType[ nId ] ;
else
nRet = T_Error;
return nRet;
}
inline const SingleRefData* TokenPool::GetSRD( const TokenId& rId ) const
{
register SingleRefData* pRet;
UINT16 nId = (UINT16) rId - 1;
if( nId < nElementAkt && pType[ nId ] == T_RefC )
pRet = ppP_RefTr[ pElement[ nId ] ];
else
pRet = NULL;
return pRet;
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>fix for fdo#39678: don't write password algorithm in odf 1.0 and 1.1<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xmlsubti.hxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: sab $ $Date: 2001-11-01 18:55:57 $
*
* 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_XMLSUBTI_HXX
#define SC_XMLSUBTI_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEET_HPP_
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_
#include <com/sun/star/table/XCellRange.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef __SGI_STL_VECTOR
#include <vector>
#endif
#include <list>
#ifndef _SC_XMLTABLESHAPERESIZER_HXX
#include "XMLTableShapeResizer.hxx"
#endif
class ScXMLImport;
const nDefaultRowCount = 20;
const nDefaultColCount = 20;
const nDefaultTabCount = 10;
typedef std::vector<sal_Int32> ScMysalIntVec;
typedef std::list<sal_Int32> ScMysalIntList;
class ScMyTableData
{
private:
com::sun::star::table::CellAddress aTableCellPos;
ScMysalIntVec nColsPerCol;
ScMysalIntVec nRealCols;
ScMysalIntVec nRowsPerRow;
ScMysalIntVec nRealRows;
sal_Int32 nSpannedCols;
sal_Int32 nColCount;
sal_Int32 nSubTableSpanned;
ScMysalIntList nChangedCols;
public:
ScMyTableData(sal_Int16 nSheet = -1, sal_Int32 nCol = -1, sal_Int32 nRow = -1);
~ScMyTableData();
com::sun::star::table::CellAddress GetCellPos() const { return aTableCellPos; }
sal_Int32 GetRow() const { return aTableCellPos.Row; }
sal_Int32 GetColumn() const { return aTableCellPos.Column; }
void AddRow();
void AddColumn();
void SetFirstColumn() { aTableCellPos.Column = -1; }
sal_Int32 FindNextCol(const sal_Int32 nIndex) const;
sal_Int32 GetColsPerCol(const sal_Int32 nIndex) const { return nColsPerCol[nIndex]; }
void SetColsPerCol(const sal_Int32 nIndex, sal_Int32 nValue = 1) { nColsPerCol[nIndex] = nValue; }
sal_Int32 GetRealCols(const sal_Int32 nIndex, const sal_Bool bIsNormal = sal_True) const;
void SetRealCols(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealCols[nIndex] = nValue; }
sal_Int32 GetRowsPerRow(const sal_Int32 nIndex) const { return nRowsPerRow[nIndex]; }
void SetRowsPerRow(const sal_Int32 nIndex, const sal_Int32 nValue = 1) { nRowsPerRow[nIndex] = nValue; }
sal_Int32 GetRealRows(const sal_Int32 nIndex) const { return nIndex < 0 ? 0 : nRealRows[nIndex]; }
void SetRealRows(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealRows[nIndex] = nValue; }
sal_Int32 GetSpannedCols() const { return nSpannedCols; }
void SetSpannedCols(const sal_Int32 nTempSpannedCols) { nSpannedCols = nTempSpannedCols; }
sal_Int32 GetColCount() const { return nColCount; }
void SetColCount(const sal_Int32 nTempColCount) { nColCount = nTempColCount; }
sal_Int32 GetSubTableSpanned() const { return nSubTableSpanned; }
void SetSubTableSpanned(const sal_Int32 nValue) { nSubTableSpanned = nValue; }
sal_Int32 GetChangedCols(const sal_Int32 nFromIndex, const sal_Int32 nToIndex) const;
void SetChangedCols(const sal_Int32 nValue);
};
//*******************************************************************************************************************************
class ScMyTables
{
private:
ScXMLImport& rImport;
ScMyShapeResizer aResizeShapes;
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > xCurrentSheet;
::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange > xCurrentCellRange;
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > xDrawPage;
::com::sun::star::uno::Reference < ::com::sun::star::drawing::XShapes > xShapes;
rtl::OUString sCurrentSheetName;
rtl::OUString sPassword;
std::vector<ScMyTableData*> aTableVec;
com::sun::star::table::CellAddress aRealCellPos;
sal_Int32 nCurrentColStylePos;
sal_Int16 nCurrentDrawPage;
sal_Int16 nCurrentXShapes;
sal_Int16 nTableCount;
sal_Int16 nCurrentSheet;
sal_Bool bProtection : 1;
sal_Bool IsMerged (const com::sun::star::uno::Reference <com::sun::star::table::XCellRange>& xCellRange,
const sal_Int32 nCol, const sal_Int32 nRow,
com::sun::star::table::CellRangeAddress& aCellAddress) const;
void UnMerge();
void DoMerge(sal_Int32 nCount = -1);
void InsertRow();
void NewRow();
void InsertColumn();
void NewColumn(sal_Bool bIsCovered);
public:
ScMyTables(ScXMLImport& rImport);
~ScMyTables();
void NewSheet(const rtl::OUString& sTableName, const rtl::OUString& sStyleName,
const sal_Bool bProtection, const rtl::OUString& sPassword);
void AddRow();
void SetRowStyle(const rtl::OUString& rCellStyleName);
void CloseRow();
void AddColumn(sal_Bool bIsCovered);
void NewTable(sal_Int32 nTempSpannedCols);
void UpdateRowHeights();
void ResizeShapes() { aResizeShapes.ResizeShapes(); }
void DeleteTable();
com::sun::star::table::CellAddress GetRealCellPos();
void AddColCount(sal_Int32 nTempColCount);
void AddColStyle(const sal_Int32 nRepeat, const rtl::OUString& rCellStyleName);
rtl::OUString GetCurrentSheetName() const { return sCurrentSheetName; }
sal_Int16 GetCurrentSheet() const { return nCurrentSheet; }
sal_Int32 GetCurrentColumn() const { return aTableVec[nTableCount - 1]->GetColCount(); }
sal_Int32 GetCurrentRow() const { return aTableVec[nTableCount - 1]->GetRow(); }
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet >
GetCurrentXSheet() { return xCurrentSheet; }
::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange >
GetCurrentXCellRange() { return xCurrentCellRange; }
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >
GetCurrentXDrawPage();
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >
GetCurrentXShapes();
sal_Bool HasDrawPage();
sal_Bool HasXShapes();
void AddShape(com::sun::star::uno::Reference <com::sun::star::drawing::XShape>& rShape,
rtl::OUString* pRangeList,
com::sun::star::table::CellAddress& rStartAddress,
com::sun::star::table::CellAddress& rEndAddress,
sal_Int32 nEndX, sal_Int32 nEndY);
};
#endif
<commit_msg>INTEGRATION: CWS calc10 (1.21.166); FILE MERGED 2003/05/21 16:22:43 sab 1.21.166.1: #109439#; don't set value or string if it is a cell in a matrix range<commit_after>/*************************************************************************
*
* $RCSfile: xmlsubti.hxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: vg $ $Date: 2003-05-27 10:38:10 $
*
* 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_XMLSUBTI_HXX
#define SC_XMLSUBTI_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEET_HPP_
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_
#include <com/sun/star/table/XCellRange.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef __SGI_STL_VECTOR
#include <vector>
#endif
#include <list>
#ifndef _SC_XMLTABLESHAPERESIZER_HXX
#include "XMLTableShapeResizer.hxx"
#endif
class ScXMLImport;
const nDefaultRowCount = 20;
const nDefaultColCount = 20;
const nDefaultTabCount = 10;
typedef std::vector<sal_Int32> ScMysalIntVec;
typedef std::list<sal_Int32> ScMysalIntList;
class ScMyTableData
{
private:
com::sun::star::table::CellAddress aTableCellPos;
ScMysalIntVec nColsPerCol;
ScMysalIntVec nRealCols;
ScMysalIntVec nRowsPerRow;
ScMysalIntVec nRealRows;
sal_Int32 nSpannedCols;
sal_Int32 nColCount;
sal_Int32 nSubTableSpanned;
ScMysalIntList nChangedCols;
public:
ScMyTableData(sal_Int16 nSheet = -1, sal_Int32 nCol = -1, sal_Int32 nRow = -1);
~ScMyTableData();
com::sun::star::table::CellAddress GetCellPos() const { return aTableCellPos; }
sal_Int32 GetRow() const { return aTableCellPos.Row; }
sal_Int32 GetColumn() const { return aTableCellPos.Column; }
void AddRow();
void AddColumn();
void SetFirstColumn() { aTableCellPos.Column = -1; }
sal_Int32 FindNextCol(const sal_Int32 nIndex) const;
sal_Int32 GetColsPerCol(const sal_Int32 nIndex) const { return nColsPerCol[nIndex]; }
void SetColsPerCol(const sal_Int32 nIndex, sal_Int32 nValue = 1) { nColsPerCol[nIndex] = nValue; }
sal_Int32 GetRealCols(const sal_Int32 nIndex, const sal_Bool bIsNormal = sal_True) const;
void SetRealCols(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealCols[nIndex] = nValue; }
sal_Int32 GetRowsPerRow(const sal_Int32 nIndex) const { return nRowsPerRow[nIndex]; }
void SetRowsPerRow(const sal_Int32 nIndex, const sal_Int32 nValue = 1) { nRowsPerRow[nIndex] = nValue; }
sal_Int32 GetRealRows(const sal_Int32 nIndex) const { return nIndex < 0 ? 0 : nRealRows[nIndex]; }
void SetRealRows(const sal_Int32 nIndex, const sal_Int32 nValue) { nRealRows[nIndex] = nValue; }
sal_Int32 GetSpannedCols() const { return nSpannedCols; }
void SetSpannedCols(const sal_Int32 nTempSpannedCols) { nSpannedCols = nTempSpannedCols; }
sal_Int32 GetColCount() const { return nColCount; }
void SetColCount(const sal_Int32 nTempColCount) { nColCount = nTempColCount; }
sal_Int32 GetSubTableSpanned() const { return nSubTableSpanned; }
void SetSubTableSpanned(const sal_Int32 nValue) { nSubTableSpanned = nValue; }
sal_Int32 GetChangedCols(const sal_Int32 nFromIndex, const sal_Int32 nToIndex) const;
void SetChangedCols(const sal_Int32 nValue);
};
//*******************************************************************************************************************************
class ScMyTables
{
private:
typedef std::list<com::sun::star::table::CellRangeAddress> ScMyMatrixRangeList;
ScXMLImport& rImport;
ScMyShapeResizer aResizeShapes;
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > xCurrentSheet;
::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange > xCurrentCellRange;
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > xDrawPage;
::com::sun::star::uno::Reference < ::com::sun::star::drawing::XShapes > xShapes;
rtl::OUString sCurrentSheetName;
rtl::OUString sPassword;
std::vector<ScMyTableData*> aTableVec;
ScMyMatrixRangeList aMatrixRangeList;
com::sun::star::table::CellAddress aRealCellPos;
sal_Int32 nCurrentColStylePos;
sal_Int16 nCurrentDrawPage;
sal_Int16 nCurrentXShapes;
sal_Int16 nTableCount;
sal_Int16 nCurrentSheet;
sal_Bool bProtection : 1;
sal_Bool IsMerged (const com::sun::star::uno::Reference <com::sun::star::table::XCellRange>& xCellRange,
const sal_Int32 nCol, const sal_Int32 nRow,
com::sun::star::table::CellRangeAddress& aCellAddress) const;
void UnMerge();
void DoMerge(sal_Int32 nCount = -1);
void InsertRow();
void NewRow();
void InsertColumn();
void NewColumn(sal_Bool bIsCovered);
public:
ScMyTables(ScXMLImport& rImport);
~ScMyTables();
void NewSheet(const rtl::OUString& sTableName, const rtl::OUString& sStyleName,
const sal_Bool bProtection, const rtl::OUString& sPassword);
void AddRow();
void SetRowStyle(const rtl::OUString& rCellStyleName);
void CloseRow();
void AddColumn(sal_Bool bIsCovered);
void NewTable(sal_Int32 nTempSpannedCols);
void UpdateRowHeights();
void ResizeShapes() { aResizeShapes.ResizeShapes(); }
void DeleteTable();
com::sun::star::table::CellAddress GetRealCellPos();
void AddColCount(sal_Int32 nTempColCount);
void AddColStyle(const sal_Int32 nRepeat, const rtl::OUString& rCellStyleName);
rtl::OUString GetCurrentSheetName() const { return sCurrentSheetName; }
sal_Int16 GetCurrentSheet() const { return nCurrentSheet; }
sal_Int32 GetCurrentColumn() const { return aTableVec[nTableCount - 1]->GetColCount(); }
sal_Int32 GetCurrentRow() const { return aTableVec[nTableCount - 1]->GetRow(); }
::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet >
GetCurrentXSheet() { return xCurrentSheet; }
::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange >
GetCurrentXCellRange() { return xCurrentCellRange; }
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >
GetCurrentXDrawPage();
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >
GetCurrentXShapes();
sal_Bool HasDrawPage();
sal_Bool HasXShapes();
void AddShape(com::sun::star::uno::Reference <com::sun::star::drawing::XShape>& rShape,
rtl::OUString* pRangeList,
com::sun::star::table::CellAddress& rStartAddress,
com::sun::star::table::CellAddress& rEndAddress,
sal_Int32 nEndX, sal_Int32 nEndY);
void AddMatrixRange(sal_uInt32 nStartColumn, sal_uInt32 nStartRow, sal_uInt32 nEndColumn, sal_uInt32 nEndRow);
sal_Bool IsPartOfMatrix(sal_uInt32 nColumn, sal_uInt32 nRow);
};
#endif
<|endoftext|>
|
<commit_before>// implementation for steepest_descent.h
#include <cmath>
#include <set>
#include <utils/plot_tools.h>
#include <adaptive/apply.h>
#include <numerics/corner_singularity.h>
#include <frame_evaluate.h>
using std::set;
namespace FrameTL
{
/*!
*/
template<class VALUE = double>
class Singularity1D_RHS_2
: public Function<1, VALUE>
{
public:
Singularity1D_RHS_2() {};
virtual ~Singularity1D_RHS_2() {};
VALUE value(const Point<1>& p,
const unsigned int component = 0) const
{
return -sin(3.*M_PI*p[0])*9.*M_PI*M_PI - 4.;
}
void vector_value(const Point<1> &p,
Vector<VALUE>& values) const { ; }
};
/*!
special function with steep gradients
near the right end of the interval
*/
template<class VALUE = double>
class Singularity1D_2
: public Function<1, VALUE>
{
public:
Singularity1D_2() {};
virtual ~Singularity1D_2() {};
VALUE value(const Point<1>& p,
const unsigned int component = 0) const
{
if (0. <= p[0] && p[0] < 0.5)
return -sin(3.*M_PI*p[0]) + 2.*p[0]*p[0];
if (0.5 <= p[0] && p[0] <= 1.0)
return -sin(3.*M_PI*p[0]) + 2.*(1-p[0])*(1-p[0]);
return 0.;
}
void vector_value(const Point<1> &p,
Vector<VALUE>& values) const { ; }
};
template <class PROBLEM>
void steepest_descent_SOLVE(const PROBLEM& P, const double epsilon,
InfiniteVector<double, typename PROBLEM::Index>& u_epsilon)
{
typedef DSBasis<2,2> Basis1D;
// Point<2> origin;
// origin[0] = 0.0;
// origin[1] = 0.0;
// CornerSingularity sing2D(origin, 0.5, 1.5);
// CornerSingularityRHS singRhs(origin, 0.5, 1.5);
// typedef DSBasis<2,2> Basis1D;
// Singularity1D_RHS_2<double> sing1D;
Singularity1D_2<double> exactSolution1D;
unsigned int loops = 0;
const int jmax = 10;
typedef typename PROBLEM::Index Index;
double a_inv = P.norm_Ainv();
double kappa = P.norm_A()*a_inv;
double omega_i = a_inv*P.F_norm();
cout << "a_inv = " << a_inv << endl;
cout << "omega_i = " << omega_i << endl;
//double delta = 1./(5.*kappa+a_inv);
double delta = 0.9;
cout << "delta = " << delta << endl;
//const double A = 1 + delta;
const double A = 1.;
//const double C = 1.0 / ((1 - ((kappa*(delta*delta+2.*delta)+a_inv*delta)/((1-delta)*(1-delta))))
// * (((1-delta)*(1-delta))/(a_inv)));
const double C = 1.0;
cout << "C = " << C << endl;
const double B = C * (A*A);
cout << "B = " << B << endl;
//double lambda = (kappa-1)/(kappa+1) + P.norm_A()*std::max(3.*A*A*B,C*(1./(1-delta)))*delta;
//double lambda = ((kappa-1)/(kappa+1)+1.)/2.;
double lambda = 0.6;
cout << "lambda = " << lambda << endl;
const double C3 = B;
cout << "C3 = " << C3 << endl;
double mu = 1.0001; //shall be > 1
//beta in (0,1)
double beta = 0.5;
//let K be such that beta^K * omega <= epsilon
unsigned int K = (int) (log(epsilon/omega_i) / log(beta) + 1);
//let M be such that lambda^M <= ((1-delta) / (1+delta)) * (beta / ((1+3*mu)*kappa))
int M = std::max((int) ((log( ((1-delta)/(1+delta)) * (beta / ((1+3.0*mu)*kappa)) )
/ log(lambda)) + 1),1);
//int M = 1;
InfiniteVector<double, Index> w, tilde_r;
cout << "K = " << K << endl;
cout << "M = " << M << endl;
map<double,double> log_10_residual_norms;
map<double,double> degrees_of_freedom;
map<double,double> asymptotic;
map<double,double> time_asymptotic;
map<double,double> log_10_L2_error;
bool exit = 0;
double time = 0;
clock_t tstart, tend;
tstart = clock();
EvaluateFrame<Basis1D,1,1> evalObj;
double acctime = 0;
for (unsigned int i = 1; i < K; i++) {
//omega_i *= 0.000001;/*beta;*/
omega_i *= beta;
double xi_i = omega_i / ((1+3.0*mu)*C3*M);
double nu_i = 0.;
RES(P, w, xi_i, delta, omega_i/((1+3.*mu)*a_inv), jmax,
tilde_r, nu_i, CDD1);
while ( nu_i > omega_i/((1+3.*mu)*a_inv)) {
InfiniteVector<double, Index> z_i;
//APPLY(P, tilde_r, delta*l2_norm(tilde_r), z_i, jmax, CDD1);
tend = clock();
time = (double)(tend-tstart)/CLOCKS_PER_SEC;
APPLY_COARSE(P, tilde_r, delta*l2_norm(tilde_r), z_i, 0.00000001, jmax, CDD1);
acctime += ((double)(tend-tstart)/CLOCKS_PER_SEC - time);
cout << "time = " << acctime << endl;
double d = ((tilde_r*tilde_r)/(z_i*tilde_r));
w += d*tilde_r;
cout << "descent param = " << d << endl;
++loops;
//degrees_of_freedom[loops] = w.size();
RES(P, w, xi_i, delta, omega_i/((1+3.*mu)*a_inv), jmax,
tilde_r, nu_i, CDD1);
cout << "loop: " << loops << " nu = "
<< nu_i << " epsilon = " << omega_i/((1+3.*mu)*a_inv) << endl;
cout << "xi: " << xi_i << endl;
double tmp = l2_norm(tilde_r);
double tmp1 = log10(tmp);
cout << "residual norm = " << tmp << endl;
asymptotic[log10( (double)w.size() )] = tmp1;
log_10_residual_norms[loops] = tmp1;
u_epsilon = w;
P.rescale(u_epsilon,-1);
//double L2err = evalObj.L_2_error(P.basis(), u_epsilon, exactSolution1D, 7, 0.0, 1.0);
//log_10_L2_error[loops] = log10(L2err);
//cout << "L_2 error = " << L2err << endl;
//tend = clock();
//time = (double)(tend-tstart)/CLOCKS_PER_SEC;
//time_asymptotic[log10(time)] = tmp1;
cout << "active indices: " << w.size() << endl;
// if (loops % 10 == 0) {
// std::ofstream os3("steep1D_asymptotic.m");
// matlab_output(asymptotic,os3);
// os3.close();
// std::ofstream os4("steep_1D_L2_errors.m");
// matlab_output(log_10_L2_error,os4);
// os4.close();
// }
// if (loops == 1 || loops == 5 || loops == 10 || loops == 20 || loops == 40 || loops == 55){
// u_epsilon = w;
// P.rescale(u_epsilon,-1);
// char filename1[50];
// char filename2[50];
// sprintf(filename1, "%s%d%s%d%s", "approx_sol_steep22_2D_out_", loops, "_nactive_", w.size(),".m");
// sprintf(filename2, "%s%d%s%d%s", "error_steep_2D_out_", loops, "_nactive_", w.size(),".m");
// Array1D<SampledMapping<1> > U = evalObj.evaluate(P.basis(), u_epsilon, true, 6);//expand in primal basis
// cout << "...plotting approximate solution" << endl;
// Array1D<SampledMapping<1> > Error = evalObj.evaluate_difference(P.basis(), u_epsilon, exactSolution1D, 6);
// cout << "...plotting error" << endl;
// double L2err = evalObj.L_2_error(P.basis(), u_epsilon, exactSolution1D, 7, 0.0, 1.0);
// cout << "L_2 error = " << L2err << endl;
// std::ofstream ofs5(filename1);
// matlab_output(ofs5,U);
// ofs5.close();
// std::ofstream ofs6(filename2);
// matlab_output(ofs6,Error);
// ofs6.close();
if (tmp < 0.005 || loops == 300) {
u_epsilon = w;
exit = true;
break;
}
}//end while
cout << "#######################" << endl;
cout << "exiting inner loop" << endl;
cout << "#######################" << endl;
if (exit)
break;
}// end for
// InfiniteVector<double, Index> tmp;
// w.COARSE(((3.*mu*omega_i)/(1+3.*mu)),tmp);
// w = tmp;
std::ofstream os1("residual_norms_steep.m");
matlab_output(log_10_residual_norms,os1);
os1.close();
// std::ofstream os2("degrees_of_freedom.m");
// matlab_output(degrees_of_freedom,os2);
// os2.close();
std::ofstream os3("asymptotic.m");
matlab_output(asymptotic,os3);
os3.close();
// std::ofstream os4("time_asymptotic.m");
// matlab_output(time_asymptotic,os4);
// os4.close();
}
}
<commit_msg>just to be up to date<commit_after>// implementation for steepest_descent.h
#include <cmath>
#include <set>
#include <utils/plot_tools.h>
#include <adaptive/apply.h>
#include <numerics/corner_singularity.h>
#include <frame_evaluate.h>
using std::set;
namespace FrameTL
{
/*!
*/
template<class VALUE = double>
class Singularity1D_RHS_2
: public Function<1, VALUE>
{
public:
Singularity1D_RHS_2() {};
virtual ~Singularity1D_RHS_2() {};
VALUE value(const Point<1>& p,
const unsigned int component = 0) const
{
return -sin(3.*M_PI*p[0])*9.*M_PI*M_PI - 4.;
}
void vector_value(const Point<1> &p,
Vector<VALUE>& values) const { ; }
};
/*!
special function with steep gradients
near the right end of the interval
*/
template<class VALUE = double>
class Singularity1D_2
: public Function<1, VALUE>
{
public:
Singularity1D_2() {};
virtual ~Singularity1D_2() {};
VALUE value(const Point<1>& p,
const unsigned int component = 0) const
{
if (0. <= p[0] && p[0] < 0.5)
return -sin(3.*M_PI*p[0]) + 2.*p[0]*p[0];
if (0.5 <= p[0] && p[0] <= 1.0)
return -sin(3.*M_PI*p[0]) + 2.*(1-p[0])*(1-p[0]);
return 0.;
}
void vector_value(const Point<1> &p,
Vector<VALUE>& values) const { ; }
};
template <class PROBLEM>
void steepest_descent_SOLVE(const PROBLEM& P, const double epsilon,
InfiniteVector<double, typename PROBLEM::Index>& u_epsilon)
{
typedef DSBasis<2,2> Basis1D;
// Point<2> origin;
// origin[0] = 0.0;
// origin[1] = 0.0;
// CornerSingularity sing2D(origin, 0.5, 1.5);
// CornerSingularityRHS singRhs(origin, 0.5, 1.5);
// typedef DSBasis<2,2> Basis1D;
// Singularity1D_RHS_2<double> sing1D;
Singularity1D_2<double> exactSolution1D;
unsigned int loops = 0;
const int jmax = 10;
typedef typename PROBLEM::Index Index;
double a_inv = P.norm_Ainv();
double kappa = P.norm_A()*a_inv;
double omega_i = a_inv*P.F_norm();
cout << "a_inv = " << a_inv << endl;
cout << "omega_i = " << omega_i << endl;
//double delta = 1./(5.*kappa+a_inv);
double delta = 1;
cout << "delta = " << delta << endl;
//const double A = 1 + delta;
const double A = 1.;
//const double C = 1.0 / ((1 - ((kappa*(delta*delta+2.*delta)+a_inv*delta)/((1-delta)*(1-delta))))
// * (((1-delta)*(1-delta))/(a_inv)));
const double C = 1.0;
cout << "C = " << C << endl;
const double B = C * (A*A);
cout << "B = " << B << endl;
//double lambda = (kappa-1)/(kappa+1) + P.norm_A()*std::max(3.*A*A*B,C*(1./(1-delta)))*delta;
//double lambda = ((kappa-1)/(kappa+1)+1.)/2.;
double lambda = 0.6;
cout << "lambda = " << lambda << endl;
const double C3 = B;
cout << "C3 = " << C3 << endl;
double mu = 1.0001; //shall be > 1
//beta in (0,1)
double beta = 0.5;
//let K be such that beta^K * omega <= epsilon
unsigned int K = (int) (log(epsilon/omega_i) / log(beta) + 1);
//let M be such that lambda^M <= ((1-delta) / (1+delta)) * (beta / ((1+3*mu)*kappa))
int M = std::max((int) ((log( ((1-delta)/(1+delta)) * (beta / ((1+3.0*mu)*kappa)) )
/ log(lambda)) + 1),1);
//int M = 1;
InfiniteVector<double, Index> w, tilde_r;
cout << "K = " << K << endl;
cout << "M = " << M << endl;
map<double,double> log_10_residual_norms;
map<double,double> degrees_of_freedom;
map<double,double> asymptotic;
map<double,double> time_asymptotic;
map<double,double> log_10_L2_error;
bool exit = 0;
double time = 0;
clock_t tstart, tend;
tstart = clock();
EvaluateFrame<Basis1D,1,1> evalObj;
double acctime = 0;
for (unsigned int i = 1; i < K; i++) {
//omega_i *= 0.000001;/*beta;*/
omega_i *= beta;
double xi_i = omega_i / ((1+3.0*mu)*C3*M);
double nu_i = 0.;
RES(P, w, xi_i, delta, omega_i/((1+3.*mu)*a_inv), jmax,
tilde_r, nu_i, CDD1);
while ( nu_i > omega_i/((1+3.*mu)*a_inv)) {
InfiniteVector<double, Index> z_i;
//APPLY(P, tilde_r, delta*l2_norm(tilde_r), z_i, jmax, CDD1);
// tend = clock();
// time = (double)(tend-tstart)/CLOCKS_PER_SEC;
APPLY_COARSE(P, tilde_r, delta*l2_norm(tilde_r), z_i, 0.00000001, jmax, CDD1);
// acctime += ((double)(tend-tstart)/CLOCKS_PER_SEC - time);
// cout << "time = " << acctime << endl;
double d = ((tilde_r*tilde_r)/(z_i*tilde_r));
w += d*tilde_r;
cout << "descent param = " << d << endl;
++loops;
//degrees_of_freedom[loops] = w.size();
RES(P, w, xi_i, delta, omega_i/((1+3.*mu)*a_inv), jmax,
tilde_r, nu_i, CDD1);
cout << "loop: " << loops << " nu = "
<< nu_i << " epsilon = " << omega_i/((1+3.*mu)*a_inv) << endl;
cout << "xi: " << xi_i << endl;
double tmp = l2_norm(tilde_r);
double tmp1 = log10(tmp);
cout << "residual norm = " << tmp << endl;
asymptotic[log10( (double)w.size() )] = tmp1;
log_10_residual_norms[loops] = tmp1;
u_epsilon = w;
P.rescale(u_epsilon,-1);
//double L2err = evalObj.L_2_error(P.basis(), u_epsilon, exactSolution1D, 7, 0.0, 1.0);
//log_10_L2_error[loops] = log10(L2err);
//cout << "L_2 error = " << L2err << endl;
//tend = clock();
//time = (double)(tend-tstart)/CLOCKS_PER_SEC;
//time_asymptotic[log10(time)] = tmp1;
cout << "active indices: " << w.size() << endl;
// if (loops % 10 == 0) {
// std::ofstream os3("steep1D_asymptotic.m");
// matlab_output(asymptotic,os3);
// os3.close();
// std::ofstream os4("steep_1D_L2_errors.m");
// matlab_output(log_10_L2_error,os4);
// os4.close();
// }
// if (loops == 1 || loops == 5 || loops == 10 || loops == 20 || loops == 40 || loops == 55){
// u_epsilon = w;
// P.rescale(u_epsilon,-1);
// char filename1[50];
// char filename2[50];
// sprintf(filename1, "%s%d%s%d%s", "approx_sol_steep22_2D_out_", loops, "_nactive_", w.size(),".m");
// sprintf(filename2, "%s%d%s%d%s", "error_steep_2D_out_", loops, "_nactive_", w.size(),".m");
// Array1D<SampledMapping<1> > U = evalObj.evaluate(P.basis(), u_epsilon, true, 6);//expand in primal basis
// cout << "...plotting approximate solution" << endl;
// Array1D<SampledMapping<1> > Error = evalObj.evaluate_difference(P.basis(), u_epsilon, exactSolution1D, 6);
// cout << "...plotting error" << endl;
// double L2err = evalObj.L_2_error(P.basis(), u_epsilon, exactSolution1D, 7, 0.0, 1.0);
// cout << "L_2 error = " << L2err << endl;
// std::ofstream ofs5(filename1);
// matlab_output(ofs5,U);
// ofs5.close();
// std::ofstream ofs6(filename2);
// matlab_output(ofs6,Error);
// ofs6.close();
if (tmp < 0.01 || loops == 300) {
u_epsilon = w;
exit = true;
break;
}
}//end while
cout << "#######################" << endl;
cout << "exiting inner loop" << endl;
cout << "#######################" << endl;
if (exit)
break;
}// end for
// InfiniteVector<double, Index> tmp;
// w.COARSE(((3.*mu*omega_i)/(1+3.*mu)),tmp);
// w = tmp;
std::ofstream os1("residual_norms_steep.m");
matlab_output(log_10_residual_norms,os1);
os1.close();
// std::ofstream os2("degrees_of_freedom.m");
// matlab_output(degrees_of_freedom,os2);
// os2.close();
std::ofstream os3("asymptotic.m");
matlab_output(asymptotic,os3);
os3.close();
// std::ofstream os4("time_asymptotic.m");
// matlab_output(time_asymptotic,os4);
// os4.close();
}
}
<|endoftext|>
|
<commit_before>/**
* @file sparse_coding_impl.hpp
* @author Nishant Mehta
*
* Implementation of Sparse Coding with Dictionary Learning using l1 (LASSO) or
* l1+l2 (Elastic Net) regularization.
*/
#ifndef __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP
#define __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP
// In case it hasn't already been included.
#include "sparse_coding.hpp"
namespace mlpack {
namespace sparse_coding {
// TODO: parameterizable; options to methods?
#define OBJ_TOL 1e-2 // 1E-9
#define NEWTON_TOL 1e-6 // 1E-9
template<typename DictionaryInitializer>
SparseCoding<DictionaryInitializer>::SparseCoding(const arma::mat& data,
const size_t atoms,
const double lambda1,
const double lambda2) :
atoms(atoms),
data(data),
codes(atoms, data.n_cols),
lambda1(lambda1),
lambda2(lambda2)
{
// Initialize the dictionary.
DictionaryInitializer::Initialize(data, atoms, dictionary);
}
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::Encode(const size_t maxIterations)
{
double lastObjVal = DBL_MAX;
// Take the initial coding step, which has to happen before entering the main
// optimization loop.
Log::Info << "Initial Coding Step." << std::endl;
OptimizeCode();
arma::uvec adjacencies = find(codes);
Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem))
/ ((double) (atoms * data.n_cols)) << "%." << std::endl;
Log::Info << " Objective value: " << Objective() << "." << std::endl;
for (size_t t = 1; t != maxIterations; ++t)
{
Log::Info << "Iteration " << t << " of " << maxIterations << "."
<< std::endl;
// First step: optimize the dictionary.
Log::Info << "Performing dictionary step... " << std::endl;
OptimizeDictionary(adjacencies);
Log::Info << " Objective value: " << Objective() << "." << std::endl;
// Second step: perform the coding.
Log::Info << "Performing coding step..." << std::endl;
OptimizeCode();
// Get the indices of all the nonzero elements in the codes.
adjacencies = find(codes);
Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem))
/ ((double) (atoms * data.n_cols)) << "%." << std::endl;
// Find the new objective value and improvement so we can check for
// convergence.
double curObjVal = Objective();
double improvement = lastObjVal - curObjVal;
Log::Info << " Objective value: " << curObjVal << " (improvement "
<< std::scientific << improvement << ")." << std::endl;
// Have we converged?
if (improvement < OBJ_TOL)
{
Log::Info << "Converged within tolerance " << OBJ_TOL << ".\n";
break;
}
lastObjVal = curObjVal;
}
}
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::OptimizeCode()
{
// When using the Cholesky version of LARS, this is correct even if
// lambda2 > 0.
arma::mat matGram = trans(dictionary) * dictionary;
for (size_t i = 0; i < data.n_cols; ++i)
{
// Report progress.
if ((i % 100) == 0)
Log::Debug << "Optimization at point " << i << "." << std::endl;
bool useCholesky = true;
regression::LARS lars(useCholesky, matGram, lambda1, lambda2);
// Create an alias of the code (using the same memory), and then LARS will
// place the result directly into that; then we will not need to have an
// extra copy.
arma::vec code = codes.unsafe_col(i);
lars.Regress(dictionary, data.unsafe_col(i), code, true);
}
}
// Dictionary step for optimization.
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::OptimizeDictionary(
const arma::uvec& adjacencies)
{
// Count the number of atomic neighbors for each point x^i.
arma::uvec neighborCounts = arma::zeros<arma::uvec>(data.n_cols, 1);
if (adjacencies.n_elem > 0)
{
// This gets the column index. Intentional integer division.
size_t curPointInd = (size_t) (adjacencies(0) / atoms);
size_t nextColIndex = (curPointInd + 1) * atoms;
for (size_t l = 1; l < adjacencies.n_elem; ++l)
{
// If l no longer refers to an element in this column, advance the column
// number accordingly.
if (adjacencies(l) >= nextColIndex)
{
curPointInd = (size_t) (adjacencies(l) / atoms);
nextColIndex = (curPointInd + 1) * atoms;
}
++neighborCounts(curPointInd);
}
}
// Handle the case of inactive atoms (atoms not used in the given coding).
std::vector<size_t> inactiveAtoms;
std::vector<size_t> activeAtoms;
activeAtoms.reserve(atoms);
for (size_t j = 0; j < atoms; ++j)
{
if (accu(codes.row(j) != 0) == 0)
inactiveAtoms.push_back(j);
else
activeAtoms.push_back(j);
}
const size_t nActiveAtoms = activeAtoms.size();
const size_t nInactiveAtoms = inactiveAtoms.size();
// Efficient construction of Z restricted to active atoms.
arma::mat matActiveZ;
if (inactiveAtoms.empty())
{
matActiveZ = codes;
}
else
{
arma::uvec inactiveAtomsVec =
arma::conv_to<arma::uvec>::from(inactiveAtoms);
RemoveRows(codes, inactiveAtomsVec, matActiveZ);
}
arma::uvec atomReverseLookup(atoms);
for (size_t i = 0; i < nActiveAtoms; ++i)
atomReverseLookup(activeAtoms[i]) = i;
if (nInactiveAtoms > 0)
{
Log::Warn << "There are " << nInactiveAtoms
<< " inactive atoms. They will be re-initialized randomly.\n";
}
Log::Debug << "Solving Dual via Newton's Method.\n";
arma::mat dictionaryEstimate;
// Solve using Newton's method in the dual - note that the final dot
// multiplication with inv(A) seems to be unavoidable. Although more
// expensive, the code written this way (we use solve()) should be more
// numerically stable than just using inv(A) for everything.
arma::vec dualVars = arma::zeros<arma::vec>(nActiveAtoms);
//vec dualVars = 1e-14 * ones<vec>(nActiveAtoms);
// Method used by feature sign code - fails miserably here. Perhaps the
// MATLAB optimizer fmincon does something clever?
//vec dualVars = 10.0 * randu(nActiveAtoms, 1);
//vec dualVars = diagvec(solve(dictionary, data * trans(codes))
// - codes * trans(codes));
//for (size_t i = 0; i < dualVars.n_elem; i++)
// if (dualVars(i) < 0)
// dualVars(i) = 0;
bool converged = false;
arma::mat codesXT = matActiveZ * trans(data);
arma::mat codesZT = matActiveZ * trans(matActiveZ);
for (size_t t = 1; !converged; ++t)
{
arma::mat A = codesZT + diagmat(dualVars);
arma::mat matAInvZXT = solve(A, codesXT);
arma::vec gradient = -(arma::sum(arma::square(matAInvZXT), 1) -
arma::ones<arma::vec>(nActiveAtoms));
arma::mat hessian = -(-2 * (matAInvZXT * trans(matAInvZXT)) % inv(A));
arma::vec searchDirection = -solve(hessian, gradient);
//vec searchDirection = -gradient;
// Armijo line search.
const double c = 1e-4;
double alpha = 1.0;
const double rho = 0.9;
double sufficientDecrease = c * dot(gradient, searchDirection);
/*
{
double sumDualVars = sum(dualVars);
double fOld = -(-trace(trans(codesXT) * matAInvZXT) - sumDualVars);
Log::Debug << "fOld = " << fOld << "." << std::endl;
double fNew =
-(-trace(trans(codesXT) * solve(codesZT +
diagmat(dualVars + alpha * searchDirection), codesXT))
- (sumDualVars + alpha * sum(searchDirection)) );
Log::Debug << "fNew = " << fNew << "." << std::endl;
}
*/
double improvement;
while (true)
{
// Calculate objective.
double sumDualVars = sum(dualVars);
double fOld = -(-trace(trans(codesXT) * matAInvZXT) - sumDualVars);
double fNew = -(-trace(trans(codesXT) * solve(codesZT +
diagmat(dualVars + alpha * searchDirection), codesXT)) -
(sumDualVars + alpha * sum(searchDirection)));
if (fNew <= fOld + alpha * sufficientDecrease)
{
searchDirection = alpha * searchDirection;
improvement = fOld - fNew;
break;
}
alpha *= rho;
}
// End of Armijo line search code.
dualVars += searchDirection;
double normGradient = norm(gradient, 2);
Log::Debug << "Newton Method iteration " << t << ":" << std::endl;
Log::Debug << " Gradient norm: " << std::scientific << normGradient
<< "." << std::endl;
Log::Debug << " Improvement: " << std::scientific << improvement << ".\n";
if (improvement < NEWTON_TOL)
converged = true;
}
if (inactiveAtoms.empty())
{
dictionaryEstimate = trans(solve(codesZT + diagmat(dualVars), codesXT));
}
else
{
arma::mat dictionaryActiveEstimate = trans(solve(codesZT +
diagmat(dualVars), codesXT));
dictionaryEstimate = arma::zeros(data.n_rows, atoms);
for (size_t i = 0; i < nActiveAtoms; ++i)
dictionaryEstimate.col(activeAtoms[i]) = dictionaryActiveEstimate.col(i);
for (size_t i = 0; i < nInactiveAtoms; ++i)
{
// Make a new random atom estimate.
dictionaryEstimate.col(inactiveAtoms[i]) =
(data.col(math::RandInt(data.n_cols)) +
data.col(math::RandInt(data.n_cols)) +
data.col(math::RandInt(data.n_cols)));
dictionaryEstimate.col(inactiveAtoms[i]) /=
norm(dictionaryEstimate.col(inactiveAtoms[i]), 2);
}
}
dictionary = dictionaryEstimate;
}
// Project each atom of the dictionary back into the unit ball (if necessary).
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::ProjectDictionary()
{
for (size_t j = 0; j < atoms; j++)
{
double atomNorm = norm(dictionary.col(j), 2);
if (atomNorm > 1)
{
Log::Info << "Norm of atom " << j << " exceeds 1 (" << std::scientific
<< atomNorm << "). Shrinking...\n";
dictionary.col(j) /= atomNorm;
}
}
}
// Compute the objective function.
template<typename DictionaryInitializer>
double SparseCoding<DictionaryInitializer>::Objective()
{
double l11NormZ = sum(sum(abs(codes)));
double froNormResidual = norm(data - (dictionary * codes), "fro");
if (lambda2 > 0)
{
double froNormZ = norm(codes, "fro");
return 0.5 * (std::pow(froNormResidual, 2.0) + (lambda2 *
std::pow(froNormZ, 2.0))) + (lambda1 * l11NormZ);
}
else // It can be simpler.
{
return 0.5 * std::pow(froNormResidual, 2.0) + lambda1 * l11NormZ;
}
}
void RemoveRows(const arma::mat& X,
const arma::uvec& rowsToRemove,
arma::mat& modX)
{
const size_t cols = X.n_cols;
const size_t rows = X.n_rows;
const size_t nRemove = rowsToRemove.n_elem;
const size_t nKeep = rows - nRemove;
if (nRemove == 0)
{
modX = X;
}
else
{
modX.set_size(nKeep, cols);
size_t curRow = 0;
size_t removeInd = 0;
// First, check 0 to first row to remove.
if (rowsToRemove(0) > 0)
{
// Note that this implies that n_rows > 1.
size_t height = rowsToRemove(0);
modX(arma::span(curRow, curRow + height - 1), arma::span::all) =
X(arma::span(0, rowsToRemove(0) - 1), arma::span::all);
curRow += height;
}
// Now, check i'th row to remove to (i + 1)'th row to remove, until i is the
// penultimate row.
while (removeInd < nRemove - 1)
{
size_t height = rowsToRemove[removeInd + 1] -
rowsToRemove[removeInd] - 1;
if (height > 0)
{
modX(arma::span(curRow, curRow + height - 1), arma::span::all) =
X(arma::span(rowsToRemove[removeInd] + 1,
rowsToRemove[removeInd + 1] - 1), arma::span::all);
curRow += height;
}
removeInd++;
}
// Now that i is the last row to remove, check last row to remove to last
// row.
if (rowsToRemove[removeInd] < rows - 1)
{
modX(arma::span(curRow, nKeep - 1), arma::span::all) =
X(arma::span(rowsToRemove[removeInd] + 1, rows - 1),
arma::span::all);
}
}
}
}; // namespace sparse_coding
}; // namespace mlpack
#endif
<commit_msg>Stop using activeAtoms because it isn't necessary (minor speed boost). Clean up code just a little more.<commit_after>/**
* @file sparse_coding_impl.hpp
* @author Nishant Mehta
*
* Implementation of Sparse Coding with Dictionary Learning using l1 (LASSO) or
* l1+l2 (Elastic Net) regularization.
*/
#ifndef __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP
#define __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP
// In case it hasn't already been included.
#include "sparse_coding.hpp"
namespace mlpack {
namespace sparse_coding {
// TODO: parameterizable; options to methods?
#define OBJ_TOL 1e-2 // 1E-9
#define NEWTON_TOL 1e-6 // 1E-9
template<typename DictionaryInitializer>
SparseCoding<DictionaryInitializer>::SparseCoding(const arma::mat& data,
const size_t atoms,
const double lambda1,
const double lambda2) :
atoms(atoms),
data(data),
codes(atoms, data.n_cols),
lambda1(lambda1),
lambda2(lambda2)
{
// Initialize the dictionary.
DictionaryInitializer::Initialize(data, atoms, dictionary);
}
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::Encode(const size_t maxIterations)
{
double lastObjVal = DBL_MAX;
// Take the initial coding step, which has to happen before entering the main
// optimization loop.
Log::Info << "Initial Coding Step." << std::endl;
OptimizeCode();
arma::uvec adjacencies = find(codes);
Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem))
/ ((double) (atoms * data.n_cols)) << "%." << std::endl;
Log::Info << " Objective value: " << Objective() << "." << std::endl;
for (size_t t = 1; t != maxIterations; ++t)
{
Log::Info << "Iteration " << t << " of " << maxIterations << "."
<< std::endl;
// First step: optimize the dictionary.
Log::Info << "Performing dictionary step... " << std::endl;
OptimizeDictionary(adjacencies);
Log::Info << " Objective value: " << Objective() << "." << std::endl;
// Second step: perform the coding.
Log::Info << "Performing coding step..." << std::endl;
OptimizeCode();
// Get the indices of all the nonzero elements in the codes.
adjacencies = find(codes);
Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem))
/ ((double) (atoms * data.n_cols)) << "%." << std::endl;
// Find the new objective value and improvement so we can check for
// convergence.
double curObjVal = Objective();
double improvement = lastObjVal - curObjVal;
Log::Info << " Objective value: " << curObjVal << " (improvement "
<< std::scientific << improvement << ")." << std::endl;
// Have we converged?
if (improvement < OBJ_TOL)
{
Log::Info << "Converged within tolerance " << OBJ_TOL << ".\n";
break;
}
lastObjVal = curObjVal;
}
}
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::OptimizeCode()
{
// When using the Cholesky version of LARS, this is correct even if
// lambda2 > 0.
arma::mat matGram = trans(dictionary) * dictionary;
for (size_t i = 0; i < data.n_cols; ++i)
{
// Report progress.
if ((i % 100) == 0)
Log::Debug << "Optimization at point " << i << "." << std::endl;
bool useCholesky = true;
regression::LARS lars(useCholesky, matGram, lambda1, lambda2);
// Create an alias of the code (using the same memory), and then LARS will
// place the result directly into that; then we will not need to have an
// extra copy.
arma::vec code = codes.unsafe_col(i);
lars.Regress(dictionary, data.unsafe_col(i), code, true);
}
}
// Dictionary step for optimization.
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::OptimizeDictionary(
const arma::uvec& adjacencies)
{
// Count the number of atomic neighbors for each point x^i.
arma::uvec neighborCounts = arma::zeros<arma::uvec>(data.n_cols, 1);
if (adjacencies.n_elem > 0)
{
// This gets the column index. Intentional integer division.
size_t curPointInd = (size_t) (adjacencies(0) / atoms);
size_t nextColIndex = (curPointInd + 1) * atoms;
for (size_t l = 1; l < adjacencies.n_elem; ++l)
{
// If l no longer refers to an element in this column, advance the column
// number accordingly.
if (adjacencies(l) >= nextColIndex)
{
curPointInd = (size_t) (adjacencies(l) / atoms);
nextColIndex = (curPointInd + 1) * atoms;
}
++neighborCounts(curPointInd);
}
}
// Handle the case of inactive atoms (atoms not used in the given coding).
std::vector<size_t> inactiveAtoms;
std::vector<size_t> activeAtoms;
activeAtoms.reserve(atoms);
for (size_t j = 0; j < atoms; ++j)
{
if (accu(codes.row(j) != 0) == 0)
inactiveAtoms.push_back(j);
}
const size_t nInactiveAtoms = inactiveAtoms.size();
const size_t nActiveAtoms = atoms - nInactiveAtoms;
// Efficient construction of Z restricted to active atoms.
arma::mat matActiveZ;
if (inactiveAtoms.empty())
{
matActiveZ = codes;
}
else
{
arma::uvec inactiveAtomsVec =
arma::conv_to<arma::uvec>::from(inactiveAtoms);
RemoveRows(codes, inactiveAtomsVec, matActiveZ);
}
if (nInactiveAtoms > 0)
{
Log::Warn << "There are " << nInactiveAtoms
<< " inactive atoms. They will be re-initialized randomly.\n";
}
Log::Debug << "Solving Dual via Newton's Method.\n";
// Solve using Newton's method in the dual - note that the final dot
// multiplication with inv(A) seems to be unavoidable. Although more
// expensive, the code written this way (we use solve()) should be more
// numerically stable than just using inv(A) for everything.
arma::vec dualVars = arma::zeros<arma::vec>(nActiveAtoms);
//vec dualVars = 1e-14 * ones<vec>(nActiveAtoms);
// Method used by feature sign code - fails miserably here. Perhaps the
// MATLAB optimizer fmincon does something clever?
//vec dualVars = 10.0 * randu(nActiveAtoms, 1);
//vec dualVars = diagvec(solve(dictionary, data * trans(codes))
// - codes * trans(codes));
//for (size_t i = 0; i < dualVars.n_elem; i++)
// if (dualVars(i) < 0)
// dualVars(i) = 0;
bool converged = false;
arma::mat codesXT = matActiveZ * trans(data);
arma::mat codesZT = matActiveZ * trans(matActiveZ);
double improvement;
for (size_t t = 1; !converged; ++t)
{
arma::mat A = codesZT + diagmat(dualVars);
arma::mat matAInvZXT = solve(A, codesXT);
arma::vec gradient = -(arma::sum(arma::square(matAInvZXT), 1) -
arma::ones<arma::vec>(nActiveAtoms));
arma::mat hessian = -(-2 * (matAInvZXT * trans(matAInvZXT)) % inv(A));
arma::vec searchDirection = -solve(hessian, gradient);
// Armijo line search.
const double c = 1e-4;
double alpha = 1.0;
const double rho = 0.9;
double sufficientDecrease = c * dot(gradient, searchDirection);
while (true)
{
// Calculate objective.
double sumDualVars = sum(dualVars);
double fOld = -(-trace(trans(codesXT) * matAInvZXT) - sumDualVars);
double fNew = -(-trace(trans(codesXT) * solve(codesZT +
diagmat(dualVars + alpha * searchDirection), codesXT)) -
(sumDualVars + alpha * sum(searchDirection)));
if (fNew <= fOld + alpha * sufficientDecrease)
{
searchDirection = alpha * searchDirection;
improvement = fOld - fNew;
break;
}
alpha *= rho;
}
// Take step and print useful information.
dualVars += searchDirection;
double normGradient = norm(gradient, 2);
Log::Debug << "Newton Method iteration " << t << ":" << std::endl;
Log::Debug << " Gradient norm: " << std::scientific << normGradient
<< "." << std::endl;
Log::Debug << " Improvement: " << std::scientific << improvement << ".\n";
if (improvement < NEWTON_TOL)
converged = true;
}
if (inactiveAtoms.empty())
{
// Directly update dictionary.
dictionary = trans(solve(codesZT + diagmat(dualVars), codesXT));
}
else
{
arma::mat activeDictionary = trans(solve(codesZT +
diagmat(dualVars), codesXT));
// Update all atoms.
size_t currentInactiveIndex = 0;
for (size_t i = 0; i < atoms; ++i)
{
if (inactiveAtoms[currentInactiveIndex] == i)
{
// This atom is inactive. Reinitialize it randomly.
dictionary.col(i) = (data.col(math::RandInt(data.n_cols)) +
data.col(math::RandInt(data.n_cols)) +
data.col(math::RandInt(data.n_cols)));
dictionary.col(i) /= norm(dictionary.col(i), 2);
// Increment inactive index counter.
++currentInactiveIndex;
}
else
{
// Update estimate.
dictionary.col(i) = activeDictionary.col(i - currentInactiveIndex);
}
}
}
}
// Project each atom of the dictionary back into the unit ball (if necessary).
template<typename DictionaryInitializer>
void SparseCoding<DictionaryInitializer>::ProjectDictionary()
{
for (size_t j = 0; j < atoms; j++)
{
double atomNorm = norm(dictionary.col(j), 2);
if (atomNorm > 1)
{
Log::Info << "Norm of atom " << j << " exceeds 1 (" << std::scientific
<< atomNorm << "). Shrinking...\n";
dictionary.col(j) /= atomNorm;
}
}
}
// Compute the objective function.
template<typename DictionaryInitializer>
double SparseCoding<DictionaryInitializer>::Objective()
{
double l11NormZ = sum(sum(abs(codes)));
double froNormResidual = norm(data - (dictionary * codes), "fro");
if (lambda2 > 0)
{
double froNormZ = norm(codes, "fro");
return 0.5 * (std::pow(froNormResidual, 2.0) + (lambda2 *
std::pow(froNormZ, 2.0))) + (lambda1 * l11NormZ);
}
else // It can be simpler.
{
return 0.5 * std::pow(froNormResidual, 2.0) + lambda1 * l11NormZ;
}
}
void RemoveRows(const arma::mat& X,
const arma::uvec& rowsToRemove,
arma::mat& modX)
{
const size_t cols = X.n_cols;
const size_t rows = X.n_rows;
const size_t nRemove = rowsToRemove.n_elem;
const size_t nKeep = rows - nRemove;
if (nRemove == 0)
{
modX = X;
}
else
{
modX.set_size(nKeep, cols);
size_t curRow = 0;
size_t removeInd = 0;
// First, check 0 to first row to remove.
if (rowsToRemove(0) > 0)
{
// Note that this implies that n_rows > 1.
size_t height = rowsToRemove(0);
modX(arma::span(curRow, curRow + height - 1), arma::span::all) =
X(arma::span(0, rowsToRemove(0) - 1), arma::span::all);
curRow += height;
}
// Now, check i'th row to remove to (i + 1)'th row to remove, until i is the
// penultimate row.
while (removeInd < nRemove - 1)
{
size_t height = rowsToRemove[removeInd + 1] -
rowsToRemove[removeInd] - 1;
if (height > 0)
{
modX(arma::span(curRow, curRow + height - 1), arma::span::all) =
X(arma::span(rowsToRemove[removeInd] + 1,
rowsToRemove[removeInd + 1] - 1), arma::span::all);
curRow += height;
}
removeInd++;
}
// Now that i is the last row to remove, check last row to remove to last
// row.
if (rowsToRemove[removeInd] < rows - 1)
{
modX(arma::span(curRow, nKeep - 1), arma::span::all) =
X(arma::span(rowsToRemove[removeInd] + 1, rows - 1),
arma::span::all);
}
}
}
}; // namespace sparse_coding
}; // namespace mlpack
#endif
<|endoftext|>
|
<commit_before>/**
* @file
* @brief Definition of default digitization module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#ifndef ALLPIX_DEFAULT_DIGITIZER_MODULE_H
#define ALLPIX_DEFAULT_DIGITIZER_MODULE_H
#include <memory>
#include <random>
#include <string>
#include "core/config/Configuration.hpp"
#include "core/messenger/Messenger.hpp"
#include "core/module/Module.hpp"
#include "objects/PixelCharge.hpp"
#include <TH1D.h>
#include <TH2D.h>
namespace allpix {
/**
* @ingroup Modules
* @brief Module to simulate digitization of collected charges
* @note This module supports parallelization
*
* This module provides a relatively simple simulation of the frontend electronics behavior. It simulates the
* propagation of the signal of collected charges through the amplifier, comparator and ADC while adding electronics
* noise and simulating the threshold as well as accounting for threshold dispersion and ADC noise.
*/
class DefaultDigitizerModule : public Module {
public:
/**
* @brief Constructor for this detector-specific module
* @param config Configuration object for this module as retrieved from the steering file
* @param messenger Pointer to the messenger object to allow binding to messages on the bus
* @param detector Pointer to the detector for this module instance
*/
DefaultDigitizerModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector);
/**
* @brief Initialize optional ROOT histograms
*/
void init() override;
/**
* @brief Simulate digitization process
*/
void run(unsigned int) override;
/**
* @brief Finalize and write optional histograms
*/
void finalize() override;
private:
std::mt19937_64 random_generator_;
Messenger* messenger_;
// Input message with the charges on the pixels
std::shared_ptr<PixelChargeMessage> pixel_message_;
// Statistics
unsigned long long total_hits_{};
// Output histograms
TH1D *h_pxq, *h_pxq_noise, *h_thr, *h_pxq_thr, *h_pxq_adc_smear, *h_pxq_adc;
TH2D* h_calibration;
};
} // namespace allpix
#endif /* ALLPIX_DEFAULT_DIGITIZER_MODULE_H */
<commit_msg>DefaultDigitizer: do nullptr initialization for ROOT histograms<commit_after>/**
* @file
* @brief Definition of default digitization module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#ifndef ALLPIX_DEFAULT_DIGITIZER_MODULE_H
#define ALLPIX_DEFAULT_DIGITIZER_MODULE_H
#include <memory>
#include <random>
#include <string>
#include "core/config/Configuration.hpp"
#include "core/messenger/Messenger.hpp"
#include "core/module/Module.hpp"
#include "objects/PixelCharge.hpp"
#include <TH1D.h>
#include <TH2D.h>
namespace allpix {
/**
* @ingroup Modules
* @brief Module to simulate digitization of collected charges
* @note This module supports parallelization
*
* This module provides a relatively simple simulation of the frontend electronics behavior. It simulates the
* propagation of the signal of collected charges through the amplifier, comparator and ADC while adding electronics
* noise and simulating the threshold as well as accounting for threshold dispersion and ADC noise.
*/
class DefaultDigitizerModule : public Module {
public:
/**
* @brief Constructor for this detector-specific module
* @param config Configuration object for this module as retrieved from the steering file
* @param messenger Pointer to the messenger object to allow binding to messages on the bus
* @param detector Pointer to the detector for this module instance
*/
DefaultDigitizerModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector);
/**
* @brief Initialize optional ROOT histograms
*/
void init() override;
/**
* @brief Simulate digitization process
*/
void run(unsigned int) override;
/**
* @brief Finalize and write optional histograms
*/
void finalize() override;
private:
std::mt19937_64 random_generator_;
Messenger* messenger_;
// Input message with the charges on the pixels
std::shared_ptr<PixelChargeMessage> pixel_message_;
// Statistics
unsigned long long total_hits_{};
// Output histograms
TH1D *h_pxq{}, *h_pxq_noise{}, *h_thr{}, *h_pxq_thr{}, *h_pxq_adc_smear{}, *h_pxq_adc{};
TH2D* h_calibration{};
};
} // namespace allpix
#endif /* ALLPIX_DEFAULT_DIGITIZER_MODULE_H */
<|endoftext|>
|
<commit_before>/**
* @file
* @brief Implementation of Geant4 deposition module
* @remarks Based on code from Mathieu Benoit
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "DepositionGeant4Module.hpp"
#include <limits>
#include <string>
#include <utility>
#include <G4EmParameters.hh>
#include <G4HadronicProcessStore.hh>
#include <G4LogicalVolume.hh>
#include <G4PhysListFactory.hh>
#include <G4RunManager.hh>
#include <G4StepLimiterPhysics.hh>
#include <G4UImanager.hh>
#include <G4UserLimits.hh>
#include "core/config/exceptions.h"
#include "core/geometry/GeometryManager.hpp"
#include "core/module/exceptions.h"
#include "core/utils/log.h"
#include "objects/DepositedCharge.hpp"
#include "tools/ROOT.h"
#include "tools/geant4.h"
#include "GeneratorActionG4.hpp"
#include "SensitiveDetectorActionG4.hpp"
#define G4_NUM_SEEDS 10
using namespace allpix;
/**
* Includes the particle source point to the geometry using \ref GeometryManager::addPoint.
*/
DepositionGeant4Module::DepositionGeant4Module(Configuration config, Messenger* messenger, GeometryManager* geo_manager)
: Module(std::move(config)), messenger_(messenger), geo_manager_(geo_manager), last_event_num_(1),
run_manager_g4_(nullptr) {
// Create user limits for maximum step length in the sensor
user_limits_ = std::make_unique<G4UserLimits>(config_.get<double>("max_step_length", Units::get(1.0, "um")));
// Set default physics list
config_.setDefault("physics_list", "FTFP_BERT_LIV");
config_.setDefault<bool>("output_plots", false);
config_.setDefault<int>("output_plots_scale", Units::get(100, "ke"));
// Add the particle source position to the geometry
geo_manager_->addPoint(config_.get<ROOT::Math::XYZPoint>("beam_position"));
}
/**
* Module depends on \ref GeometryBuilderGeant4Module loaded first, because it owns the pointer to the Geant4 run manager.
*/
void DepositionGeant4Module::init() {
// Load the G4 run manager (which is owned by the geometry builder)
run_manager_g4_ = G4RunManager::GetRunManager();
if(run_manager_g4_ == nullptr) {
throw ModuleError("Cannot deposit charges using Geant4 without a Geant4 geometry builder");
}
// Suppress all output from G4
SUPPRESS_STREAM(G4cout);
// Get UI manager for sending commands
G4UImanager* ui_g4 = G4UImanager::GetUIpointer();
// Apply optional PAI model
if(config_.get<bool>("enable_pai", false)) {
LOG(TRACE) << "Enabling PAI model on all detectors";
G4EmParameters::Instance();
for(auto& detector : geo_manager_->getDetectors()) {
// Get logical volume
auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log");
if(logical_volume == nullptr) {
throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)");
}
// Create region
G4Region* region = new G4Region(detector->getName() + "_sensor_region");
region->AddRootLogicalVolume(logical_volume.get());
auto pai_model = config_.get<std::string>("pai_model", "pai");
auto lcase_model = pai_model;
std::transform(lcase_model.begin(), lcase_model.end(), lcase_model.begin(), ::tolower);
if(lcase_model == "pai") {
pai_model = "PAI";
} else if(lcase_model == "paiphoton") {
pai_model = "PAIphoton";
} else {
throw InvalidValueError(config_, "pai_model", "model has to be either 'pai' or 'paiphoton'");
}
ui_g4->ApplyCommand("/process/em/AddPAIRegion all " + region->GetName() + " " + pai_model);
}
}
// Find the physics list
G4PhysListFactory physListFactory;
G4VModularPhysicsList* physicsList = physListFactory.GetReferencePhysList(config_.get<std::string>("physics_list"));
if(physicsList == nullptr) {
std::string message = "specified physics list does not exists";
std::vector<G4String> base_lists = physListFactory.AvailablePhysLists();
message += " (available base lists are ";
for(auto& base_list : base_lists) {
message += base_list;
message += ", ";
}
message = message.substr(0, message.size() - 2);
message += " with optional suffixes for electromagnetic lists ";
std::vector<G4String> em_lists = physListFactory.AvailablePhysListsEM();
for(auto& em_list : em_lists) {
if(em_list.empty()) {
continue;
}
message += em_list;
message += ", ";
}
message = message.substr(0, message.size() - 2);
message += ")";
throw InvalidValueError(config_, "physics_list", message);
} else {
LOG(INFO) << "Using G4 physics list \"" << config_.get<std::string>("physics_list") << "\"";
}
// Register a step limiter (uses the user limits defined earlier)
physicsList->RegisterPhysics(new G4StepLimiterPhysics());
// Set the range-cut off threshold for secondary production:
double production_cut;
if(config_.has("range_cut")) {
production_cut = config_.get<double>("range_cut");
LOG(INFO) << "Setting configured G4 production cut to " << Units::display(production_cut, {"mm", "um"});
} else {
// Define the production cut as one fifth of the minimum size (thickness, pitch) among the detectors
double min_size = std::numeric_limits<double>::max();
std::string min_detector;
for(auto& detector : geo_manager_->getDetectors()) {
auto model = detector->getModel();
double prev_min_size = min_size;
min_size = std::min(std::min(std::min(min_size, model->getPixelSize().x()), model->getPixelSize().y()),
model->getSensorSize().z());
if(min_size != prev_min_size) {
min_detector = detector->getName();
}
}
production_cut = min_size / 5;
LOG(INFO) << "Setting G4 production cut to " << Units::display(production_cut, {"mm", "um"})
<< ", derived from properties of detector \"" << min_detector << "\"";
}
ui_g4->ApplyCommand("/run/setCut " + std::to_string(production_cut));
// Initialize the physics list
LOG(TRACE) << "Initializing physics processes";
run_manager_g4_->SetUserInitialization(physicsList);
run_manager_g4_->InitializePhysics();
// Initialize the full run manager to ensure correct state flags
run_manager_g4_->Initialize();
// Build particle generator
LOG(TRACE) << "Constructing particle source";
auto generator = new GeneratorActionG4(config_);
run_manager_g4_->SetUserAction(generator);
// Get the creation energy for charge (default is silicon electron hole pair energy)
auto charge_creation_energy = config_.get<double>("charge_creation_energy", Units::get(3.64, "eV"));
// Loop through all detectors and set the sensitive detector action that handles the particle passage
bool useful_deposition = false;
for(auto& detector : geo_manager_->getDetectors()) {
// Do not add sensitive detector for detectors that have no listeners for the deposited charges
// FIXME Probably the MCParticle has to be checked as well
if(!messenger_->hasReceiver(this,
std::make_shared<DepositedChargeMessage>(std::vector<DepositedCharge>(), detector))) {
LOG(INFO) << "Not depositing charges in " << detector->getName()
<< " because there is no listener for its output";
continue;
}
useful_deposition = true;
// Get model of the sensitive device
auto sensitive_detector_action = new SensitiveDetectorActionG4(this, detector, messenger_, charge_creation_energy);
auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log");
if(logical_volume == nullptr) {
throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)");
}
// Apply the user limits to this element
logical_volume->SetUserLimits(user_limits_.get());
// Add the sensitive detector action
logical_volume->SetSensitiveDetector(sensitive_detector_action);
sensors_.push_back(sensitive_detector_action);
// If requested, prepare output plots
if(config_.get<bool>("output_plots")) {
LOG(TRACE) << "Creating output plots";
// Plot axis are in kilo electrons - convert from framework units!
int maximum = static_cast<int>(Units::convert(config_.get<int>("output_plots_scale"), "ke"));
int nbins = 5 * maximum;
// Create histograms if needed
std::string plot_name = "deposited_charge_" + sensitive_detector_action->getName();
charge_per_event_[sensitive_detector_action->getName()] =
new TH1D(plot_name.c_str(), "deposited charge per event;deposited charge [ke];events", nbins, 0, maximum);
}
}
if(!useful_deposition) {
LOG(ERROR) << "Not a single listener for deposited charges, module is useless!";
}
// Disable verbose messages from processes
ui_g4->ApplyCommand("/process/verbose 0");
ui_g4->ApplyCommand("/process/em/verbose 0");
ui_g4->ApplyCommand("/process/eLoss/verbose 0");
G4HadronicProcessStore::Instance()->SetVerbose(0);
// Set the random seed for Geant4 generation
// NOTE Assumes this is the only Geant4 module using random numbers
std::string seed_command = "/random/setSeeds ";
for(int i = 0; i < G4_NUM_SEEDS; ++i) {
seed_command += std::to_string(static_cast<uint32_t>(getRandomSeed() % INT_MAX));
if(i != G4_NUM_SEEDS - 1) {
seed_command += " ";
}
}
ui_g4->ApplyCommand(seed_command);
// Release the output stream
RELEASE_STREAM(G4cout);
}
void DepositionGeant4Module::run(unsigned int event_num) {
// Suppress output stream if not in debugging mode
IFLOG(DEBUG);
else {
SUPPRESS_STREAM(G4cout);
}
// Start a single event from the beam
LOG(TRACE) << "Enabling beam";
run_manager_g4_->BeamOn(static_cast<int>(config_.get<unsigned int>("number_of_particles", 1)));
last_event_num_ = event_num;
// Release the stream (if it was suspended)
RELEASE_STREAM(G4cout);
// Dispatch the necessary messages
for(auto& sensor : sensors_) {
sensor->dispatchMessages();
// Fill output plots if requested:
if(config_.get<bool>("output_plots")) {
double charge = static_cast<double>(Units::convert(sensor->getDepositedCharge(), "ke"));
charge_per_event_[sensor->getName()]->Fill(charge);
}
}
}
void DepositionGeant4Module::finalize() {
size_t total_charges = 0;
for(auto& sensor : sensors_) {
total_charges += sensor->getTotalDepositedCharge();
}
if(config_.get<bool>("output_plots")) {
// Write histograms
LOG(TRACE) << "Writing output plots to file";
for(auto& plot : charge_per_event_) {
plot.second->Write();
}
}
// Print summary or warns if module did not output any charges
if(!sensors_.empty() && total_charges > 0 && last_event_num_ > 0) {
size_t average_charge = total_charges / sensors_.size() / last_event_num_;
LOG(INFO) << "Deposited total of " << total_charges << " charges in " << sensors_.size() << " sensor(s) (average of "
<< average_charge << " per sensor for every event)";
} else {
LOG(WARNING) << "No charges deposited";
}
}
<commit_msg>std::min: use initializer list instead of nested calls<commit_after>/**
* @file
* @brief Implementation of Geant4 deposition module
* @remarks Based on code from Mathieu Benoit
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "DepositionGeant4Module.hpp"
#include <limits>
#include <string>
#include <utility>
#include <G4EmParameters.hh>
#include <G4HadronicProcessStore.hh>
#include <G4LogicalVolume.hh>
#include <G4PhysListFactory.hh>
#include <G4RunManager.hh>
#include <G4StepLimiterPhysics.hh>
#include <G4UImanager.hh>
#include <G4UserLimits.hh>
#include "core/config/exceptions.h"
#include "core/geometry/GeometryManager.hpp"
#include "core/module/exceptions.h"
#include "core/utils/log.h"
#include "objects/DepositedCharge.hpp"
#include "tools/ROOT.h"
#include "tools/geant4.h"
#include "GeneratorActionG4.hpp"
#include "SensitiveDetectorActionG4.hpp"
#define G4_NUM_SEEDS 10
using namespace allpix;
/**
* Includes the particle source point to the geometry using \ref GeometryManager::addPoint.
*/
DepositionGeant4Module::DepositionGeant4Module(Configuration config, Messenger* messenger, GeometryManager* geo_manager)
: Module(std::move(config)), messenger_(messenger), geo_manager_(geo_manager), last_event_num_(1),
run_manager_g4_(nullptr) {
// Create user limits for maximum step length in the sensor
user_limits_ = std::make_unique<G4UserLimits>(config_.get<double>("max_step_length", Units::get(1.0, "um")));
// Set default physics list
config_.setDefault("physics_list", "FTFP_BERT_LIV");
config_.setDefault<bool>("output_plots", false);
config_.setDefault<int>("output_plots_scale", Units::get(100, "ke"));
// Add the particle source position to the geometry
geo_manager_->addPoint(config_.get<ROOT::Math::XYZPoint>("beam_position"));
}
/**
* Module depends on \ref GeometryBuilderGeant4Module loaded first, because it owns the pointer to the Geant4 run manager.
*/
void DepositionGeant4Module::init() {
// Load the G4 run manager (which is owned by the geometry builder)
run_manager_g4_ = G4RunManager::GetRunManager();
if(run_manager_g4_ == nullptr) {
throw ModuleError("Cannot deposit charges using Geant4 without a Geant4 geometry builder");
}
// Suppress all output from G4
SUPPRESS_STREAM(G4cout);
// Get UI manager for sending commands
G4UImanager* ui_g4 = G4UImanager::GetUIpointer();
// Apply optional PAI model
if(config_.get<bool>("enable_pai", false)) {
LOG(TRACE) << "Enabling PAI model on all detectors";
G4EmParameters::Instance();
for(auto& detector : geo_manager_->getDetectors()) {
// Get logical volume
auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log");
if(logical_volume == nullptr) {
throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)");
}
// Create region
G4Region* region = new G4Region(detector->getName() + "_sensor_region");
region->AddRootLogicalVolume(logical_volume.get());
auto pai_model = config_.get<std::string>("pai_model", "pai");
auto lcase_model = pai_model;
std::transform(lcase_model.begin(), lcase_model.end(), lcase_model.begin(), ::tolower);
if(lcase_model == "pai") {
pai_model = "PAI";
} else if(lcase_model == "paiphoton") {
pai_model = "PAIphoton";
} else {
throw InvalidValueError(config_, "pai_model", "model has to be either 'pai' or 'paiphoton'");
}
ui_g4->ApplyCommand("/process/em/AddPAIRegion all " + region->GetName() + " " + pai_model);
}
}
// Find the physics list
G4PhysListFactory physListFactory;
G4VModularPhysicsList* physicsList = physListFactory.GetReferencePhysList(config_.get<std::string>("physics_list"));
if(physicsList == nullptr) {
std::string message = "specified physics list does not exists";
std::vector<G4String> base_lists = physListFactory.AvailablePhysLists();
message += " (available base lists are ";
for(auto& base_list : base_lists) {
message += base_list;
message += ", ";
}
message = message.substr(0, message.size() - 2);
message += " with optional suffixes for electromagnetic lists ";
std::vector<G4String> em_lists = physListFactory.AvailablePhysListsEM();
for(auto& em_list : em_lists) {
if(em_list.empty()) {
continue;
}
message += em_list;
message += ", ";
}
message = message.substr(0, message.size() - 2);
message += ")";
throw InvalidValueError(config_, "physics_list", message);
} else {
LOG(INFO) << "Using G4 physics list \"" << config_.get<std::string>("physics_list") << "\"";
}
// Register a step limiter (uses the user limits defined earlier)
physicsList->RegisterPhysics(new G4StepLimiterPhysics());
// Set the range-cut off threshold for secondary production:
double production_cut;
if(config_.has("range_cut")) {
production_cut = config_.get<double>("range_cut");
LOG(INFO) << "Setting configured G4 production cut to " << Units::display(production_cut, {"mm", "um"});
} else {
// Define the production cut as one fifth of the minimum size (thickness, pitch) among the detectors
double min_size = std::numeric_limits<double>::max();
std::string min_detector;
for(auto& detector : geo_manager_->getDetectors()) {
auto model = detector->getModel();
double prev_min_size = min_size;
min_size =
std::min({min_size, model->getPixelSize().x(), model->getPixelSize().y(), model->getSensorSize().z()});
if(min_size != prev_min_size) {
min_detector = detector->getName();
}
}
production_cut = min_size / 5;
LOG(INFO) << "Setting G4 production cut to " << Units::display(production_cut, {"mm", "um"})
<< ", derived from properties of detector \"" << min_detector << "\"";
}
ui_g4->ApplyCommand("/run/setCut " + std::to_string(production_cut));
// Initialize the physics list
LOG(TRACE) << "Initializing physics processes";
run_manager_g4_->SetUserInitialization(physicsList);
run_manager_g4_->InitializePhysics();
// Initialize the full run manager to ensure correct state flags
run_manager_g4_->Initialize();
// Build particle generator
LOG(TRACE) << "Constructing particle source";
auto generator = new GeneratorActionG4(config_);
run_manager_g4_->SetUserAction(generator);
// Get the creation energy for charge (default is silicon electron hole pair energy)
auto charge_creation_energy = config_.get<double>("charge_creation_energy", Units::get(3.64, "eV"));
// Loop through all detectors and set the sensitive detector action that handles the particle passage
bool useful_deposition = false;
for(auto& detector : geo_manager_->getDetectors()) {
// Do not add sensitive detector for detectors that have no listeners for the deposited charges
// FIXME Probably the MCParticle has to be checked as well
if(!messenger_->hasReceiver(this,
std::make_shared<DepositedChargeMessage>(std::vector<DepositedCharge>(), detector))) {
LOG(INFO) << "Not depositing charges in " << detector->getName()
<< " because there is no listener for its output";
continue;
}
useful_deposition = true;
// Get model of the sensitive device
auto sensitive_detector_action = new SensitiveDetectorActionG4(this, detector, messenger_, charge_creation_energy);
auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log");
if(logical_volume == nullptr) {
throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)");
}
// Apply the user limits to this element
logical_volume->SetUserLimits(user_limits_.get());
// Add the sensitive detector action
logical_volume->SetSensitiveDetector(sensitive_detector_action);
sensors_.push_back(sensitive_detector_action);
// If requested, prepare output plots
if(config_.get<bool>("output_plots")) {
LOG(TRACE) << "Creating output plots";
// Plot axis are in kilo electrons - convert from framework units!
int maximum = static_cast<int>(Units::convert(config_.get<int>("output_plots_scale"), "ke"));
int nbins = 5 * maximum;
// Create histograms if needed
std::string plot_name = "deposited_charge_" + sensitive_detector_action->getName();
charge_per_event_[sensitive_detector_action->getName()] =
new TH1D(plot_name.c_str(), "deposited charge per event;deposited charge [ke];events", nbins, 0, maximum);
}
}
if(!useful_deposition) {
LOG(ERROR) << "Not a single listener for deposited charges, module is useless!";
}
// Disable verbose messages from processes
ui_g4->ApplyCommand("/process/verbose 0");
ui_g4->ApplyCommand("/process/em/verbose 0");
ui_g4->ApplyCommand("/process/eLoss/verbose 0");
G4HadronicProcessStore::Instance()->SetVerbose(0);
// Set the random seed for Geant4 generation
// NOTE Assumes this is the only Geant4 module using random numbers
std::string seed_command = "/random/setSeeds ";
for(int i = 0; i < G4_NUM_SEEDS; ++i) {
seed_command += std::to_string(static_cast<uint32_t>(getRandomSeed() % INT_MAX));
if(i != G4_NUM_SEEDS - 1) {
seed_command += " ";
}
}
ui_g4->ApplyCommand(seed_command);
// Release the output stream
RELEASE_STREAM(G4cout);
}
void DepositionGeant4Module::run(unsigned int event_num) {
// Suppress output stream if not in debugging mode
IFLOG(DEBUG);
else {
SUPPRESS_STREAM(G4cout);
}
// Start a single event from the beam
LOG(TRACE) << "Enabling beam";
run_manager_g4_->BeamOn(static_cast<int>(config_.get<unsigned int>("number_of_particles", 1)));
last_event_num_ = event_num;
// Release the stream (if it was suspended)
RELEASE_STREAM(G4cout);
// Dispatch the necessary messages
for(auto& sensor : sensors_) {
sensor->dispatchMessages();
// Fill output plots if requested:
if(config_.get<bool>("output_plots")) {
double charge = static_cast<double>(Units::convert(sensor->getDepositedCharge(), "ke"));
charge_per_event_[sensor->getName()]->Fill(charge);
}
}
}
void DepositionGeant4Module::finalize() {
size_t total_charges = 0;
for(auto& sensor : sensors_) {
total_charges += sensor->getTotalDepositedCharge();
}
if(config_.get<bool>("output_plots")) {
// Write histograms
LOG(TRACE) << "Writing output plots to file";
for(auto& plot : charge_per_event_) {
plot.second->Write();
}
}
// Print summary or warns if module did not output any charges
if(!sensors_.empty() && total_charges > 0 && last_event_num_ > 0) {
size_t average_charge = total_charges / sensors_.size() / last_event_num_;
LOG(INFO) << "Deposited total of " << total_charges << " charges in " << sensors_.size() << " sensor(s) (average of "
<< average_charge << " per sensor for every event)";
} else {
LOG(WARNING) << "No charges deposited";
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "ocean.h"
#include "../use/texture.h"
#include "../water/grid.h"
namespace redc { namespace effects
{
void Ocean_Effect::init(gfx::IDriver& driver,
po::variables_map const&) noexcept
{
// Make a grid and upload it
auto water_grid = water::gen_grid(200);
water_base_ = {{0.0f, 1.0f, 0.0f}, 0.0f};
elements_ = water_grid.size();
grid_mesh_ = driver.make_mesh_repr();
auto uv_buf =
grid_mesh_->allocate_buffer(sizeof(float) * 2 * water_grid.size(),
redc::Usage_Hint::Draw,
redc::Upload_Hint::Static);
grid_mesh_->format_buffer(uv_buf, 0, 2, Buffer_Format::Float, 0, 0);
grid_mesh_->enable_vertex_attrib(0);
grid_mesh_->buffer_data(uv_buf, 0, sizeof(float) * 2 * water_grid.size(),
&water_grid[0]);
grid_mesh_->set_primitive_type(Primitive_Type::Triangle);
// Initialize the shader
shader_ = driver.make_shader_repr();
shader_->load_vertex_part("shader/water/vs.glsl");
shader_->load_fragment_part("shader/water/fs.glsl");
auto plane_loc = shader_->get_location("plane");
shader_->set_vec4(plane_loc, plane_as_vec4(water_base_));
time_loc_ = shader_->get_location("time");
shader_->set_float(time_loc_, 0.0f);
Ocean_Gen params;
params.octaves = 5;
params.amplitude = 0.2f;
params.frequency = 0.5f;
params.persistence = .5f;
params.lacunarity = .6f;
set_ocean_gen_parameters(params);
projector_loc_ = shader_->get_location("projector");
shader_->set_view_name("view");
shader_->set_projection_name("proj");
shader_->set_matrix(projector_loc_, glm::mat4(1.0f));
shader_->set_view(glm::mat4(1.0f));
shader_->set_projection(glm::mat4(1.0f));
cam_pos_loc_ = shader_->get_location("camera_pos");
light_dir_loc_ = shader_->get_location("light_dir");
auto water_envmap_loc = shader_->get_location("envmap");
shader_->set_integer(water_envmap_loc, 0);
start_ = std::chrono::high_resolution_clock::now();
}
void Ocean_Effect::render(gfx::IDriver& driver,
gfx::Camera const& cam) noexcept
{
// Render water
driver.use_shader(*shader_);
use_camera(driver, cam);
shader_->set_vec3(cam_pos_loc_, cam.look_at.eye);
// In case they have changed in the meantime
update_ocean_gen_params();
shader_->set_vec3(light_dir_loc_,
glm::normalize(glm::vec3(5.0f, 5.0f, -6.0f)));
auto intersections = water::find_visible(cam, water_base_.dist, max_disp_);
if(intersections.size())
{
auto projector = build_projector(cam, water_base_, max_disp_);
auto range = build_min_max_mat(intersections, projector, water_base_);
projector = projector * range;
shader_->set_matrix(projector_loc_, projector);
namespace chrono = std::chrono;
// current time
auto now = chrono::high_resolution_clock::now();
// microseconds since start
auto us = chrono::duration_cast<chrono::microseconds>(now - start_);
// time in seconds since start
float time_s = us.count() / 1000000.0f;
shader_->set_float(time_loc_, time_s);
grid_mesh_->draw_arrays(0, elements_);
}
}
void Ocean_Effect::set_ocean_gen_parameters(Ocean_Gen const& gen) noexcept
{
gen_params_ = gen;
needs_gen_params_update_ = true;
}
void Ocean_Effect::update_ocean_gen_params() noexcept
{
// Update the uniforms in the shader.
if(needs_gen_params_update_)
{
needs_gen_params_update_ = false;
shader_->set_integer(shader_->get_location("octaves_in"),
gen_params_.octaves);
shader_->set_float(shader_->get_location("amplitude_in"),
gen_params_.amplitude);
shader_->set_float(shader_->get_location("frequency_in"),
gen_params_.frequency);
shader_->set_float(shader_->get_location("persistence_in"),
gen_params_.persistence);
shader_->set_float(shader_->get_location("lacunarity_in"),
gen_params_.lacunarity);
// TODO: Base this off the above parameters.
max_disp_ = 1.0f;
}
}
} }
<commit_msg>Speed up ocean<commit_after>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "ocean.h"
#include "../use/texture.h"
#include "../water/grid.h"
namespace redc { namespace effects
{
void Ocean_Effect::init(gfx::IDriver& driver,
po::variables_map const&) noexcept
{
// Make a grid and upload it
auto water_grid = water::gen_grid(200);
water_base_ = {{0.0f, 1.0f, 0.0f}, 0.0f};
elements_ = water_grid.size();
grid_mesh_ = driver.make_mesh_repr();
auto uv_buf =
grid_mesh_->allocate_buffer(sizeof(float) * 2 * water_grid.size(),
redc::Usage_Hint::Draw,
redc::Upload_Hint::Static);
grid_mesh_->format_buffer(uv_buf, 0, 2, Buffer_Format::Float, 0, 0);
grid_mesh_->enable_vertex_attrib(0);
grid_mesh_->buffer_data(uv_buf, 0, sizeof(float) * 2 * water_grid.size(),
&water_grid[0]);
grid_mesh_->set_primitive_type(Primitive_Type::Triangle);
// Initialize the shader
shader_ = driver.make_shader_repr();
shader_->load_vertex_part("shader/water/vs.glsl");
shader_->load_fragment_part("shader/water/fs.glsl");
auto plane_loc = shader_->get_location("plane");
shader_->set_vec4(plane_loc, plane_as_vec4(water_base_));
time_loc_ = shader_->get_location("time");
shader_->set_float(time_loc_, 0.0f);
Ocean_Gen params;
params.octaves = 5;
params.amplitude = 0.2f;
params.frequency = 0.5f;
params.persistence = .5f;
params.lacunarity = .6f;
set_ocean_gen_parameters(params);
projector_loc_ = shader_->get_location("projector");
shader_->set_view_name("view");
shader_->set_projection_name("proj");
shader_->set_matrix(projector_loc_, glm::mat4(1.0f));
shader_->set_view(glm::mat4(1.0f));
shader_->set_projection(glm::mat4(1.0f));
cam_pos_loc_ = shader_->get_location("camera_pos");
light_dir_loc_ = shader_->get_location("light_dir");
auto water_envmap_loc = shader_->get_location("envmap");
shader_->set_integer(water_envmap_loc, 0);
start_ = std::chrono::high_resolution_clock::now();
}
void Ocean_Effect::render(gfx::IDriver& driver,
gfx::Camera const& cam) noexcept
{
// Render water
driver.use_shader(*shader_);
use_camera(driver, cam);
shader_->set_vec3(cam_pos_loc_, cam.look_at.eye);
// In case they have changed in the meantime
update_ocean_gen_params();
shader_->set_vec3(light_dir_loc_,
glm::normalize(glm::vec3(5.0f, 5.0f, -6.0f)));
auto intersections = water::find_visible(cam, water_base_.dist, max_disp_);
if(intersections.size())
{
auto projector = build_projector(cam, water_base_, max_disp_);
auto range = build_min_max_mat(intersections, projector, water_base_);
projector = projector * range;
shader_->set_matrix(projector_loc_, projector);
namespace chrono = std::chrono;
// current time
auto now = chrono::high_resolution_clock::now();
// microseconds since start
auto us = chrono::duration_cast<chrono::microseconds>(now - start_);
// time in seconds since start
float time_s = us.count() / 10000.0f;
shader_->set_float(time_loc_, time_s);
grid_mesh_->draw_arrays(0, elements_);
}
}
void Ocean_Effect::set_ocean_gen_parameters(Ocean_Gen const& gen) noexcept
{
gen_params_ = gen;
needs_gen_params_update_ = true;
}
void Ocean_Effect::update_ocean_gen_params() noexcept
{
// Update the uniforms in the shader.
if(needs_gen_params_update_)
{
needs_gen_params_update_ = false;
shader_->set_integer(shader_->get_location("octaves_in"),
gen_params_.octaves);
shader_->set_float(shader_->get_location("amplitude_in"),
gen_params_.amplitude);
shader_->set_float(shader_->get_location("frequency_in"),
gen_params_.frequency);
shader_->set_float(shader_->get_location("persistence_in"),
gen_params_.persistence);
shader_->set_float(shader_->get_location("lacunarity_in"),
gen_params_.lacunarity);
// TODO: Base this off the above parameters.
max_disp_ = 1.0f;
}
}
} }
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include "Futaba30xServo.hpp"
// todo rosparam
const int step = 23;
const double step_rad = static_cast<double>(step)*0.1f*M_PI/180.0f;
class FutabaDriver {
private :
tf::TransformBroadcaster laser_tilt_pub;
tf::TransformBroadcaster laser_offset_pub;
Futaba30x servo;
ros::Rate loop_rate;
int step_cnt;
bool is_up;
public :
FutabaDriver(ros::NodeHandle &node, int fd) :
servo(fd, 1), loop_rate(20), step_cnt(0), is_up(true)
{
servo.torque_on();
}
void run() {
while (ros::ok()) {
// 現在のtfデータ発行
PublishLaserTf();
// サーボ動かす
MoveToNextAngle();
// ros::spinOnce();
loop_rate.sleep();
}
}
private :
void PublishLaserTf() {
// 現在のサーボの角度を通知
laser_tilt_pub.sendTransform(
tf::StampedTransform(
tf::Transform(tf::Quaternion(-step_cnt*step_rad, 0, 0), tf::Vector3(0.0, 0.0, 0.675)),
ros::Time::now(),"body", "laser_link"
)
);
// サーボの回転中心と,URGのオフセット FIXME 毎回更新しなくてもいいデータ
laser_offset_pub.sendTransform(
tf::StampedTransform(
tf::Transform(tf::Quaternion(0, 0, 0), tf::Vector3(0.0, 0.0, 0.09)), // TODO オフセットの実際の値
ros::Time::now(),"laser_link", "rear_laser"
)
);
}
// 現在のURGのスキャンデータを,laser_assemblerに対して発行するよう要求
void MoveToNextAngle() {
if (step_cnt>=20 && is_up) is_up = false;
else if (step_cnt<=0 && !is_up) is_up = true;
else step_cnt += is_up ? 1 : -1;
servo.move(step*step_cnt, 5);
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "servo_driver");
ros::NodeHandle node;
struct termios oldtio, newtio; /* シリアル通信設定 */
// todo 変更可能に
int servo_fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY); /* デバイスをオープンする */
ioctl(servo_fd, TCGETS, &oldtio); /* 現在のシリアルポートの設定を待避させる */
newtio = oldtio; /* ポートの設定をコピー */
// 通信設定
newtio.c_cc[VMIN] = 1; // 最低一文字送受信
newtio.c_cc[VTIME] = 0;
// キャラクラビット8, 受信可能に,制御信号無視
newtio.c_cflag = CS8 | CREAD | CLOCAL;
// ブレーク信号無視, パリティ無視
newtio.c_iflag = IGNBRK | IGNPAR;
int ret = cfsetspeed(&newtio, B460800);
if (ret < 0) {
ROS_INFO("Error in cfsetspeed");
close(servo_fd);
return 1;
}
ioctl(servo_fd, TCSETS, &newtio);
FutabaDriver futaba_driver(node, servo_fd);
futaba_driver.run();
return 0;
}
<commit_msg>Fixed init bug<commit_after>#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include "Futaba30xServo.hpp"
// todo rosparam
const int step = 23;
const double step_rad = static_cast<double>(step)*0.1f*M_PI/180.0f;
class FutabaDriver {
private :
tf::TransformBroadcaster laser_tilt_pub;
tf::TransformBroadcaster laser_offset_pub;
Futaba30x servo;
ros::Rate loop_rate;
int step_cnt;
bool is_up;
int servo_fd;
std::string port_name;
public :
FutabaDriver(ros::NodeHandle &node) :
servo(servo_fd, 1), loop_rate(20), step_cnt(0), is_up(true),
port_name("/dev/ttyUSB0")
{
ros::NodeHandle private_nh("~");
private_nh.getParam("port_name",port_name);
servo.torque_on();
}
bool init(){
/* シリアル通信設定 */
struct termios oldtio, newtio;
servo_fd = open(port_name.c_str(), O_RDWR | O_NOCTTY); /* デバイスをオープンする */
ioctl(servo_fd, TCGETS, &oldtio); /* 現在のシリアルポートの設定を待避させる */
newtio = oldtio; /* ポートの設定をコピー */
// 通信設定
newtio.c_cc[VMIN] = 1; // 最低一文字送受信
newtio.c_cc[VTIME] = 0;
// キャラクラビット8, 受信可能に,制御信号無視
newtio.c_cflag = CS8 | CREAD | CLOCAL;
// ブレーク信号無視, パリティ無視
newtio.c_iflag = IGNBRK | IGNPAR;
int ret = cfsetspeed(&newtio, B460800);
if (ret < 0) {
ROS_INFO("Error in cfsetspeed");
close(servo_fd);
return 1;
}
ioctl(servo_fd, TCSETS, &newtio);
}
void run() {
while (ros::ok()) {
// 現在のtfデータ発行
PublishLaserTf();
// サーボ動かす
MoveToNextAngle();
// ros::spinOnce();
loop_rate.sleep();
}
}
private :
void PublishLaserTf() {
// 現在のサーボの角度を通知
laser_tilt_pub.sendTransform(
tf::StampedTransform(
tf::Transform(tf::Quaternion(-step_cnt*step_rad, 0, 0), tf::Vector3(0.0, 0.0, 0.675)),
ros::Time::now(),"body", "laser_link"
)
);
// サーボの回転中心と,URGのオフセット FIXME 毎回更新しなくてもいいデータ
laser_offset_pub.sendTransform(
tf::StampedTransform(
tf::Transform(tf::Quaternion(0, 0, 0), tf::Vector3(0.0, 0.0, 0.09)), // TODO オフセットの実際の値
ros::Time::now(),"laser_link", "rear_laser"
)
);
}
// 現在のURGのスキャンデータを,laser_assemblerに対して発行するよう要求
void MoveToNextAngle() {
if (step_cnt>=20 && is_up) is_up = false;
else if (step_cnt<=0 && !is_up) is_up = true;
else step_cnt += is_up ? 1 : -1;
servo.move(step*step_cnt, 5);
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "servo_driver");
ros::NodeHandle node;
FutabaDriver futaba_driver(node);
if(futaba_driver.init()){
return 0;
}
futaba_driver.run();
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.