<commit_before>/*
 * Copyright (c) 2015 WinT 3794 <http://wint3794.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

//=============================================================================
// System includes
//=============================================================================

#include <QObject>
#include <QSpinBox>
#include <QComboBox>
#include <QCheckBox>
#include <QTabWidget>
#include <QPushButton>
#include <QApplication>
#include <QInputDialog>

#include <qlogging.h>
#include <QtMessageHandler>

//=============================================================================
// Application includes
//=============================================================================

#include "Global/Global.h"
#include "Global/Beeper.h"
#include "Global/AppTheme.h"
#include "Global/Settings.h"
#include "Global/Languages.h"

#include "Updater/Updater.h"
#include "MainWindow/MainWindow.h"

//=============================================================================
// Called when a widget is clicked
//=============================================================================

void BEEP()
{
    BEEPER()->beep (440, 100);
}

//=============================================================================
// Avoid logging Qt warnings about our UI hacks
//=============================================================================

void messageHandler (QtMsgType type,
                     const QMessageLogContext& context,
                     const QString& msg)
{
    QByteArray localMsg = msg.toLocal8Bit();

    switch (type)
        {
        case QtDebugMsg:
            fprintf (stderr,
                     "DEBUG: %s (%s:%u, %s)\n",
                     localMsg.constData(),
                     context.file,
                     context.line,
                     context.function);
            break;
        case QtInfoMsg:
            fprintf (stderr,
                     "INFO: %s (%s:%u, %s)\n",
                     localMsg.constData(),
                     context.file,
                     context.line,
                     context.function);
            break;
        case QtWarningMsg:
            break;
        case QtCriticalMsg:
            fprintf (stderr,
                     "CRITICAL: %s (%s:%u, %s)\n",
                     localMsg.constData(),
                     context.file,
                     context.line,
                     context.function);
        case QtFatalMsg:
            fprintf (stderr,
                     "FATAL: %s (%s:%u, %s)\n",
                     localMsg.constData(),
                     context.file,
                     context.line,
                     context.function);
            break;
        }
}

//=============================================================================
// Main entry-point of the application
//=============================================================================

int main (int argc, char* argv[])
{
    qInstallMessageHandler (messageHandler);
    DS_LogMessage (kInfoLevel, "Starting application....");

    /* Configure application information */
    QApplication app (argc, argv);
    app.setApplicationVersion ("0.15");
    app.setOrganizationName   ("WinT 3794");
    app.setApplicationName    ("QDriverStation");
    app.setOrganizationDomain ("www.wint3794.org");
    app.installTranslator     (Languages::translator());

    /* Create the main window and check for updates */
    app.setFont (Languages::appFont());
    Updater updater;
    MainWindow mainwindow;

    /* Repeat this line to be sure that font is applied on everything */
    GLOBAL_INIT();
    AppTheme::init();
    app.setFont (Languages::appFont());

    /* Avoid compilation warnings */
    Q_UNUSED (updater);
    Q_UNUSED (mainwindow);

    /* Beep whenever a button or checkbox is clicked */
    foreach (QWidget* widget, app.allWidgets())
        {
            /* Do the conversions */
            QSpinBox*    spin   = qobject_cast<QSpinBox*> (widget);
            QCheckBox*   check  = qobject_cast<QCheckBox*> (widget);
            QComboBox*   combo  = qobject_cast<QComboBox*> (widget);
            QTabWidget*  tabwid = qobject_cast<QTabWidget*> (widget);
            QPushButton* button = qobject_cast<QPushButton*> (widget);

            /* The widget is a spin box */
            if (spin != Q_NULLPTR)
                QObject::connect (spin,
                                  static_cast<void (QSpinBox::*) (int)
                                  > (&QSpinBox::valueChanged),
                                  BEEP);

            /* The widget is a combo box */
            else if (combo != Q_NULLPTR)
                QObject::connect (combo,
                                  static_cast<void (QComboBox::*) (int)
                                  > (&QComboBox::currentIndexChanged),
                                  BEEP);

            /* The widget is a check box */
            else if (check != Q_NULLPTR)
                QObject::connect (check, &QCheckBox::clicked, BEEP);

            /* The widget is a tab widget */
            else if (tabwid != Q_NULLPTR)
                QObject::connect (tabwid, &QTabWidget::currentChanged, BEEP);

            /* The widget is a button */
            else if (button != Q_NULLPTR)
                QObject::connect (button, &QPushButton::clicked, BEEP);
        }

    /* Ask for team number on first launch */
    if (Settings::get ("First launch", true).toBool())
        {
            DS()->setTeamNumber (QInputDialog::getInt (Q_NULLPTR,
                                 QObject::tr ("QDriverStation"),
                                 QObject::tr ("Please input your team number:"),
                                 0, 0, 9999, 1, 0,
                                 Qt::WindowStaysOnTopHint));
            Settings::set ("First launch", false);
        }

    return app.exec();
}
<commit_msg>Update main.cpp<commit_after>/*
 * Copyright (c) 2015 WinT 3794 <http://wint3794.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

//=============================================================================
// System includes
//=============================================================================

#include <QObject>
#include <QSpinBox>
#include <QComboBox>
#include <QCheckBox>
#include <QTabWidget>
#include <QPushButton>
#include <QApplication>
#include <QInputDialog>

//=============================================================================
// Application includes
//=============================================================================

#include "Global/Global.h"
#include "Global/Beeper.h"
#include "Global/AppTheme.h"
#include "Global/Settings.h"
#include "Global/Languages.h"

#include "Updater/Updater.h"
#include "MainWindow/MainWindow.h"

//=============================================================================
// Called when a widget is clicked
//=============================================================================

void BEEP()
{
    BEEPER()->beep (440, 100);
}

//=============================================================================
// Avoid logging Qt warnings about our UI hacks
//=============================================================================

void messageHandler (QtMsgType type,
                     const QMessageLogContext& context,
                     const QString& msg)
{
    QByteArray localMsg = msg.toLocal8Bit();

    switch (type)
        {
        case QtDebugMsg:
            fprintf (stderr,
                     "DEBUG: %s (%s:%u, %s)\n",
                     localMsg.constData(),
                     context.file,
                     context.line,
                     context.function);
            break;
        case QtWarningMsg:
            break;
        case QtCriticalMsg:
            fprintf (stderr,
                     "CRITICAL: %s (%s:%u, %s)\n",
                     localMsg.constData(),
                     context.file,
                     context.line,
                     context.function);
        case QtFatalMsg:
            fprintf (stderr,
                     "FATAL: %s (%s:%u, %s)\n",
                     localMsg.constData(),
                     context.file,
                     context.line,
                     context.function);
            break;
        default:
            fprintf (stderr,
                     "INFO: %s (%s:%u, %s)\n",
                     localMsg.constData(),
                     context.file,
                     context.line,
                     context.function);
            break;
        }
}

//=============================================================================
// Main entry-point of the application
//=============================================================================

int main (int argc, char* argv[])
{
    qInstallMessageHandler (messageHandler);
    DS_LogMessage (kInfoLevel, "Starting application....");

    /* Configure application information */
    QApplication app (argc, argv);
    app.setApplicationVersion ("0.15");
    app.setOrganizationName   ("WinT 3794");
    app.setApplicationName    ("QDriverStation");
    app.setOrganizationDomain ("www.wint3794.org");
    app.installTranslator     (Languages::translator());

    /* Create the main window and check for updates */
    app.setFont (Languages::appFont());
    Updater updater;
    MainWindow mainwindow;

    /* Repeat this line to be sure that font is applied on everything */
    GLOBAL_INIT();
    AppTheme::init();
    app.setFont (Languages::appFont());

    /* Avoid compilation warnings */
    Q_UNUSED (updater);
    Q_UNUSED (mainwindow);

    /* Beep whenever a button or checkbox is clicked */
    foreach (QWidget* widget, app.allWidgets())
        {
            /* Do the conversions */
            QSpinBox*    spin   = qobject_cast<QSpinBox*> (widget);
            QCheckBox*   check  = qobject_cast<QCheckBox*> (widget);
            QComboBox*   combo  = qobject_cast<QComboBox*> (widget);
            QTabWidget*  tabwid = qobject_cast<QTabWidget*> (widget);
            QPushButton* button = qobject_cast<QPushButton*> (widget);

            /* The widget is a spin box */
            if (spin != Q_NULLPTR)
                QObject::connect (spin,
                                  static_cast<void (QSpinBox::*) (int)
                                  > (&QSpinBox::valueChanged),
                                  BEEP);

            /* The widget is a combo box */
            else if (combo != Q_NULLPTR)
                QObject::connect (combo,
                                  static_cast<void (QComboBox::*) (int)
                                  > (&QComboBox::currentIndexChanged),
                                  BEEP);

            /* The widget is a check box */
            else if (check != Q_NULLPTR)
                QObject::connect (check, &QCheckBox::clicked, BEEP);

            /* The widget is a tab widget */
            else if (tabwid != Q_NULLPTR)
                QObject::connect (tabwid, &QTabWidget::currentChanged, BEEP);

            /* The widget is a button */
            else if (button != Q_NULLPTR)
                QObject::connect (button, &QPushButton::clicked, BEEP);
        }

    /* Ask for team number on first launch */
    if (Settings::get ("First launch", true).toBool())
        {
            DS()->setTeamNumber (QInputDialog::getInt (Q_NULLPTR,
                                 QObject::tr ("QDriverStation"),
                                 QObject::tr ("Please input your team number:"),
                                 0, 0, 9999, 1, 0,
                                 Qt::WindowStaysOnTopHint));
            Settings::set ("First launch", false);
        }

    return app.exec();
}
<|endoftext|>


<commit_before>/*
 * This file is part of qtagger.
 *
 * © 2010 Fernando Tarlá Cardoso Lemos
 *
 * Refer to the LICENSE file for licensing information.
 *
 */

#include <boost/scoped_ptr.hpp>
#include <cstdlib>
#include <getopt.h>
#include <iostream>
#include <locale>
#include <string>

#include "BasicStringFilter.h"
#include "InteractiveTagger.h"
#include "SimpleCapitalizationFilter.h"
#include "StandardConsole.h"
#include "TitleCapitalizationFilter.h"

static void print_usage(std::ostream &out)
{
    out << "\
Usage: \n\
    qtagger [--dir-rename-format] [--file-rename-format format] \\\n\
            [--input-filter filter] [--output-filter filter] \\\n\
            <path> [path2] [path3] ...\n\
    qtagger --help\n\
\n\
Available filters: basic, first_upper, lower, title, upper\n\
\n\
Example:\n\
    qtagger --file-rename-format '%%track. %%album' \\\n\
        --dir-rename-format '%%album (%%year)' \\\n\
        --input-filter title --output-filter basic\n\
" << std::endl;
}

static BasicStringFilter *select_string_filter(const std::string &filter)
{
    if (filter == "basic")
        return new BasicStringFilter;
    else if (filter == "title")
        return new TitleCapitalizationFilter;
    else if (filter == "lower")
        return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_ALL_LOWER);
    else if (filter == "upper")
        return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_ALL_UPPER);
    else if (filter == "first_upper")
        return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_FIRST_UPPER);
    else
        return NULL;
}

int main(int argc, char **argv)
{
    // Set the global locale for case conversion purposes
    const char *locale_name = getenv("LANG");
    if (locale_name) {
        std::ios_base::sync_with_stdio(false);
        std::locale locale(std::locale::classic(), locale_name, std::locale::ctype);
        std::locale::global(locale);
        std::wcout.imbue(locale);
        std::wcin.imbue(locale);
    }
    else {
        std::cerr << "WARNING: $LANG is not defined" << std::endl;
    }

    struct option long_options[] = {
        {"dir-rename-format", required_argument, NULL, 'd'},
        {"input-filter", required_argument, NULL, 'i'},
        {"file-rename-format", required_argument, NULL, 'f'},
        {"help", no_argument, NULL, 'h'},
        {"output-filter", required_argument, NULL, 'o'},
        {NULL, 0, NULL, 0}
    };

    // Create the interactive tagger
    InteractiveTagger itag;
    boost::scoped_ptr<BasicStringFilter> input_filter, output_filter;

    // Parse the command line options
    int opt;
    while ((opt = getopt_long(argc, argv, "d:i:f:o:h", long_options, NULL)) != -1) {
        switch (opt) {
            case 'd':
                itag.set_dir_rename_format(optarg);
                break;
            case 'f':
                itag.set_file_rename_format(optarg);
                break;
            case 'i':
                input_filter.reset(select_string_filter(optarg));
                if (!input_filter.get()) {
                    print_usage(std::cerr);
                    return EXIT_FAILURE;
                }
                break;
            case 'h':
                print_usage(std::cout);
                return EXIT_SUCCESS;
            case 'o':
                output_filter.reset(select_string_filter(optarg));
                if (!output_filter.get()) {
                    print_usage(std::cerr);
                    return EXIT_FAILURE;
                }
                break;
            default:
                print_usage(std::cerr);
                return EXIT_FAILURE;
        }
    }

    // We need at least one path
    if (optind >= argc) {
        print_usage(std::cerr);
        return EXIT_FAILURE;
    }

    // Add the filters
    if (!input_filter.get())
        input_filter.reset(new BasicStringFilter);
    itag.set_input_filter(input_filter.get());
    itag.set_output_filter(output_filter.get());

    // Create the interactive terminal
    StandardConsole console;
    itag.set_terminal(&console);

    // Perform the interactive tagging
    itag.tag(argc - optind, (const char **)&argv[optind]);

    return EXIT_SUCCESS;
}
<commit_msg>This is not printf, no need for %%.<commit_after>/*
 * This file is part of qtagger.
 *
 * © 2010 Fernando Tarlá Cardoso Lemos
 *
 * Refer to the LICENSE file for licensing information.
 *
 */

#include <boost/scoped_ptr.hpp>
#include <cstdlib>
#include <getopt.h>
#include <iostream>
#include <locale>
#include <string>

#include "BasicStringFilter.h"
#include "InteractiveTagger.h"
#include "SimpleCapitalizationFilter.h"
#include "StandardConsole.h"
#include "TitleCapitalizationFilter.h"

static void print_usage(std::ostream &out)
{
    out << "\
Usage: \n\
    qtagger [--dir-rename-format] [--file-rename-format format] \\\n\
            [--input-filter filter] [--output-filter filter] \\\n\
            <path> [path2] [path3] ...\n\
    qtagger --help\n\
\n\
Available filters: basic, first_upper, lower, title, upper\n\
\n\
Example:\n\
    qtagger --file-rename-format '%track. %album' \\\n\
        --dir-rename-format '%album (%year)' \\\n\
        --input-filter title --output-filter basic\n\
" << std::endl;
}

static BasicStringFilter *select_string_filter(const std::string &filter)
{
    if (filter == "basic")
        return new BasicStringFilter;
    else if (filter == "title")
        return new TitleCapitalizationFilter;
    else if (filter == "lower")
        return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_ALL_LOWER);
    else if (filter == "upper")
        return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_ALL_UPPER);
    else if (filter == "first_upper")
        return new SimpleCapitalizationFilter(SimpleCapitalizationFilter::CAPITALIZATION_MODE_FIRST_UPPER);
    else
        return NULL;
}

int main(int argc, char **argv)
{
    // Set the global locale for case conversion purposes
    const char *locale_name = getenv("LANG");
    if (locale_name) {
        std::ios_base::sync_with_stdio(false);
        std::locale locale(std::locale::classic(), locale_name, std::locale::ctype);
        std::locale::global(locale);
        std::wcout.imbue(locale);
        std::wcin.imbue(locale);
    }
    else {
        std::cerr << "WARNING: $LANG is not defined" << std::endl;
    }

    struct option long_options[] = {
        {"dir-rename-format", required_argument, NULL, 'd'},
        {"input-filter", required_argument, NULL, 'i'},
        {"file-rename-format", required_argument, NULL, 'f'},
        {"help", no_argument, NULL, 'h'},
        {"output-filter", required_argument, NULL, 'o'},
        {NULL, 0, NULL, 0}
    };

    // Create the interactive tagger
    InteractiveTagger itag;
    boost::scoped_ptr<BasicStringFilter> input_filter, output_filter;

    // Parse the command line options
    int opt;
    while ((opt = getopt_long(argc, argv, "d:i:f:o:h", long_options, NULL)) != -1) {
        switch (opt) {
            case 'd':
                itag.set_dir_rename_format(optarg);
                break;
            case 'f':
                itag.set_file_rename_format(optarg);
                break;
            case 'i':
                input_filter.reset(select_string_filter(optarg));
                if (!input_filter.get()) {
                    print_usage(std::cerr);
                    return EXIT_FAILURE;
                }
                break;
            case 'h':
                print_usage(std::cout);
                return EXIT_SUCCESS;
            case 'o':
                output_filter.reset(select_string_filter(optarg));
                if (!output_filter.get()) {
                    print_usage(std::cerr);
                    return EXIT_FAILURE;
                }
                break;
            default:
                print_usage(std::cerr);
                return EXIT_FAILURE;
        }
    }

    // We need at least one path
    if (optind >= argc) {
        print_usage(std::cerr);
        return EXIT_FAILURE;
    }

    // Add the filters
    if (!input_filter.get())
        input_filter.reset(new BasicStringFilter);
    itag.set_input_filter(input_filter.get());
    itag.set_output_filter(output_filter.get());

    // Create the interactive terminal
    StandardConsole console;
    itag.set_terminal(&console);

    // Perform the interactive tagging
    itag.tag(argc - optind, (const char **)&argv[optind]);

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "GameCtrl.h"

int main() {
    auto game = GameCtrl::getInstance();

    // Set FPS. Default is 60.0
    game->setFPS(60.0);

    // Set whether to enable the snake AI. Default is true.
    game->setEnableAI(true);

    // Set interval time between each snake's movement. Default is 30 ms.
    // To play classic snake game, set to 200ms is perfect.
    game->setMoveInterval(30);

    // Set whether to record snake's movements to file. Default is false.
    // Movements will be written to file "movements.txt".
    game->setRecordMovements(false);

    // Set whether to run the test program. Default is false.
    game->setRunTest(false);

    // Set map's size(including boundaries)
    // Default is 10*10. Minimum is 4*4.
    game->setMapRow(10);
    game->setMapCol(10);

    return game->run();
}
<commit_msg>Resize grid to 20x20 for better visibility<commit_after>#include "GameCtrl.h"

int main() {
    auto game = GameCtrl::getInstance();

    // Set FPS. Default is 60.0
    game->setFPS(60.0);

    // Set whether to enable the snake AI. Default is true.
    game->setEnableAI(true);

    // Set interval time between each snake's movement. Default is 30 ms.
    // To play classic snake game, set to 200ms is perfect.
    game->setMoveInterval(30);

    // Set whether to record snake's movements to file. Default is false.
    // Movements will be written to file "movements.txt".
    game->setRecordMovements(false);

    // Set whether to run the test program. Default is false.
    game->setRunTest(false);

    // Set map's size(including boundaries)
    // Default is 10*10. Minimum is 4*4.
    game->setMapRow(20);
    game->setMapCol(20);

    return game->run();
}
<|endoftext|>


<commit_before>#include <iostream>
#include "input/filter.h"
#include "input/format.h"
#include "encoder/encoder.h"
#include "sjoin/sjoin.h"
#include "virtualizer/virtualizer.h"
#include <ctime>
#include <stdio.h>

int process_filter_graph(Format *fmt, Filter *filter, std::string sofa_file_name) {
    FILE *f;
    const char *filename = "FL.aac";

    AVPacket packet, packet0;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_;
    complete_sofa sofa_;

    AVPacket packet_out;
    int got_output;

    Encoder *encoder = new Encoder(AV_CODEC_ID_AC3,
            fmt->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP);

    SJoin  *sjoin  = new SJoin(encoder);

    f = fopen(filename, "wb");
    if(!f) {
        std::cout << "Error opening file" << std::endl;
    }

    int ret = 0;

    /* Read all of the packets */
    packet0.data = NULL;
    packet.data = NULL;
    while(1) {

        if(!packet0.data) {
            ret = av_read_frame(fmt->format_ctx, &packet);
            if(ret < 0) break;
            packet0 = packet;
        }

        if(packet.stream_index == fmt->audio_stream_index) {
            got_frame = 0;
            ret = avcodec_decode_audio4(fmt->decoder_ctx, frame, &got_frame, &packet);

            if(ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
                continue;
            }

            packet.size -= ret;
            packet.data += ret;

            if(got_frame) {

                /* push audio from decoded frame through filter graph */
                if(av_buffersrc_add_frame_flags(filter->abuffer_ctx, frame, 0) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n");
                    break;
                }

                while(ret >= 0) {
                    // This is where you will work with each processed frame.

                    int i;

                    i = 0;
                    for (auto it = filter->abuffersink_ctx_map.begin();
                            it != filter->abuffersink_ctx_map.end(); it++) {

                        ret = av_buffersink_get_frame(it->second, filt_frame);
                        if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;

                        int sample_count = filt_frame->nb_samples;
                        int sample_rate = filt_frame->sample_rate;

                        if (c2v_.count(it->first) == 0) {
                            float x;
                            float y;
                            float z;
                            Filter::get_coords(it->first, &x, &y, &z);

                            if (sofa_.hrtf == NULL) {
                                //TODO: delete these after execution
                                Virtualizer * virt = new Virtualizer(sofa_file_name.c_str(), sample_rate, x, y, z);
                                c2v_.insert(std::make_pair(it->first, virt));
                                sofa_ = virt->get_hrtf();
                            }
                            else {
                                //TODO: delete these after execution
                                Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x, y, z);
                                c2v_.insert(std::make_pair(it->first, virt));
                            }
                        }

                        float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        float ** float_results = c2v_[it->first]->process(samples, sample_count);

                        uint8_t * result_l = Virtualizer::get_short_samples(float_results[0],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        uint8_t * result_r = Virtualizer::get_short_samples(float_results[1],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        delete[] float_results[0];
                        delete[] float_results[1];
                        delete[] float_results;
                        delete[] samples;

                        AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r,
                                result_l);

                       if(it->first == 0) {
                           //std::cout << l_frame->nb_samples << std::endl;
                           //std::cout << l_frame->format << std::endl;
                           // This will move once virtualizaiton works
                        av_init_packet(&packet_out);
                        packet_out.data = NULL;
                        packet_out.size = 0;

                        ret = avcodec_encode_audio2(encoder->codec_ctx, &packet_out, virt_frame, &got_output);
                        if(ret < 0) exit(1);
                        if(got_output) {
                          fwrite(packet_out.data, 1, packet_out.size, f);
                          av_free_packet(&packet_out);
                        }
                       }

                        //AVFrame *r_frame = encoder->fill_new_frame(result_r, 2);

                        /*
                        if(av_buffersrc_add_frame_flags(sjoin->right_abuffers_ctx[i], r_frame, 0) < 0) {
                            av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n");
                            break;
                        }
                        */
                        // TODO: do something with the result

                        //std::cout << "FR";
                        av_frame_unref(filt_frame);
                        //av_frame_unref(r_frame);
                        i++;
                    }
                    av_frame_unref(filt_frame);
                }
            }
            if(packet.size <= 0) av_free_packet(&packet0);
        } else {
            av_free_packet(&packet0);
        }
    }
    fclose(f);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);
    delete filter;
    delete fmt;
}

int main(int argc, char *argv[]) {
    std::string videoFile = std::string(argv[1]);
    std::string sofaFile = std::string(argv[2]);

    clock_t begin = clock();
    Format *format = new Format(videoFile);
    Filter *filter = new Filter(format);
    clock_t end = clock();

    std::cout << "Filter initialization: " << (double)(end - begin) / CLOCKS_PER_SEC << " s" << std::endl;

    begin = clock();
    process_filter_graph(format, filter, sofaFile);
    end = clock();

    std::cout << "Processing Time: " << (double)(end - begin) / CLOCKS_PER_SEC << " s" << std::endl;
    return 0;
}
<commit_msg>Fixed bad commits<commit_after>#include <iostream>
#include "input/filter.h"
#include "input/format.h"
#include "encoder/encoder.h"
//#include "sjoin/sjoin.h"
#include "sjoin/testjoin.h"
#include "virtualizer/virtualizer.h"
#include <ctime>
#include <stdio.h>
#include <libavutil/fifo.h>

typedef struct {
     const AVClass    *classs;
     AVFifoBuffer     *fifo;
     AVRational        time_base;     ///< time_base to set in the output link
     AVRational        frame_rate;    ///< frame_rate to set in the output link
     unsigned          nb_failed_requests;
     unsigned          warning_limit;

     /* video only */
     int               w, h;
     enum AVPixelFormat  pix_fmt;
     AVRational        pixel_aspect;
     char              *sws_param;

     /* audio only */
     int sample_rate;
     enum AVSampleFormat sample_fmt;
     char               *sample_fmt_str;
     int channels;
     uint64_t channel_layout;
     char    *channel_layout_str;

     int eof;
 } BufferSourceContext;

int process_filter_graph(Format *fmt, Filter *filter, std::string sofa_file_name) {
    FILE *f;
    const char *filename = "FL.aac";

    AVPacket packet, packet0;
    AVFrame *frame = av_frame_alloc();
    AVFrame *filt_frame = av_frame_alloc();
    int got_frame;

    std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_;
    complete_sofa sofa_;

    AVPacket packet_out;
    int got_output;

    Encoder *encoder = new Encoder(AV_CODEC_ID_AC3,
            fmt->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP);

    //SJoin  *sjoin  = new SJoin(encoder);
    TestJoin *testjoin = new TestJoin(encoder);

    f = fopen(filename, "wb");
    if(!f) {
        std::cout << "Error opening file" << std::endl;
    }

    int ret = 0;

    /* Read all of the packets */
    packet0.data = NULL;
    packet.data = NULL;
    while(1) {

        if(!packet0.data) {
            ret = av_read_frame(fmt->format_ctx, &packet);
            if(ret < 0) break;
            packet0 = packet;
        }

        if(packet.stream_index == fmt->audio_stream_index) {
            got_frame = 0;
            ret = avcodec_decode_audio4(fmt->decoder_ctx, frame, &got_frame, &packet);

            if(ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
                continue;
            }

            packet.size -= ret;
            packet.data += ret;

            if(got_frame) {

                /* push audio from decoded frame through filter graph */
                if(av_buffersrc_add_frame_flags(filter->abuffer_ctx, frame, 0) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n");
                    break;
                }

                while(ret >= 0) {
                    // This is where you will work with each processed frame.

                    int i;

                    i = 0;
                    for (auto it = filter->abuffersink_ctx_map.begin();
                            it != filter->abuffersink_ctx_map.end(); it++) {

                        ret = av_buffersink_get_frame(it->second, filt_frame);
                        if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;

                        int sample_count = filt_frame->nb_samples;
                        int sample_rate = filt_frame->sample_rate;

                        if (c2v_.count(it->first) == 0) {
                            float x;
                            float y;
                            float z;
                            Filter::get_coords(it->first, &x, &y, &z);

                            if (sofa_.hrtf == NULL) {
                                //TODO: delete these after execution
                                Virtualizer * virt = new Virtualizer(sofa_file_name.c_str(), sample_rate, x, y, z);
                                c2v_.insert(std::make_pair(it->first, virt));
                                sofa_ = virt->get_hrtf();
                            }
                            else {
                                //TODO: delete these after execution
                                Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x, y, z);
                                c2v_.insert(std::make_pair(it->first, virt));
                            }
                        }

                        float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        float ** float_results = c2v_[it->first]->process(samples, sample_count);

                        uint8_t * result_l = Virtualizer::get_short_samples(float_results[0],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        uint8_t * result_r = Virtualizer::get_short_samples(float_results[1],
                                fmt->decoder_ctx->sample_fmt, sample_count);

                        delete[] float_results[0];
                        delete[] float_results[1];
                        delete[] float_results;
                        delete[] samples;

                        AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r,
                                result_l);

                        virt_frame->format = AV_SAMPLE_FMT_FLTP;
                        virt_frame->sample_rate = 48000;
                        virt_frame->channel_layout = 3;

                        if(it->first == 0) {
                           //std::cout << l_frame->nb_samples << std::endl;
                           //std::cout << l_frame->format << std::endl;
                           // This will move once virtualizaiton works
                            av_init_packet(&packet_out);
                            packet_out.data = NULL;
                            packet_out.size = 0;

                            ret = avcodec_encode_audio2(encoder->codec_ctx, &packet_out, virt_frame, &got_output);
                            if(ret < 0) exit(1);
                            if(got_output) {
                                fwrite(packet_out.data, 1, packet_out.size, f);
                                av_free_packet(&packet_out);
                            }
                        }

                        if(av_buffersrc_add_frame_flags(testjoin->abuffer_ctx, virt_frame, 0) < 0)
                            av_log(NULL, AV_LOG_ERROR, "Error feeding into filtergraph\n");
                                               AVFrame *test_virt_frame = av_frame_alloc();
                        ret = av_buffersink_get_frame(testjoin->abuffersink_ctx, test_virt_frame);
                        if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;

                        /*
                        if(av_buffersrc_add_frame_flags(sjoin->right_abuffers_ctx[i], r_frame, 0) < 0) {
                            av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n");
                            break;
                        }
                        */
                        // TODO: do something with the result

                        //std::cout << "FR";
                        av_frame_unref(virt_frame);
                        av_frame_unref(filt_frame);
                        //av_frame_unref(r_frame);
                        i++;
                    }
                    av_frame_unref(filt_frame);
                }
            }
            if(packet.size <= 0) av_free_packet(&packet0);
        } else {
            av_free_packet(&packet0);
        }
    }
    fclose(f);
    av_frame_free(&frame);
    av_frame_free(&filt_frame);
    delete filter;
    delete fmt;
}

int main(int argc, char *argv[]) {
    std::string videoFile = std::string(argv[1]);
    std::string sofaFile = std::string(argv[2]);

    clock_t begin = clock();
    Format *format = new Format(videoFile);
    Filter *filter = new Filter(format);
    clock_t end = clock();

    std::cout << "Filter initialization: " << (double)(end - begin) / CLOCKS_PER_SEC << " s" << std::endl;

    begin = clock();
    process_filter_graph(format, filter, sofaFile);
    end = clock();

    std::cout << "Processing Time: " << (double)(end - begin) / CLOCKS_PER_SEC << " s" << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#include "math/vec.hpp"
#include <iostream>

int main(int , char *[]) {
	std::cout << "Hello World!\n";
}<commit_msg>Add main loop<commit_after>#include "math/vec.hpp"
#include <iostream>
#include <algorithm>
#include <SDL2/SDL.h>

static void show_error(const char* message) {
	if (SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", message, nullptr) != 0) {
		std::cerr << message << std::endl;
	}
}

void game_loop(SDL_Window* window) {
	bool running = true;

	Sint32 frame_time_behind = 0;
	static const Sint32 MAX_LAG_TIME = 100;

	const Sint32 fixed_frame_time = 1000 / 60;

	while (running) {
		// The duration we're hoping to have on this frame
		const Sint32 desired_frame_time = fixed_frame_time - frame_time_behind;

		const Uint32 frame_start = SDL_GetTicks();

		SDL_Event ev;
		while (SDL_PollEvent(&ev)) {
			switch (ev.type) {
			case SDL_QUIT:
				running = false;
				break;
			default:
				break;
			}
		}

		// do update here

		SDL_GL_SwapWindow(window);

		const Sint32 time_elapsed_in_frame = SDL_GetTicks() - frame_start;

		std::cout << "FRAMETIME: " << time_elapsed_in_frame << '\n';

		if (time_elapsed_in_frame < desired_frame_time) {
			const Sint32 sleep_len = desired_frame_time - time_elapsed_in_frame;
			SDL_Delay(sleep_len);
		}

		frame_time_behind -= fixed_frame_time;
		frame_time_behind += SDL_GetTicks() - frame_start;
		if (frame_time_behind > MAX_LAG_TIME) {
			frame_time_behind = MAX_LAG_TIME;
		}
	}
}

int main(int , char *[]) {
	if (SDL_Init(SDL_INIT_VIDEO) != 0) {
		show_error("Failed to initialize SDL");
		return 1;
	}

	SDL_Window* window = SDL_CreateWindow("Super Match 5 DX", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL);
	if (window == nullptr) {
		show_error("Failed to create window.");
		return 1;
	}

	game_loop(window);

	SDL_DestroyWindow(window);
	SDL_Quit();
	return 0;
}
<|endoftext|>


<commit_before>#include "axisanalogbinding.h"

/**********************************************************************************************************************/
/* Public API                                                                                */
/**********************************************************************************************************************/

/**
 * @brief Default Constructor
 * @param parent The parent QObject.
 */
AxisAnalogBinding::AxisAnalogBinding(QObject *parent) :
    ControlBinding(parent),
    _sensitivity(0),
    _offset(0),
    _deadzone(0),
    _instantaneousValue(0)
{
} // end AxisAnalogBinding

/**********************************************************************************************************************/
/* Slots                                                                                */
/**********************************************************************************************************************/

/**
 * @brief Should get called whenever the connected InputSignal's value changes.
 * @param position The position of the axis.
 */
void AxisAnalogBinding::onSignalUpdated(float position)
{
    _instantaneousValue = position;
    emit stateChanged();
} // onSignalUpdated
<commit_msg>started taking sensitivity, deadzone and offset into account.<commit_after>#include "axisanalogbinding.h"

/**********************************************************************************************************************/
/* Public API                                                                                */
/**********************************************************************************************************************/

/**
 * @brief Default Constructor
 * @param parent The parent QObject.
 */
AxisAnalogBinding::AxisAnalogBinding(QObject *parent) :
    ControlBinding(parent),
    _sensitivity(0),
    _offset(0),
    _deadzone(0),
    _instantaneousValue(0)
{
} // end AxisAnalogBinding

/**********************************************************************************************************************/
/* Slots                                                                                */
/**********************************************************************************************************************/

/**
 * @brief Should get called whenever the connected InputSignal's value changes.
 * @param position The position of the axis.
 */
void AxisAnalogBinding::onSignalUpdated(float position)
{
    float value = position + _offset;
    if(value > 0)
    {
        if(value < _deadzone)
        {
            value = 0;
        }
        else
        {
            value -= _deadzone;
        } // end if
    }
    else
    {
        if(value > -_deadzone)
        {
            value = 0;
        }
        else
        {
            value += _deadzone;
        } // end if
    } // end if

    _instantaneousValue = _sensitivity * value;
    emit stateChanged();
} // onSignalUpdated
<|endoftext|>


<commit_before>/*
 * DesktopMacDetectRHome.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopDetectRHome.hpp"

#include <vector>

#include <boost/algorithm/string/trim.hpp>

#include <QtCore>
#include <QMessageBox>

#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/system/System.hpp>

#include "config.h"

using namespace core;

namespace desktop {

namespace {

// MacOS X Specific
#ifdef __APPLE__

#define kLibRFileName            "libR.dylib "
#define kLibraryPathEnvVariable  "DYLD_LIBRARY_PATH"

 // define search paths to match shell search path behavior (including
 // /opt/local/bin being first since that is where macports puts it)
 std::vector<std::string> rSearchPaths()
 {
    std::vector<std::string> rPaths;
    rPaths.push_back("/opt/local/bin/R");
    rPaths.push_back("/usr/bin/R");
    rPaths.push_back("/usr/local/bin/R");
    return rPaths;
 }

 // no extra paths on the mac
 std::string extraLibrayPaths()
 {
    return std::string();
 }

// Linux specific
#else

#define kLibRFileName            "libR.so"
#define kLibraryPathEnvVariable  "LD_LIBRARY_PATH"

 // define search paths to match shell search path behavior (note differs
 // from macox by having /usr/local/bin first)
 std::vector<std::string> rSearchPaths()
 {
    std::vector<std::string> rPaths;
    rPaths.push_back("/usr/local/bin/R");
    rPaths.push_back("/usr/bin/R");
    return rPaths;
 }

 // extra paths from R (for rjava) on linux
 std::string extraLibraryPaths()
 {
    std::string libraryPaths;

    FilePath supportingFilePath = desktop::options().supportingFilePath();
    FilePath scriptPath = supportingFilePath.complete("bin/r-ldpath");
    if (!scriptPath.exists())
      scriptPath = supportingFilePath.complete("session/r-ldpath");
    if (scriptPath.exists())
    {
       // run script
       Error error = system::captureCommand(scriptPath.absolutePath(),
                                            &libraryPaths);
       if (error)
          LOG_ERROR(error);
    }

    return libraryPaths;
 }

#endif

FilePath detectRHome()
{
   // scan possible locations for R (need these because on the mac
   // our path as a GUI app is very limited)
   FilePath rPath;
   std::vector<std::string> rPaths = rSearchPaths();
   for(std::vector<std::string>::const_iterator it = rPaths.begin();
       it != rPaths.end(); ++it)
   {
      FilePath candidatePath(*it);
      if (candidatePath.exists())
      {
         rPath = candidatePath ;
         break;
      }
   }

   // if we didn't find one then bail
   if (rPath.empty())
   {
      LOG_ERROR_MESSAGE("Couldn't find R on known path");
      return FilePath();
   }

   // run R to detect R home
   std::string output;
   std::string command = rPath.absolutePath() + " RHOME";
   Error error = core::system::captureCommand(command, &output);
   if (error)
   {
      LOG_ERROR(error);
      return FilePath();
   }
   boost::algorithm::trim(output);

   // return the home path if we got one
   if (!output.empty())
      return FilePath(output);
   else
      return FilePath();
}

void showRNotFoundError(const std::string& msg)
{
   QMessageBox::critical(NULL, "R Not Found", QString::fromStdString(msg));
}

} // anonymous namespace

bool prepareEnvironment(Options&)
{
   // declare home path and doc dir -- can get them from the environment
   // or by probing the system
   FilePath homePath, rDocDir;

   // first check environment
   std::string home = core::system::getenv("R_HOME");
   if (!home.empty())
      homePath = FilePath(home);
   std::string doc = core::system::getenv("R_DOC_DIR");
   if (!doc.empty())
      rDocDir = FilePath(doc);

   // probe for home path if necessary
   if (homePath.empty())
      homePath = detectRHome();

   // if that didn't work then try the configured path as a last ditch
   if (!homePath.exists())
      homePath = FilePath(CONFIG_R_HOME_PATH);

   // verify and set home path
   if (homePath.exists())
   {
      core::system::setenv("R_HOME", homePath.absolutePath());
   }
   else
   {
      showRNotFoundError("R home path (" + homePath.absolutePath() +
                         ") does not exist. Is R installed on "
                         "this system?");
      return false;
   }

   // complete doc dir if necesary
   if (rDocDir.empty())
      rDocDir = homePath.complete("doc");

   // doc dir may be in configured location (/usr/share) rather than
   // a subdirectory of R_HOME (this is in fact the case for the
   // debian r-base package). so check the configuired location as
   // a last ditch
   if (!rDocDir.exists())
      rDocDir = FilePath(CONFIG_R_DOC_PATH);

   // verify and set doc dir
   if (rDocDir.exists())
   {
       core::system::setenv("R_DOC_DIR", rDocDir.absolutePath());
   }
   else
   {
      showRNotFoundError("R doc directory (" + rDocDir.absolutePath() +
                         ") does not exist.");
      return false;
   }

   // verify and set library path
   FilePath rLibPath = homePath.complete("lib");
   if (rLibPath.exists())
   {
      // make sure the R lib was built
      FilePath libRpath = rLibPath.complete(kLibRFileName);
      if (libRpath.exists())
      {
         // initialize library path from existing value + any extras
         std::string libraryPath = core::system::getenv(kLibraryPathEnvVariable);
         if (!libraryPath.empty())
            libraryPath.append(":");
         libraryPath.append(rLibPath.absolutePath());
         std::string extraPaths = extraLibraryPaths();
         if (!extraPaths.empty())
            libraryPath.append(":" + extraPaths);

         // set it
         core::system::setenv(kLibraryPathEnvVariable, libraryPath);
      }
      else
      {
         showRNotFoundError(rLibPath.filename() + " not found in R library "
                            "path. If this is a custom build of R, was it "
                            "built with the --enable-R-shlib option?");
         return false;
      }
   }
   else
   {
      showRNotFoundError("R library directory (" + rLibPath.absolutePath() +
                         ") does not exist.");
      return false;
   }

   return true;
}

} // namespace desktop
<commit_msg>fix mac build issue<commit_after>/*
 * DesktopMacDetectRHome.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopDetectRHome.hpp"

#include <vector>

#include <boost/algorithm/string/trim.hpp>

#include <QtCore>
#include <QMessageBox>

#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/system/System.hpp>

#include "config.h"

using namespace core;

namespace desktop {

namespace {

// MacOS X Specific
#ifdef __APPLE__

#define kLibRFileName            "libR.dylib "
#define kLibraryPathEnvVariable  "DYLD_LIBRARY_PATH"

 // define search paths to match shell search path behavior (including
 // /opt/local/bin being first since that is where macports puts it)
 std::vector<std::string> rSearchPaths()
 {
    std::vector<std::string> rPaths;
    rPaths.push_back("/opt/local/bin/R");
    rPaths.push_back("/usr/bin/R");
    rPaths.push_back("/usr/local/bin/R");
    return rPaths;
 }

 // no extra paths on the mac
 std::string extraLibraryPaths()
 {
    return std::string();
 }

// Linux specific
#else

#define kLibRFileName            "libR.so"
#define kLibraryPathEnvVariable  "LD_LIBRARY_PATH"

 // define search paths to match shell search path behavior (note differs
 // from macox by having /usr/local/bin first)
 std::vector<std::string> rSearchPaths()
 {
    std::vector<std::string> rPaths;
    rPaths.push_back("/usr/local/bin/R");
    rPaths.push_back("/usr/bin/R");
    return rPaths;
 }

 // extra paths from R (for rjava) on linux
 std::string extraLibraryPaths()
 {
    std::string libraryPaths;

    FilePath supportingFilePath = desktop::options().supportingFilePath();
    FilePath scriptPath = supportingFilePath.complete("bin/r-ldpath");
    if (!scriptPath.exists())
      scriptPath = supportingFilePath.complete("session/r-ldpath");
    if (scriptPath.exists())
    {
       // run script
       Error error = system::captureCommand(scriptPath.absolutePath(),
                                            &libraryPaths);
       if (error)
          LOG_ERROR(error);
    }

    return libraryPaths;
 }

#endif

FilePath detectRHome()
{
   // scan possible locations for R (need these because on the mac
   // our path as a GUI app is very limited)
   FilePath rPath;
   std::vector<std::string> rPaths = rSearchPaths();
   for(std::vector<std::string>::const_iterator it = rPaths.begin();
       it != rPaths.end(); ++it)
   {
      FilePath candidatePath(*it);
      if (candidatePath.exists())
      {
         rPath = candidatePath ;
         break;
      }
   }

   // if we didn't find one then bail
   if (rPath.empty())
   {
      LOG_ERROR_MESSAGE("Couldn't find R on known path");
      return FilePath();
   }

   // run R to detect R home
   std::string output;
   std::string command = rPath.absolutePath() + " RHOME";
   Error error = core::system::captureCommand(command, &output);
   if (error)
   {
      LOG_ERROR(error);
      return FilePath();
   }
   boost::algorithm::trim(output);

   // return the home path if we got one
   if (!output.empty())
      return FilePath(output);
   else
      return FilePath();
}

void showRNotFoundError(const std::string& msg)
{
   QMessageBox::critical(NULL, "R Not Found", QString::fromStdString(msg));
}

} // anonymous namespace

bool prepareEnvironment(Options&)
{
   // declare home path and doc dir -- can get them from the environment
   // or by probing the system
   FilePath homePath, rDocDir;

   // first check environment
   std::string home = core::system::getenv("R_HOME");
   if (!home.empty())
      homePath = FilePath(home);
   std::string doc = core::system::getenv("R_DOC_DIR");
   if (!doc.empty())
      rDocDir = FilePath(doc);

   // probe for home path if necessary
   if (homePath.empty())
      homePath = detectRHome();

   // if that didn't work then try the configured path as a last ditch
   if (!homePath.exists())
      homePath = FilePath(CONFIG_R_HOME_PATH);

   // verify and set home path
   if (homePath.exists())
   {
      core::system::setenv("R_HOME", homePath.absolutePath());
   }
   else
   {
      showRNotFoundError("R home path (" + homePath.absolutePath() +
                         ") does not exist. Is R installed on "
                         "this system?");
      return false;
   }

   // complete doc dir if necesary
   if (rDocDir.empty())
      rDocDir = homePath.complete("doc");

   // doc dir may be in configured location (/usr/share) rather than
   // a subdirectory of R_HOME (this is in fact the case for the
   // debian r-base package). so check the configuired location as
   // a last ditch
   if (!rDocDir.exists())
      rDocDir = FilePath(CONFIG_R_DOC_PATH);

   // verify and set doc dir
   if (rDocDir.exists())
   {
       core::system::setenv("R_DOC_DIR", rDocDir.absolutePath());
   }
   else
   {
      showRNotFoundError("R doc directory (" + rDocDir.absolutePath() +
                         ") does not exist.");
      return false;
   }

   // verify and set library path
   FilePath rLibPath = homePath.complete("lib");
   if (rLibPath.exists())
   {
      // make sure the R lib was built
      FilePath libRpath = rLibPath.complete(kLibRFileName);
      if (libRpath.exists())
      {
         // initialize library path from existing value + any extras
         std::string libraryPath = core::system::getenv(kLibraryPathEnvVariable);
         if (!libraryPath.empty())
            libraryPath.append(":");
         libraryPath.append(rLibPath.absolutePath());
         std::string extraPaths = extraLibraryPaths();
         if (!extraPaths.empty())
            libraryPath.append(":" + extraPaths);

         // set it
         core::system::setenv(kLibraryPathEnvVariable, libraryPath);
      }
      else
      {
         showRNotFoundError(rLibPath.filename() + " not found in R library "
                            "path. If this is a custom build of R, was it "
                            "built with the --enable-R-shlib option?");
         return false;
      }
   }
   else
   {
      showRNotFoundError("R library directory (" + rLibPath.absolutePath() +
                         ") does not exist.");
      return false;
   }

   return true;
}

} // namespace desktop
<|endoftext|>


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

#include "main.h"

#include "core.h"
#include "natives.h"
#include "utility.h"

#include <boost/scoped_ptr.hpp>

#include <sampgdk/core.h>

#include <set>

extern void *pAMXFunctions;

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
	return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)
{
	core.reset(new Core);
	pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
	sampgdk::logprintf("\n\n*** Streamer Plugin v%s by Incognito loaded ***\n", PLUGIN_VERSION);
	return sampgdk::Load(sampgdk::GetCurrentPluginHandle(), ppData);
}

PLUGIN_EXPORT void PLUGIN_CALL Unload()
{
	core.reset();
	sampgdk::logprintf("\n\n*** Streamer Plugin v%s by Incognito unloaded ***\n", PLUGIN_VERSION);
	sampgdk::Unload(sampgdk::GetCurrentPluginHandle());
}

AMX_NATIVE_INFO natives[] =
{
	// Settings
	{ "Streamer_GetTickRate", Natives::Streamer_GetTickRate },
	{ "Streamer_SetTickRate", Natives::Streamer_SetTickRate },
	{ "Streamer_GetMaxItems", Natives::Streamer_GetMaxItems },
	{ "Streamer_SetMaxItems", Natives::Streamer_SetMaxItems },
	{ "Streamer_GetVisibleItems", Natives::Streamer_GetVisibleItems },
	{ "Streamer_SetVisibleItems", Natives::Streamer_SetVisibleItems },
	{ "Streamer_GetCellDistance", Natives::Streamer_GetCellDistance },
	{ "Streamer_SetCellDistance", Natives::Streamer_SetCellDistance },
	{ "Streamer_GetCellSize", Natives::Streamer_GetCellSize },
	{ "Streamer_SetCellSize", Natives::Streamer_SetCellSize },
	// Updates
	{ "Streamer_ProcessActiveItems", Natives::Streamer_ProcessActiveItems },
	{ "Streamer_ToggleIdleUpdate", Natives::Streamer_ToggleIdleUpdate },
	{ "Streamer_IsToggleIdleUpdate", Natives::Streamer_IsToggleIdleUpdate },
	{ "Streamer_ToggleItemUpdate", Natives::Streamer_ToggleItemUpdate },
	{ "Streamer_IsToggleItemUpdate", Natives::Streamer_IsToggleItemUpdate },
	{ "Streamer_Update", Natives::Streamer_Update },
	{ "Streamer_UpdateEx", Natives::Streamer_UpdateEx },
	// Data Manipulation
	{ "Streamer_GetFloatData", Natives::Streamer_GetFloatData },
	{ "Streamer_SetFloatData", Natives::Streamer_SetFloatData },
	{ "Streamer_GetIntData", Natives::Streamer_GetIntData },
	{ "Streamer_SetIntData", Natives::Streamer_SetIntData },
	{ "Streamer_GetArrayData", Natives::Streamer_GetArrayData },
	{ "Streamer_SetArrayData", Natives::Streamer_SetArrayData },
	{ "Streamer_IsInArrayData", Natives::Streamer_IsInArrayData },
	{ "Streamer_AppendArrayData", Natives::Streamer_AppendArrayData },
	{ "Streamer_RemoveArrayData", Natives::Streamer_RemoveArrayData },
	{ "Streamer_GetUpperBound", Natives::Streamer_GetUpperBound },
	// Miscellaneous
	{ "Streamer_GetDistanceToItem", Natives::Streamer_GetDistanceToItem },
	{ "Streamer_GetItemInternalID", Natives::Streamer_GetItemInternalID },
	{ "Streamer_GetItemStreamerID", Natives::Streamer_GetItemStreamerID },
	{ "Streamer_IsItemVisible", Natives::Streamer_IsItemVisible },
	{ "Streamer_DestroyAllVisibleItems", Natives::Streamer_DestroyAllVisibleItems },
	{ "Streamer_CountVisibleItems", Natives::Streamer_CountVisibleItems },
	{ "Streamer_DestroyAllItems", Natives::Streamer_DestroyAllItems },
	{ "Streamer_CountItems", Natives::Streamer_CountItems },
	// Objects
	{ "CreateDynamicObject", Natives::CreateDynamicObject },
	{ "DestroyDynamicObject", Natives::DestroyDynamicObject },
	{ "IsValidDynamicObject", Natives::IsValidDynamicObject },
	{ "SetDynamicObjectPos", Natives::SetDynamicObjectPos },
	{ "GetDynamicObjectPos", Natives::GetDynamicObjectPos },
	{ "SetDynamicObjectRot", Natives::SetDynamicObjectRot },
	{ "GetDynamicObjectRot", Natives::GetDynamicObjectRot },
	{ "MoveDynamicObject", Natives::MoveDynamicObject },
	{ "StopDynamicObject", Natives::StopDynamicObject },
	{ "IsDynamicObjectMoving", Natives::IsDynamicObjectMoving },
	{ "AttachCameraToDynamicObject", Natives::AttachCameraToDynamicObject },
	{ "AttachDynamicObjectToVehicle", Natives::AttachDynamicObjectToVehicle },
	{ "EditDynamicObject", Natives::EditDynamicObject },
	{ "GetDynamicObjectMaterial", Natives::GetDynamicObjectMaterial },
	{ "SetDynamicObjectMaterial", Natives::SetDynamicObjectMaterial },
	{ "GetDynamicObjectMaterialText", Natives::GetDynamicObjectMaterialText },
	{ "SetDynamicObjectMaterialText", Natives::SetDynamicObjectMaterialText },
	// Pickups
	{ "CreateDynamicPickup", Natives::CreateDynamicPickup },
	{ "DestroyDynamicPickup", Natives::DestroyDynamicPickup },
	{ "IsValidDynamicPickup", Natives::IsValidDynamicPickup },
	// Checkpoints
	{ "CreateDynamicCP", Natives::CreateDynamicCP },
	{ "DestroyDynamicCP", Natives::DestroyDynamicCP },
	{ "IsValidDynamicCP", Natives::IsValidDynamicCP },
	{ "TogglePlayerDynamicCP", Natives::TogglePlayerDynamicCP },
	{ "TogglePlayerAllDynamicCPs", Natives::TogglePlayerAllDynamicCPs },
	{ "IsPlayerInDynamicCP", Natives::IsPlayerInDynamicCP },
	{ "GetPlayerVisibleDynamicCP", Natives::GetPlayerVisibleDynamicCP },
	// Race Checkpoints
	{ "CreateDynamicRaceCP", Natives::CreateDynamicRaceCP },
	{ "DestroyDynamicRaceCP", Natives::DestroyDynamicRaceCP },
	{ "IsValidDynamicRaceCP", Natives::IsValidDynamicRaceCP },
	{ "TogglePlayerDynamicRaceCP", Natives::TogglePlayerDynamicRaceCP },
	{ "TogglePlayerAllDynamicRaceCPs", Natives::TogglePlayerAllDynamicRaceCPs },
	{ "IsPlayerInDynamicRaceCP", Natives::IsPlayerInDynamicRaceCP },
	{ "GetPlayerVisibleDynamicRaceCP", Natives::GetPlayerVisibleDynamicRaceCP },
	// Map Icons
	{ "CreateDynamicMapIcon", Natives::CreateDynamicMapIcon },
	{ "DestroyDynamicMapIcon", Natives::DestroyDynamicMapIcon },
	{ "IsValidDynamicMapIcon", Natives::IsValidDynamicMapIcon },
	// 3D Text Labels
	{ "CreateDynamic3DTextLabel", Natives::CreateDynamic3DTextLabel },
	{ "DestroyDynamic3DTextLabel", Natives::DestroyDynamic3DTextLabel },
	{ "IsValidDynamic3DTextLabel", Natives::IsValidDynamic3DTextLabel },
	{ "GetDynamic3DTextLabelText", Natives::GetDynamic3DTextLabelText },
	{ "UpdateDynamic3DTextLabelText", Natives::UpdateDynamic3DTextLabelText },
	// Areas
	{ "CreateDynamicCircle", Natives::CreateDynamicCircle },
	{ "CreateDynamicRectangle", Natives::CreateDynamicRectangle },
	{ "CreateDynamicSphere", Natives::CreateDynamicSphere },
	{ "CreateDynamicCube", Natives::CreateDynamicCube },
	{ "CreateDynamicPolygon", Natives::CreateDynamicPolygon },
	{ "DestroyDynamicArea", Natives::DestroyDynamicArea },
	{ "IsValidDynamicArea", Natives::IsValidDynamicArea },
	{ "GetDynamicPolygonPoints", Natives::GetDynamicPolygonPoints },
	{ "GetDynamicPolygonNumberPoints", Natives::GetDynamicPolygonNumberPoints },
	{ "TogglePlayerDynamicArea", Natives::TogglePlayerDynamicArea },
	{ "TogglePlayerAllDynamicAreas", Natives::TogglePlayerAllDynamicAreas },
	{ "IsPlayerInDynamicArea", Natives::IsPlayerInDynamicArea },
	{ "IsPlayerInAnyDynamicArea", Natives::IsPlayerInAnyDynamicArea },
	{ "IsAnyPlayerInDynamicArea", Natives::IsAnyPlayerInDynamicArea },
	{ "IsAnyPlayerInAnyDynamicArea", Natives::IsAnyPlayerInAnyDynamicArea },
	{ "IsPointInDynamicArea", Natives::IsPointInDynamicArea },
	{ "IsPointInAnyDynamicArea", Natives::IsPointInAnyDynamicArea },
	{ "GetPlayerDynamicAreas", Natives::GetPlayerDynamicAreas },
	{ "GetPlayerNumberDynamicAreas", Natives::GetPlayerNumberDynamicAreas },
	{ "AttachDynamicAreaToObject", Natives::AttachDynamicAreaToObject },
	{ "AttachDynamicAreaToPlayer", Natives::AttachDynamicAreaToPlayer },
	{ "AttachDynamicAreaToVehicle", Natives::AttachDynamicAreaToVehicle },
	// Extended
	{ "CreateDynamicObjectEx", Natives::CreateDynamicObjectEx },
	{ "CreateDynamicPickupEx", Natives::CreateDynamicPickupEx },
	{ "CreateDynamicCPEx", Natives::CreateDynamicCPEx },
	{ "CreateDynamicRaceCPEx", Natives::CreateDynamicRaceCPEx },
	{ "CreateDynamicMapIconEx", Natives::CreateDynamicMapIconEx },
	{ "CreateDynamic3DTextLabelEx", Natives::CreateDynamic3DTextLabelEx },
	{ "CreateDynamicCircleEx", Natives::CreateDynamicCircleEx },
	{ "CreateDynamicRectangleEx", Natives::CreateDynamicRectangleEx },
	{ "CreateDynamicSphereEx", Natives::CreateDynamicSphereEx },
	{ "CreateDynamicCubeEx", Natives::CreateDynamicCubeEx },
	{ "CreateDynamicPolygonEx", Natives::CreateDynamicPolygonEx },
	// Internal
	{ "Streamer_CallbackHook", Natives::Streamer_CallbackHook },
	// Deprecated
	{ "Streamer_TickRate", Natives::Streamer_SetTickRate },
	{ "Streamer_MaxItems", Natives::Streamer_SetMaxItems },
	{ "Streamer_VisibleItems", Natives::Streamer_SetVisibleItems },
	{ "Streamer_CellDistance", Natives::Streamer_SetCellDistance },
	{ "Streamer_CellSize", Natives::Streamer_SetCellSize },
	{ "DestroyAllDynamicObjects", Natives::DestroyAllDynamicObjects },
	{ "CountDynamicObjects", Natives::CountDynamicObjects },
	{ "DestroyAllDynamicPickups", Natives::DestroyAllDynamicPickups },
	{ "CountDynamicPickups", Natives::CountDynamicPickups },
	{ "DestroyAllDynamicCPs", Natives::DestroyAllDynamicCPs },
	{ "CountDynamicCPs", Natives::CountDynamicCPs },
	{ "DestroyAllDynamicRaceCPs", Natives::DestroyAllDynamicRaceCPs },
	{ "CountDynamicRaceCPs", Natives::CountDynamicRaceCPs },
	{ "DestroyAllDynamicMapIcons", Natives::DestroyAllDynamicMapIcons },
	{ "CountDynamicMapIcons", Natives::CountDynamicMapIcons },
	{ "DestroyAllDynamic3DTextLabels", Natives::DestroyAllDynamic3DTextLabels },
	{ "CountDynamic3DTextLabels", Natives::CountDynamic3DTextLabels },
	{ "DestroyAllDynamicAreas", Natives::DestroyAllDynamicAreas },
	{ "CountDynamicAreas", Natives::CountDynamicAreas },
	{ 0, 0 }
};

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)
{
	core->getData()->interfaces.insert(amx);
	return Utility::checkInterfaceAndRegisterNatives(amx, natives);
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)
{
	core->getData()->interfaces.erase(amx);
	Utility::destroyAllItemsInInterface(amx);
	return AMX_ERR_NONE;
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick()
{
	core->getStreamer()->startAutomaticUpdate();
}
<commit_msg>Fix plugin load message on Linux<commit_after>/*
 * Copyright (C) 2014 Incognito
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "main.h"

#include "core.h"
#include "natives.h"
#include "utility.h"

#include <boost/scoped_ptr.hpp>

#include <sampgdk/core.h>

#include <set>

typedef void (*logprintf_t)(const char*, ...);

extern void *pAMXFunctions;

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
	return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)
{
	core.reset(new Core);
	pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
	logprintf_t logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
	logprintf("\n\n*** Streamer Plugin v%s by Incognito loaded ***\n", PLUGIN_VERSION);
	return sampgdk::Load(sampgdk::GetCurrentPluginHandle(), ppData);
}

PLUGIN_EXPORT void PLUGIN_CALL Unload()
{
	core.reset();
	sampgdk::logprintf("\n\n*** Streamer Plugin v%s by Incognito unloaded ***\n", PLUGIN_VERSION);
	sampgdk::Unload(sampgdk::GetCurrentPluginHandle());
}

AMX_NATIVE_INFO natives[] =
{
	// Settings
	{ "Streamer_GetTickRate", Natives::Streamer_GetTickRate },
	{ "Streamer_SetTickRate", Natives::Streamer_SetTickRate },
	{ "Streamer_GetMaxItems", Natives::Streamer_GetMaxItems },
	{ "Streamer_SetMaxItems", Natives::Streamer_SetMaxItems },
	{ "Streamer_GetVisibleItems", Natives::Streamer_GetVisibleItems },
	{ "Streamer_SetVisibleItems", Natives::Streamer_SetVisibleItems },
	{ "Streamer_GetCellDistance", Natives::Streamer_GetCellDistance },
	{ "Streamer_SetCellDistance", Natives::Streamer_SetCellDistance },
	{ "Streamer_GetCellSize", Natives::Streamer_GetCellSize },
	{ "Streamer_SetCellSize", Natives::Streamer_SetCellSize },
	// Updates
	{ "Streamer_ProcessActiveItems", Natives::Streamer_ProcessActiveItems },
	{ "Streamer_ToggleIdleUpdate", Natives::Streamer_ToggleIdleUpdate },
	{ "Streamer_IsToggleIdleUpdate", Natives::Streamer_IsToggleIdleUpdate },
	{ "Streamer_ToggleItemUpdate", Natives::Streamer_ToggleItemUpdate },
	{ "Streamer_IsToggleItemUpdate", Natives::Streamer_IsToggleItemUpdate },
	{ "Streamer_Update", Natives::Streamer_Update },
	{ "Streamer_UpdateEx", Natives::Streamer_UpdateEx },
	// Data Manipulation
	{ "Streamer_GetFloatData", Natives::Streamer_GetFloatData },
	{ "Streamer_SetFloatData", Natives::Streamer_SetFloatData },
	{ "Streamer_GetIntData", Natives::Streamer_GetIntData },
	{ "Streamer_SetIntData", Natives::Streamer_SetIntData },
	{ "Streamer_GetArrayData", Natives::Streamer_GetArrayData },
	{ "Streamer_SetArrayData", Natives::Streamer_SetArrayData },
	{ "Streamer_IsInArrayData", Natives::Streamer_IsInArrayData },
	{ "Streamer_AppendArrayData", Natives::Streamer_AppendArrayData },
	{ "Streamer_RemoveArrayData", Natives::Streamer_RemoveArrayData },
	{ "Streamer_GetUpperBound", Natives::Streamer_GetUpperBound },
	// Miscellaneous
	{ "Streamer_GetDistanceToItem", Natives::Streamer_GetDistanceToItem },
	{ "Streamer_GetItemInternalID", Natives::Streamer_GetItemInternalID },
	{ "Streamer_GetItemStreamerID", Natives::Streamer_GetItemStreamerID },
	{ "Streamer_IsItemVisible", Natives::Streamer_IsItemVisible },
	{ "Streamer_DestroyAllVisibleItems", Natives::Streamer_DestroyAllVisibleItems },
	{ "Streamer_CountVisibleItems", Natives::Streamer_CountVisibleItems },
	{ "Streamer_DestroyAllItems", Natives::Streamer_DestroyAllItems },
	{ "Streamer_CountItems", Natives::Streamer_CountItems },
	// Objects
	{ "CreateDynamicObject", Natives::CreateDynamicObject },
	{ "DestroyDynamicObject", Natives::DestroyDynamicObject },
	{ "IsValidDynamicObject", Natives::IsValidDynamicObject },
	{ "SetDynamicObjectPos", Natives::SetDynamicObjectPos },
	{ "GetDynamicObjectPos", Natives::GetDynamicObjectPos },
	{ "SetDynamicObjectRot", Natives::SetDynamicObjectRot },
	{ "GetDynamicObjectRot", Natives::GetDynamicObjectRot },
	{ "MoveDynamicObject", Natives::MoveDynamicObject },
	{ "StopDynamicObject", Natives::StopDynamicObject },
	{ "IsDynamicObjectMoving", Natives::IsDynamicObjectMoving },
	{ "AttachCameraToDynamicObject", Natives::AttachCameraToDynamicObject },
	{ "AttachDynamicObjectToVehicle", Natives::AttachDynamicObjectToVehicle },
	{ "EditDynamicObject", Natives::EditDynamicObject },
	{ "GetDynamicObjectMaterial", Natives::GetDynamicObjectMaterial },
	{ "SetDynamicObjectMaterial", Natives::SetDynamicObjectMaterial },
	{ "GetDynamicObjectMaterialText", Natives::GetDynamicObjectMaterialText },
	{ "SetDynamicObjectMaterialText", Natives::SetDynamicObjectMaterialText },
	// Pickups
	{ "CreateDynamicPickup", Natives::CreateDynamicPickup },
	{ "DestroyDynamicPickup", Natives::DestroyDynamicPickup },
	{ "IsValidDynamicPickup", Natives::IsValidDynamicPickup },
	// Checkpoints
	{ "CreateDynamicCP", Natives::CreateDynamicCP },
	{ "DestroyDynamicCP", Natives::DestroyDynamicCP },
	{ "IsValidDynamicCP", Natives::IsValidDynamicCP },
	{ "TogglePlayerDynamicCP", Natives::TogglePlayerDynamicCP },
	{ "TogglePlayerAllDynamicCPs", Natives::TogglePlayerAllDynamicCPs },
	{ "IsPlayerInDynamicCP", Natives::IsPlayerInDynamicCP },
	{ "GetPlayerVisibleDynamicCP", Natives::GetPlayerVisibleDynamicCP },
	// Race Checkpoints
	{ "CreateDynamicRaceCP", Natives::CreateDynamicRaceCP },
	{ "DestroyDynamicRaceCP", Natives::DestroyDynamicRaceCP },
	{ "IsValidDynamicRaceCP", Natives::IsValidDynamicRaceCP },
	{ "TogglePlayerDynamicRaceCP", Natives::TogglePlayerDynamicRaceCP },
	{ "TogglePlayerAllDynamicRaceCPs", Natives::TogglePlayerAllDynamicRaceCPs },
	{ "IsPlayerInDynamicRaceCP", Natives::IsPlayerInDynamicRaceCP },
	{ "GetPlayerVisibleDynamicRaceCP", Natives::GetPlayerVisibleDynamicRaceCP },
	// Map Icons
	{ "CreateDynamicMapIcon", Natives::CreateDynamicMapIcon },
	{ "DestroyDynamicMapIcon", Natives::DestroyDynamicMapIcon },
	{ "IsValidDynamicMapIcon", Natives::IsValidDynamicMapIcon },
	// 3D Text Labels
	{ "CreateDynamic3DTextLabel", Natives::CreateDynamic3DTextLabel },
	{ "DestroyDynamic3DTextLabel", Natives::DestroyDynamic3DTextLabel },
	{ "IsValidDynamic3DTextLabel", Natives::IsValidDynamic3DTextLabel },
	{ "GetDynamic3DTextLabelText", Natives::GetDynamic3DTextLabelText },
	{ "UpdateDynamic3DTextLabelText", Natives::UpdateDynamic3DTextLabelText },
	// Areas
	{ "CreateDynamicCircle", Natives::CreateDynamicCircle },
	{ "CreateDynamicRectangle", Natives::CreateDynamicRectangle },
	{ "CreateDynamicSphere", Natives::CreateDynamicSphere },
	{ "CreateDynamicCube", Natives::CreateDynamicCube },
	{ "CreateDynamicPolygon", Natives::CreateDynamicPolygon },
	{ "DestroyDynamicArea", Natives::DestroyDynamicArea },
	{ "IsValidDynamicArea", Natives::IsValidDynamicArea },
	{ "GetDynamicPolygonPoints", Natives::GetDynamicPolygonPoints },
	{ "GetDynamicPolygonNumberPoints", Natives::GetDynamicPolygonNumberPoints },
	{ "TogglePlayerDynamicArea", Natives::TogglePlayerDynamicArea },
	{ "TogglePlayerAllDynamicAreas", Natives::TogglePlayerAllDynamicAreas },
	{ "IsPlayerInDynamicArea", Natives::IsPlayerInDynamicArea },
	{ "IsPlayerInAnyDynamicArea", Natives::IsPlayerInAnyDynamicArea },
	{ "IsAnyPlayerInDynamicArea", Natives::IsAnyPlayerInDynamicArea },
	{ "IsAnyPlayerInAnyDynamicArea", Natives::IsAnyPlayerInAnyDynamicArea },
	{ "IsPointInDynamicArea", Natives::IsPointInDynamicArea },
	{ "IsPointInAnyDynamicArea", Natives::IsPointInAnyDynamicArea },
	{ "GetPlayerDynamicAreas", Natives::GetPlayerDynamicAreas },
	{ "GetPlayerNumberDynamicAreas", Natives::GetPlayerNumberDynamicAreas },
	{ "AttachDynamicAreaToObject", Natives::AttachDynamicAreaToObject },
	{ "AttachDynamicAreaToPlayer", Natives::AttachDynamicAreaToPlayer },
	{ "AttachDynamicAreaToVehicle", Natives::AttachDynamicAreaToVehicle },
	// Extended
	{ "CreateDynamicObjectEx", Natives::CreateDynamicObjectEx },
	{ "CreateDynamicPickupEx", Natives::CreateDynamicPickupEx },
	{ "CreateDynamicCPEx", Natives::CreateDynamicCPEx },
	{ "CreateDynamicRaceCPEx", Natives::CreateDynamicRaceCPEx },
	{ "CreateDynamicMapIconEx", Natives::CreateDynamicMapIconEx },
	{ "CreateDynamic3DTextLabelEx", Natives::CreateDynamic3DTextLabelEx },
	{ "CreateDynamicCircleEx", Natives::CreateDynamicCircleEx },
	{ "CreateDynamicRectangleEx", Natives::CreateDynamicRectangleEx },
	{ "CreateDynamicSphereEx", Natives::CreateDynamicSphereEx },
	{ "CreateDynamicCubeEx", Natives::CreateDynamicCubeEx },
	{ "CreateDynamicPolygonEx", Natives::CreateDynamicPolygonEx },
	// Internal
	{ "Streamer_CallbackHook", Natives::Streamer_CallbackHook },
	// Deprecated
	{ "Streamer_TickRate", Natives::Streamer_SetTickRate },
	{ "Streamer_MaxItems", Natives::Streamer_SetMaxItems },
	{ "Streamer_VisibleItems", Natives::Streamer_SetVisibleItems },
	{ "Streamer_CellDistance", Natives::Streamer_SetCellDistance },
	{ "Streamer_CellSize", Natives::Streamer_SetCellSize },
	{ "DestroyAllDynamicObjects", Natives::DestroyAllDynamicObjects },
	{ "CountDynamicObjects", Natives::CountDynamicObjects },
	{ "DestroyAllDynamicPickups", Natives::DestroyAllDynamicPickups },
	{ "CountDynamicPickups", Natives::CountDynamicPickups },
	{ "DestroyAllDynamicCPs", Natives::DestroyAllDynamicCPs },
	{ "CountDynamicCPs", Natives::CountDynamicCPs },
	{ "DestroyAllDynamicRaceCPs", Natives::DestroyAllDynamicRaceCPs },
	{ "CountDynamicRaceCPs", Natives::CountDynamicRaceCPs },
	{ "DestroyAllDynamicMapIcons", Natives::DestroyAllDynamicMapIcons },
	{ "CountDynamicMapIcons", Natives::CountDynamicMapIcons },
	{ "DestroyAllDynamic3DTextLabels", Natives::DestroyAllDynamic3DTextLabels },
	{ "CountDynamic3DTextLabels", Natives::CountDynamic3DTextLabels },
	{ "DestroyAllDynamicAreas", Natives::DestroyAllDynamicAreas },
	{ "CountDynamicAreas", Natives::CountDynamicAreas },
	{ 0, 0 }
};

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)
{
	core->getData()->interfaces.insert(amx);
	return Utility::checkInterfaceAndRegisterNatives(amx, natives);
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)
{
	core->getData()->interfaces.erase(amx);
	Utility::destroyAllItemsInInterface(amx);
	return AMX_ERR_NONE;
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick()
{
	core->getStreamer()->startAutomaticUpdate();
}
<|endoftext|>


<commit_before>/*
 * SessionSpelling.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionSpelling.hpp"

#include <boost/shared_ptr.hpp>

#include <core/Error.hpp>
#include <core/Exec.hpp>

#include <core/spelling/SpellChecker.hpp>
#include <core/spelling/HunspellDictionaryManager.hpp>

#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <r/RUtil.hpp>
#include <r/RExec.hpp>

#include <session/SessionModuleContext.hpp>

using namespace core;

namespace session {
namespace modules {
namespace spelling {

namespace {

class SpellingEngine : boost::noncopyable
{
private:
   friend SpellingEngine& spellingEngine();
   SpellingEngine()
      : dictManager_(
            session::options().hunspellDictionariesPath(),
            module_context::userScratchPath().complete("dictionaries"))
   {
   }

public:
   core::spelling::hunspell::DictionaryManager& dictionaryManager()
   {
      return dictManager_;
   }

   core::spelling::SpellChecker& spellChecker(const std::string& langId)
   {
      if (!pSpellChecker_ || (langId != currentLangId_))
      {
         core::spelling::hunspell::Dictionary dict =
                           dictManager_.dictionaryForLanguageId(langId);
         if (!dict.empty())
         {
            Error error = core::spelling::createHunspell(dict.dicPath(),
                                                         &pSpellChecker_,
                                                         &r::util::iconvstr);
            if (!error)
               currentLangId_ = langId;
            else
               pSpellChecker_.reset(new core::spelling::NoSpellChecker());
         }
         else
         {
            pSpellChecker_.reset(new core::spelling::NoSpellChecker());
         }
      }
      return *pSpellChecker_;
   }

private:
   core::spelling::hunspell::DictionaryManager dictManager_;
   boost::shared_ptr<core::spelling::SpellChecker> pSpellChecker_;
   std::string currentLangId_;
};

SpellingEngine& spellingEngine()
{
   static SpellingEngine instance;
   return instance;
}

// R function for testing & debugging
SEXP rs_checkSpelling(SEXP wordSEXP)
{
   bool isCorrect;
   std::string word = r::sexp::asString(wordSEXP);

   Error error = spellingEngine().spellChecker("en_US").checkSpelling(
                                                                   word,
                                                                   &isCorrect);

   // We'll return true here so as not to tie up the front end.
   if (error)
   {
      LOG_ERROR(error);
      isCorrect = true;
   }

   r::sexp::Protect rProtect;
   return r::sexp::create(isCorrect, &rProtect);
}

json::Object dictionaryAsJson(const core::spelling::hunspell::Dictionary& dict)
{
   json::Object dictJson;
   dictJson["id"] = dict.id();
   dictJson["name"] = dict.name();
   return dictJson;
}

FilePath userDictionariesDir()
{
   return module_context::userScratchPath().childPath("dictionaries");
}

FilePath allLanguagesDir()
{
   return module_context::userScratchPath().childPath(
                                          "dictionaries/languages-system");
}

Error checkSpelling(const json::JsonRpcRequest& request,
                    json::JsonRpcResponse* pResponse)
{
   std::string langId, word;
   Error error = json::readParams(request.params, &langId, &word);
   if (error)
      return error;

   bool isCorrect;
   error = spellingEngine().spellChecker(langId).checkSpelling(word,&isCorrect);
   if (error)
      return error;

   pResponse->setResult(isCorrect);

   return Success();
}

Error suggestionList(const json::JsonRpcRequest& request,
                     json::JsonRpcResponse* pResponse)
{
   std::string langId, word;
   Error error = json::readParams(request.params, &langId, &word);
   if (error)
      return error;

   std::vector<std::string> sugs;
   error = spellingEngine().spellChecker(langId).suggestionList(word,&sugs);
   if (error)
      return error;

   json::Array sugsJson;
   std::transform(sugs.begin(),
                  sugs.end(),
                  std::back_inserter(sugsJson),
                  json::toJsonString);
   pResponse->setResult(sugsJson);

   return Success();
}

Error addToDictionary(const json::JsonRpcRequest& request,
                     json::JsonRpcResponse* pResponse)
{
   std::string langId, word;
   Error error = json::readParams(request.params, &langId, &word);
   if (error)
      return error;

   bool added;
   error = spellingEngine().spellChecker(langId).addWord(word,&added);
   if (error)
      return error;

   pResponse->setResult(added);
   return Success();
}

Error installAllDictionaries(const json::JsonRpcRequest& request,
                             json::JsonRpcResponse* pResponse)
{
   // form system path to all languages dir
   std::string targetDir = string_utils::utf8ToSystem(
                                    allLanguagesDir().absolutePath());

   // perform the download
   r::exec::RFunction dlFunc(".rs.downloadAllDictionaries", targetDir);
   Error error = dlFunc.call();
   if (error)
   {
      std::string userMessage = r::endUserErrorMessage(error);
      pResponse->setError(error, json::Value(userMessage));
      return Success();
   }
   else
   {
      pResponse->setResult(spelling::spellingPrefsContextAsJson());
      return Success();
   }
}

} // anonymous namespace

core::json::Object spellingPrefsContextAsJson()
{
   using namespace core::spelling::hunspell;

   core::json::Object contextJson;

   DictionaryManager dictManager(options().hunspellDictionariesPath(),
                                 userDictionariesDir());

   std::vector<Dictionary> dictionaries;
   Error error = dictManager.availableLanguages(&dictionaries);
   if (error)
   {
      LOG_ERROR(error);
      return core::json::Object();
   }

   core::json::Array dictionariesJson;
   std::transform(dictionaries.begin(),
                  dictionaries.end(),
                  std::back_inserter(dictionariesJson),
                  dictionaryAsJson);

   // return json
   contextJson["all_languages_installed"] = dictManager.allLanguagesInstalled();
   contextJson["available_languages"] = dictionariesJson;
   return contextJson;
}

Error initialize()
{
   // register rs_ensureFileHidden with R
   R_CallMethodDef methodDef;

   methodDef.name = "rs_checkSpelling" ;
   methodDef.fun = (DL_FUNC) rs_checkSpelling ;
   methodDef.numArgs = 1;
   r::routines::addCallMethod(methodDef);

   // register rpc methods
   using boost::bind;
   using namespace module_context;
   ExecBlock initBlock ;
   initBlock.addFunctions()
      (bind(registerRpcMethod, "check_spelling", checkSpelling))
      (bind(registerRpcMethod, "suggestion_list", suggestionList))
      (bind(registerRpcMethod, "add_to_dictionary", addToDictionary))
      (bind(registerRpcMethod, "install_all_dictionaries", installAllDictionaries))
      (bind(sourceModuleRFile, "SessionSpelling.R"));
   return initBlock.execute();
}

} // namespace spelling
} // namespace modules
} // namesapce session

<commit_msg>route spelling calls through spelling engine<commit_after>/*
 * SessionSpelling.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionSpelling.hpp"

#include <boost/shared_ptr.hpp>

#include <core/Error.hpp>
#include <core/Exec.hpp>

#include <core/spelling/SpellChecker.hpp>
#include <core/spelling/HunspellDictionaryManager.hpp>

#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <r/RUtil.hpp>
#include <r/RExec.hpp>

#include <session/SessionModuleContext.hpp>

using namespace core;

namespace session {
namespace modules {
namespace spelling {

namespace {

class SpellingEngine : boost::noncopyable
{
private:
   friend SpellingEngine& spellingEngine();
   SpellingEngine()
      : dictManager_(
            session::options().hunspellDictionariesPath(),
            module_context::userScratchPath().complete("dictionaries"))
   {
   }

public:
   core::spelling::hunspell::DictionaryManager& dictionaryManager()
   {
      return dictManager_;
   }

   Error checkSpelling(const std::string& langId,
                       const std::string& word,
                       bool *pCorrect)
   {
      return spellChecker(langId).checkSpelling(word, pCorrect);
   }

   Error suggestionList(const std::string& langId,
                        const std::string& word,
                        std::vector<std::string>* pSugs)
   {
      return spellChecker(langId).suggestionList(word, pSugs);
   }

   Error addWord(const std::string& langId,
                 const std::string& word,
                 bool* pAdded)
   {
      return spellChecker(langId).addWord(word, pAdded);
   }

private:
   core::spelling::SpellChecker& spellChecker(const std::string& langId)
   {
      if (!pSpellChecker_ || (langId != currentLangId_))
      {
         core::spelling::hunspell::Dictionary dict =
                           dictManager_.dictionaryForLanguageId(langId);
         if (!dict.empty())
         {
            Error error = core::spelling::createHunspell(dict.dicPath(),
                                                         &pSpellChecker_,
                                                         &r::util::iconvstr);
            if (!error)
               currentLangId_ = langId;
            else
               pSpellChecker_.reset(new core::spelling::NoSpellChecker());
         }
         else
         {
            pSpellChecker_.reset(new core::spelling::NoSpellChecker());
         }
      }
      return *pSpellChecker_;
   }

private:
   core::spelling::hunspell::DictionaryManager dictManager_;
   boost::shared_ptr<core::spelling::SpellChecker> pSpellChecker_;
   std::string currentLangId_;
};

SpellingEngine& spellingEngine()
{
   static SpellingEngine instance;
   return instance;
}

// R function for testing & debugging
SEXP rs_checkSpelling(SEXP wordSEXP)
{
   bool isCorrect;
   std::string word = r::sexp::asString(wordSEXP);

   Error error = spellingEngine().checkSpelling("en_US", word, &isCorrect);

   // We'll return true here so as not to tie up the front end.
   if (error)
   {
      LOG_ERROR(error);
      isCorrect = true;
   }

   r::sexp::Protect rProtect;
   return r::sexp::create(isCorrect, &rProtect);
}

json::Object dictionaryAsJson(const core::spelling::hunspell::Dictionary& dict)
{
   json::Object dictJson;
   dictJson["id"] = dict.id();
   dictJson["name"] = dict.name();
   return dictJson;
}

FilePath userDictionariesDir()
{
   return module_context::userScratchPath().childPath("dictionaries");
}

FilePath allLanguagesDir()
{
   return module_context::userScratchPath().childPath(
                                          "dictionaries/languages-system");
}

Error checkSpelling(const json::JsonRpcRequest& request,
                    json::JsonRpcResponse* pResponse)
{
   std::string langId, word;
   Error error = json::readParams(request.params, &langId, &word);
   if (error)
      return error;

   bool isCorrect;
   error = spellingEngine().checkSpelling(langId, word, &isCorrect);
   if (error)
      return error;

   pResponse->setResult(isCorrect);

   return Success();
}

Error suggestionList(const json::JsonRpcRequest& request,
                     json::JsonRpcResponse* pResponse)
{
   std::string langId, word;
   Error error = json::readParams(request.params, &langId, &word);
   if (error)
      return error;

   std::vector<std::string> sugs;
   error = spellingEngine().suggestionList(langId, word, &sugs);
   if (error)
      return error;

   json::Array sugsJson;
   std::transform(sugs.begin(),
                  sugs.end(),
                  std::back_inserter(sugsJson),
                  json::toJsonString);
   pResponse->setResult(sugsJson);

   return Success();
}

Error addToDictionary(const json::JsonRpcRequest& request,
                     json::JsonRpcResponse* pResponse)
{
   std::string langId, word;
   Error error = json::readParams(request.params, &langId, &word);
   if (error)
      return error;

   bool added;
   error = spellingEngine().addWord(langId, word, &added);
   if (error)
      return error;

   pResponse->setResult(added);
   return Success();
}

Error installAllDictionaries(const json::JsonRpcRequest& request,
                             json::JsonRpcResponse* pResponse)
{
   // form system path to all languages dir
   std::string targetDir = string_utils::utf8ToSystem(
                                    allLanguagesDir().absolutePath());

   // perform the download
   r::exec::RFunction dlFunc(".rs.downloadAllDictionaries", targetDir);
   Error error = dlFunc.call();
   if (error)
   {
      std::string userMessage = r::endUserErrorMessage(error);
      pResponse->setError(error, json::Value(userMessage));
      return Success();
   }
   else
   {
      pResponse->setResult(spelling::spellingPrefsContextAsJson());
      return Success();
   }
}

} // anonymous namespace

core::json::Object spellingPrefsContextAsJson()
{
   using namespace core::spelling::hunspell;

   core::json::Object contextJson;

   DictionaryManager dictManager(options().hunspellDictionariesPath(),
                                 userDictionariesDir());

   std::vector<Dictionary> dictionaries;
   Error error = dictManager.availableLanguages(&dictionaries);
   if (error)
   {
      LOG_ERROR(error);
      return core::json::Object();
   }

   core::json::Array dictionariesJson;
   std::transform(dictionaries.begin(),
                  dictionaries.end(),
                  std::back_inserter(dictionariesJson),
                  dictionaryAsJson);

   // return json
   contextJson["all_languages_installed"] = dictManager.allLanguagesInstalled();
   contextJson["available_languages"] = dictionariesJson;
   return contextJson;
}

Error initialize()
{
   // register rs_ensureFileHidden with R
   R_CallMethodDef methodDef;

   methodDef.name = "rs_checkSpelling" ;
   methodDef.fun = (DL_FUNC) rs_checkSpelling ;
   methodDef.numArgs = 1;
   r::routines::addCallMethod(methodDef);

   // register rpc methods
   using boost::bind;
   using namespace module_context;
   ExecBlock initBlock ;
   initBlock.addFunctions()
      (bind(registerRpcMethod, "check_spelling", checkSpelling))
      (bind(registerRpcMethod, "suggestion_list", suggestionList))
      (bind(registerRpcMethod, "add_to_dictionary", addToDictionary))
      (bind(registerRpcMethod, "install_all_dictionaries", installAllDictionaries))
      (bind(sourceModuleRFile, "SessionSpelling.R"));
   return initBlock.execute();
}

} // namespace spelling
} // namespace modules
} // namesapce session

<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Razor - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2011 Razor team
 * Authors:
 *   Christian Surlykke <christian@surlykke.dk>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <razorqt/razorapplication.h>
#include "razortranslate.h"
#include "razorautosuspend.h"

#include <QMessageBox>

int main(int argc, char *argv[])
{

    RazorApplication a(argc, argv);

    TRANSLATE_APP;

    /*TrayIcon w;
    w.show();*/
    RazorAutosuspendd razorAutosuspendd;
    return a.exec();
}
<commit_msg>razor-autosuspend registers as dbus-service (org.razor-qt.razor-autosuspend) - fixes #346<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Razor - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2011 Razor team
 * Authors:
 *   Christian Surlykke <christian@surlykke.dk>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <QDBusConnection>
#include <QDebug>

#include <razorqt/razorapplication.h>
#include "razortranslate.h"
#include "razorautosuspend.h"

int main(int argc, char *argv[])
{

    RazorApplication a(argc, argv);

    TRANSLATE_APP;

    // To ensure only one instance of razor-autosuspend is running we register as a DBus service and refuse to run
    // if not able to do so.
    // We do not register any object as we don't have any dbus-operations to expose.g
    if (! QDBusConnection::sessionBus().registerService("org.razor-qt.razor-autosuspend"))
    {
        qWarning() << "Unable to register 'org.razor-qt.razor-autosuspend' service - is another instance of razor-autosuspend running?";
        return 1;
    }
    else
    {
        RazorAutosuspendd razorAutosuspendd;
        return a.exec();
    }
}
<|endoftext|>