<commit_before>/********************************************************************
 * livegrep -- chunk.cc
 * Copyright (c) 2011-2013 Nelson Elhage
 *
 * This program is free software. You may use, redistribute, and/or
 * modify it under the terms listed in the COPYING file.
 ********************************************************************/
#include "chunk.h"
#include "radix_sort.h"
#include "radix_sorter.h"

#include <re2/re2.h>
#include <gflags/gflags.h>

#include <limits>

using re2::StringPiece;

DECLARE_bool(index);

void chunk::add_chunk_file(indexed_file *sf, const StringPiece& line)
{
    int l = (unsigned char*)line.data() - data;
    int r = l + line.size();
    chunk_file *f = NULL;
    int min_dist = numeric_limits<int>::max(), dist;
    for (vector<chunk_file>::iterator it = cur_file.begin();
         it != cur_file.end(); it ++) {
        if (l <= it->left)
            dist = max(0, it->left - r);
        else if (r >= it->right)
            dist = max(0, l - it->right);
        else
            dist = 0;
        assert(dist == 0 || r < it->left || l > it->right);
        if (dist < min_dist) {
            min_dist = dist;
            f = &(*it);
        }
    }
    if (f && min_dist < kMaxGap) {
        f->expand(l, r);
        return;
    }
    chunk_files++;
    cur_file.push_back(chunk_file());
    chunk_file& cf = cur_file.back();
    cf.files.push_front(sf);
    cf.left = l;
    cf.right = r;
}

void chunk::finish_file() {
    int right = -1;
    sort(cur_file.begin(), cur_file.end());
    for (vector<chunk_file>::iterator it = cur_file.begin();
         it != cur_file.end(); it ++) {
        assert(right < it->left);
        right = max(right, it->right);
    }
    files.insert(files.end(), cur_file.begin(), cur_file.end());
    cur_file.clear();
}

int chunk::chunk_files = 0;

void radix_sorter::sort(uint32_t *l, uint32_t *r) {
    cmp_suffix cmp(*this);
    indexer idx(*this);
    msd_radix_sort(l, r, 0, idx, cmp);
    assert(is_sorted(l, r, cmp));
}

void chunk::finalize() {
    if (FLAGS_index) {
        for (int i = 0; i < size; i++)
            suffixes[i] = i;
        radix_sorter sorter(data, size);
        sorter.sort(suffixes, suffixes + size);
    }
}

void chunk::finalize_files() {
    sort(files.begin(), files.end());

    vector<chunk_file>::iterator out, in;
    out = in = files.begin();
    while (in != files.end()) {
        *out = *in;
        ++in;
        while (in != files.end() &&
               out->left == in->left &&
               out->right == in->right) {
            out->files.push_back(in->files.front());
            ++in;
        }
        ++out;
    }
    files.resize(out - files.begin());
    build_tree();
}

void chunk::build_tree() {
    assert(is_sorted(files.begin(), files.end()));
    cf_root = build_tree(0, files.size());
}

chunk_file_node *chunk::build_tree(int left, int right) {
    if (right == left)
        return 0;
    int mid = (left + right) / 2;
    chunk_file_node *node = new chunk_file_node;

    node->chunk = &files[mid];
    node->left  = build_tree(left, mid);
    node->right = build_tree(mid + 1, right);
    node->right_limit = node->chunk->right;
    if (node->left && node->left->right_limit > node->right_limit)
        node->right_limit = node->left->right_limit;
    if (node->right && node->right->right_limit > node->right_limit)
        node->right_limit = node->right->right_limit;
    assert(!node->left  || *(node->left->chunk) < *(node->chunk));
    assert(!node->right || *(node->chunk) < *(node->right->chunk));
    return node;
}
<commit_msg>Put an expensive assertion behind an ifdef<commit_after>/********************************************************************
 * livegrep -- chunk.cc
 * Copyright (c) 2011-2013 Nelson Elhage
 *
 * This program is free software. You may use, redistribute, and/or
 * modify it under the terms listed in the COPYING file.
 ********************************************************************/
#include "chunk.h"
#include "radix_sort.h"
#include "radix_sorter.h"

#include <re2/re2.h>
#include <gflags/gflags.h>

#include <limits>

using re2::StringPiece;

DECLARE_bool(index);

void chunk::add_chunk_file(indexed_file *sf, const StringPiece& line)
{
    int l = (unsigned char*)line.data() - data;
    int r = l + line.size();
    chunk_file *f = NULL;
    int min_dist = numeric_limits<int>::max(), dist;
    for (vector<chunk_file>::iterator it = cur_file.begin();
         it != cur_file.end(); it ++) {
        if (l <= it->left)
            dist = max(0, it->left - r);
        else if (r >= it->right)
            dist = max(0, l - it->right);
        else
            dist = 0;
        assert(dist == 0 || r < it->left || l > it->right);
        if (dist < min_dist) {
            min_dist = dist;
            f = &(*it);
        }
    }
    if (f && min_dist < kMaxGap) {
        f->expand(l, r);
        return;
    }
    chunk_files++;
    cur_file.push_back(chunk_file());
    chunk_file& cf = cur_file.back();
    cf.files.push_front(sf);
    cf.left = l;
    cf.right = r;
}

void chunk::finish_file() {
    int right = -1;
    sort(cur_file.begin(), cur_file.end());
    for (vector<chunk_file>::iterator it = cur_file.begin();
         it != cur_file.end(); it ++) {
        assert(right < it->left);
        right = max(right, it->right);
    }
    files.insert(files.end(), cur_file.begin(), cur_file.end());
    cur_file.clear();
}

int chunk::chunk_files = 0;

void radix_sorter::sort(uint32_t *l, uint32_t *r) {
    cmp_suffix cmp(*this);
    indexer idx(*this);
    msd_radix_sort(l, r, 0, idx, cmp);

#ifdef DEBUG_RADIX_SORT
    assert(is_sorted(l, r, cmp));
#endif
}

void chunk::finalize() {
    if (FLAGS_index) {
        for (int i = 0; i < size; i++)
            suffixes[i] = i;
        radix_sorter sorter(data, size);
        sorter.sort(suffixes, suffixes + size);
    }
}

void chunk::finalize_files() {
    sort(files.begin(), files.end());

    vector<chunk_file>::iterator out, in;
    out = in = files.begin();
    while (in != files.end()) {
        *out = *in;
        ++in;
        while (in != files.end() &&
               out->left == in->left &&
               out->right == in->right) {
            out->files.push_back(in->files.front());
            ++in;
        }
        ++out;
    }
    files.resize(out - files.begin());
    build_tree();
}

void chunk::build_tree() {
    assert(is_sorted(files.begin(), files.end()));
    cf_root = build_tree(0, files.size());
}

chunk_file_node *chunk::build_tree(int left, int right) {
    if (right == left)
        return 0;
    int mid = (left + right) / 2;
    chunk_file_node *node = new chunk_file_node;

    node->chunk = &files[mid];
    node->left  = build_tree(left, mid);
    node->right = build_tree(mid + 1, right);
    node->right_limit = node->chunk->right;
    if (node->left && node->left->right_limit > node->right_limit)
        node->right_limit = node->left->right_limit;
    if (node->right && node->right->right_limit > node->right_limit)
        node->right_limit = node->right->right_limit;
    assert(!node->left  || *(node->left->chunk) < *(node->chunk));
    assert(!node->right || *(node->chunk) < *(node->right->chunk));
    return node;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * ALMA - Atacama Large Millimeter Array
 * Copyright (c) ESO - European Southern Observatory, 2011
 * (in the framework of the ALMA collaboration).
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *******************************************************************************/
#include "Timestamp.h"
#include <sys/time.h>
#include <sstream>
#include <iostream>
#include <stdio.h>

using std::stringstream;
using std::string;
using acsalarm::Timestamp;

/**
 * Default no-args constructor, creates an instance with the time at instantiation.
 */
Timestamp::Timestamp()
{
	// TODO later: portability issues with gettimeofday?
	// i.e. will this work on non-unix platforms? do we care?
	timeval tim;
	gettimeofday(&tim, NULL);
	setSeconds(tim.tv_sec);
	setMicroSeconds(tim.tv_usec);
}

/**
 * Constructor to instantiate and configure a Timestamp with a time.
 */
Timestamp::Timestamp(long secs, long microSecs)
{
	setSeconds(secs);
	setMicroSeconds(microSecs);
}

/*
 * Copy constructor
 */
Timestamp::Timestamp(const Timestamp & ts)
{
	seconds = ts.seconds;
	microSeconds = ts.microSeconds;
}

/**
 * Destructor.
 */
Timestamp::~Timestamp()
{
}

/*
 * Assignment operator.
 */
Timestamp & Timestamp::operator=(const Timestamp & rhs)
{
	setSeconds(rhs.seconds);
	setMicroSeconds(rhs.microSeconds);
	return *this;
}

/*
 * Equality operator.
 */
int Timestamp::operator==(const Timestamp &rhs) const
{
	int retVal = 1;
	if(rhs.seconds != seconds || rhs.microSeconds != microSeconds)
	{
		retVal = 0;
	}
	return retVal;
}

std::string Timestamp::toISOFormat() const {
	struct timeval tval;
	tval.tv_sec=getSeconds();
	tval.tv_usec=getMicroSeconds();

	struct tm* temptm = gmtime(&tval.tv_sec);

	char tmbuf[64], buf[64];
	strftime(tmbuf, sizeof tmbuf, "%FT%H:%M:%S", temptm);
	snprintf(buf, sizeof buf, "%s.%03ld", tmbuf, tval.tv_usec/1000);

	std::string ret=buf;
	return ret;
}

<commit_msg>ICT-4351: Changed method gmtime to its thread-safe version gmtime_r<commit_after>/*******************************************************************************
 * ALMA - Atacama Large Millimeter Array
 * Copyright (c) ESO - European Southern Observatory, 2011
 * (in the framework of the ALMA collaboration).
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *******************************************************************************/
#include "Timestamp.h"
#include <sys/time.h>
#include <sstream>
#include <iostream>
#include <stdio.h>

using std::stringstream;
using std::string;
using acsalarm::Timestamp;

/**
 * Default no-args constructor, creates an instance with the time at instantiation.
 */
Timestamp::Timestamp()
{
	// TODO later: portability issues with gettimeofday?
	// i.e. will this work on non-unix platforms? do we care?
	timeval tim;
	gettimeofday(&tim, NULL);
	setSeconds(tim.tv_sec);
	setMicroSeconds(tim.tv_usec);
}

/**
 * Constructor to instantiate and configure a Timestamp with a time.
 */
Timestamp::Timestamp(long secs, long microSecs)
{
	setSeconds(secs);
	setMicroSeconds(microSecs);
}

/*
 * Copy constructor
 */
Timestamp::Timestamp(const Timestamp & ts)
{
	seconds = ts.seconds;
	microSeconds = ts.microSeconds;
}

/**
 * Destructor.
 */
Timestamp::~Timestamp()
{
}

/*
 * Assignment operator.
 */
Timestamp & Timestamp::operator=(const Timestamp & rhs)
{
	setSeconds(rhs.seconds);
	setMicroSeconds(rhs.microSeconds);
	return *this;
}

/*
 * Equality operator.
 */
int Timestamp::operator==(const Timestamp &rhs) const
{
	int retVal = 1;
	if(rhs.seconds != seconds || rhs.microSeconds != microSeconds)
	{
		retVal = 0;
	}
	return retVal;
}

std::string Timestamp::toISOFormat() const {
	struct timeval tval;
	tval.tv_sec=getSeconds();
	tval.tv_usec=getMicroSeconds();

	struct tm temptm = {0};
	gmtime_r(&tval.tv_sec,&temptm);

	char tmbuf[64], buf[64];
	strftime(tmbuf, sizeof tmbuf, "%FT%H:%M:%S", &temptm);
	snprintf(buf, sizeof buf, "%s.%03ld", tmbuf, tval.tv_usec/1000);

	std::string ret=buf;
	return ret;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "translator.h"
#include "profileevaluator.h"

#ifndef QT_BOOTSTRAPPED
#include <QtCore/QCoreApplication>
#include <QtCore/QTranslator>
#endif
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QRegExp>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QTextStream>

#include <iostream>

QT_USE_NAMESPACE

#ifdef QT_BOOTSTRAPPED
static void initBinaryDir(
#ifndef Q_OS_WIN
        const char *argv0
#endif
        );

struct LR {
    static inline QString tr(const char *sourceText, const char *comment = 0)
    {
        return QCoreApplication::translate("LRelease", sourceText, comment);
    }
};
#else
class LR {
    Q_DECLARE_TR_FUNCTIONS(LRelease)
};
#endif

static void printOut(const QString & out)
{
    QTextStream stream(stdout);
    stream << out;
}

static void printUsage()
{
    printOut(LR::tr(
        "Usage:\n"
        "    lrelease [options] project-file\n"
        "    lrelease [options] ts-files [-qm qm-file]\n\n"
        "lrelease is part of Qt's Linguist tool chain. It can be used as a\n"
        "stand-alone tool to convert XML-based translations files in the TS\n"
        "format into the 'compiled' QM format used by QTranslator objects.\n\n"
        "Options:\n"
        "    -help  Display this information and exit\n"
        "    -idbased\n"
        "           Use IDs instead of source strings for message keying\n"
        "    -compress\n"
        "           Compress the QM files\n"
        "    -nounfinished\n"
        "           Do not include unfinished translations\n"
        "    -removeidentical\n"
        "           If the translated text is the same as\n"
        "           the source text, do not include the message\n"
        "    -markuntranslated <prefix>\n"
        "           If a message has no real translation, use the source text\n"
        "           prefixed with the given string instead\n"
        "    -silent\n"
        "           Do not explain what is being done\n"
        "    -version\n"
        "           Display the version of lrelease and exit\n"
    ));
}

static bool loadTsFile(Translator &tor, const QString &tsFileName, bool /* verbose */)
{
    ConversionData cd;
    bool ok = tor.load(tsFileName, cd, QLatin1String("auto"));
    if (!ok) {
        std::cerr << qPrintable(LR::tr("lrelease error: %1").arg(cd.error()));
    } else {
        if (!cd.errors().isEmpty())
            printOut(cd.error());
    }
    cd.clearErrors();
    return ok;
}

static bool releaseTranslator(Translator &tor, const QString &qmFileName,
    ConversionData &cd, bool removeIdentical)
{
    tor.reportDuplicates(tor.resolveDuplicates(), qmFileName, cd.isVerbose());

    if (cd.isVerbose())
        printOut(LR::tr("Updating '%1'...\n").arg(qmFileName));
    if (removeIdentical) {
        if (cd.isVerbose())
            printOut(LR::tr("Removing translations equal to source text in '%1'...\n").arg(qmFileName));
        tor.stripIdenticalSourceTranslations();
    }

    QFile file(qmFileName);
    if (!file.open(QIODevice::WriteOnly)) {
        std::cerr << qPrintable(LR::tr("lrelease error: cannot create '%1': %2\n")
                                .arg(qmFileName, file.errorString()));
        return false;
    }

    tor.normalizeTranslations(cd);
    bool ok = tor.release(&file, cd);
    file.close();

    if (!ok) {
        std::cerr << qPrintable(LR::tr("lrelease error: cannot save '%1': %2")
                                .arg(qmFileName, cd.error()));
    } else if (!cd.errors().isEmpty()) {
        printOut(cd.error());
    }
    cd.clearErrors();
    return ok;
}

static bool releaseTsFile(const QString& tsFileName,
    ConversionData &cd, bool removeIdentical)
{
    Translator tor;
    if (!loadTsFile(tor, tsFileName, cd.isVerbose()))
        return false;

    QString qmFileName = tsFileName;
    foreach (const Translator::FileFormat &fmt, Translator::registeredFileFormats()) {
        if (qmFileName.endsWith(QLatin1Char('.') + fmt.extension)) {
            qmFileName.chop(fmt.extension.length() + 1);
            break;
        }
    }
    qmFileName += QLatin1String(".qm");

    return releaseTranslator(tor, qmFileName, cd, removeIdentical);
}

int main(int argc, char **argv)
{
#ifdef QT_BOOTSTRAPPED
    initBinaryDir(
#ifndef Q_OS_WIN
            argv[0]
#endif
            );
#else
    QCoreApplication app(argc, argv);
#ifndef Q_OS_WIN32
    QTranslator translator;
    QTranslator qtTranslator;
    QString sysLocale = QLocale::system().name();
    QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir)
        && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) {
        app.installTranslator(&translator);
        app.installTranslator(&qtTranslator);
    }
#endif // Q_OS_WIN32
#endif // QT_BOOTSTRAPPED

    ConversionData cd;
    cd.m_verbose = true; // the default is true starting with Qt 4.2
    bool removeIdentical = false;
    Translator tor;
    QStringList inputFiles;
    QString outputFile;

    for (int i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-compress")) {
            cd.m_saveMode = SaveStripped;
            continue;
        } else if (!strcmp(argv[i], "-idbased")) {
            cd.m_idBased = true;
            continue;
        } else if (!strcmp(argv[i], "-nocompress")) {
            cd.m_saveMode = SaveEverything;
            continue;
        } else if (!strcmp(argv[i], "-removeidentical")) {
            removeIdentical = true;
            continue;
        } else if (!strcmp(argv[i], "-nounfinished")) {
            cd.m_ignoreUnfinished = true;
            continue;
        } else if (!strcmp(argv[i], "-markuntranslated")) {
            if (i == argc - 1) {
                printUsage();
                return 1;
            }
            cd.m_unTrPrefix = QString::fromLocal8Bit(argv[++i]);
        } else if (!strcmp(argv[i], "-silent")) {
            cd.m_verbose = false;
            continue;
        } else if (!strcmp(argv[i], "-verbose")) {
            cd.m_verbose = true;
            continue;
        } else if (!strcmp(argv[i], "-version")) {
            printOut(LR::tr("lrelease version %1\n").arg(QLatin1String(QT_VERSION_STR)));
            return 0;
        } else if (!strcmp(argv[i], "-qm")) {
            if (i == argc - 1) {
                printUsage();
                return 1;
            }
            outputFile = QString::fromLocal8Bit(argv[++i]);
        } else if (!strcmp(argv[i], "-help")) {
            printUsage();
            return 0;
        } else if (argv[i][0] == '-') {
            printUsage();
            return 1;
        } else {
            inputFiles << QString::fromLocal8Bit(argv[i]);
        }
    }

    if (inputFiles.isEmpty()) {
        printUsage();
        return 1;
    }

    foreach (const QString &inputFile, inputFiles) {
        if (inputFile.endsWith(QLatin1String(".pro"), Qt::CaseInsensitive)
            || inputFile.endsWith(QLatin1String(".pri"), Qt::CaseInsensitive)) {
            QFileInfo fi(inputFile);
            ProFile pro(fi.absoluteFilePath());

            ProFileEvaluator visitor;
            visitor.setVerbose(cd.isVerbose());

            if (!visitor.queryProFile(&pro)) {
                std::cerr << qPrintable(LR::tr(
                          "lrelease error: cannot read project file '%1'.\n")
                          .arg(inputFile));
                continue;
            }
            if (!visitor.accept(&pro)) {
                std::cerr << qPrintable(LR::tr(
                          "lrelease error: cannot process project file '%1'.\n")
                          .arg(inputFile));
                continue;
            }

            QStringList translations = visitor.values(QLatin1String("TRANSLATIONS"));
            if (translations.isEmpty()) {
                std::cerr << qPrintable(LR::tr(
                          "lrelease warning: Met no 'TRANSLATIONS' entry in project file '%1'\n")
                          .arg(inputFile));
            } else {
                QDir proDir(fi.absolutePath());
                foreach (const QString &trans, translations)
                    if (!releaseTsFile(QFileInfo(proDir, trans).filePath(), cd, removeIdentical))
                        return 1;
            }
        } else {
            if (outputFile.isEmpty()) {
                if (!releaseTsFile(inputFile, cd, removeIdentical))
                    return 1;
            } else {
                if (!loadTsFile(tor, inputFile, cd.isVerbose()))
                    return 1;
            }
        }
    }

    if (!outputFile.isEmpty())
        return releaseTranslator(tor, outputFile, cd, removeIdentical) ? 0 : 1;

    return 0;
}

#ifdef QT_BOOTSTRAPPED

#ifdef Q_OS_WIN
# include <windows.h>
#endif

static QString binDir;

static void initBinaryDir(
#ifndef Q_OS_WIN
        const char *_argv0
#endif
        )
{
#ifdef Q_OS_WIN
    wchar_t module_name[MAX_PATH];
    GetModuleFileName(0, module_name, MAX_PATH);
    QFileInfo filePath = QString::fromWCharArray(module_name);
    binDir = filePath.filePath();
#else
    QString argv0 = QFile::decodeName(QByteArray(_argv0));
    QString absPath;

    if (!argv0.isEmpty() && argv0.at(0) == QLatin1Char('/')) {
        /*
          If argv0 starts with a slash, it is already an absolute
          file path.
        */
        absPath = argv0;
    } else if (argv0.contains(QLatin1Char('/'))) {
        /*
          If argv0 contains one or more slashes, it is a file path
          relative to the current directory.
        */
        absPath = QDir::current().absoluteFilePath(argv0);
    } else {
        /*
          Otherwise, the file path has to be determined using the
          PATH environment variable.
        */
        QByteArray pEnv = qgetenv("PATH");
        QDir currentDir = QDir::current();
        QStringList paths = QString::fromLocal8Bit(pEnv.constData()).split(QLatin1String(":"));
        for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) {
            if ((*p).isEmpty())
                continue;
            QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0);
            QFileInfo candidate_fi(candidate);
            if (candidate_fi.exists() && !candidate_fi.isDir()) {
                binDir = candidate_fi.canonicalPath();
                return;
            }
        }
        return;
    }

    QFileInfo fi(absPath);
    if (fi.exists())
        binDir = fi.canonicalPath();
#endif
}

QT_BEGIN_NAMESPACE

// The name is hard-coded in QLibraryInfo
QString qmake_libraryInfoFile()
{
    if (binDir.isEmpty())
        return QString();
    return QDir(binDir).filePath(QString::fromLatin1("qt.conf"));
}

QT_END_NAMESPACE

#endif // QT_BOOTSTRAPPED
<commit_msg>Added missing header to lrelease.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "translator.h"
#include "profileevaluator.h"

#ifndef QT_BOOTSTRAPPED
#include <QtCore/QCoreApplication>
#include <QtCore/QTranslator>
#endif
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QRegExp>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QTextStream>
#include <QtCore/QLibraryInfo>

#include <iostream>

QT_USE_NAMESPACE

#ifdef QT_BOOTSTRAPPED
static void initBinaryDir(
#ifndef Q_OS_WIN
        const char *argv0
#endif
        );

struct LR {
    static inline QString tr(const char *sourceText, const char *comment = 0)
    {
        return QCoreApplication::translate("LRelease", sourceText, comment);
    }
};
#else
class LR {
    Q_DECLARE_TR_FUNCTIONS(LRelease)
};
#endif

static void printOut(const QString & out)
{
    QTextStream stream(stdout);
    stream << out;
}

static void printUsage()
{
    printOut(LR::tr(
        "Usage:\n"
        "    lrelease [options] project-file\n"
        "    lrelease [options] ts-files [-qm qm-file]\n\n"
        "lrelease is part of Qt's Linguist tool chain. It can be used as a\n"
        "stand-alone tool to convert XML-based translations files in the TS\n"
        "format into the 'compiled' QM format used by QTranslator objects.\n\n"
        "Options:\n"
        "    -help  Display this information and exit\n"
        "    -idbased\n"
        "           Use IDs instead of source strings for message keying\n"
        "    -compress\n"
        "           Compress the QM files\n"
        "    -nounfinished\n"
        "           Do not include unfinished translations\n"
        "    -removeidentical\n"
        "           If the translated text is the same as\n"
        "           the source text, do not include the message\n"
        "    -markuntranslated <prefix>\n"
        "           If a message has no real translation, use the source text\n"
        "           prefixed with the given string instead\n"
        "    -silent\n"
        "           Do not explain what is being done\n"
        "    -version\n"
        "           Display the version of lrelease and exit\n"
    ));
}

static bool loadTsFile(Translator &tor, const QString &tsFileName, bool /* verbose */)
{
    ConversionData cd;
    bool ok = tor.load(tsFileName, cd, QLatin1String("auto"));
    if (!ok) {
        std::cerr << qPrintable(LR::tr("lrelease error: %1").arg(cd.error()));
    } else {
        if (!cd.errors().isEmpty())
            printOut(cd.error());
    }
    cd.clearErrors();
    return ok;
}

static bool releaseTranslator(Translator &tor, const QString &qmFileName,
    ConversionData &cd, bool removeIdentical)
{
    tor.reportDuplicates(tor.resolveDuplicates(), qmFileName, cd.isVerbose());

    if (cd.isVerbose())
        printOut(LR::tr("Updating '%1'...\n").arg(qmFileName));
    if (removeIdentical) {
        if (cd.isVerbose())
            printOut(LR::tr("Removing translations equal to source text in '%1'...\n").arg(qmFileName));
        tor.stripIdenticalSourceTranslations();
    }

    QFile file(qmFileName);
    if (!file.open(QIODevice::WriteOnly)) {
        std::cerr << qPrintable(LR::tr("lrelease error: cannot create '%1': %2\n")
                                .arg(qmFileName, file.errorString()));
        return false;
    }

    tor.normalizeTranslations(cd);
    bool ok = tor.release(&file, cd);
    file.close();

    if (!ok) {
        std::cerr << qPrintable(LR::tr("lrelease error: cannot save '%1': %2")
                                .arg(qmFileName, cd.error()));
    } else if (!cd.errors().isEmpty()) {
        printOut(cd.error());
    }
    cd.clearErrors();
    return ok;
}

static bool releaseTsFile(const QString& tsFileName,
    ConversionData &cd, bool removeIdentical)
{
    Translator tor;
    if (!loadTsFile(tor, tsFileName, cd.isVerbose()))
        return false;

    QString qmFileName = tsFileName;
    foreach (const Translator::FileFormat &fmt, Translator::registeredFileFormats()) {
        if (qmFileName.endsWith(QLatin1Char('.') + fmt.extension)) {
            qmFileName.chop(fmt.extension.length() + 1);
            break;
        }
    }
    qmFileName += QLatin1String(".qm");

    return releaseTranslator(tor, qmFileName, cd, removeIdentical);
}

int main(int argc, char **argv)
{
#ifdef QT_BOOTSTRAPPED
    initBinaryDir(
#ifndef Q_OS_WIN
            argv[0]
#endif
            );
#else
    QCoreApplication app(argc, argv);
#ifndef Q_OS_WIN32
    QTranslator translator;
    QTranslator qtTranslator;
    QString sysLocale = QLocale::system().name();
    QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir)
        && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) {
        app.installTranslator(&translator);
        app.installTranslator(&qtTranslator);
    }
#endif // Q_OS_WIN32
#endif // QT_BOOTSTRAPPED

    ConversionData cd;
    cd.m_verbose = true; // the default is true starting with Qt 4.2
    bool removeIdentical = false;
    Translator tor;
    QStringList inputFiles;
    QString outputFile;

    for (int i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-compress")) {
            cd.m_saveMode = SaveStripped;
            continue;
        } else if (!strcmp(argv[i], "-idbased")) {
            cd.m_idBased = true;
            continue;
        } else if (!strcmp(argv[i], "-nocompress")) {
            cd.m_saveMode = SaveEverything;
            continue;
        } else if (!strcmp(argv[i], "-removeidentical")) {
            removeIdentical = true;
            continue;
        } else if (!strcmp(argv[i], "-nounfinished")) {
            cd.m_ignoreUnfinished = true;
            continue;
        } else if (!strcmp(argv[i], "-markuntranslated")) {
            if (i == argc - 1) {
                printUsage();
                return 1;
            }
            cd.m_unTrPrefix = QString::fromLocal8Bit(argv[++i]);
        } else if (!strcmp(argv[i], "-silent")) {
            cd.m_verbose = false;
            continue;
        } else if (!strcmp(argv[i], "-verbose")) {
            cd.m_verbose = true;
            continue;
        } else if (!strcmp(argv[i], "-version")) {
            printOut(LR::tr("lrelease version %1\n").arg(QLatin1String(QT_VERSION_STR)));
            return 0;
        } else if (!strcmp(argv[i], "-qm")) {
            if (i == argc - 1) {
                printUsage();
                return 1;
            }
            outputFile = QString::fromLocal8Bit(argv[++i]);
        } else if (!strcmp(argv[i], "-help")) {
            printUsage();
            return 0;
        } else if (argv[i][0] == '-') {
            printUsage();
            return 1;
        } else {
            inputFiles << QString::fromLocal8Bit(argv[i]);
        }
    }

    if (inputFiles.isEmpty()) {
        printUsage();
        return 1;
    }

    foreach (const QString &inputFile, inputFiles) {
        if (inputFile.endsWith(QLatin1String(".pro"), Qt::CaseInsensitive)
            || inputFile.endsWith(QLatin1String(".pri"), Qt::CaseInsensitive)) {
            QFileInfo fi(inputFile);
            ProFile pro(fi.absoluteFilePath());

            ProFileEvaluator visitor;
            visitor.setVerbose(cd.isVerbose());

            if (!visitor.queryProFile(&pro)) {
                std::cerr << qPrintable(LR::tr(
                          "lrelease error: cannot read project file '%1'.\n")
                          .arg(inputFile));
                continue;
            }
            if (!visitor.accept(&pro)) {
                std::cerr << qPrintable(LR::tr(
                          "lrelease error: cannot process project file '%1'.\n")
                          .arg(inputFile));
                continue;
            }

            QStringList translations = visitor.values(QLatin1String("TRANSLATIONS"));
            if (translations.isEmpty()) {
                std::cerr << qPrintable(LR::tr(
                          "lrelease warning: Met no 'TRANSLATIONS' entry in project file '%1'\n")
                          .arg(inputFile));
            } else {
                QDir proDir(fi.absolutePath());
                foreach (const QString &trans, translations)
                    if (!releaseTsFile(QFileInfo(proDir, trans).filePath(), cd, removeIdentical))
                        return 1;
            }
        } else {
            if (outputFile.isEmpty()) {
                if (!releaseTsFile(inputFile, cd, removeIdentical))
                    return 1;
            } else {
                if (!loadTsFile(tor, inputFile, cd.isVerbose()))
                    return 1;
            }
        }
    }

    if (!outputFile.isEmpty())
        return releaseTranslator(tor, outputFile, cd, removeIdentical) ? 0 : 1;

    return 0;
}

#ifdef QT_BOOTSTRAPPED

#ifdef Q_OS_WIN
# include <windows.h>
#endif

static QString binDir;

static void initBinaryDir(
#ifndef Q_OS_WIN
        const char *_argv0
#endif
        )
{
#ifdef Q_OS_WIN
    wchar_t module_name[MAX_PATH];
    GetModuleFileName(0, module_name, MAX_PATH);
    QFileInfo filePath = QString::fromWCharArray(module_name);
    binDir = filePath.filePath();
#else
    QString argv0 = QFile::decodeName(QByteArray(_argv0));
    QString absPath;

    if (!argv0.isEmpty() && argv0.at(0) == QLatin1Char('/')) {
        /*
          If argv0 starts with a slash, it is already an absolute
          file path.
        */
        absPath = argv0;
    } else if (argv0.contains(QLatin1Char('/'))) {
        /*
          If argv0 contains one or more slashes, it is a file path
          relative to the current directory.
        */
        absPath = QDir::current().absoluteFilePath(argv0);
    } else {
        /*
          Otherwise, the file path has to be determined using the
          PATH environment variable.
        */
        QByteArray pEnv = qgetenv("PATH");
        QDir currentDir = QDir::current();
        QStringList paths = QString::fromLocal8Bit(pEnv.constData()).split(QLatin1String(":"));
        for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) {
            if ((*p).isEmpty())
                continue;
            QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0);
            QFileInfo candidate_fi(candidate);
            if (candidate_fi.exists() && !candidate_fi.isDir()) {
                binDir = candidate_fi.canonicalPath();
                return;
            }
        }
        return;
    }

    QFileInfo fi(absPath);
    if (fi.exists())
        binDir = fi.canonicalPath();
#endif
}

QT_BEGIN_NAMESPACE

// The name is hard-coded in QLibraryInfo
QString qmake_libraryInfoFile()
{
    if (binDir.isEmpty())
        return QString();
    return QDir(binDir).filePath(QString::fromLatin1("qt.conf"));
}

QT_END_NAMESPACE

#endif // QT_BOOTSTRAPPED
<|endoftext|>


<commit_before><commit_msg>WaE: type name first seen using 'class' now seen using 'struct'<commit_after><|endoftext|>


<commit_before>#include "scimed/wx.h"

// todo:
// add loading, zooming and panning in image
// add loading/saving and specifying areas
// add preview pane

class MyFrame: public wxFrame
{
 public:
  MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(NULL, wxID_ANY, title, pos, size) {
    SetMenuBar(CreateMenuBar());
    CreateStatusBar();
    SetStatusText("Welcome to wxWidgets!");

    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExit, this, wxID_EXIT);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnAbout, this, wxID_ABOUT);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnSave, this, wxID_SAVE);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnSaveAs, this, wxID_SAVEAS);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnOpen, this, wxID_OPEN);
  }

 private:
  wxMenu* CreateFileMenu() {
    wxMenu *menuFile = new wxMenu;
    menuFile->Append(wxID_OPEN);
    menuFile->Append(wxID_SAVE);
    menuFile->Append(wxID_SAVEAS);
    menuFile->AppendSeparator();
    menuFile->Append(wxID_EXIT);
    return menuFile;
  }

  wxMenu* CreateHelpMenu() {
    wxMenu *menuHelp = new wxMenu;
    menuHelp->Append(wxID_ABOUT);
    return menuHelp;
  }

  wxMenuBar* CreateMenuBar() {
    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(CreateFileMenu(), "&File");
    menuBar->Append(CreateHelpMenu(), "&Help");
    return menuBar;
  }

  void OnSave(wxCommandEvent& event){
  }

  void OnSaveAs(wxCommandEvent& event){
  }

  void OnOpen(wxCommandEvent& event){
  }

  void OnExit(wxCommandEvent& event){
    Close(true);
  }

  void OnAbout(wxCommandEvent& event){
    wxMessageBox("Scimed - the Scalable Image Editor", "About Scimed", wxOK | wxICON_INFORMATION);
  }
};

////////////////////////////////////////////////////////////////////////////////

class MyApp: public wxApp
{
 public:
  virtual bool OnInit() {
    MyFrame *frame = new MyFrame( "Scimed", wxPoint(50, 50), wxSize(450, 340) );
    frame->Show( true );
    return true;
  }
};
wxIMPLEMENT_APP(MyApp);<commit_msg>load and display png<commit_after>#include "scimed/wx.h"
#include <wx/sizer.h>

// todo:
// add loading, zooming and panning in image
// add loading/saving and specifying areas
// add preview pane

class wxImagePanel : public wxPanel
{
  wxImage image;
  wxBitmap resized;
  int w, h;
  bool displayImage_;

 public:
  explicit wxImagePanel(wxFrame* parent)
      : wxPanel(parent), displayImage_(false)
  {
    Bind(wxEVT_SIZE, &wxImagePanel::OnSize, this);
    Bind(wxEVT_PAINT, &wxImagePanel::OnPaint, this);
  }

  bool LoadImage(wxString file, wxBitmapType format) {
    displayImage_ = image.LoadFile(file, format);
    w = -1;
    h = -1;
    // displayImage_ = true;

    if( displayImage_ ) {
      Refresh();
    }

    return displayImage_;
  }

  void OnPaint(wxPaintEvent & evt) {
    if(displayImage_ == false) {
      return;
    }

    wxPaintDC dc(this);

    int neww, newh;
    dc.GetSize( &neww, &newh );

    if( neww != w || newh != h ) {
      resized = wxBitmap( image.Scale( neww, newh /*, wxIMAGE_QUALITY_HIGH*/ ) );
      w = neww;
      h = newh;
      dc.DrawBitmap( resized, 0, 0, false );
    }
    else {
      dc.DrawBitmap( resized, 0, 0, false );
    }
  }

  void OnSize(wxSizeEvent& event){
    Refresh();
    //skip the event.
    event.Skip();
  }

  // some useful events
  /*
   void mouseMoved(wxMouseEvent& event);
   void mouseDown(wxMouseEvent& event);
   void mouseWheelMoved(wxMouseEvent& event);
   void mouseReleased(wxMouseEvent& event);
   void rightClick(wxMouseEvent& event);
   void mouseLeftWindow(wxMouseEvent& event);
   void keyPressed(wxKeyEvent& event);
   void keyReleased(wxKeyEvent& event);
   */
};

// some useful events
/*
 void wxImagePanel::mouseMoved(wxMouseEvent& event) {}
 void wxImagePanel::mouseDown(wxMouseEvent& event) {}
 void wxImagePanel::mouseWheelMoved(wxMouseEvent& event) {}
 void wxImagePanel::mouseReleased(wxMouseEvent& event) {}
 void wxImagePanel::rightClick(wxMouseEvent& event) {}
 void wxImagePanel::mouseLeftWindow(wxMouseEvent& event) {}
 void wxImagePanel::keyPressed(wxKeyEvent& event) {}
 void wxImagePanel::keyReleased(wxKeyEvent& event) {}
 */

class MyFrame: public wxFrame
{
 public:
  MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(NULL, wxID_ANY, title, pos, size), title_(title) {
    SetMenuBar(CreateMenuBar());
    CreateStatusBar();
    SetStatusText("");

    wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
    drawPane = new wxImagePanel(this);
    sizer->Add(drawPane, 1, wxEXPAND);
    SetSizer(sizer);

    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExit, this, wxID_EXIT);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnAbout, this, wxID_ABOUT);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnSave, this, wxID_SAVE);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnSaveAs, this, wxID_SAVEAS);
    Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnOpen, this, wxID_OPEN);
  }

 private:
  wxImagePanel * drawPane;
  wxString title_;
  wxString filename_;

  void UpdateTitle() {
    if( filename_.IsEmpty() ) {
      SetTitle( title_ );
    }
    else {
      SetTitle( title_ + " - " + filename_ );
    }
  }

  wxMenu* CreateFileMenu() {
    wxMenu *menuFile = new wxMenu;
    menuFile->Append(wxID_OPEN);
    menuFile->Append(wxID_SAVE);
    menuFile->Append(wxID_SAVEAS);
    menuFile->AppendSeparator();
    menuFile->Append(wxID_EXIT);
    return menuFile;
  }

  wxMenu* CreateHelpMenu() {
    wxMenu *menuHelp = new wxMenu;
    menuHelp->Append(wxID_ABOUT);
    return menuHelp;
  }

  wxMenuBar* CreateMenuBar() {
    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(CreateFileMenu(), "&File");
    menuBar->Append(CreateHelpMenu(), "&Help");
    return menuBar;
  }

  void OnSave(wxCommandEvent& event){
    if( filename_.IsEmpty() ) {
      OnSaveAs(event);
      return;
    }

    // do saving...
  }

  void OnSaveAs(wxCommandEvent& event) {
    wxFileDialog saveFileDialog(this, _("Save scim file"), "", "", "SCIM files (*.png)|*.png", wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
    if (saveFileDialog.ShowModal() == wxID_CANCEL) {
      return;
    }
    filename_ = saveFileDialog.GetPath();
    UpdateTitle();
    OnSave(event);
  }

  void OnOpen(wxCommandEvent& event) {
    wxFileDialog openFileDialog(this, _("Open scim file"), "", "", "SCIM files (*.png)|*.png", wxFD_OPEN|wxFD_FILE_MUST_EXIST);
    if (openFileDialog.ShowModal() == wxID_CANCEL) {
      return;
    }

    if( drawPane->LoadImage(openFileDialog.GetPath(), wxBITMAP_TYPE_PNG) ) {
      filename_ = openFileDialog.GetPath();
    }
    else {
      filename_ = "";
    }
    UpdateTitle();
  }

  void OnExit(wxCommandEvent& event){
    Close(true);
  }

  void OnAbout(wxCommandEvent& event){
    wxMessageBox("Scimed - the Scalable Image Editor", "About Scimed", wxOK | wxICON_INFORMATION);
  }
};

////////////////////////////////////////////////////////////////////////////////

class MyApp: public wxApp
{
 public:
  virtual bool OnInit() {
    wxInitAllImageHandlers();
    MyFrame *frame = new MyFrame( "Scimed", wxPoint(50, 50), wxSize(450, 340) );
    frame->Show( true );
    return true;
  }
};
wxIMPLEMENT_APP(MyApp);
<|endoftext|>


<commit_before>// Copyright (C) 2011 Oliver Schulz <oliver.schulz@tu-dortmund.de>

// This is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#include <string>
#include <iostream>
#include <cstdlib>
#include <cstring>

#include <unistd.h>

#include <TROOT.h>
#include <TSystem.h>
#include <TApplication.h>
#include <THttpServer.h>

#include "logging.h"
#include "Props.h"
#include "ApplicationBric.h"

using namespace std;
using namespace dbrx;

PropVal g_config = Props();
Name g_logLevelOverride;
unique_ptr<TApplication> g_rootApplication;

void configureLogging() {
	// g_logLevel overrides logging config in g_config
	if (! g_logLevelOverride.empty()) {
		g_config["logLevel"] = g_logLevelOverride;
	}

	if (g_config.contains("logLevel")) {
		auto level = LoggingFacility::levelOf(g_config.at("logLevel").asString());
		if (level != log_level()) {
			dbrx_log_debug("Changing logging level to %s", LoggingFacility::nameOf(level));
			log_level(level);
		}
	}
}

void configureLogging(const std::string &levelName) {
	if (!levelName.empty()) {
		Name normalizedLevelName = LoggingFacility::nameOf(LoggingFacility::levelOf(levelName));
		g_logLevelOverride = normalizedLevelName;
		configureLogging();
	}
}

void addConfigFrom(PropVal &config, const std::string &from) {
	dbrx_log_debug("Reading \"%s\"", from);
	PropVal p = PropVal::fromFile(from);
	dbrx_log_debug("Done reading");
	if (!p.isProps()) throw invalid_argument("Invalid config in \"%s\", but contain an object, not a value or an array"_format(from));
	config.asProps() += p.asProps();
}

void addGlobalConfigFrom(const std::string &from) {
	dbrx_log_debug("Adding \"%s\" to config", from);
	addConfigFrom(g_config, from);
}

void printConfig(std::ostream &out, const PropVal &config, const std::string &format) {
	if (format == "json") { config.toJSON(out); out << endl; }
	else throw invalid_argument("Unknown configuration output format");
}

void task_config_printUsage(const char* progName) {
	cerr << "Syntax: " << progName << " [OPTIONS] CONFIG.." << endl;
	cerr << "" << endl;
	cerr << "Options:" << endl;
	cerr << "-?          Show help" << endl;
	cerr << "-f FORMAT   Set output format (formats: [json], ...)" << endl;
	cerr << "-l LEVEL    Set logging level" << endl;
	cerr << "" << endl;
	cerr << "Combine and output given configurations in specified format (JSON by default)." << endl;
	cerr << "Supported output formats: \"json\" (more formats to come in future versions)." << endl;
}

int task_config(int argc, char *argv[], char *envp[]) {
	string outputFormat("json");

	int opt = 0;
	while ((opt = getopt(argc, argv, "?c:l:f:j")) != -1) {
		switch (opt) {
			case '?': { task_config_printUsage(argv[0]); return 0; }
			case 'l': { configureLogging(optarg); break; }
			case 'f': {
				dbrx_log_debug("Setting output format to %s", optarg);
				outputFormat = string(optarg);
				break;
			}
			default: throw invalid_argument("Unkown command line option");
		}
	}

	PropVal config = Props();
	while (optind < argc) {
		std::string from = argv[optind++];
		dbrx_log_debug("Reading config from \"%s\"", from);
		addConfigFrom(config, from);
	}

	printConfig(cout, config, outputFormat);
}

void task_run_printUsage(const char* progName) {
	cerr << "Syntax: " << progName << " [OPTIONS] CONFIG.." << endl;
	cerr << "" << endl;
	cerr << "Options:" << endl;
	cerr << "-?          Show help" << endl;
	cerr << "-c SETTINGS Load configuration/settings" << endl;
	cerr << "-l LEVEL    Set logging level (default: \"info\")" << endl;
	cerr << "-w          Enable HTTP server" << endl;
	cerr << "-p PORT     HTTP server port (default: 8080)" << endl;
	cerr << "-k          Don't exit after processing (e.g. to keep HTTP server running)" << endl;
	cerr << "" << endl;
	cerr << "Run the given bric configuration. If multiple configuration are given, they" << endl;
	cerr << "are merged together (from left to right)." << endl;
}

int task_run(int argc, char *argv[], char *envp[]) {
	bool enableHTTP = false;
	uint16_t httpPort = 8080;
	bool keepRunning = false;

	int opt = 0;
	while ((opt = getopt(argc, argv, "?c:l:wp:k")) != -1) {
		switch (opt) {
			case '?': { task_run_printUsage(argv[0]); return 0; }
			case 'l': { configureLogging(optarg); break; }
			case 'w': { enableHTTP = true; break; }
			case 'p': { httpPort = atoi(optarg); break; }
			case 'k': { keepRunning = true; break; }
			default: throw invalid_argument("Unkown command line option");
		}
	}

	if (! (optind < argc)) {
		task_run_printUsage(argv[0]);
		return 1;
	}

	while (optind < argc) {
		std::string from = argv[optind++];
		dbrx_log_debug("Reading config from \"%s\"", from);
		addGlobalConfigFrom(from);
	}
	configureLogging();

	unique_ptr<THttpServer> httpServer;
	if (enableHTTP) {
		dbrx_log_info("Starting HTTP server on port %s", httpPort);
		httpServer = unique_ptr<THttpServer>(
			new THttpServer("civetweb:%s"_format(httpPort).c_str()));
	}

	ApplicationBric app("dbrx");
	app.applyConfig(g_config);
	app.run();

	if (keepRunning) {
		dbrx_log_info("Keeping program running");
		if (httpServer) dbrx_log_info("HTTP server active on port %s", httpPort);
		g_rootApplication->Run(true);
	}

	return 0;
}

void main_printUsage(const char* progName) {
	cerr << "Syntax: " << progName << " COMMAND ..." << endl << endl;
	cerr << "Commands: " << endl;
	cerr << "  config" << endl;
	cerr << "  run" << endl;
	cerr << "" << endl;
	cerr << "Use" << endl;
	cerr << "" << endl;
	cerr << "    " << progName << " COMMAND -?" << endl;
	cerr << "" << endl;
	cerr << "to get help for the individual commands." << endl;
}

int main(int argc, char *argv[], char *envp[]) {
	try {
		// Have to create an application to activate ROOT's on-demand class loader
		// (still true for ROOT-6?):
		g_rootApplication = unique_ptr<TApplication>(new TApplication("dbrx", 0, 0));

		// Set ROOT program name (necessary / useful ?):
		gSystem->SetProgname("dbrx");

		// Have to tell ROOT to load vector dlls, otherwise ROOT will produce
		// "is not of a class known to ROOT" errors on creation of STL vector
		// branches (still true for ROOT-6?):
		gROOT->ProcessLineSync("#include <vector>");

		// Make sure Cling has all databricxx headers loaded. This currently
		// seems to be the only way, gSystem->Load("libdatabricxx.so") is not
		// sufficient for some reason:
		gROOT->ProcessLineSync("dbrx::PropVal();");

		string progName(argv[0]);

		if (argc < 2) { main_printUsage(argv[0]); return 1; }

		string cmd(argv[1]);

		int cmd_argc = argc - 1;
		char **cmd_argv = argv + 1;

		if (cmd == "-?") { main_printUsage(argv[0]); return 0; }
		if (cmd == "config") return task_config(cmd_argc, cmd_argv, envp);
		else if (cmd == "run") return task_run(cmd_argc, cmd_argv, envp);
		else throw invalid_argument("Command \"%s\" not supported."_format(cmd));
	}
	catch(std::exception &e) {
		dbrx_log_error("%s (%s)",e.what(), typeid(e).name());
		return 1;
	}

	dbrx_log_info("Done.");
}
<commit_msg>Renamed dbrx command "config" to "get-config"<commit_after>// Copyright (C) 2011 Oliver Schulz <oliver.schulz@tu-dortmund.de>

// This is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#include <string>
#include <iostream>
#include <cstdlib>
#include <cstring>

#include <unistd.h>

#include <TROOT.h>
#include <TSystem.h>
#include <TApplication.h>
#include <THttpServer.h>

#include "logging.h"
#include "Props.h"
#include "ApplicationBric.h"

using namespace std;
using namespace dbrx;

PropVal g_config = Props();
Name g_logLevelOverride;
unique_ptr<TApplication> g_rootApplication;

void configureLogging() {
	// g_logLevel overrides logging config in g_config
	if (! g_logLevelOverride.empty()) {
		g_config["logLevel"] = g_logLevelOverride;
	}

	if (g_config.contains("logLevel")) {
		auto level = LoggingFacility::levelOf(g_config.at("logLevel").asString());
		if (level != log_level()) {
			dbrx_log_debug("Changing logging level to %s", LoggingFacility::nameOf(level));
			log_level(level);
		}
	}
}

void configureLogging(const std::string &levelName) {
	if (!levelName.empty()) {
		Name normalizedLevelName = LoggingFacility::nameOf(LoggingFacility::levelOf(levelName));
		g_logLevelOverride = normalizedLevelName;
		configureLogging();
	}
}

void addConfigFrom(PropVal &config, const std::string &from) {
	dbrx_log_debug("Reading \"%s\"", from);
	PropVal p = PropVal::fromFile(from);
	dbrx_log_debug("Done reading");
	if (!p.isProps()) throw invalid_argument("Invalid config in \"%s\", but contain an object, not a value or an array"_format(from));
	config.asProps() += p.asProps();
}

void addGlobalConfigFrom(const std::string &from) {
	dbrx_log_debug("Adding \"%s\" to config", from);
	addConfigFrom(g_config, from);
}

void printConfig(std::ostream &out, const PropVal &config, const std::string &format) {
	if (format == "json") { config.toJSON(out); out << endl; }
	else throw invalid_argument("Unknown configuration output format");
}

void task_get_config_printUsage(const char* progName) {
	cerr << "Syntax: " << progName << " [OPTIONS] CONFIG.." << endl;
	cerr << "" << endl;
	cerr << "Options:" << endl;
	cerr << "-?          Show help" << endl;
	cerr << "-f FORMAT   Set output format (formats: [json], ...)" << endl;
	cerr << "-l LEVEL    Set logging level" << endl;
	cerr << "" << endl;
	cerr << "Combine and output given configurations in specified format (JSON by default)." << endl;
	cerr << "Supported output formats: \"json\" (more formats to come in future versions)." << endl;
}

int task_get_config(int argc, char *argv[], char *envp[]) {
	string outputFormat("json");

	int opt = 0;
	while ((opt = getopt(argc, argv, "?c:l:f:j")) != -1) {
		switch (opt) {
			case '?': { task_get_config_printUsage(argv[0]); return 0; }
			case 'l': { configureLogging(optarg); break; }
			case 'f': {
				dbrx_log_debug("Setting output format to %s", optarg);
				outputFormat = string(optarg);
				break;
			}
			default: throw invalid_argument("Unkown command line option");
		}
	}

	PropVal config = Props();
	while (optind < argc) {
		std::string from = argv[optind++];
		dbrx_log_debug("Reading config from \"%s\"", from);
		addConfigFrom(config, from);
	}

	printConfig(cout, config, outputFormat);
}

void task_run_printUsage(const char* progName) {
	cerr << "Syntax: " << progName << " [OPTIONS] CONFIG.." << endl;
	cerr << "" << endl;
	cerr << "Options:" << endl;
	cerr << "-?          Show help" << endl;
	cerr << "-c SETTINGS Load configuration/settings" << endl;
	cerr << "-l LEVEL    Set logging level (default: \"info\")" << endl;
	cerr << "-w          Enable HTTP server" << endl;
	cerr << "-p PORT     HTTP server port (default: 8080)" << endl;
	cerr << "-k          Don't exit after processing (e.g. to keep HTTP server running)" << endl;
	cerr << "" << endl;
	cerr << "Run the given bric configuration. If multiple configuration are given, they" << endl;
	cerr << "are merged together (from left to right)." << endl;
}

int task_run(int argc, char *argv[], char *envp[]) {
	bool enableHTTP = false;
	uint16_t httpPort = 8080;
	bool keepRunning = false;

	int opt = 0;
	while ((opt = getopt(argc, argv, "?c:l:wp:k")) != -1) {
		switch (opt) {
			case '?': { task_run_printUsage(argv[0]); return 0; }
			case 'l': { configureLogging(optarg); break; }
			case 'w': { enableHTTP = true; break; }
			case 'p': { httpPort = atoi(optarg); break; }
			case 'k': { keepRunning = true; break; }
			default: throw invalid_argument("Unkown command line option");
		}
	}

	if (! (optind < argc)) {
		task_run_printUsage(argv[0]);
		return 1;
	}

	while (optind < argc) {
		std::string from = argv[optind++];
		dbrx_log_debug("Reading config from \"%s\"", from);
		addGlobalConfigFrom(from);
	}
	configureLogging();

	unique_ptr<THttpServer> httpServer;
	if (enableHTTP) {
		dbrx_log_info("Starting HTTP server on port %s", httpPort);
		httpServer = unique_ptr<THttpServer>(
			new THttpServer("civetweb:%s"_format(httpPort).c_str()));
	}

	ApplicationBric app("dbrx");
	app.applyConfig(g_config);
	app.run();

	if (keepRunning) {
		dbrx_log_info("Keeping program running");
		if (httpServer) dbrx_log_info("HTTP server active on port %s", httpPort);
		g_rootApplication->Run(true);
	}

	return 0;
}

void main_printUsage(const char* progName) {
	cerr << "Syntax: " << progName << " COMMAND ..." << endl << endl;
	cerr << "Commands: " << endl;
	cerr << "  get-config" << endl;
	cerr << "  run" << endl;
	cerr << "" << endl;
	cerr << "Use" << endl;
	cerr << "" << endl;
	cerr << "    " << progName << " COMMAND -?" << endl;
	cerr << "" << endl;
	cerr << "to get help for the individual commands." << endl;
}

int main(int argc, char *argv[], char *envp[]) {
	try {
		// Have to create an application to activate ROOT's on-demand class loader
		// (still true for ROOT-6?):
		g_rootApplication = unique_ptr<TApplication>(new TApplication("dbrx", 0, 0));

		// Set ROOT program name (necessary / useful ?):
		gSystem->SetProgname("dbrx");

		// Have to tell ROOT to load vector dlls, otherwise ROOT will produce
		// "is not of a class known to ROOT" errors on creation of STL vector
		// branches (still true for ROOT-6?):
		gROOT->ProcessLineSync("#include <vector>");

		// Make sure Cling has all databricxx headers loaded. This currently
		// seems to be the only way, gSystem->Load("libdatabricxx.so") is not
		// sufficient for some reason:
		gROOT->ProcessLineSync("dbrx::PropVal();");

		string progName(argv[0]);

		if (argc < 2) { main_printUsage(argv[0]); return 1; }

		string cmd(argv[1]);

		int cmd_argc = argc - 1;
		char **cmd_argv = argv + 1;

		if (cmd == "-?") { main_printUsage(argv[0]); return 0; }
		if (cmd == "get-config") return task_get_config(cmd_argc, cmd_argv, envp);
		else if (cmd == "run") return task_run(cmd_argc, cmd_argv, envp);
		else throw invalid_argument("Command \"%s\" not supported."_format(cmd));
	}
	catch(std::exception &e) {
		dbrx_log_error("%s (%s)",e.what(), typeid(e).name());
		return 1;
	}

	dbrx_log_info("Done.");
}
<|endoftext|>


<commit_before>// Maintainer: Jan Kristian Sto. Domingo [jstod001@ucr.edu]
// exec.cpp for rshell

#include <iostream>
#include <cstring>
#include <string>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

//Notes on function formats:
//execvp(const char *file, char *const argv[])

// tokenCounter function used to determine size of dynamically
// allocated array for use in the execvp function
unsigned tokenCounter(char* a)
{
    unsigned count = 0;
    char* token;

    token = strtok(a, " ;");

    while(token != NULL)
    {
        token = strtok(NULL, " ;");
        count++;
    }

    return count;
}

int main()
{
    int PID = fork();
    if(PID == 0)
    {
        //cout << "child process" << endl;

        // command prompt
        char* username = getlogin();
        char hostname[20];
        gethostname(hostname, 20);
        cout << username << "@" << hostname << "$ ";

        string str_input;
        getline(cin, str_input);

        // output message for test purposes
        // cout << "Original string: " << str_input << endl << endl;

        char* c_input = new char[str_input.length() + 1];
        strcpy(c_input, str_input.c_str());

        // output message for test purposes
        // cout << "Converted to cstring: " << c_input << endl << endl;

        // new cstring now has to be tokenized and placed into a char**
        // for the exec vp function

        char* tmp = new char[str_input.length() + 1];
        strcpy(tmp, c_input);
        // tmp protects the original cstring input
        // tmp will be used for the tokenCounter function

        unsigned token_count = 0;
        token_count = tokenCounter(tmp);

        char** arg;
        arg = new char* [token_count];

        // output message for test purposes
        // cout << "c_input after tokenCounter: " << c_input << endl;

        // the following chunk of code will take each token
        // and place it into arg which will then be used as
        // a parameter in execvp
        unsigned i = 0;
        char* ptr;
        ptr = strtok(c_input, " ;");
        while(ptr != NULL)
        {
            arg[i] = ptr;
            // cout message for test purposes
            cout << "arg[" << i << "] = " << arg[i] << endl;
            ptr = strtok(NULL, " ;");
            i++;
        }

        //cout << arg[0] << endl;
        if(string(arg[0]) == "exit")
        {
            cout << "executing exit(0)" << endl;
            exit(0);
        }
        else
        {
            cout << "in execvp" << endl;
            execvp(arg[0], arg);
            perror(arg[0]);
        }
    }
    else
    {
        if(PID == -1)
        {
            perror("fork");
        }
        int w = wait(0);
        if(w == -1)
        {
            perror("wait");
        }
        //cout << "parent process" << endl;
    }

    return 0;
}

<commit_msg>removed some test comments from exec.cpp<commit_after>// Maintainer: Jan Kristian Sto. Domingo [jstod001@ucr.edu]
// exec.cpp for rshell

#include <iostream>
#include <cstring>
#include <string>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

//Notes on function formats:
//execvp(const char *file, char *const argv[])

// tokenCounter function used to determine size of dynamically
// allocated array for use in the execvp function
unsigned tokenCounter(char* a)
{
    unsigned count = 0;
    char* token;

    token = strtok(a, " ;");

    while(token != NULL)
    {
        token = strtok(NULL, " ;");
        count++;
    }

    return count;
}

int main()
{
    int PID = fork();
    if(PID == 0)
    {
        //cout << "child process" << endl;

        // command prompt
        char* username = getlogin();
        char hostname[20];
        gethostname(hostname, 20);
        cout << username << "@" << hostname << "$ ";

        string str_input;
        getline(cin, str_input);

        // output message for test purposes
        // cout << "Original string: " << str_input << endl << endl;

        char* c_input = new char[str_input.length() + 1];
        strcpy(c_input, str_input.c_str());

        // output message for test purposes
        // cout << "Converted to cstring: " << c_input << endl << endl;

        // new cstring now has to be tokenized and placed into a char**
        // for the exec vp function

        char* tmp = new char[str_input.length() + 1];
        strcpy(tmp, c_input);
        // tmp protects the original cstring input
        // tmp will be used for the tokenCounter function

        unsigned token_count = 0;
        token_count = tokenCounter(tmp);

        char** arg;
        arg = new char* [token_count];

        // output message for test purposes
        // cout << "c_input after tokenCounter: " << c_input << endl;

        // the following chunk of code will take each token
        // and place it into arg which will then be used as
        // a parameter in execvp
        unsigned i = 0;
        char* ptr;
        ptr = strtok(c_input, " ;");
        while(ptr != NULL)
        {
            arg[i] = ptr;
            // cout message for test purposes
            //cout << "arg[" << i << "] = " << arg[i] << endl;
            ptr = strtok(NULL, " ;");
            i++;
        }

        //cout << arg[0] << endl;
        if(string(arg[0]) == "exit")
        {
            //cout message for test purposes
            //cout << "executing exit(0)" << endl;
            exit(0);
        }
        else
        {
            //cout message for test purposes
            //cout << "in execvp" << endl;
            execvp(arg[0], arg);
            perror(arg[0]);
        }
    }
    else
    {
        if(PID == -1)
        {
            perror("fork");
        }
        int w = wait(0);
        if(w == -1)
        {
            perror("wait");
        }
        //cout << "parent process" << endl;
    }

    return 0;
}

<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"

#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _MODE_T_
typedef int mode_t;
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);

#endif

#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef O_RANDOM
#define O_RANDOM 0
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

namespace
{
	enum { mode_in = 1, mode_out = 2 };

	mode_t map_open_mode(int m)
	{
		if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
		assert(false);
		return 0;
	}

#ifdef WIN32
	std::string utf8_native(std::string const& s)
	{
		try
		{
			std::wstring ws;
			libtorrent::utf8_wchar(s, ws);
			std::size_t size = wcstombs(0, ws.c_str(), 0);
			if (size == std::size_t(-1)) return s;
			std::string ret;
			ret.resize(size);
			size = wcstombs(&ret[0], ws.c_str(), size + 1);
			if (size == wchar_t(-1)) return s;
			ret.resize(size);
			return ret;
		}
		catch(std::exception)
		{
			return s;
		}
	}
#else
	std::string utf8_native(std::string const& s)
	{
		return s;
	}
#endif

}

namespace libtorrent
{

	namespace fs = boost::filesystem;

	const file::open_mode file::in(mode_in);
	const file::open_mode file::out(mode_out);

	const file::seek_mode file::begin(1);
	const file::seek_mode file::end(2);

	struct file::impl
	{
		impl()
			: m_fd(-1)
			, m_open_mode(0)
		{}

		impl(fs::path const& path, int mode)
			: m_fd(-1)
			, m_open_mode(0)
		{
			open(path, mode);
		}

		~impl()
		{
			close();
		}

		void open(fs::path const& path, int mode)
		{
			assert(path.is_complete());
			close();
#if defined(_WIN32) && defined(UNICODE)
			std::wstring wpath(safe_convert(path.native_file_string()));
			m_fd = ::_wopen(
				wpath.c_str()
				, map_open_mode(mode)
				, S_IREAD | S_IWRITE);
#else
#ifdef _WIN32
			m_fd = ::_open(
#else
			m_fd = ::open(
#endif
				utf8_native(path.native_file_string()).c_str()
				, map_open_mode(mode)
#ifdef _WIN32
				, S_IREAD | S_IWRITE);
#else
				, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
#endif
			if (m_fd == -1)
			{
				std::stringstream msg;
				msg << "open failed: '" << path.native_file_string() << "'. "
					<< strerror(errno);
				throw file_error(msg.str());
			}
			m_open_mode = mode;
		}

		void close()
		{
			if (m_fd == -1) return;

#ifdef _WIN32
			::_close(m_fd);
#else
			::close(m_fd);
#endif
			m_fd = -1;
			m_open_mode = 0;
		}

		size_type read(char* buf, size_type num_bytes)
		{
			assert(m_open_mode & mode_in);
			assert(m_fd != -1);

#ifdef _WIN32
			size_type ret = ::_read(m_fd, buf, num_bytes);
#else
			size_type ret = ::read(m_fd, buf, num_bytes);
#endif
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "read failed: " << strerror(errno);
				throw file_error(msg.str());
			}
			return ret;
		}

		size_type write(const char* buf, size_type num_bytes)
		{
			assert(m_open_mode & mode_out);
			assert(m_fd != -1);

			// TODO: Test this a bit more, what happens with random failures in
			// the files?
//			if ((rand() % 100) > 80)
//				throw file_error("debug");

#ifdef _WIN32
			size_type ret = ::_write(m_fd, buf, num_bytes);
#else
			size_type ret = ::write(m_fd, buf, num_bytes);
#endif
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "write failed: " << strerror(errno);
				throw file_error(msg.str());
			}
			return ret;
		}

		void set_size(size_type s)
		{
			size_type pos = tell();
			// Only set size if current file size not equals s.
			// 2 as "m" argument is to be sure seek() sets SEEK_END on
			// all compilers.
			if(s != seek(0, 2))
			{
				seek(s - 1);
				char dummy = 0;
				read(&dummy, 1);
				seek(s - 1);
				write(&dummy, 1);
			}
			seek(pos);
		}

		size_type seek(size_type offset, int m = 1)
		{
			assert(m_open_mode);
			assert(m_fd != -1);

			int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
			size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
			size_type ret = lseek(m_fd, offset, seekdir);
#endif

			// For some strange reason this fails
			// on win32. Use windows specific file
			// wrapper instead.
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "seek failed: '" << strerror(errno)
					<< "' fd: " << m_fd
					<< " offset: " << offset
					<< " seekdir: " << seekdir;
				throw file_error(msg.str());
			}
			return ret;
		}

		size_type tell()
		{
			assert(m_open_mode);
			assert(m_fd != -1);

#ifdef _WIN32
			return _telli64(m_fd);
#else
			return lseek(m_fd, 0, SEEK_CUR);
#endif
		}

		int m_fd;
		int m_open_mode;
	};

	// pimpl forwardings

	file::file() : m_impl(new impl()) {}

	file::file(fs::path const& p, file::open_mode m)
		: m_impl(new impl(p, m.m_mask))
	{}

	file::~file() {}

	void file::open(fs::path const& p, file::open_mode m)
	{
		m_impl->open(p, m.m_mask);
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buf, size_type num_bytes)
	{
		return m_impl->write(buf, num_bytes);
	}

	size_type file::read(char* buf, size_type num_bytes)
	{
		return m_impl->read(buf, num_bytes);
	}

	void file::set_size(size_type s)
	{
		m_impl->set_size(s);
	}

	size_type file::seek(size_type pos, file::seek_mode m)
	{
		return m_impl->seek(pos, m.m_val);
	}

	size_type file::tell()
	{
		return m_impl->tell();
	}

}
<commit_msg>changed to use ftruncate to allocate files<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"

#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _MODE_T_
typedef int mode_t;
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);

#endif

#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef O_RANDOM
#define O_RANDOM 0
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

namespace
{
	enum { mode_in = 1, mode_out = 2 };

	mode_t map_open_mode(int m)
	{
		if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
		assert(false);
		return 0;
	}

#ifdef WIN32
	std::string utf8_native(std::string const& s)
	{
		try
		{
			std::wstring ws;
			libtorrent::utf8_wchar(s, ws);
			std::size_t size = wcstombs(0, ws.c_str(), 0);
			if (size == std::size_t(-1)) return s;
			std::string ret;
			ret.resize(size);
			size = wcstombs(&ret[0], ws.c_str(), size + 1);
			if (size == wchar_t(-1)) return s;
			ret.resize(size);
			return ret;
		}
		catch(std::exception)
		{
			return s;
		}
	}
#else
	std::string utf8_native(std::string const& s)
	{
		return s;
	}
#endif

}

namespace libtorrent
{

	namespace fs = boost::filesystem;

	const file::open_mode file::in(mode_in);
	const file::open_mode file::out(mode_out);

	const file::seek_mode file::begin(1);
	const file::seek_mode file::end(2);

	struct file::impl
	{
		impl()
			: m_fd(-1)
			, m_open_mode(0)
		{}

		impl(fs::path const& path, int mode)
			: m_fd(-1)
			, m_open_mode(0)
		{
			open(path, mode);
		}

		~impl()
		{
			close();
		}

		void open(fs::path const& path, int mode)
		{
			assert(path.is_complete());
			close();
#if defined(_WIN32) && defined(UNICODE)
			std::wstring wpath(safe_convert(path.native_file_string()));
			m_fd = ::_wopen(
				wpath.c_str()
				, map_open_mode(mode)
				, S_IREAD | S_IWRITE);
#else
#ifdef _WIN32
			m_fd = ::_open(
#else
			m_fd = ::open(
#endif
				utf8_native(path.native_file_string()).c_str()
				, map_open_mode(mode)
#ifdef _WIN32
				, S_IREAD | S_IWRITE);
#else
				, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
#endif
			if (m_fd == -1)
			{
				std::stringstream msg;
				msg << "open failed: '" << path.native_file_string() << "'. "
					<< strerror(errno);
				throw file_error(msg.str());
			}
			m_open_mode = mode;
		}

		void close()
		{
			if (m_fd == -1) return;

#ifdef _WIN32
			::_close(m_fd);
#else
			::close(m_fd);
#endif
			m_fd = -1;
			m_open_mode = 0;
		}

		size_type read(char* buf, size_type num_bytes)
		{
			assert(m_open_mode & mode_in);
			assert(m_fd != -1);

#ifdef _WIN32
			size_type ret = ::_read(m_fd, buf, num_bytes);
#else
			size_type ret = ::read(m_fd, buf, num_bytes);
#endif
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "read failed: " << strerror(errno);
				throw file_error(msg.str());
			}
			return ret;
		}

		size_type write(const char* buf, size_type num_bytes)
		{
			assert(m_open_mode & mode_out);
			assert(m_fd != -1);

			// TODO: Test this a bit more, what happens with random failures in
			// the files?
//			if ((rand() % 100) > 80)
//				throw file_error("debug");

#ifdef _WIN32
			size_type ret = ::_write(m_fd, buf, num_bytes);
#else
			size_type ret = ::write(m_fd, buf, num_bytes);
#endif
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "write failed: " << strerror(errno);
				throw file_error(msg.str());
			}
			return ret;
		}

		void set_size(size_type s)
		{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
			if (ftruncate(m_fd, s) < 0)
			{
				std::stringstream msg;
				msg << "ftruncate failed: '" << strerror(errno);
				throw file_error(msg.str());
			}
#endif
		}

		size_type seek(size_type offset, int m = 1)
		{
			assert(m_open_mode);
			assert(m_fd != -1);

			int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
			size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
			size_type ret = lseek(m_fd, offset, seekdir);
#endif

			// For some strange reason this fails
			// on win32. Use windows specific file
			// wrapper instead.
			if (ret == -1)
			{
				std::stringstream msg;
				msg << "seek failed: '" << strerror(errno)
					<< "' fd: " << m_fd
					<< " offset: " << offset
					<< " seekdir: " << seekdir;
				throw file_error(msg.str());
			}
			return ret;
		}

		size_type tell()
		{
			assert(m_open_mode);
			assert(m_fd != -1);

#ifdef _WIN32
			return _telli64(m_fd);
#else
			return lseek(m_fd, 0, SEEK_CUR);
#endif
		}

		int m_fd;
		int m_open_mode;
	};

	// pimpl forwardings

	file::file() : m_impl(new impl()) {}

	file::file(fs::path const& p, file::open_mode m)
		: m_impl(new impl(p, m.m_mask))
	{}

	file::~file() {}

	void file::open(fs::path const& p, file::open_mode m)
	{
		m_impl->open(p, m.m_mask);
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buf, size_type num_bytes)
	{
		return m_impl->write(buf, num_bytes);
	}

	size_type file::read(char* buf, size_type num_bytes)
	{
		return m_impl->read(buf, num_bytes);
	}

	void file::set_size(size_type s)
	{
		m_impl->set_size(s);
	}

	size_type file::seek(size_type pos, file::seek_mode m)
	{
		return m_impl->seek(pos, m.m_val);
	}

	size_type file::tell()
	{
		return m_impl->tell();
	}

}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SERVER_ROUTE_HPP
#define SERVER_ROUTE_HPP

#include <regex>
#include <string>
#include <delegate>

#include "request.hpp"
#include "response.hpp"
#include "../route/path_to_regex.hpp"

namespace server {

using End_point  = delegate<void(Request_ptr, Response_ptr)>;
using Route_expr = std::regex;

struct Route {
  Route(const std::string& ex, End_point e)
    : path{ex}
    , end_point{e}
  {
    expr = route::Path_to_regex::path_to_regex(path, keys);
  }

  std::string path;
  Route_expr  expr;
  End_point   end_point;
  route::Keys keys;
}; //< struct Route

} //< namespace server

#endif //< SERVER_ROUTE_HPP
<commit_msg>route: Add attribute to bring most viewed route to front of queue<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SERVER_ROUTE_HPP
#define SERVER_ROUTE_HPP

#include <regex>
#include <string>
#include <delegate>

#include "request.hpp"
#include "response.hpp"
#include "../route/path_to_regex.hpp"

namespace server {

using End_point  = delegate<void(Request_ptr, Response_ptr)>;
using Route_expr = std::regex;

struct Route {
  Route(const std::string& ex, End_point e)
    : path{ex}
    , end_point{e}
  {
    expr = route::Path_to_regex::path_to_regex(path, keys);
  }

  std::string path;
  Route_expr  expr;
  End_point   end_point;
  route::Keys keys;
  unsigned    hits;
}; //< struct Route

inline bool operator < (const Route& lhs, const Route& rhs) noexcept {
  return lhs.hits < rhs.hits;
}

} //< namespace server

#endif //< SERVER_ROUTE_HPP
<|endoftext|>


<commit_before>
#include "game.hpp"

#include "seoSplasher/splashState.hpp"
#include "seoSplasher/splashMenu.hpp"

// set packfile name/filepath if one is being used
#define PACKFILE_NAME "seoSplasherResources.dat"

// set to true if a packfile is being used
#define IS_USING_PACKFILE true

// if not using cmake to build and using the ResourcePacker lib,
// define ResourcePacker_FOUND

#if defined(ResourcePacker_FOUND)
#else
#  define IS_USING_PACKFILE false
#endif

#if IS_USING_PACKFILE == true
#  define RESOURCE_MANAGER_MODE GameResources::PACKFILE
#else
#  define RESOURCE_MANAGER_MODE GameResources::DEFAULT
#endif

Game::Game()
: window(sf::VideoMode(720,480), "SFML App"),
resourceManager(&stateStack, RESOURCE_MANAGER_MODE, PACKFILE_NAME),
mPlayer(),
sPlayer(),
stateStack(Context(window, resourceManager, mPlayer, sPlayer, ecEngine, rGen, isQuitting, mode, scontext, sfxContext)),
isQuitting(false),
mode(0)
{
    registerResources();
    registerStates();

    frameTime = sf::seconds(1.f / 60.f);
}

void Game::run()
{
    sf::Clock clock;
    sf::Time lastUpdateTime = sf::Time::Zero;
    while (window.isOpen() && !isQuitting)
    {
        lastUpdateTime += clock.restart();
        while (lastUpdateTime > frameTime)
        {
            lastUpdateTime -= frameTime;
            processEvents();
            update(frameTime);
        }
        draw();
    }

    if(window.isOpen())
        window.close();
}

void Game::processEvents()
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        stateStack.handleEvent(event);
        if(event.type == sf::Event::Closed)
            window.close();
    }
}

void Game::update(sf::Time deltaTime)
{
    stateStack.update(deltaTime);
}

void Game::draw()
{
    window.clear();
    stateStack.draw();
    window.display();
}

// register resources via resourceManager
// Resource IDs must be listed in resourceIdentifiers.hpp
void Game::registerResources()
{
    resourceManager.registerTexture(Textures::WALL, "wall.png");
    resourceManager.registerTexture(Textures::BREAKABLE, "breakable.png");
    resourceManager.registerTexture(Textures::BALLOON_0, "balloon00.png");
    resourceManager.registerTexture(Textures::BALLOON_1, "balloon01.png");
    resourceManager.registerTexture(Textures::BALLOON_2, "balloon02.png");
    resourceManager.registerTexture(Textures::SUPER_BALLOON_0, "superBalloon00.png");
    resourceManager.registerTexture(Textures::SUPER_BALLOON_1, "superBalloon01.png");
    resourceManager.registerTexture(Textures::SUPER_BALLOON_2, "superBalloon02.png");
    resourceManager.registerTexture(Textures::C_BALLOON_0, "controlledBalloon00.png");
    resourceManager.registerTexture(Textures::C_BALLOON_1, "controlledBalloon01.png");
    resourceManager.registerTexture(Textures::C_BALLOON_2, "controlledBalloon02.png");
    resourceManager.registerTexture(Textures::C_SUPER_BALLOON_0, "controlledSuperBalloon00.png");
    resourceManager.registerTexture(Textures::C_SUPER_BALLOON_1, "controlledSuperBalloon01.png");
    resourceManager.registerTexture(Textures::C_SUPER_BALLOON_2, "controlledSuperBalloon02.png");
    resourceManager.registerTexture(Textures::PLAYER_ONE, "player1.png");
    resourceManager.registerTexture(Textures::PLAYER_TWO, "player2.png");
    resourceManager.registerTexture(Textures::PLAYER_THREE, "player3.png");
    resourceManager.registerTexture(Textures::PLAYER_FOUR, "player4.png");
    resourceManager.registerTexture(Textures::C_PLAYER_ONE, "computer1.png");
    resourceManager.registerTexture(Textures::C_PLAYER_TWO, "computer2.png");
    resourceManager.registerTexture(Textures::C_PLAYER_THREE, "computer3.png");
    resourceManager.registerTexture(Textures::C_PLAYER_FOUR, "computer4.png");
    resourceManager.registerTexture(Textures::SPLOSION_PLUS, "splosionPLUS.png");
    resourceManager.registerTexture(Textures::SPLOSION_VERT, "splosionVERT.png");
    resourceManager.registerTexture(Textures::SPLOSION_HORIZ, "splosionHORIZ.png");
    resourceManager.registerTexture(Textures::BALLOON_UP_0, "balloonUp00.png");
    resourceManager.registerTexture(Textures::BALLOON_UP_1, "balloonUp01.png");
    resourceManager.registerTexture(Textures::BALLOON_UP_2, "balloonUp02.png");
    resourceManager.registerTexture(Textures::RANGE_UP_0, "rangeUp00.png");
    resourceManager.registerTexture(Textures::RANGE_UP_1, "rangeUp01.png");
    resourceManager.registerTexture(Textures::RANGE_UP_2, "rangeUp02.png");
    resourceManager.registerTexture(Textures::SPEED_UP_0, "speedUp00.png");
    resourceManager.registerTexture(Textures::SPEED_UP_1, "speedUp01.png");
    resourceManager.registerTexture(Textures::SPEED_UP_2, "speedUp02.png");
    resourceManager.registerTexture(Textures::KICK_UPGRADE_0, "kickUpgrade00.png");
    resourceManager.registerTexture(Textures::KICK_UPGRADE_1, "kickUpgrade01.png");
    resourceManager.registerTexture(Textures::KICK_UPGRADE_2, "kickUpgrade02.png");
    resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_0, "rControl00.png");
    resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_1, "rControl01.png");
    resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_2, "rControl02.png");
    resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_0, "superBalloonUp00.png");
    resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_1, "superBalloonUp01.png");
    resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_2, "superBalloonUp02.png");
    resourceManager.registerTexture(Textures::PIERCE_UPGRADE_0, "pierceUp00.png");
    resourceManager.registerTexture(Textures::PIERCE_UPGRADE_1, "pierceUp01.png");
    resourceManager.registerTexture(Textures::PIERCE_UPGRADE_2, "pierceUp02.png");
    resourceManager.registerTexture(Textures::SPREAD_UPGRADE_0, "spreadUp00.png");
    resourceManager.registerTexture(Textures::SPREAD_UPGRADE_1, "spreadUp01.png");
    resourceManager.registerTexture(Textures::SPREAD_UPGRADE_2, "spreadUp02.png");
    resourceManager.registerTexture(Textures::GHOST_UPGRADE_0, "ghostUp00.png");
    resourceManager.registerTexture(Textures::GHOST_UPGRADE_1, "ghostUp01.png");
    resourceManager.registerTexture(Textures::GHOST_UPGRADE_2, "ghostUp02.png");

    resourceManager.registerFont(Fonts::CLEAR_SANS, "ClearSans-Regular.ttf");

    resourceManager.registerSoundBuffer(Sound::BREAKABLE, "breakable.ogg");
    resourceManager.registerSoundBuffer(Sound::COUNTDOWN_0, "countdown0.ogg");
    resourceManager.registerSoundBuffer(Sound::COUNTDOWN_1, "countdown1.ogg");
    resourceManager.registerSoundBuffer(Sound::DEATH, "death.ogg");
    resourceManager.registerSoundBuffer(Sound::KICK, "kick.ogg");
    resourceManager.registerSoundBuffer(Sound::SPLOSION, "splosion.ogg");
    resourceManager.registerSoundBuffer(Sound::POWERUP, "powerup.ogg");
    resourceManager.registerSoundBuffer(Sound::TRY_AGAIN_TUNE, "tryagain.ogg");
    resourceManager.registerSoundBuffer(Sound::VICTORY_TUNE, "victory.ogg");
}

// register states via stateStack
// State IDs must be listed in stateIdentifiers.hpp
void Game::registerStates()
{
    stateStack.registerState<SplashState>(States::SPLASH);
    stateStack.registerState<SplashMenu>(States::MENU);

    stateStack.pushState(States::MENU);
}
<commit_msg>Fixed name of program<commit_after>
#include "game.hpp"

#include "seoSplasher/splashState.hpp"
#include "seoSplasher/splashMenu.hpp"

// set packfile name/filepath if one is being used
#define PACKFILE_NAME "seoSplasherResources.dat"

// set to true if a packfile is being used
#define IS_USING_PACKFILE true

// if not using cmake to build and using the ResourcePacker lib,
// define ResourcePacker_FOUND

#if defined(ResourcePacker_FOUND)
#else
#  define IS_USING_PACKFILE false
#endif

#if IS_USING_PACKFILE == true
#  define RESOURCE_MANAGER_MODE GameResources::PACKFILE
#else
#  define RESOURCE_MANAGER_MODE GameResources::DEFAULT
#endif

Game::Game()
: window(sf::VideoMode(720,480), "SeoSplasher"),
resourceManager(&stateStack, RESOURCE_MANAGER_MODE, PACKFILE_NAME),
mPlayer(),
sPlayer(),
stateStack(Context(window, resourceManager, mPlayer, sPlayer, ecEngine, rGen, isQuitting, mode, scontext, sfxContext)),
isQuitting(false),
mode(0)
{
    registerResources();
    registerStates();

    frameTime = sf::seconds(1.f / 60.f);
}

void Game::run()
{
    sf::Clock clock;
    sf::Time lastUpdateTime = sf::Time::Zero;
    while (window.isOpen() && !isQuitting)
    {
        lastUpdateTime += clock.restart();
        while (lastUpdateTime > frameTime)
        {
            lastUpdateTime -= frameTime;
            processEvents();
            update(frameTime);
        }
        draw();
    }

    if(window.isOpen())
        window.close();
}

void Game::processEvents()
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        stateStack.handleEvent(event);
        if(event.type == sf::Event::Closed)
            window.close();
    }
}

void Game::update(sf::Time deltaTime)
{
    stateStack.update(deltaTime);
}

void Game::draw()
{
    window.clear();
    stateStack.draw();
    window.display();
}

// register resources via resourceManager
// Resource IDs must be listed in resourceIdentifiers.hpp
void Game::registerResources()
{
    resourceManager.registerTexture(Textures::WALL, "wall.png");
    resourceManager.registerTexture(Textures::BREAKABLE, "breakable.png");
    resourceManager.registerTexture(Textures::BALLOON_0, "balloon00.png");
    resourceManager.registerTexture(Textures::BALLOON_1, "balloon01.png");
    resourceManager.registerTexture(Textures::BALLOON_2, "balloon02.png");
    resourceManager.registerTexture(Textures::SUPER_BALLOON_0, "superBalloon00.png");
    resourceManager.registerTexture(Textures::SUPER_BALLOON_1, "superBalloon01.png");
    resourceManager.registerTexture(Textures::SUPER_BALLOON_2, "superBalloon02.png");
    resourceManager.registerTexture(Textures::C_BALLOON_0, "controlledBalloon00.png");
    resourceManager.registerTexture(Textures::C_BALLOON_1, "controlledBalloon01.png");
    resourceManager.registerTexture(Textures::C_BALLOON_2, "controlledBalloon02.png");
    resourceManager.registerTexture(Textures::C_SUPER_BALLOON_0, "controlledSuperBalloon00.png");
    resourceManager.registerTexture(Textures::C_SUPER_BALLOON_1, "controlledSuperBalloon01.png");
    resourceManager.registerTexture(Textures::C_SUPER_BALLOON_2, "controlledSuperBalloon02.png");
    resourceManager.registerTexture(Textures::PLAYER_ONE, "player1.png");
    resourceManager.registerTexture(Textures::PLAYER_TWO, "player2.png");
    resourceManager.registerTexture(Textures::PLAYER_THREE, "player3.png");
    resourceManager.registerTexture(Textures::PLAYER_FOUR, "player4.png");
    resourceManager.registerTexture(Textures::C_PLAYER_ONE, "computer1.png");
    resourceManager.registerTexture(Textures::C_PLAYER_TWO, "computer2.png");
    resourceManager.registerTexture(Textures::C_PLAYER_THREE, "computer3.png");
    resourceManager.registerTexture(Textures::C_PLAYER_FOUR, "computer4.png");
    resourceManager.registerTexture(Textures::SPLOSION_PLUS, "splosionPLUS.png");
    resourceManager.registerTexture(Textures::SPLOSION_VERT, "splosionVERT.png");
    resourceManager.registerTexture(Textures::SPLOSION_HORIZ, "splosionHORIZ.png");
    resourceManager.registerTexture(Textures::BALLOON_UP_0, "balloonUp00.png");
    resourceManager.registerTexture(Textures::BALLOON_UP_1, "balloonUp01.png");
    resourceManager.registerTexture(Textures::BALLOON_UP_2, "balloonUp02.png");
    resourceManager.registerTexture(Textures::RANGE_UP_0, "rangeUp00.png");
    resourceManager.registerTexture(Textures::RANGE_UP_1, "rangeUp01.png");
    resourceManager.registerTexture(Textures::RANGE_UP_2, "rangeUp02.png");
    resourceManager.registerTexture(Textures::SPEED_UP_0, "speedUp00.png");
    resourceManager.registerTexture(Textures::SPEED_UP_1, "speedUp01.png");
    resourceManager.registerTexture(Textures::SPEED_UP_2, "speedUp02.png");
    resourceManager.registerTexture(Textures::KICK_UPGRADE_0, "kickUpgrade00.png");
    resourceManager.registerTexture(Textures::KICK_UPGRADE_1, "kickUpgrade01.png");
    resourceManager.registerTexture(Textures::KICK_UPGRADE_2, "kickUpgrade02.png");
    resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_0, "rControl00.png");
    resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_1, "rControl01.png");
    resourceManager.registerTexture(Textures::RCONTROL_UPGRADE_2, "rControl02.png");
    resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_0, "superBalloonUp00.png");
    resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_1, "superBalloonUp01.png");
    resourceManager.registerTexture(Textures::SBALLOON_UPGRADE_2, "superBalloonUp02.png");
    resourceManager.registerTexture(Textures::PIERCE_UPGRADE_0, "pierceUp00.png");
    resourceManager.registerTexture(Textures::PIERCE_UPGRADE_1, "pierceUp01.png");
    resourceManager.registerTexture(Textures::PIERCE_UPGRADE_2, "pierceUp02.png");
    resourceManager.registerTexture(Textures::SPREAD_UPGRADE_0, "spreadUp00.png");
    resourceManager.registerTexture(Textures::SPREAD_UPGRADE_1, "spreadUp01.png");
    resourceManager.registerTexture(Textures::SPREAD_UPGRADE_2, "spreadUp02.png");
    resourceManager.registerTexture(Textures::GHOST_UPGRADE_0, "ghostUp00.png");
    resourceManager.registerTexture(Textures::GHOST_UPGRADE_1, "ghostUp01.png");
    resourceManager.registerTexture(Textures::GHOST_UPGRADE_2, "ghostUp02.png");

    resourceManager.registerFont(Fonts::CLEAR_SANS, "ClearSans-Regular.ttf");

    resourceManager.registerSoundBuffer(Sound::BREAKABLE, "breakable.ogg");
    resourceManager.registerSoundBuffer(Sound::COUNTDOWN_0, "countdown0.ogg");
    resourceManager.registerSoundBuffer(Sound::COUNTDOWN_1, "countdown1.ogg");
    resourceManager.registerSoundBuffer(Sound::DEATH, "death.ogg");
    resourceManager.registerSoundBuffer(Sound::KICK, "kick.ogg");
    resourceManager.registerSoundBuffer(Sound::SPLOSION, "splosion.ogg");
    resourceManager.registerSoundBuffer(Sound::POWERUP, "powerup.ogg");
    resourceManager.registerSoundBuffer(Sound::TRY_AGAIN_TUNE, "tryagain.ogg");
    resourceManager.registerSoundBuffer(Sound::VICTORY_TUNE, "victory.ogg");
}

// register states via stateStack
// State IDs must be listed in stateIdentifiers.hpp
void Game::registerStates()
{
    stateStack.registerState<SplashState>(States::SPLASH);
    stateStack.registerState<SplashMenu>(States::MENU);

    stateStack.pushState(States::MENU);
}
<|endoftext|>