<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 Qt Build Suite.
**
** 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 "rulesapplicator.h"

#include "artifact.h"
#include "buildgraph.h"
#include "productbuilddata.h"
#include "projectbuilddata.h"
#include "rulesevaluationcontext.h"
#include "transformer.h"
#include <jsextensions/moduleproperties.h>
#include <language/artifactproperties.h>
#include <language/language.h>
#include <language/scriptengine.h>
#include <logging/translator.h>
#include <tools/error.h>
#include <tools/scripttools.h>
#include <tools/qbsassert.h>

#include <QDir>

namespace qbs {
namespace Internal {

RulesApplicator::RulesApplicator(const ResolvedProductPtr &product,
                                 ArtifactsPerFileTagMap &artifactsPerFileTag, const Logger &logger)
    : m_product(product)
    , m_artifactsPerFileTag(artifactsPerFileTag)
    , m_logger(logger)
    , m_productObjectId(-1)
{
}

void RulesApplicator::applyAllRules()
{
    RulesEvaluationContext::Scope s(m_product->topLevelProject()->buildData->evaluationContext.data());
    foreach (const RuleConstPtr &rule, m_product->topSortedRules())
        applyRule(rule);
}

void RulesApplicator::applyRule(const RuleConstPtr &rule)
{
    m_rule = rule;
    QScriptValue scopeValue = scope();
    setupScriptEngineForProduct(engine(), m_product, m_rule, scopeValue, this);
    Q_ASSERT_X(scope().property("product").strictlyEquals(engine()->evaluate("product")),
               "BG", "Product object is not in current scope.");
    m_productObjectId = scopeValue.property(QLatin1String("product")).objectId();

    ArtifactList inputArtifacts;
    foreach (const FileTag &fileTag, m_rule->inputs)
        inputArtifacts.unite(m_artifactsPerFileTag.value(fileTag));
    if (m_rule->multiplex) { // apply the rule once for a set of inputs
        if (!inputArtifacts.isEmpty())
            doApply(inputArtifacts);
    } else { // apply the rule once for each input
        ArtifactList lst;
        foreach (Artifact * const inputArtifact, inputArtifacts) {
            setupScriptEngineForArtifact(inputArtifact);
            lst += inputArtifact;
            doApply(lst);
            lst.clear();
        }
    }
}

void RulesApplicator::doApply(const ArtifactList &inputArtifacts)
{
    evalContext()->checkForCancelation();

    if (m_logger.debugEnabled()) {
        m_logger.qbsDebug() << "[BG] apply rule " << m_rule->toString() << " "
                   << toStringList(inputArtifacts).join(",\n            ");
    }

    QList<QPair<const RuleArtifact *, Artifact *> > ruleArtifactArtifactMap;
    QList<Artifact *> outputArtifacts;

    ArtifactList usingArtifacts;
    if (!m_rule->usings.isEmpty()) {
        const FileTags usingsFileTags = m_rule->usings;
        foreach (const ResolvedProductPtr &dep, m_product->dependencies) {
            QBS_CHECK(dep->buildData);
            ArtifactList artifactsToCheck;
            foreach (Artifact *targetArtifact, dep->buildData->targetArtifacts)
                artifactsToCheck.unite(targetArtifact->transformer->outputs);
            foreach (Artifact *artifact, artifactsToCheck) {
                if (artifact->fileTags.matches(usingsFileTags))
                    usingArtifacts.insert(artifact);
            }
        }
    }

    m_transformer.clear();
    // create the output artifacts from the set of input artifacts
    foreach (const RuleArtifactConstPtr &ruleArtifact, m_rule->artifacts) {
        Artifact * const outputArtifact = createOutputArtifact(ruleArtifact, inputArtifacts);
        outputArtifacts << outputArtifact;
        ruleArtifactArtifactMap << qMakePair(ruleArtifact.data(), outputArtifact);
    }

    foreach (Artifact *outputArtifact, outputArtifacts) {
        // insert the output artifacts into the pool of artifacts
        foreach (const FileTag &fileTag, outputArtifact->fileTags)
            m_artifactsPerFileTag[fileTag].insert(outputArtifact);

        // connect artifacts that match the file tags in explicitlyDependsOn
        foreach (const FileTag &fileTag, m_rule->explicitlyDependsOn)
            foreach (Artifact *dependency, m_artifactsPerFileTag.value(fileTag))
                loggedConnect(outputArtifact, dependency, m_logger);

        // Transformer setup
        for (ArtifactList::const_iterator it = usingArtifacts.constBegin();
             it != usingArtifacts.constEnd(); ++it)
        {
            Artifact *dep = *it;
            loggedConnect(outputArtifact, dep, m_logger);
            m_transformer->inputs.insert(dep);
        }
        m_transformer->outputs.insert(outputArtifact);

        m_product->topLevelProject()->buildData->artifactsThatMustGetNewTransformers
                -= outputArtifact;
    }

    m_transformer->setupInputs(engine(), scope());

    // change the transformer outputs according to the bindings in Artifact
    QScriptValue scriptValue;
    for (int i = ruleArtifactArtifactMap.count(); --i >= 0;) {
        const RuleArtifact *ra = ruleArtifactArtifactMap.at(i).first;
        if (ra->bindings.isEmpty())
            continue;

        // expose attributes of this artifact
        Artifact *outputArtifact = ruleArtifactArtifactMap.at(i).second;
        outputArtifact->properties = outputArtifact->properties->clone();

        scope().setProperty("fileName", engine()->toScriptValue(outputArtifact->filePath()));
        scope().setProperty("fileTags",
                            toScriptValue(engine(), outputArtifact->fileTags.toStringList()));

        QVariantMap artifactModulesCfg = outputArtifact->properties->value().value("modules").toMap();
        for (int i=0; i < ra->bindings.count(); ++i) {
            const RuleArtifact::Binding &binding = ra->bindings.at(i);
            scriptValue = engine()->evaluate(binding.code);
            if (Q_UNLIKELY(scriptValue.isError())) {
                QString msg = QLatin1String("evaluating rule binding '%1': %2");
                throw ErrorInfo(msg.arg(binding.name.join(QLatin1String(".")), scriptValue.toString()), binding.location);
            }
            setConfigProperty(artifactModulesCfg, binding.name, scriptValue.toVariant());
        }
        QVariantMap outputArtifactConfig = outputArtifact->properties->value();
        outputArtifactConfig.insert("modules", artifactModulesCfg);
        outputArtifact->properties->setValue(outputArtifactConfig);
    }

    m_transformer->setupOutputs(engine(), scope());
    m_transformer->createCommands(m_rule->script, evalContext());
    if (Q_UNLIKELY(m_transformer->commands.isEmpty()))
        throw ErrorInfo(QString("There's a rule without commands: %1.").arg(m_rule->toString()), m_rule->script->location);
}

void RulesApplicator::setupScriptEngineForArtifact(Artifact *artifact)
{
    QString inFileName = artifact->fileName();
    QString inBaseName = FileInfo::baseName(artifact->filePath());
    QString inCompleteBaseName = FileInfo::completeBaseName(artifact->filePath());

    QString basedir;
    if (artifact->artifactType == Artifact::SourceFile) {
        QDir sourceDir(m_product->sourceDirectory);
        basedir = FileInfo::path(sourceDir.relativeFilePath(artifact->filePath()));
    } else {
        QDir buildDir(m_product->topLevelProject()->buildDirectory);
        basedir = FileInfo::path(buildDir.relativeFilePath(artifact->filePath()));
    }

    // expose per file properties we want to use in an Artifact within a Rule
    QScriptValue scriptValue = engine()->newObject();
    ModuleProperties::init(scriptValue, artifact);
    scriptValue.setProperty("fileName", inFileName);
    scriptValue.setProperty("baseName", inBaseName);
    scriptValue.setProperty("completeBaseName", inCompleteBaseName);
    scriptValue.setProperty("baseDir", basedir);

    scope().setProperty("input", scriptValue);
    Q_ASSERT_X(scriptValue.strictlyEquals(engine()->evaluate("input")),
               "BG", "The input object is not in current scope.");
}

Artifact *RulesApplicator::createOutputArtifact(const RuleArtifactConstPtr &ruleArtifact,
        const ArtifactList &inputArtifacts)
{
    QScriptValue scriptValue = engine()->evaluate(ruleArtifact->fileName);
    if (Q_UNLIKELY(scriptValue.isError() || engine()->hasUncaughtException()))
        throw ErrorInfo("Error in Rule.Artifact fileName: " + scriptValue.toString());
    QString outputPath = scriptValue.toString();
    outputPath.replace("..", "dotdot");     // don't let the output artifact "escape" its build dir
    outputPath = resolveOutPath(outputPath);

    Artifact *outputArtifact = lookupArtifact(m_product, outputPath);
    if (outputArtifact) {
        if (outputArtifact->transformer && outputArtifact->transformer != m_transformer) {
            // This can happen when applying rules after scanning for additional file tags.
            // We just regenerate the transformer.
            if (m_logger.traceEnabled()) {
                m_logger.qbsTrace() << QString::fromLocal8Bit("[BG] regenerating transformer "
                        "for '%1'").arg(relativeArtifactFileName(outputArtifact));
            }
            m_transformer = outputArtifact->transformer;
            m_transformer->inputs.unite(inputArtifacts);

            if (Q_UNLIKELY(m_transformer->inputs.count() > 1 && !m_rule->multiplex)) {
                QString th = "[" + outputArtifact->fileTags.toStringList().join(", ") + "]";
                QString e = Tr::tr("Conflicting rules for producing %1 %2 \n").arg(outputArtifact->filePath(), th);
                th = "[" + m_rule->inputs.toStringList().join(", ")
                   + "] -> [" + outputArtifact->fileTags.toStringList().join(", ") + "]";

                e += QString("  while trying to apply:   %1:%2:%3  %4\n")
                    .arg(m_rule->script->location.fileName())
                    .arg(m_rule->script->location.line())
                    .arg(m_rule->script->location.column())
                    .arg(th);

                e += QString("  was already defined in:  %1:%2:%3  %4\n")
                    .arg(outputArtifact->transformer->rule->script->location.fileName())
                    .arg(outputArtifact->transformer->rule->script->location.line())
                    .arg(outputArtifact->transformer->rule->script->location.column())
                    .arg(th);
                throw ErrorInfo(e);
            }
        }
        outputArtifact->fileTags += ruleArtifact->fileTags;
    } else {
        outputArtifact = new Artifact(m_product->topLevelProject());
        outputArtifact->artifactType = Artifact::Generated;
        outputArtifact->setFilePath(outputPath);
        outputArtifact->fileTags = ruleArtifact->fileTags;
        outputArtifact->alwaysUpdated = ruleArtifact->alwaysUpdated;
        insertArtifact(m_product, outputArtifact, m_logger);
    }

    if (outputArtifact->fileTags.isEmpty())
        outputArtifact->fileTags = m_product->fileTagsForFileName(outputArtifact->fileName());

    if (m_rule->multiplex)
        outputArtifact->properties = m_product->properties;
    else
        outputArtifact->properties= (*inputArtifacts.constBegin())->properties;

    for (int i = 0; i < m_product->artifactProperties.count(); ++i) {
        const ArtifactPropertiesConstPtr &props = m_product->artifactProperties.at(i);
        if (outputArtifact->fileTags.matches(props->fileTagsFilter())) {
            outputArtifact->properties = props->propertyMap();
            break;
        }
    }

    foreach (Artifact *inputArtifact, inputArtifacts) {
        QBS_CHECK(outputArtifact != inputArtifact);
        loggedConnect(outputArtifact, inputArtifact, m_logger);
    }

    // create transformer if not already done so
    if (!m_transformer) {
        m_transformer = Transformer::create();
        m_transformer->rule = m_rule;
        m_transformer->inputs = inputArtifacts;
    }
    outputArtifact->transformer = m_transformer;

    return outputArtifact;
}

QString RulesApplicator::resolveOutPath(const QString &path) const
{
    QString buildDir = m_product->topLevelProject()->buildDirectory;
    QString result = FileInfo::resolvePath(buildDir, path);
    result = QDir::cleanPath(result);
    return result;
}

RulesEvaluationContextPtr RulesApplicator::evalContext() const
{
    return m_product->topLevelProject()->buildData->evaluationContext;
}

ScriptEngine *RulesApplicator::engine() const
{
    return evalContext()->engine();
}

QScriptValue RulesApplicator::scope() const
{
    return evalContext()->scope();
}

void RulesApplicator::onPropertyRead(const QScriptValue &object, const QString &name,
                                     const QScriptValue &value)
{
    if (object.objectId() == m_productObjectId)
        engine()->addProperty(
                    Property(QString(), name, value.toVariant(), Property::PropertyInProduct));
}

} // namespace Internal
} // namespace qbs
<commit_msg>assign the product's build config to rule outputs<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 Qt Build Suite.
**
** 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 "rulesapplicator.h"

#include "artifact.h"
#include "buildgraph.h"
#include "productbuilddata.h"
#include "projectbuilddata.h"
#include "rulesevaluationcontext.h"
#include "transformer.h"
#include <jsextensions/moduleproperties.h>
#include <language/artifactproperties.h>
#include <language/language.h>
#include <language/scriptengine.h>
#include <logging/translator.h>
#include <tools/error.h>
#include <tools/scripttools.h>
#include <tools/qbsassert.h>

#include <QDir>

namespace qbs {
namespace Internal {

RulesApplicator::RulesApplicator(const ResolvedProductPtr &product,
                                 ArtifactsPerFileTagMap &artifactsPerFileTag, const Logger &logger)
    : m_product(product)
    , m_artifactsPerFileTag(artifactsPerFileTag)
    , m_logger(logger)
    , m_productObjectId(-1)
{
}

void RulesApplicator::applyAllRules()
{
    RulesEvaluationContext::Scope s(m_product->topLevelProject()->buildData->evaluationContext.data());
    foreach (const RuleConstPtr &rule, m_product->topSortedRules())
        applyRule(rule);
}

void RulesApplicator::applyRule(const RuleConstPtr &rule)
{
    m_rule = rule;
    QScriptValue scopeValue = scope();
    setupScriptEngineForProduct(engine(), m_product, m_rule, scopeValue, this);
    Q_ASSERT_X(scope().property("product").strictlyEquals(engine()->evaluate("product")),
               "BG", "Product object is not in current scope.");
    m_productObjectId = scopeValue.property(QLatin1String("product")).objectId();

    ArtifactList inputArtifacts;
    foreach (const FileTag &fileTag, m_rule->inputs)
        inputArtifacts.unite(m_artifactsPerFileTag.value(fileTag));
    if (m_rule->multiplex) { // apply the rule once for a set of inputs
        if (!inputArtifacts.isEmpty())
            doApply(inputArtifacts);
    } else { // apply the rule once for each input
        ArtifactList lst;
        foreach (Artifact * const inputArtifact, inputArtifacts) {
            setupScriptEngineForArtifact(inputArtifact);
            lst += inputArtifact;
            doApply(lst);
            lst.clear();
        }
    }
}

void RulesApplicator::doApply(const ArtifactList &inputArtifacts)
{
    evalContext()->checkForCancelation();

    if (m_logger.debugEnabled()) {
        m_logger.qbsDebug() << "[BG] apply rule " << m_rule->toString() << " "
                   << toStringList(inputArtifacts).join(",\n            ");
    }

    QList<QPair<const RuleArtifact *, Artifact *> > ruleArtifactArtifactMap;
    QList<Artifact *> outputArtifacts;

    ArtifactList usingArtifacts;
    if (!m_rule->usings.isEmpty()) {
        const FileTags usingsFileTags = m_rule->usings;
        foreach (const ResolvedProductPtr &dep, m_product->dependencies) {
            QBS_CHECK(dep->buildData);
            ArtifactList artifactsToCheck;
            foreach (Artifact *targetArtifact, dep->buildData->targetArtifacts)
                artifactsToCheck.unite(targetArtifact->transformer->outputs);
            foreach (Artifact *artifact, artifactsToCheck) {
                if (artifact->fileTags.matches(usingsFileTags))
                    usingArtifacts.insert(artifact);
            }
        }
    }

    m_transformer.clear();
    // create the output artifacts from the set of input artifacts
    foreach (const RuleArtifactConstPtr &ruleArtifact, m_rule->artifacts) {
        Artifact * const outputArtifact = createOutputArtifact(ruleArtifact, inputArtifacts);
        outputArtifacts << outputArtifact;
        ruleArtifactArtifactMap << qMakePair(ruleArtifact.data(), outputArtifact);
    }

    foreach (Artifact *outputArtifact, outputArtifacts) {
        // insert the output artifacts into the pool of artifacts
        foreach (const FileTag &fileTag, outputArtifact->fileTags)
            m_artifactsPerFileTag[fileTag].insert(outputArtifact);

        // connect artifacts that match the file tags in explicitlyDependsOn
        foreach (const FileTag &fileTag, m_rule->explicitlyDependsOn)
            foreach (Artifact *dependency, m_artifactsPerFileTag.value(fileTag))
                loggedConnect(outputArtifact, dependency, m_logger);

        // Transformer setup
        for (ArtifactList::const_iterator it = usingArtifacts.constBegin();
             it != usingArtifacts.constEnd(); ++it)
        {
            Artifact *dep = *it;
            loggedConnect(outputArtifact, dep, m_logger);
            m_transformer->inputs.insert(dep);
        }
        m_transformer->outputs.insert(outputArtifact);

        m_product->topLevelProject()->buildData->artifactsThatMustGetNewTransformers
                -= outputArtifact;
    }

    m_transformer->setupInputs(engine(), scope());

    // change the transformer outputs according to the bindings in Artifact
    QScriptValue scriptValue;
    for (int i = ruleArtifactArtifactMap.count(); --i >= 0;) {
        const RuleArtifact *ra = ruleArtifactArtifactMap.at(i).first;
        if (ra->bindings.isEmpty())
            continue;

        // expose attributes of this artifact
        Artifact *outputArtifact = ruleArtifactArtifactMap.at(i).second;
        outputArtifact->properties = outputArtifact->properties->clone();

        scope().setProperty("fileName", engine()->toScriptValue(outputArtifact->filePath()));
        scope().setProperty("fileTags",
                            toScriptValue(engine(), outputArtifact->fileTags.toStringList()));

        QVariantMap artifactModulesCfg = outputArtifact->properties->value().value("modules").toMap();
        for (int i=0; i < ra->bindings.count(); ++i) {
            const RuleArtifact::Binding &binding = ra->bindings.at(i);
            scriptValue = engine()->evaluate(binding.code);
            if (Q_UNLIKELY(scriptValue.isError())) {
                QString msg = QLatin1String("evaluating rule binding '%1': %2");
                throw ErrorInfo(msg.arg(binding.name.join(QLatin1String(".")), scriptValue.toString()), binding.location);
            }
            setConfigProperty(artifactModulesCfg, binding.name, scriptValue.toVariant());
        }
        QVariantMap outputArtifactConfig = outputArtifact->properties->value();
        outputArtifactConfig.insert("modules", artifactModulesCfg);
        outputArtifact->properties->setValue(outputArtifactConfig);
    }

    m_transformer->setupOutputs(engine(), scope());
    m_transformer->createCommands(m_rule->script, evalContext());
    if (Q_UNLIKELY(m_transformer->commands.isEmpty()))
        throw ErrorInfo(QString("There's a rule without commands: %1.").arg(m_rule->toString()), m_rule->script->location);
}

void RulesApplicator::setupScriptEngineForArtifact(Artifact *artifact)
{
    QString inFileName = artifact->fileName();
    QString inBaseName = FileInfo::baseName(artifact->filePath());
    QString inCompleteBaseName = FileInfo::completeBaseName(artifact->filePath());

    QString basedir;
    if (artifact->artifactType == Artifact::SourceFile) {
        QDir sourceDir(m_product->sourceDirectory);
        basedir = FileInfo::path(sourceDir.relativeFilePath(artifact->filePath()));
    } else {
        QDir buildDir(m_product->topLevelProject()->buildDirectory);
        basedir = FileInfo::path(buildDir.relativeFilePath(artifact->filePath()));
    }

    // expose per file properties we want to use in an Artifact within a Rule
    QScriptValue scriptValue = engine()->newObject();
    ModuleProperties::init(scriptValue, artifact);
    scriptValue.setProperty("fileName", inFileName);
    scriptValue.setProperty("baseName", inBaseName);
    scriptValue.setProperty("completeBaseName", inCompleteBaseName);
    scriptValue.setProperty("baseDir", basedir);

    scope().setProperty("input", scriptValue);
    Q_ASSERT_X(scriptValue.strictlyEquals(engine()->evaluate("input")),
               "BG", "The input object is not in current scope.");
}

Artifact *RulesApplicator::createOutputArtifact(const RuleArtifactConstPtr &ruleArtifact,
        const ArtifactList &inputArtifacts)
{
    QScriptValue scriptValue = engine()->evaluate(ruleArtifact->fileName);
    if (Q_UNLIKELY(scriptValue.isError() || engine()->hasUncaughtException()))
        throw ErrorInfo("Error in Rule.Artifact fileName: " + scriptValue.toString());
    QString outputPath = scriptValue.toString();
    outputPath.replace("..", "dotdot");     // don't let the output artifact "escape" its build dir
    outputPath = resolveOutPath(outputPath);

    Artifact *outputArtifact = lookupArtifact(m_product, outputPath);
    if (outputArtifact) {
        if (outputArtifact->transformer && outputArtifact->transformer != m_transformer) {
            // This can happen when applying rules after scanning for additional file tags.
            // We just regenerate the transformer.
            if (m_logger.traceEnabled()) {
                m_logger.qbsTrace() << QString::fromLocal8Bit("[BG] regenerating transformer "
                        "for '%1'").arg(relativeArtifactFileName(outputArtifact));
            }
            m_transformer = outputArtifact->transformer;
            m_transformer->inputs.unite(inputArtifacts);

            if (Q_UNLIKELY(m_transformer->inputs.count() > 1 && !m_rule->multiplex)) {
                QString th = "[" + outputArtifact->fileTags.toStringList().join(", ") + "]";
                QString e = Tr::tr("Conflicting rules for producing %1 %2 \n").arg(outputArtifact->filePath(), th);
                th = "[" + m_rule->inputs.toStringList().join(", ")
                   + "] -> [" + outputArtifact->fileTags.toStringList().join(", ") + "]";

                e += QString("  while trying to apply:   %1:%2:%3  %4\n")
                    .arg(m_rule->script->location.fileName())
                    .arg(m_rule->script->location.line())
                    .arg(m_rule->script->location.column())
                    .arg(th);

                e += QString("  was already defined in:  %1:%2:%3  %4\n")
                    .arg(outputArtifact->transformer->rule->script->location.fileName())
                    .arg(outputArtifact->transformer->rule->script->location.line())
                    .arg(outputArtifact->transformer->rule->script->location.column())
                    .arg(th);
                throw ErrorInfo(e);
            }
        }
        outputArtifact->fileTags += ruleArtifact->fileTags;
    } else {
        outputArtifact = new Artifact(m_product->topLevelProject());
        outputArtifact->artifactType = Artifact::Generated;
        outputArtifact->setFilePath(outputPath);
        outputArtifact->fileTags = ruleArtifact->fileTags;
        outputArtifact->alwaysUpdated = ruleArtifact->alwaysUpdated;
        outputArtifact->properties = m_product->properties;
        insertArtifact(m_product, outputArtifact, m_logger);
    }

    if (outputArtifact->fileTags.isEmpty())
        outputArtifact->fileTags = m_product->fileTagsForFileName(outputArtifact->fileName());

    for (int i = 0; i < m_product->artifactProperties.count(); ++i) {
        const ArtifactPropertiesConstPtr &props = m_product->artifactProperties.at(i);
        if (outputArtifact->fileTags.matches(props->fileTagsFilter())) {
            outputArtifact->properties = props->propertyMap();
            break;
        }
    }

    foreach (Artifact *inputArtifact, inputArtifacts) {
        QBS_CHECK(outputArtifact != inputArtifact);
        loggedConnect(outputArtifact, inputArtifact, m_logger);
    }

    // create transformer if not already done so
    if (!m_transformer) {
        m_transformer = Transformer::create();
        m_transformer->rule = m_rule;
        m_transformer->inputs = inputArtifacts;
    }
    outputArtifact->transformer = m_transformer;

    return outputArtifact;
}

QString RulesApplicator::resolveOutPath(const QString &path) const
{
    QString buildDir = m_product->topLevelProject()->buildDirectory;
    QString result = FileInfo::resolvePath(buildDir, path);
    result = QDir::cleanPath(result);
    return result;
}

RulesEvaluationContextPtr RulesApplicator::evalContext() const
{
    return m_product->topLevelProject()->buildData->evaluationContext;
}

ScriptEngine *RulesApplicator::engine() const
{
    return evalContext()->engine();
}

QScriptValue RulesApplicator::scope() const
{
    return evalContext()->scope();
}

void RulesApplicator::onPropertyRead(const QScriptValue &object, const QString &name,
                                     const QScriptValue &value)
{
    if (object.objectId() == m_productObjectId)
        engine()->addProperty(
                    Property(QString(), name, value.toVariant(), Property::PropertyInProduct));
}

} // namespace Internal
} // namespace qbs
<|endoftext|>


<commit_before>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>

#include <tiramisu/debug.h>
#include <tiramisu/core.h>

#include <string.h>
#include <Halide.h>

#include "wrapper_tutorial_06.h"

using namespace tiramisu;

/**
 * Test reductions.
 *
 * We want to represent the following program
 *
 * result = 0
 * for (int i = 0; i < N; i++)
 *      result = result + input[i];
 *
 * This program computes the sum of all the elements in the
 * buffer input[].
 *
 * In order to implement this program, we create the following two
 * computations
 * {result[0]       }: 0
 * {result[i]: 0<i<N}: result(i-1) + input(i)
 *
 * The final result will be in result(N-1).
 *
 * The data mapping should be as follows
 *
 * {result[i]->result_scalar[0]}
 * {input[i]->input_buffer[i]}
 *
 * This means that each computation result[i] is stored
 * in the scalar "result_scalar[0]" and that each computation
 * input[i] is retrieved from input_buffer[i].
 *
 */

void generate_function(std::string name, int size, int val0)
{
    tiramisu::global::set_default_tiramisu_options();
    global::set_loop_iterator_type(p_int32);

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------

    tiramisu::function function0(name);
    tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, &function0);
    tiramisu::var i = tiramisu::var("i");
    tiramisu::computation input("[N]->{input[i]}", tiramisu::expr(), false, p_uint8, &function0);
    tiramisu::computation result("[N]->{result[0]}", tiramisu::expr(input(0)), true, p_uint8, &function0);
    result.add_definitions("[N]->{result[i]: 1<=i<N}", (result(i - 1) + input(i)), true, p_uint8, &function0);

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------

    result.get_update(1).after(result, computation::root);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------

    tiramisu::buffer input_buffer("input_buffer", {size}, tiramisu::p_uint8, a_input, &function0);
    tiramisu::buffer result_scalar("result_scalar", {1}, tiramisu::p_uint8, a_output, &function0);
    input.set_access("[N]->{input[i]->input_buffer[i]}");
    result.set_access("[N]->{result[i]->result_scalar[0]}");
    result.get_update(1).set_access("[N]->{result[i]->result_scalar[0]}");

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------

    function0.set_arguments({&input_buffer, &result_scalar});
    function0.gen_time_space_domain();
    function0.gen_isl_ast();
    function0.gen_halide_stmt();
    function0.gen_c_code();
    function0.gen_halide_obj("build/generated_fct_tutorial_06.o");
}

int main(int argc, char **argv)
{
    generate_function("tiramisu_generated_code", SIZE1, 0);

    return 0;
}
<commit_msg>Update tutorial_06.cpp<commit_after>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>

#include <tiramisu/debug.h>
#include <tiramisu/core.h>

#include <string.h>
#include <Halide.h>

#include "wrapper_tutorial_06.h"

using namespace tiramisu;

/**
 * Test reductions.
 *
 * We want to represent the following program
 *
 * result = 0
 * for (int i = 0; i < N; i++)
 *      result = result + input[i];
 *
 * This program computes the sum of all the elements in the
 * buffer input[].
 *
 * In order to implement this program, we create the following two
 * computations
 * {result[0]       }: 0
 * {result[i]: 0<i<N}: result(i-1) + input(i)
 *
 * The final result will be in result(N-1).
 *
 * The data mapping should be as follows
 *
 * {result[i]->result_scalar[0]}
 * {input[i]->input_buffer[i]}
 *
 * This means that each computation result[i] is stored
 * in the scalar "result_scalar[0]" and that each computation
 * input[i] is retrieved from input_buffer[i].
 *
 */

void generate_function(std::string name, int size, int val0)
{
    tiramisu::global::set_default_tiramisu_options();

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------

    tiramisu::function function0(name);
    tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, &function0);
    tiramisu::var i = tiramisu::var("i");
    tiramisu::computation input("[N]->{input[i]}", tiramisu::expr(), false, p_uint8, &function0);
    tiramisu::computation result("[N]->{result[0]}", tiramisu::expr(input(0)), true, p_uint8, &function0);
    result.add_definitions("[N]->{result[i]: 1<=i<N}", (result(i - 1) + input(i)), true, p_uint8, &function0);

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------

    result.get_update(1).after(result, computation::root);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------

    tiramisu::buffer input_buffer("input_buffer", {size}, tiramisu::p_uint8, a_input, &function0);
    tiramisu::buffer result_scalar("result_scalar", {1}, tiramisu::p_uint8, a_output, &function0);
    input.set_access("[N]->{input[i]->input_buffer[i]}");
    result.set_access("[N]->{result[i]->result_scalar[0]}");
    result.get_update(1).set_access("[N]->{result[i]->result_scalar[0]}");

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------

    function0.set_arguments({&input_buffer, &result_scalar});
    function0.gen_time_space_domain();
    function0.gen_isl_ast();
    function0.gen_halide_stmt();
    function0.gen_c_code();
    function0.gen_halide_obj("build/generated_fct_tutorial_06.o");
}

int main(int argc, char **argv)
{
    generate_function("tiramisu_generated_code", SIZE1, 0);

    return 0;
}
<|endoftext|>


<commit_before>// KMail Account

#include <stdlib.h>
#include <unistd.h>

#include <assert.h>
#include <kapplication.h>

#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>

#include "kmacctmgr.h"
#include "kmacctfolder.h"
#include "kmfoldermgr.h"
#include "kmfiltermgr.h"
#include "kmsender.h"
#include "kmbroadcaststatus.h"

//----------------------
#include "kmaccount.moc"

//-----------------------------------------------------------------------------
KMPrecommand::KMPrecommand(const QString &precommand, QObject *parent)
 : QObject(parent)
{
  mPrecommand = precommand;
  KMBroadcastStatus::instance()->setStatusMsg(
      i18n("Executing precommand %1").arg(precommand ));

  mPrecommandProcess << precommand;

  connect(&mPrecommandProcess, SIGNAL(processExited(KProcess *)),
          SLOT(precommandExited(KProcess *)));
}

//-----------------------------------------------------------------------------
KMPrecommand::~KMPrecommand()
{
}

//-----------------------------------------------------------------------------
bool KMPrecommand::start()
{
  bool ok = mPrecommandProcess.start( KProcess::NotifyOnExit );
  if (!ok) KMessageBox::error(0, i18n("Couldn't execute precommand '%1'.")
    .arg(mPrecommand));
  return ok;
}

//-----------------------------------------------------------------------------
void KMPrecommand::precommandExited(KProcess *p)
{
  int exitCode = p->normalExit() ? p->exitStatus() : -1;
  if (exitCode)
    KMessageBox::error(0, i18n("The precommand exited with code %1:\n%2")
      .arg(exitCode).arg(strerror(exitCode)));
  emit finished(!exitCode);
}

//-----------------------------------------------------------------------------
KMAccount::KMAccount(KMAcctMgr* aOwner, const QString& aName)
{
  assert(aOwner != NULL);

  mOwner  = aOwner;
  mName   = aName;
  mFolder = NULL;
  mTimer  = NULL;
  mInterval = 0;
  mExclude = false;
  mCheckingMail = FALSE;
  mPrecommandSuccess = TRUE;
  connect(&mReceiptTimer,SIGNAL(timeout()),SLOT(sendReceipts()));
}

//-----------------------------------------------------------------------------
KMAccount::~KMAccount()
{
  if (!kernel->shuttingDown() && mFolder) mFolder->removeAccount(this);
  if (mTimer) deinstallTimer();
}

//-----------------------------------------------------------------------------
void KMAccount::setName(const QString& aName)
{
  mName = (aName.isEmpty()) ? i18n("Unnamed") : aName;
}

//-----------------------------------------------------------------------------
void KMAccount::clearPasswd()
{
}

//-----------------------------------------------------------------------------
void KMAccount::setFolder(KMFolder* aFolder)
{
  if(!aFolder)
    {
    kdDebug(5006) << "KMAccount::setFolder() : aFolder == NULL" << endl;
    mFolder = NULL;
    return;
    }
  mFolder = (KMAcctFolder*)aFolder;
}

//-----------------------------------------------------------------------------
void KMAccount::readConfig(KConfig& config)
{
  KMAcctFolder* folder;
  QString folderName;

  mFolder = NULL;
  mName   = config.readEntry("Name", i18n("Unnamed"));
  folderName = config.readEntry("Folder", "");
  setCheckInterval(config.readNumEntry("check-interval", 0));
  setCheckExclude(config.readBoolEntry("check-exclude", false));
  setPrecommand(config.readEntry("precommand"));

  if (!folderName.isEmpty())
  {
    folder = (KMAcctFolder*)kernel->folderMgr()->findIdString(folderName);
    if (folder)
    {
      mFolder = folder;
      mFolder->addAccount(this);
    }
    else kdDebug(5006) << "Cannot find folder `" << folderName << "' for account `" << mName << "'." << endl;
  }
}

//-----------------------------------------------------------------------------
void KMAccount::writeConfig(KConfig& config)
{
  config.writeEntry("Type", type());
  config.writeEntry("Name", mName);
  config.writeEntry("Folder", mFolder ? mFolder->idString() : QString::null);
  config.writeEntry("check-interval", mInterval);
  config.writeEntry("check-exclude", mExclude);
  config.writeEntry("precommand", mPrecommand);
}

//-----------------------------------------------------------------------------
void KMAccount::sendReceipt(KMMessage* aMsg)
{
  KConfig* cfg = kapp->config();
  bool sendReceipts;

  KConfigGroupSaver saver(cfg, "General");

  sendReceipts = cfg->readBoolEntry("send-receipts", false);
  if (!sendReceipts) return;

  KMMessage *newMsg = aMsg->createDeliveryReceipt();
  if (newMsg) {
    mReceipts.append(newMsg);
    mReceiptTimer.start(0,true);
  }
}

//-----------------------------------------------------------------------------
bool KMAccount::processNewMsg(KMMessage* aMsg)
{
  int rc, processResult;

  assert(aMsg != NULL);

  // checks whether we should send delivery receipts
  // and sends them.
  sendReceipt(aMsg);

  // Set status of new messages that are marked as old to read, otherwise
  // the user won't see which messages newly arrived.
  if (aMsg->status()==KMMsgStatusOld)
    aMsg->setStatus(KMMsgStatusUnread);  // -sanders
  //    aMsg->setStatus(KMMsgStatusRead);
  else aMsg->setStatus(KMMsgStatusNew);

  // 0==message moved; 1==processing ok, no move; 2==critical error, abort!
  processResult = kernel->filterMgr()->process(aMsg,KMFilterMgr::Inbound);
  if (processResult == 2) {
    perror("Critical error: Unable to collect mail (out of space?)");
    KMessageBox::information(0,(i18n("Critical error: "
      "Unable to collect mail (out of space?)")));
    return false;
  }
  else if (processResult == 1)
  {
    kernel->filterMgr()->tempOpenFolder(mFolder);
    rc = mFolder->addMsg(aMsg);
    if (rc) {
      perror("failed to add message");
      KMessageBox::information(0, i18n("Failed to add message:\n") +
			       QString(strerror(rc)));
      return false;
    }
    else return true;
  }
  // What now -  are we owner or not?
  return true; //Everything's fine - message has been added by filter  }
}

//-----------------------------------------------------------------------------
void KMAccount::setCheckInterval(int aInterval)
{
  if (aInterval <= 0)
  {
    mInterval = 0;
    deinstallTimer();
  }
  else
  {
    mInterval = aInterval;
    installTimer();
  }
}

//-----------------------------------------------------------------------------
void KMAccount::setCheckExclude(bool aExclude)
{
  mExclude = aExclude;
}

//-----------------------------------------------------------------------------
void KMAccount::installTimer()
{
  if (mInterval <= 0) return;
  if(!mTimer)
  {
    mTimer = new QTimer();
    connect(mTimer,SIGNAL(timeout()),SLOT(mailCheck()));
  }
  else
  {
    mTimer->stop();
  }
  mTimer->start(mInterval*60000);
}

//-----------------------------------------------------------------------------
void KMAccount::deinstallTimer()
{
  if(mTimer) {
    delete mTimer;
    mTimer = NULL;
  }
}

//-----------------------------------------------------------------------------
bool KMAccount::runPrecommand(const QString &precommand)
{
  // Run the pre command if there is one
  if ( precommand.isEmpty() )
    return true;

  KMPrecommand precommandProcess(precommand, this);

  KMBroadcastStatus::instance()->setStatusMsg(
      i18n("Executing precommand %1").arg(precommand ));

  connect(&precommandProcess, SIGNAL(finished(bool)),
          SLOT(precommandExited(bool)));

  kdDebug(5006) << "Running precommand " << precommand << endl;
  if (!precommandProcess.start()) return false;

  kapp->enter_loop();

  return mPrecommandSuccess;
}

//-----------------------------------------------------------------------------
void KMAccount::precommandExited(bool success)
{
  mPrecommandSuccess = success;
  kapp->exit_loop();
}

//-----------------------------------------------------------------------------
void KMAccount::mailCheck()
{
 if (mCheckingMail) return;
 mCheckingMail = TRUE;
 kernel->acctMgr()->singleCheckMail(this,false);
 mCheckingMail = FALSE;
}

//-----------------------------------------------------------------------------
void KMAccount::sendReceipts()
{
  // re-entrant
  QValueList<KMMessage*> receipts;
  QValueList<KMMessage*>::Iterator it;
  for(it = mReceipts.begin(); it != mReceipts.end(); ++it)
    receipts.append(*it);
  mReceipts.clear();

  for(it = receipts.begin(); it != receipts.end(); ++it)
    kernel->msgSender()->send(*it);  //might process events
}

//-----------------------------------------------------------------------------
QString KMAccount::encryptStr(const QString &aStr)
{
  QString result;
  for (uint i = 0; i < aStr.length(); i++)
    result += (aStr[i].unicode() < 0x20) ? aStr[i] :
      QChar(0x1001F - aStr[i].unicode());
  return result;
}
<commit_msg>Use const init list instead of an arry of mFoo = aFoo in the ctor<commit_after>// KMail Account

#include <stdlib.h>
#include <unistd.h>

#include <assert.h>
#include <kapplication.h>

#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>

#include "kmacctmgr.h"
#include "kmacctfolder.h"
#include "kmfoldermgr.h"
#include "kmfiltermgr.h"
#include "kmsender.h"
#include "kmbroadcaststatus.h"

//----------------------
#include "kmaccount.moc"

//-----------------------------------------------------------------------------
KMPrecommand::KMPrecommand(const QString &precommand, QObject *parent)
  : QObject(parent), mPrecommand(precommand)
{
  KMBroadcastStatus::instance()->setStatusMsg(
      i18n("Executing precommand %1").arg(precommand ));

  mPrecommandProcess << precommand;

  connect(&mPrecommandProcess, SIGNAL(processExited(KProcess *)),
          SLOT(precommandExited(KProcess *)));
}

//-----------------------------------------------------------------------------
KMPrecommand::~KMPrecommand()
{
}

//-----------------------------------------------------------------------------
bool KMPrecommand::start()
{
  bool ok = mPrecommandProcess.start( KProcess::NotifyOnExit );
  if (!ok) KMessageBox::error(0, i18n("Couldn't execute precommand '%1'.")
    .arg(mPrecommand));
  return ok;
}

//-----------------------------------------------------------------------------
void KMPrecommand::precommandExited(KProcess *p)
{
  int exitCode = p->normalExit() ? p->exitStatus() : -1;
  if (exitCode)
    KMessageBox::error(0, i18n("The precommand exited with code %1:\n%2")
      .arg(exitCode).arg(strerror(exitCode)));
  emit finished(!exitCode);
}

//-----------------------------------------------------------------------------
KMAccount::KMAccount(KMAcctMgr* aOwner, const QString& aName)
  : mName(aName),
    mOwner(aOwner),
    mFolder(0),
    mTimer(0),
    mInterval(0),
    mExclude(false),
    mCheckingMail(false),
    mPrecommandSuccess(true)
{
  assert(aOwner != NULL);

  connect(&mReceiptTimer,SIGNAL(timeout()),SLOT(sendReceipts()));
}

//-----------------------------------------------------------------------------
KMAccount::~KMAccount()
{
  if (!kernel->shuttingDown() && mFolder) mFolder->removeAccount(this);
  if (mTimer) deinstallTimer();
}

//-----------------------------------------------------------------------------
void KMAccount::setName(const QString& aName)
{
  mName = (aName.isEmpty()) ? i18n("Unnamed") : aName;
}

//-----------------------------------------------------------------------------
void KMAccount::clearPasswd()
{
}

//-----------------------------------------------------------------------------
void KMAccount::setFolder(KMFolder* aFolder)
{
  if(!aFolder)
    {
    kdDebug(5006) << "KMAccount::setFolder() : aFolder == NULL" << endl;
    mFolder = NULL;
    return;
    }
  mFolder = (KMAcctFolder*)aFolder;
}

//-----------------------------------------------------------------------------
void KMAccount::readConfig(KConfig& config)
{
  KMAcctFolder* folder;
  QString folderName;

  mFolder = NULL;
  mName   = config.readEntry("Name", i18n("Unnamed"));
  folderName = config.readEntry("Folder", "");
  setCheckInterval(config.readNumEntry("check-interval", 0));
  setCheckExclude(config.readBoolEntry("check-exclude", false));
  setPrecommand(config.readEntry("precommand"));

  if (!folderName.isEmpty())
  {
    folder = (KMAcctFolder*)kernel->folderMgr()->findIdString(folderName);
    if (folder)
    {
      mFolder = folder;
      mFolder->addAccount(this);
    }
    else kdDebug(5006) << "Cannot find folder `" << folderName << "' for account `" << mName << "'." << endl;
  }
}

//-----------------------------------------------------------------------------
void KMAccount::writeConfig(KConfig& config)
{
  config.writeEntry("Type", type());
  config.writeEntry("Name", mName);
  config.writeEntry("Folder", mFolder ? mFolder->idString() : QString::null);
  config.writeEntry("check-interval", mInterval);
  config.writeEntry("check-exclude", mExclude);
  config.writeEntry("precommand", mPrecommand);
}

//-----------------------------------------------------------------------------
void KMAccount::sendReceipt(KMMessage* aMsg)
{
  KConfig* cfg = kapp->config();
  bool sendReceipts;

  KConfigGroupSaver saver(cfg, "General");

  sendReceipts = cfg->readBoolEntry("send-receipts", false);
  if (!sendReceipts) return;

  KMMessage *newMsg = aMsg->createDeliveryReceipt();
  if (newMsg) {
    mReceipts.append(newMsg);
    mReceiptTimer.start(0,true);
  }
}

//-----------------------------------------------------------------------------
bool KMAccount::processNewMsg(KMMessage* aMsg)
{
  int rc, processResult;

  assert(aMsg != NULL);

  // checks whether we should send delivery receipts
  // and sends them.
  sendReceipt(aMsg);

  // Set status of new messages that are marked as old to read, otherwise
  // the user won't see which messages newly arrived.
  if (aMsg->status()==KMMsgStatusOld)
    aMsg->setStatus(KMMsgStatusUnread);  // -sanders
  //    aMsg->setStatus(KMMsgStatusRead);
  else aMsg->setStatus(KMMsgStatusNew);

  // 0==message moved; 1==processing ok, no move; 2==critical error, abort!
  processResult = kernel->filterMgr()->process(aMsg,KMFilterMgr::Inbound);
  if (processResult == 2) {
    perror("Critical error: Unable to collect mail (out of space?)");
    KMessageBox::information(0,(i18n("Critical error: "
      "Unable to collect mail (out of space?)")));
    return false;
  }
  else if (processResult == 1)
  {
    kernel->filterMgr()->tempOpenFolder(mFolder);
    rc = mFolder->addMsg(aMsg);
    if (rc) {
      perror("failed to add message");
      KMessageBox::information(0, i18n("Failed to add message:\n") +
			       QString(strerror(rc)));
      return false;
    }
    else return true;
  }
  // What now -  are we owner or not?
  return true; //Everything's fine - message has been added by filter  }
}

//-----------------------------------------------------------------------------
void KMAccount::setCheckInterval(int aInterval)
{
  if (aInterval <= 0)
  {
    mInterval = 0;
    deinstallTimer();
  }
  else
  {
    mInterval = aInterval;
    installTimer();
  }
}

//-----------------------------------------------------------------------------
void KMAccount::setCheckExclude(bool aExclude)
{
  mExclude = aExclude;
}

//-----------------------------------------------------------------------------
void KMAccount::installTimer()
{
  if (mInterval <= 0) return;
  if(!mTimer)
  {
    mTimer = new QTimer();
    connect(mTimer,SIGNAL(timeout()),SLOT(mailCheck()));
  }
  else
  {
    mTimer->stop();
  }
  mTimer->start(mInterval*60000);
}

//-----------------------------------------------------------------------------
void KMAccount::deinstallTimer()
{
  if(mTimer) {
    delete mTimer;
    mTimer = NULL;
  }
}

//-----------------------------------------------------------------------------
bool KMAccount::runPrecommand(const QString &precommand)
{
  // Run the pre command if there is one
  if ( precommand.isEmpty() )
    return true;

  KMPrecommand precommandProcess(precommand, this);

  KMBroadcastStatus::instance()->setStatusMsg(
      i18n("Executing precommand %1").arg(precommand ));

  connect(&precommandProcess, SIGNAL(finished(bool)),
          SLOT(precommandExited(bool)));

  kdDebug(5006) << "Running precommand " << precommand << endl;
  if (!precommandProcess.start()) return false;

  kapp->enter_loop();

  return mPrecommandSuccess;
}

//-----------------------------------------------------------------------------
void KMAccount::precommandExited(bool success)
{
  mPrecommandSuccess = success;
  kapp->exit_loop();
}

//-----------------------------------------------------------------------------
void KMAccount::mailCheck()
{
 if (mCheckingMail) return;
 mCheckingMail = TRUE;
 kernel->acctMgr()->singleCheckMail(this,false);
 mCheckingMail = FALSE;
}

//-----------------------------------------------------------------------------
void KMAccount::sendReceipts()
{
  // re-entrant
  QValueList<KMMessage*> receipts;
  QValueList<KMMessage*>::Iterator it;
  for(it = mReceipts.begin(); it != mReceipts.end(); ++it)
    receipts.append(*it);
  mReceipts.clear();

  for(it = receipts.begin(); it != receipts.end(); ++it)
    kernel->msgSender()->send(*it);  //might process events
}

//-----------------------------------------------------------------------------
QString KMAccount::encryptStr(const QString &aStr)
{
  QString result;
  for (uint i = 0; i < aStr.length(); i++)
    result += (aStr[i].unicode() < 0x20) ? aStr[i] :
      QChar(0x1001F - aStr[i].unicode());
  return result;
}
<|endoftext|>


<commit_before>
#pragma once

#include <experimental/optional>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <string>

#include "base/container_iterator.hpp"
#include "base/disjoint_sets.hpp"
#include "ksp_plugin/frames.hpp"
#include "ksp_plugin/identification.hpp"
#include "ksp_plugin/part_subsets.hpp"
#include "ksp_plugin/pile_up.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"
#include "serialization/ksp_plugin.pb.h"

namespace principia {
namespace ksp_plugin {
namespace internal_part {

using base::IteratorOn;
using base::not_null;
using base::Subset;
using geometry::Position;
using geometry::Vector;
using geometry::Velocity;
using physics::DegreesOfFreedom;
using physics::DiscreteTrajectory;
using quantities::Force;
using quantities::Mass;

// Represents a KSP part.
class Part final {
 public:
  Part(PartId part_id,
       std::string const& name,
       Mass const& mass,
       DegreesOfFreedom<Barycentric> const& degrees_of_freedom,
       std::function<void()> deletion_callback);

  // Calls the deletion callback passed at construction, if any.  This part must
  // not be piled up.
  ~Part();

  PartId part_id() const;

  // Sets or returns the mass.  Event though a part is massless in the sense
  // that it doesn't exert gravity, it has a mass used to determine its
  // intrinsic acceleration.
  void set_mass(Mass const& mass);
  Mass const& mass() const;

  // Clears, increments or returns the intrinsic force exerted on the part by
  // its engines (or a tractor beam).
  // TODO(phl): Keep track of the point where the force is applied.
  void clear_intrinsic_force();
  void increment_intrinsic_force(
      Vector<Force, Barycentric> const& intrinsic_force);
  Vector<Force, Barycentric> const& intrinsic_force() const;

  // Sets or returns the degrees of freedom of the part.
  void set_degrees_of_freedom(
      DegreesOfFreedom<Barycentric> const& degrees_of_freedom);
  DegreesOfFreedom<Barycentric> const& degrees_of_freedom() const;

  // This temporarily holds the trajectory followed by the part during the call
  // to |PileUp::AdvanceTime| for the containing |PileUp|.  It read and cleared
  // by |Part::AdvanceTime| for the containing |Part|.
  DiscreteTrajectory<Barycentric>& tail();
  DiscreteTrajectory<Barycentric> const& tail() const;

  // True if and only if the last point of the tail is authoritative, i.e.,
  // corresponds to a point in the psychohistory of the enclosing Part.
  bool tail_is_authoritative() const;
  void set_tail_is_authoritative(bool tail_is_authoritative);

  // Requires |!is_piled_up()|.
  void set_containing_pile_up(IteratorOn<std::list<PileUp>> pile_up);

  // An iterator to the containing |PileUp|, if any.  Do not |Erase| this
  // iterator, use |clear_pile_up| instead, which will take care of letting all
  // parts know that their |PileUp| is gone.
  std::experimental::optional<IteratorOn<std::list<PileUp>>>
  containing_pile_up() const;

  // Whether this part is in a |PileUp|.  Equivalent to |containing_pile_up()|.
  bool is_piled_up() const;

  // If this part is in a |PileUp|, erases that |PileUp|.  After this call, all
  // parts in that |PileUp| are no longer piled up.
  void clear_pile_up();

  void WriteToMessage(not_null<serialization::Part*> message) const;
  static not_null<std::unique_ptr<Part>> ReadFromMessage(
      serialization::Part const& message,
      std::function<void()> deletion_callback);
  void FillContainingPileUpFromMessage(
      serialization::Part const& message,
      not_null<std::list<PileUp>*> const pile_ups);

  // Returns "part name (part ID)".
  std::string ShortDebugString() const;

 private:
  PartId const part_id_;
  std::string const name_;
  Mass mass_;
  Vector<Force, Barycentric> intrinsic_force_;

  std::experimental::optional<IteratorOn<std::list<PileUp>>>
      containing_pile_up_;

  DegreesOfFreedom<Barycentric> degrees_of_freedom_;
  not_null<std::unique_ptr<DiscreteTrajectory<Barycentric>>> tail_;
  bool tail_is_authoritative_ = false;

  // TODO(egg): we may want to keep track of the moment of inertia, angular
  // momentum, etc.

  // We will use union-find algorithms on |Part|s.
  not_null<std::unique_ptr<Subset<Part>::Node>> const subset_node_;
  friend class Subset<Part>::Node;

  // Called in the destructor.
  std::function<void()> deletion_callback_;
};

std::ostream& operator<<(std::ostream& out, Part const& part);

}  // namespace internal_part

using internal_part::Part;

}  // namespace ksp_plugin

namespace base {

template<>
inline not_null<Subset<ksp_plugin::Part>::Node*>
Subset<ksp_plugin::Part>::Node::Get(ksp_plugin::Part& element) {
  return element.subset_node_.get();
}

}  // namespace base
}  // namespace principia
<commit_msg>wrong comment is wrong<commit_after>
#pragma once

#include <experimental/optional>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <string>

#include "base/container_iterator.hpp"
#include "base/disjoint_sets.hpp"
#include "ksp_plugin/frames.hpp"
#include "ksp_plugin/identification.hpp"
#include "ksp_plugin/part_subsets.hpp"
#include "ksp_plugin/pile_up.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"
#include "serialization/ksp_plugin.pb.h"

namespace principia {
namespace ksp_plugin {
namespace internal_part {

using base::IteratorOn;
using base::not_null;
using base::Subset;
using geometry::Position;
using geometry::Vector;
using geometry::Velocity;
using physics::DegreesOfFreedom;
using physics::DiscreteTrajectory;
using quantities::Force;
using quantities::Mass;

// Represents a KSP part.
class Part final {
 public:
  Part(PartId part_id,
       std::string const& name,
       Mass const& mass,
       DegreesOfFreedom<Barycentric> const& degrees_of_freedom,
       std::function<void()> deletion_callback);

  // Calls the deletion callback passed at construction, if any.  This part must
  // not be piled up.
  ~Part();

  PartId part_id() const;

  // Sets or returns the mass.  Event though a part is massless in the sense
  // that it doesn't exert gravity, it has a mass used to determine its
  // intrinsic acceleration.
  void set_mass(Mass const& mass);
  Mass const& mass() const;

  // Clears, increments or returns the intrinsic force exerted on the part by
  // its engines (or a tractor beam).
  // TODO(phl): Keep track of the point where the force is applied.
  void clear_intrinsic_force();
  void increment_intrinsic_force(
      Vector<Force, Barycentric> const& intrinsic_force);
  Vector<Force, Barycentric> const& intrinsic_force() const;

  // Sets or returns the degrees of freedom of the part.
  void set_degrees_of_freedom(
      DegreesOfFreedom<Barycentric> const& degrees_of_freedom);
  DegreesOfFreedom<Barycentric> const& degrees_of_freedom() const;

  // This temporarily holds the trajectory followed by the part during the call
  // to |PileUp::AdvanceTime| for the containing |PileUp|.  It is read and
  // cleared by |Vessel::AdvanceTime| for the containing |Vessel|.
  DiscreteTrajectory<Barycentric>& tail();
  DiscreteTrajectory<Barycentric> const& tail() const;

  // True if and only if the last point of the tail is authoritative, i.e.,
  // corresponds to a point in the psychohistory of the enclosing Part.
  bool tail_is_authoritative() const;
  void set_tail_is_authoritative(bool tail_is_authoritative);

  // Requires |!is_piled_up()|.
  void set_containing_pile_up(IteratorOn<std::list<PileUp>> pile_up);

  // An iterator to the containing |PileUp|, if any.  Do not |Erase| this
  // iterator, use |clear_pile_up| instead, which will take care of letting all
  // parts know that their |PileUp| is gone.
  std::experimental::optional<IteratorOn<std::list<PileUp>>>
  containing_pile_up() const;

  // Whether this part is in a |PileUp|.  Equivalent to |containing_pile_up()|.
  bool is_piled_up() const;

  // If this part is in a |PileUp|, erases that |PileUp|.  After this call, all
  // parts in that |PileUp| are no longer piled up.
  void clear_pile_up();

  void WriteToMessage(not_null<serialization::Part*> message) const;
  static not_null<std::unique_ptr<Part>> ReadFromMessage(
      serialization::Part const& message,
      std::function<void()> deletion_callback);
  void FillContainingPileUpFromMessage(
      serialization::Part const& message,
      not_null<std::list<PileUp>*> const pile_ups);

  // Returns "part name (part ID)".
  std::string ShortDebugString() const;

 private:
  PartId const part_id_;
  std::string const name_;
  Mass mass_;
  Vector<Force, Barycentric> intrinsic_force_;

  std::experimental::optional<IteratorOn<std::list<PileUp>>>
      containing_pile_up_;

  DegreesOfFreedom<Barycentric> degrees_of_freedom_;
  not_null<std::unique_ptr<DiscreteTrajectory<Barycentric>>> tail_;
  bool tail_is_authoritative_ = false;

  // TODO(egg): we may want to keep track of the moment of inertia, angular
  // momentum, etc.

  // We will use union-find algorithms on |Part|s.
  not_null<std::unique_ptr<Subset<Part>::Node>> const subset_node_;
  friend class Subset<Part>::Node;

  // Called in the destructor.
  std::function<void()> deletion_callback_;
};

std::ostream& operator<<(std::ostream& out, Part const& part);

}  // namespace internal_part

using internal_part::Part;

}  // namespace ksp_plugin

namespace base {

template<>
inline not_null<Subset<ksp_plugin::Part>::Node*>
Subset<ksp_plugin::Part>::Node::Get(ksp_plugin::Part& element) {
  return element.subset_node_.get();
}

}  // namespace base
}  // namespace principia
<|endoftext|>


<commit_before>/*
    This file is part of ksync.

    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <qdir.h>
#include <qprinter.h>
#include <qpainter.h>

#include <kiconloader.h>
#include <kmessagebox.h>
#include <kfiledialog.h>
#include <kmenubar.h>
#include <klocale.h>
#include <kconfig.h>
#include <kstdaction.h>

#include "ksync.h"
#include "ksync.moc"
#include "ksyncview.h"
#include <kstatusbar.h>

#define ID_STATUS_MSG 1

KSync::KSync(QWidget* , const char* name):KMainWindow(0, name)
{
  config=kapp->config();

  initStatusBar();
  initActions();
  initView();

  readOptions();

  // disable actions at startup
  fileSave->setEnabled(false);
  fileSaveAs->setEnabled(false);
  filePrint->setEnabled(false);
  editCut->setEnabled(false);
  editCopy->setEnabled(false);
  editPaste->setEnabled(false);
  setAutoSaveSettings();
}

void KSync::initActions()
{
  fileNewWindow = new KAction(i18n("New &Window"), 0, 0, this, SLOT(slotFileNewWindow()), actionCollection(),"file_new_window");
  fileNew = KStdAction::openNew(this, SLOT(slotFileNew()), actionCollection());
  fileOpen = KStdAction::open(this, SLOT(slotFileOpen()), actionCollection());
  fileOpenRecent = KStdAction::openRecent(this, SLOT(slotFileOpenRecent(const KURL&)), actionCollection());
  fileSave = KStdAction::save(this, SLOT(slotFileSave()), actionCollection());
  fileSaveAs = KStdAction::saveAs(this, SLOT(slotFileSaveAs()), actionCollection());
  fileClose = KStdAction::close(this, SLOT(slotFileClose()), actionCollection());
  filePrint = KStdAction::print(this, SLOT(slotFilePrint()), actionCollection());
  fileQuit = KStdAction::quit(this, SLOT(slotFileQuit()), actionCollection());
  editCut = KStdAction::cut(this, SLOT(slotEditCut()), actionCollection());
  editCopy = KStdAction::copy(this, SLOT(slotEditCopy()), actionCollection());
  editPaste = KStdAction::paste(this, SLOT(slotEditPaste()), actionCollection());
  createStandardStatusBarAction();
  setStandardToolBarMenuEnabled(true);

  fileNewWindow->setStatusText(i18n("Opens a new application window"));
  fileNew->setStatusText(i18n("Creates a new document"));
  fileOpen->setStatusText(i18n("Opens an existing document"));
  fileOpenRecent->setStatusText(i18n("Opens a recently used file"));
  fileSave->setStatusText(i18n("Saves the actual document"));
  fileSaveAs->setStatusText(i18n("Saves the actual document as..."));
  fileClose->setStatusText(i18n("Closes the actual document"));
  filePrint ->setStatusText(i18n("Prints out the actual document"));
  fileQuit->setStatusText(i18n("Quits the application"));
  editCut->setStatusText(i18n("Cuts the selected section and puts it to the clipboard"));
  editCopy->setStatusText(i18n("Copies the selected section to the clipboard"));
  editPaste->setStatusText(i18n("Pastes the clipboard contents to actual position"));

  // use the absolute path to your ksyncui.rc file for testing purpose in createGUI();
  createGUI();

}

void KSync::initStatusBar()
{
  statusBar()->insertItem(i18n("Ready."), ID_STATUS_MSG);
}

void KSync::initView()
{
  mView = new KSyncView(this);
  setCentralWidget(mView);
//  setCaption(doc->URL().fileName(),false);
}

void KSync::openDocumentFile(const KURL& url)
{
  slotStatusMsg(i18n("Opening file..."));

//  doc->openDocument( url);
  fileOpenRecent->addURL( url );
  slotStatusMsg(i18n("Ready."));
}

void KSync::saveOptions()
{
  config->setGroup("General Options");
  fileOpenRecent->saveEntries(config,"Recent Files");

  mView->writeConfig(config);
}

void KSync::readOptions()
{
  config->setGroup("General Options");

  // initialize the recent file list
  fileOpenRecent->loadEntries(config,"Recent Files");
  mView->readConfig(config);
}

void KSync::saveProperties(KConfig *)
{
#if 0
  if(doc->URL().fileName()!=i18n("Untitled") && !doc->isModified())
  {
    // saving to tempfile not necessary

  }
  else
  {
    KURL url=doc->URL();
    _cfg->writePathEntry("filename", url.url());
    _cfg->writeEntry("modified", doc->isModified());
    QString tempname = kapp->tempSaveName(url.url());
    QString tempurl= KURL::encode_string(tempname);
    KURL _url(tempurl);
    doc->saveDocument(_url);
  }
#endif
}

void KSync::readProperties(KConfig *)
{
#if 0
  QString filename = _cfg->readPathEntry("filename");
  KURL url(filename);
  bool modified = _cfg->readBoolEntry("modified", false);
  if(modified)
  {
    bool canRecover;
    QString tempname = kapp->checkRecoverFile(filename, canRecover);
    KURL _url(tempname);

    if(canRecover)
    {
      doc->openDocument(_url);
      doc->setModified();
      setCaption(_url.fileName(),true);
      QFile::remove(tempname);
    }
  }
  else
  {
    if(!filename.isEmpty())
    {
      doc->openDocument(url);
      setCaption(url.fileName(),false);
    }
  }
#endif
}

bool KSync::queryClose()
{
//  return doc->saveModified();
  return true;
}

bool KSync::queryExit()
{
  saveOptions();
  return true;
}

void KSync::slotFileNewWindow()
{
  slotStatusMsg(i18n("Opening a new application window..."));

  KSync *new_window= new KSync();
  new_window->show();

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileNew()
{
  slotStatusMsg(i18n("Creating new document..."));

#if 0
  if(!doc->saveModified())
  {
     // here saving wasn't successful

  }
  else
  {
    doc->newDocument();
    setCaption(doc->URL().fileName(), false);
  }
#endif

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileOpen()
{
  slotStatusMsg(i18n("Opening file..."));

#if 0
  if(!doc->saveModified())
  {
     // here saving wasn't successful

  }
  else
  {
    KURL url=KFileDialog::getOpenURL(QString::null,
        i18n("*|All Files"), this, i18n("Open File"));
    if(!url.isEmpty())
    {
      doc->openDocument(url);
      setCaption(url.fileName(), false);
      fileOpenRecent->addURL( url );
    }
  }
#endif

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileOpenRecent(const KURL&)
{
  slotStatusMsg(i18n("Opening file..."));

#if 0
  if(!doc->saveModified())
  {
     // here saving wasn't successful
  }
  else
  {
    doc->openDocument(url);
    setCaption(url.fileName(), false);
  }
#endif

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileSave()
{
  slotStatusMsg(i18n("Saving file..."));

//  doc->saveDocument(doc->URL());

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileSaveAs()
{
  slotStatusMsg(i18n("Saving file with a new filename..."));

  KURL url=KFileDialog::getSaveURL(QDir::currentDirPath(),
        i18n("*|All Files"), this, i18n("Save As"));
  if(!url.isEmpty())
  {
//    doc->saveDocument(url);
    fileOpenRecent->addURL(url);
//    setCaption(url.fileName(),doc->isModified());
  }

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileClose()
{
  slotStatusMsg(i18n("Closing file..."));

  close();

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFilePrint()
{
  slotStatusMsg(i18n("Printing..."));

  QPrinter printer;
  if (printer.setup(this))
  {
    mView->print(&printer);
  }

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileQuit()
{
  slotStatusMsg(i18n("Exiting..."));
  saveOptions();
  // close the first window, the list makes the next one the first again.
  // This ensures that queryClose() is called on each window to ask for closing
  KMainWindow* w;
  if(memberList)
  {
    for(w=memberList->first(); w!=0; w=memberList->first())
    {
      // only close the window if the closeEvent is accepted. If the user presses Cancel on the saveModified() dialog,
      // the window and the application stay open.
      if(!w->close())
	break;
    }
  }
  slotStatusMsg(i18n("Ready."));
}

void KSync::slotEditCut()
{
  slotStatusMsg(i18n("Cutting selection..."));

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotEditCopy()
{
  slotStatusMsg(i18n("Copying selection to clipboard..."));

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotEditPaste()
{
  slotStatusMsg(i18n("Inserting clipboard contents..."));

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotStatusMsg(const QString &text)
{
  statusBar()->clear();
  statusBar()->changeItem(text, ID_STATUS_MSG);
}

<commit_msg>KDE_NO_COMPAT compile fixes<commit_after>/*
    This file is part of ksync.

    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <qdir.h>
#include <qprinter.h>
#include <qpainter.h>

#include <kiconloader.h>
#include <kmessagebox.h>
#include <kfiledialog.h>
#include <kmenubar.h>
#include <klocale.h>
#include <kconfig.h>
#include <kstdaction.h>

#include "ksync.h"
#include "ksync.moc"
#include "ksyncview.h"
#include <kstatusbar.h>

#define ID_STATUS_MSG 1

KSync::KSync(QWidget* , const char* name):KMainWindow(0, name)
{
  config=kapp->config();

  initStatusBar();
  initActions();
  initView();

  readOptions();

  // disable actions at startup
  fileSave->setEnabled(false);
  fileSaveAs->setEnabled(false);
  filePrint->setEnabled(false);
  editCut->setEnabled(false);
  editCopy->setEnabled(false);
  editPaste->setEnabled(false);
  setAutoSaveSettings();
}

void KSync::initActions()
{
  fileNewWindow = new KAction(i18n("New &Window"), 0, 0, this, SLOT(slotFileNewWindow()), actionCollection(),"file_new_window");
  fileNew = KStdAction::openNew(this, SLOT(slotFileNew()), actionCollection());
  fileOpen = KStdAction::open(this, SLOT(slotFileOpen()), actionCollection());
  fileOpenRecent = KStdAction::openRecent(this, SLOT(slotFileOpenRecent(const KURL&)), actionCollection());
  fileSave = KStdAction::save(this, SLOT(slotFileSave()), actionCollection());
  fileSaveAs = KStdAction::saveAs(this, SLOT(slotFileSaveAs()), actionCollection());
  fileClose = KStdAction::close(this, SLOT(slotFileClose()), actionCollection());
  filePrint = KStdAction::print(this, SLOT(slotFilePrint()), actionCollection());
  fileQuit = KStdAction::quit(this, SLOT(slotFileQuit()), actionCollection());
  editCut = KStdAction::cut(this, SLOT(slotEditCut()), actionCollection());
  editCopy = KStdAction::copy(this, SLOT(slotEditCopy()), actionCollection());
  editPaste = KStdAction::paste(this, SLOT(slotEditPaste()), actionCollection());
  createStandardStatusBarAction();
  setStandardToolBarMenuEnabled(true);

  fileNewWindow->setToolTip(i18n("Opens a new application window"));
  fileNew->setToolTip(i18n("Creates a new document"));
  fileOpen->setToolTip(i18n("Opens an existing document"));
  fileOpenRecent->setToolTip(i18n("Opens a recently used file"));
  fileSave->setToolTip(i18n("Saves the actual document"));
  fileSaveAs->setToolTip(i18n("Saves the actual document as..."));
  fileClose->setToolTip(i18n("Closes the actual document"));
  filePrint ->setToolTip(i18n("Prints out the actual document"));
  fileQuit->setToolTip(i18n("Quits the application"));
  editCut->setToolTip(i18n("Cuts the selected section and puts it to the clipboard"));
  editCopy->setToolTip(i18n("Copies the selected section to the clipboard"));
  editPaste->setToolTip(i18n("Pastes the clipboard contents to actual position"));

  // use the absolute path to your ksyncui.rc file for testing purpose in createGUI();
  createGUI();

}

void KSync::initStatusBar()
{
  statusBar()->insertItem(i18n("Ready."), ID_STATUS_MSG);
}

void KSync::initView()
{
  mView = new KSyncView(this);
  setCentralWidget(mView);
//  setCaption(doc->URL().fileName(),false);
}

void KSync::openDocumentFile(const KURL& url)
{
  slotStatusMsg(i18n("Opening file..."));

//  doc->openDocument( url);
  fileOpenRecent->addURL( url );
  slotStatusMsg(i18n("Ready."));
}

void KSync::saveOptions()
{
  config->setGroup("General Options");
  fileOpenRecent->saveEntries(config,"Recent Files");

  mView->writeConfig(config);
}

void KSync::readOptions()
{
  config->setGroup("General Options");

  // initialize the recent file list
  fileOpenRecent->loadEntries(config,"Recent Files");
  mView->readConfig(config);
}

void KSync::saveProperties(KConfig *)
{
#if 0
  if(doc->URL().fileName()!=i18n("Untitled") && !doc->isModified())
  {
    // saving to tempfile not necessary

  }
  else
  {
    KURL url=doc->URL();
    _cfg->writePathEntry("filename", url.url());
    _cfg->writeEntry("modified", doc->isModified());
    QString tempname = kapp->tempSaveName(url.url());
    QString tempurl= KURL::encode_string(tempname);
    KURL _url(tempurl);
    doc->saveDocument(_url);
  }
#endif
}

void KSync::readProperties(KConfig *)
{
#if 0
  QString filename = _cfg->readPathEntry("filename");
  KURL url(filename);
  bool modified = _cfg->readBoolEntry("modified", false);
  if(modified)
  {
    bool canRecover;
    QString tempname = kapp->checkRecoverFile(filename, canRecover);
    KURL _url(tempname);

    if(canRecover)
    {
      doc->openDocument(_url);
      doc->setModified();
      setCaption(_url.fileName(),true);
      QFile::remove(tempname);
    }
  }
  else
  {
    if(!filename.isEmpty())
    {
      doc->openDocument(url);
      setCaption(url.fileName(),false);
    }
  }
#endif
}

bool KSync::queryClose()
{
//  return doc->saveModified();
  return true;
}

bool KSync::queryExit()
{
  saveOptions();
  return true;
}

void KSync::slotFileNewWindow()
{
  slotStatusMsg(i18n("Opening a new application window..."));

  KSync *new_window= new KSync();
  new_window->show();

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileNew()
{
  slotStatusMsg(i18n("Creating new document..."));

#if 0
  if(!doc->saveModified())
  {
     // here saving wasn't successful

  }
  else
  {
    doc->newDocument();
    setCaption(doc->URL().fileName(), false);
  }
#endif

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileOpen()
{
  slotStatusMsg(i18n("Opening file..."));

#if 0
  if(!doc->saveModified())
  {
     // here saving wasn't successful

  }
  else
  {
    KURL url=KFileDialog::getOpenURL(QString::null,
        i18n("*|All Files"), this, i18n("Open File"));
    if(!url.isEmpty())
    {
      doc->openDocument(url);
      setCaption(url.fileName(), false);
      fileOpenRecent->addURL( url );
    }
  }
#endif

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileOpenRecent(const KURL&)
{
  slotStatusMsg(i18n("Opening file..."));

#if 0
  if(!doc->saveModified())
  {
     // here saving wasn't successful
  }
  else
  {
    doc->openDocument(url);
    setCaption(url.fileName(), false);
  }
#endif

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileSave()
{
  slotStatusMsg(i18n("Saving file..."));

//  doc->saveDocument(doc->URL());

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileSaveAs()
{
  slotStatusMsg(i18n("Saving file with a new filename..."));

  KURL url=KFileDialog::getSaveURL(QDir::currentDirPath(),
        i18n("*|All Files"), this, i18n("Save As"));
  if(!url.isEmpty())
  {
//    doc->saveDocument(url);
    fileOpenRecent->addURL(url);
//    setCaption(url.fileName(),doc->isModified());
  }

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileClose()
{
  slotStatusMsg(i18n("Closing file..."));

  close();

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFilePrint()
{
  slotStatusMsg(i18n("Printing..."));

  QPrinter printer;
  if (printer.setup(this))
  {
    mView->print(&printer);
  }

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotFileQuit()
{
  slotStatusMsg(i18n("Exiting..."));
  saveOptions();
  // close the first window, the list makes the next one the first again.
  // This ensures that queryClose() is called on each window to ask for closing
  KMainWindow* w;
  if(memberList)
  {
    for(w=memberList->first(); w!=0; w=memberList->first())
    {
      // only close the window if the closeEvent is accepted. If the user presses Cancel on the saveModified() dialog,
      // the window and the application stay open.
      if(!w->close())
	break;
    }
  }
  slotStatusMsg(i18n("Ready."));
}

void KSync::slotEditCut()
{
  slotStatusMsg(i18n("Cutting selection..."));

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotEditCopy()
{
  slotStatusMsg(i18n("Copying selection to clipboard..."));

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotEditPaste()
{
  slotStatusMsg(i18n("Inserting clipboard contents..."));

  slotStatusMsg(i18n("Ready."));
}

void KSync::slotStatusMsg(const QString &text)
{
  statusBar()->clear();
  statusBar()->changeItem(text, ID_STATUS_MSG);
}

<|endoftext|>


<commit_before>#include "include/AgentFactor.h"

using namespace std;

namespace bwi_actexec {

  AgentFactory::AgentFactory(Agent* ag) {

  }
}
<commit_msg>Restructure for class agent implementation - compile error forward decl?<commit_after><|endoftext|>


<commit_before>// FRAGMENT(includes)
#include <seqan/file.h>
#include <iostream>

using namespace seqan;

// FRAGMENT(open_file)
int main (int argc, char const * argv[])
{
	MultiSeqFile multiSeqFile;
	if (argc < 2 || !open(multiSeqFile.concat, argv[1], OPEN_RDONLY))
		return 1;

// FRAGMENT(guess_and_split)
	AutoSeqFormat format;
	guessFormat(multiSeqFile.concat, format);
	split(multiSeqFile, format);

// FRAGMENT(read_sequences)
	unsigned seqCount = length(multiSeqFile);
	StringSet<String<Dna5Q> > seqs;
	StringSet<CharString> seqIDs;

	reserve(seqs, seqCount, Exact());
	reserve(seqIDs, seqCount, Exact());

	String<Dna5Q> seq;
	CharString qual;
	CharString id;

	for(unsigned i = 0; i < seqCount; ++i)
	{
		assignSeq(seq, multiSeqFile[i], format);    // read sequence
		assignQual(qual, multiSeqFile[i], format);  // read ascii quality values
		assignSeqId(id, multiSeqFile[i], format);   // read sequence id

		// convert ascii to values from 0..62
		// store dna and quality together in Dna5Q
		for (unsigned j = 0; j < length(qual) && j < length(seq); ++j)
			assignQualityValue(seq[j], (int)(ordValue(qual[j]) - 33));

		// we use reserve and append, as assign is not supported
		// by StringSet<..., Owner<ConcatDirect<> > >
		appendValue(seqs, seq, Generous());
		appendValue(ids, id, Generous());
	}

// FRAGMENT(output)
	for (unsigned i = 0; i < seqCount && i < 10; ++i)
	{
		std::cout << '>' << ids[i] << std::endl;
		std::cout << seqs[i] << std::endl;
	}

	return 0;
}

<commit_msg>fixed frags<commit_after>// FRAGMENT(includes)
#define SEQAN_PROFILE
#include <seqan/file.h>
#include <iostream>

using namespace seqan;

// FRAGMENT(open_file)
int main (int argc, char const * argv[])
{
	SEQAN_PROTIMESTART(loadTime);

	MultiSeqFile multiSeqFile;
	if (argc < 2 || !open(multiSeqFile.concat, argv[1], OPEN_RDONLY))
		return 1;

// FRAGMENT(guess_and_split)
	AutoSeqFormat format;
	guessFormat(multiSeqFile.concat, format);
	split(multiSeqFile, format);

// FRAGMENT(reserve)
	unsigned seqCount = length(multiSeqFile);
	StringSet<String<Dna5Q> > seqs;
	StringSet<CharString> seqIDs;

	reserve(seqs, seqCount, Exact());
	reserve(seqIDs, seqCount, Exact());

// FRAGMENT(read_sequences)
	String<Dna5Q> seq;
	CharString qual;
	CharString id;

	for(unsigned i = 0; i < seqCount; ++i)
	{
		assignSeq(seq, multiSeqFile[i], format);    // read sequence
		assignQual(qual, multiSeqFile[i], format);  // read ascii quality values
		assignSeqId(id, multiSeqFile[i], format);   // read sequence id

		// convert ascii to values from 0..62
		// store dna and quality together in Dna5Q
		for (unsigned j = 0; j < length(qual) && j < length(seq); ++j)
			assignQualityValue(seq[j], (int)(ordValue(qual[j]) - 33));

		// we use reserve and append, as assign is not supported
		// by StringSet<..., Owner<ConcatDirect<> > >
		appendValue(seqs, seq, Generous());
		appendValue(seqIDs, id, Generous());
	}

// FRAGMENT(output)
	std::cout << "Loading " << seqCount << " sequences took " << SEQAN_PROTIMEDIFF(loadTime);
	std::cout << " seconds." << std::endl << std::endl;
	for (unsigned i = 0; i < seqCount && i < 10; ++i)
	{
		std::cout << '>' << seqIDs[i] << std::endl;
		std::cout << seqs[i] << std::endl;
	}

	return 0;
}

<|endoftext|>


<commit_before>/**
 * @file
 * @brief Implements the particle generator
 * @remark Based on code from John Idarraga
 * @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 "GeneratorActionG4.hpp"

#include <limits>
#include <memory>

#include <G4Event.hh>
#include <G4GeneralParticleSource.hh>
#include <G4ParticleDefinition.hh>
#include <G4ParticleTable.hh>
#include <G4RunManager.hh>
#include <G4UImanager.hh>
#include <core/module/exceptions.h>

#include "core/config/exceptions.h"
#include "core/utils/log.h"
#include "tools/geant4.h"

using namespace allpix;

GeneratorActionG4::GeneratorActionG4(const Configuration& config)
    : particle_source_(std::make_unique<G4GeneralParticleSource>()) {

    if(config.get<std::string>("source_type") == "macro") {

        LOG(INFO) << "Using user macro for particle source.";

        // Get the UI commander
        G4UImanager* UI = G4UImanager::GetUIpointer();

        // Execute the user's macro
        std::ifstream file(config.getPath("file_name", true));
        std::string line;
        while(std::getline(file, line)) {
            // Check for the "/gps/" pattern in the line:
            if(!line.empty()) {
                if(line.substr(0, 5) == "/gps/" || line.at(0) == '#') {
                    UI->ApplyCommand(line);
                } else {
                    LOG(WARNING) << "Ignoring Geant4 macro command: \"" + line + "\" - not related to particle source.";
                }
            }
        }

    } else {

        // Set verbosity of source to off
        particle_source_->SetVerbosity(0);

        // Get source specific parameters
        auto single_source = particle_source_->GetCurrentSource();

        // Find Geant4 particle
        auto pdg_table = G4ParticleTable::GetParticleTable();
        auto particle_type = config.get<std::string>("particle_type", "");
        std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
        auto particle_code = config.get<int>("particle_code", 0);
        G4ParticleDefinition* particle = nullptr;

        if(!particle_type.empty() && particle_code != 0) {
            if(pdg_table->FindParticle(particle_type) == pdg_table->FindParticle(particle_code)) {
                LOG(WARNING) << "particle_type and particle_code given. Continuing because they match.";
                particle = pdg_table->FindParticle(particle_code);
                if(particle == nullptr) {
                    throw InvalidValueError(config, "particle_code", "particle code does not exist.");
                }
            } else {
                throw InvalidValueError(
                    config, "particle_type", "Given particle_type does not match particle_code. Please remove one of them.");
            }
        } else if(particle_type.empty() && particle_code == 0) {
            throw InvalidValueError(config, "particle_code", "Please set particle_code or particle_type.");
        } else if(particle_code != 0) {
            particle = pdg_table->FindParticle(particle_code);
            if(particle == nullptr) {
                throw InvalidValueError(config, "particle_code", "particle code does not exist.");
            }
        } else {
            particle = pdg_table->FindParticle(particle_type);
            if(particle == nullptr) {
                throw InvalidValueError(config, "particle_type", "particle type does not exist.");
            }
        }

        LOG(DEBUG) << "Using particle " << particle->GetParticleName() << " (ID " << particle->GetPDGEncoding() << ").";

        // Set global parameters of the source
        single_source->SetNumberOfParticles(1);
        single_source->SetParticleDefinition(particle);
        // Set the primary track's start time in for the current event to zero:
        single_source->SetParticleTime(0.0);

        // Set energy parameters
        single_source->GetEneDist()->SetEnergyDisType("Gauss");
        single_source->GetEneDist()->SetMonoEnergy(config.get<double>("source_energy"));
        single_source->GetEneDist()->SetBeamSigmaInE(config.get<double>("source_energy_spread", 0.));

        // Set the centre coordinate of the source
        single_source->GetPosDist()->SetCentreCoords(config.get<G4ThreeVector>("source_position"));

        // Set other position and direction parameters according to shape
        if(config.get<std::string>("source_type") == "beam") {

            // Set position parameters
            single_source->GetPosDist()->SetPosDisType("Beam");
            single_source->GetPosDist()->SetBeamSigmaInR(config.get<double>("source_beam_size", 0));

            // Set angle distribution parameters
            single_source->GetAngDist()->SetAngDistType("beam2d");
            single_source->GetAngDist()->DefineAngRefAxes("angref1", G4ThreeVector(-1., 0, 0));
            G4TwoVector divergence = config.get<G4TwoVector>("source_beam_divergence", G4TwoVector(0., 0.));
            single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x());
            single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y());
            G4ThreeVector direction = config.get<G4ThreeVector>("source_beam_direction");
            if(fabs(direction.mag() - 1.0) > std::numeric_limits<double>::epsilon()) {
                LOG(WARNING) << "Momentum direction is not a unit vector: magnitude is ignored";
            }
            single_source->GetAngDist()->SetParticleMomentumDirection(direction);

        } else if(config.get<std::string>("source_type") == "sphere") {

            // Set position parameters
            single_source->GetPosDist()->SetPosDisType("Volume");
            single_source->GetPosDist()->SetPosDisShape("Sphere");

            // Set angle distribution parameters
            single_source->GetPosDist()->SetRadius(config.get<double>("source_sphere_radius"));
            single_source->GetAngDist()->SetAngDistType("focused");
            single_source->GetAngDist()->SetFocusPoint(G4ThreeVector(0, 0, 0));

        } else if(config.get<std::string>("source_type") == "square") {

            // Set position parameters
            single_source->GetPosDist()->SetPosDisType("Plane");
            single_source->GetPosDist()->SetPosDisShape("Square");
            single_source->GetPosDist()->SetHalfX(config.get<double>("source_square_side") / 2);
            single_source->GetPosDist()->SetHalfY(config.get<double>("source_square_side") / 2);

            // Set angle distribution parameters
            single_source->GetAngDist()->SetAngDistType("iso");
            single_source->GetAngDist()->SetMaxTheta(config.get<double>("source_square_angle", 1.571));

        } else {

            throw InvalidValueError(config, "source_type", "The source type is not valid.");
        }
    }
}

/**
 * Called automatically for every event
 */
void GeneratorActionG4::GeneratePrimaries(G4Event* event) {
    particle_source_->GeneratePrimaryVertex(event);
}
<commit_msg>Added a point source.<commit_after>/**
 * @file
 * @brief Implements the particle generator
 * @remark Based on code from John Idarraga
 * @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 "GeneratorActionG4.hpp"

#include <limits>
#include <memory>

#include <G4Event.hh>
#include <G4GeneralParticleSource.hh>
#include <G4ParticleDefinition.hh>
#include <G4ParticleTable.hh>
#include <G4RunManager.hh>
#include <G4UImanager.hh>
#include <core/module/exceptions.h>

#include "core/config/exceptions.h"
#include "core/utils/log.h"
#include "tools/geant4.h"

using namespace allpix;

GeneratorActionG4::GeneratorActionG4(const Configuration& config)
    : particle_source_(std::make_unique<G4GeneralParticleSource>()) {

    if(config.get<std::string>("source_type") == "macro") {

        LOG(INFO) << "Using user macro for particle source.";

        // Get the UI commander
        G4UImanager* UI = G4UImanager::GetUIpointer();

        // Execute the user's macro
        std::ifstream file(config.getPath("file_name", true));
        std::string line;
        while(std::getline(file, line)) {
            // Check for the "/gps/" pattern in the line:
            if(!line.empty()) {
                if(line.substr(0, 5) == "/gps/" || line.at(0) == '#') {
                    UI->ApplyCommand(line);
                } else {
                    LOG(WARNING) << "Ignoring Geant4 macro command: \"" + line + "\" - not related to particle source.";
                }
            }
        }

    } else {

        // Set verbosity of source to off
        particle_source_->SetVerbosity(0);

        // Get source specific parameters
        auto single_source = particle_source_->GetCurrentSource();

        // Find Geant4 particle
        auto pdg_table = G4ParticleTable::GetParticleTable();
        auto particle_type = config.get<std::string>("particle_type", "");
        std::transform(particle_type.begin(), particle_type.end(), particle_type.begin(), ::tolower);
        auto particle_code = config.get<int>("particle_code", 0);
        G4ParticleDefinition* particle = nullptr;

        if(!particle_type.empty() && particle_code != 0) {
            if(pdg_table->FindParticle(particle_type) == pdg_table->FindParticle(particle_code)) {
                LOG(WARNING) << "particle_type and particle_code given. Continuing because they match.";
                particle = pdg_table->FindParticle(particle_code);
                if(particle == nullptr) {
                    throw InvalidValueError(config, "particle_code", "particle code does not exist.");
                }
            } else {
                throw InvalidValueError(
                    config, "particle_type", "Given particle_type does not match particle_code. Please remove one of them.");
            }
        } else if(particle_type.empty() && particle_code == 0) {
            throw InvalidValueError(config, "particle_code", "Please set particle_code or particle_type.");
        } else if(particle_code != 0) {
            particle = pdg_table->FindParticle(particle_code);
            if(particle == nullptr) {
                throw InvalidValueError(config, "particle_code", "particle code does not exist.");
            }
        } else {
            particle = pdg_table->FindParticle(particle_type);
            if(particle == nullptr) {
                throw InvalidValueError(config, "particle_type", "particle type does not exist.");
            }
        }

        LOG(DEBUG) << "Using particle " << particle->GetParticleName() << " (ID " << particle->GetPDGEncoding() << ").";

        // Set global parameters of the source
        single_source->SetNumberOfParticles(1);
        single_source->SetParticleDefinition(particle);
        // Set the primary track's start time in for the current event to zero:
        single_source->SetParticleTime(0.0);

        // Set energy parameters
        single_source->GetEneDist()->SetEnergyDisType("Gauss");
        single_source->GetEneDist()->SetMonoEnergy(config.get<double>("source_energy"));
        single_source->GetEneDist()->SetBeamSigmaInE(config.get<double>("source_energy_spread", 0.));

        // Set the centre coordinate of the source
        single_source->GetPosDist()->SetCentreCoords(config.get<G4ThreeVector>("source_position"));

        // Set other position and direction parameters according to shape
        if(config.get<std::string>("source_type") == "beam") {

            // Set position parameters
            single_source->GetPosDist()->SetPosDisType("Beam");
            single_source->GetPosDist()->SetBeamSigmaInR(config.get<double>("source_beam_size", 0));

            // Set angle distribution parameters
            single_source->GetAngDist()->SetAngDistType("beam2d");
            single_source->GetAngDist()->DefineAngRefAxes("angref1", G4ThreeVector(-1., 0, 0));
            G4TwoVector divergence = config.get<G4TwoVector>("source_beam_divergence", G4TwoVector(0., 0.));
            single_source->GetAngDist()->SetBeamSigmaInAngX(divergence.x());
            single_source->GetAngDist()->SetBeamSigmaInAngY(divergence.y());
            G4ThreeVector direction = config.get<G4ThreeVector>("source_beam_direction");
            if(fabs(direction.mag() - 1.0) > std::numeric_limits<double>::epsilon()) {
                LOG(WARNING) << "Momentum direction is not a unit vector: magnitude is ignored";
            }
            single_source->GetAngDist()->SetParticleMomentumDirection(direction);

        } else if(config.get<std::string>("source_type") == "sphere") {

            // Set position parameters
            single_source->GetPosDist()->SetPosDisType("Volume");
            single_source->GetPosDist()->SetPosDisShape("Sphere");

            // Set angle distribution parameters
            single_source->GetPosDist()->SetRadius(config.get<double>("source_sphere_radius"));
            single_source->GetAngDist()->SetAngDistType("focused");
            single_source->GetAngDist()->SetFocusPoint(G4ThreeVector(0, 0, 0));

        } else if(config.get<std::string>("source_type") == "square") {

            // Set position parameters
            single_source->GetPosDist()->SetPosDisType("Plane");
            single_source->GetPosDist()->SetPosDisShape("Square");
            single_source->GetPosDist()->SetHalfX(config.get<double>("source_square_side") / 2);
            single_source->GetPosDist()->SetHalfY(config.get<double>("source_square_side") / 2);

            // Set angle distribution parameters
            single_source->GetAngDist()->SetAngDistType("iso");
            single_source->GetAngDist()->SetMaxTheta(config.get<double>("source_square_angle", ROOT::Math::Pi() / 2));

        } else if(config.get<std::string>("source_type") == "point") {

            // Set position parameters
            single_source->GetPosDist()->SetPosDisType("Point");

            // Set angle distribution parameters
            single_source->GetAngDist()->SetAngDistType("iso");

        } else {

            throw InvalidValueError(config, "source_type", "The source type is not valid.");
        }
    }
}

/**
 * Called automatically for every event
 */
void GeneratorActionG4::GeneratePrimaries(G4Event* event) {
    particle_source_->GeneratePrimaryVertex(event);
}
<|endoftext|>