<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2007      Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
// Copyright 2009      Jens-Michael Hoffmann <jensmh@gmx.de>
//

#include <KApplication>
#include <KLocale>
#include <KAboutData>
#include <KCmdLineArgs>
#include <KConfig>
#include <KConfigGroup>
#include <KGlobal>

#include <QtCore/QFile>

#include "ControlView.h"
#include "KdeMainWindow.h"
#include "MarbleDebug.h"

#include "MarbleTest.h"

#ifdef STATIC_BUILD
 #include <QtCore/QtPlugin>
 Q_IMPORT_PLUGIN(qjpeg)
 Q_IMPORT_PLUGIN(qsvg)
#endif

using namespace Marble;

// The GraphicsSystem needs to be set before the instantiation of the
// QApplication. Therefore we need to parse the current setting
// in this unusual place :-/

QString readGraphicsSystem( int argc, char *argv[], const KAboutData& aboutData )
{
    QCoreApplication app( argc, argv );
    KComponentData componentData( aboutData, KComponentData::SkipMainComponentRegistration );

    KConfigGroup viewGroup( componentData.config(), "View" );
    QString graphicsSystem = viewGroup.readEntry( "graphicsSystem", "NativeGraphics" );

    QString graphicsString( "native" );
    if ( graphicsSystem == QString( "RasterGraphics" ) ) {
        graphicsString = QString( "raster" );
    }
    if ( graphicsSystem == QString( "OpenGLGraphics" ) ) {
        graphicsString = QString( "opengl" );
    }

    return graphicsString;
}

int main ( int argc, char *argv[] )
{
    KAboutData aboutData( "marble", 0,
                          ki18n( "Marble Desktop Globe" ),
                          MARBLE_VERSION_STRING.toLatin1(),
                          ki18n( "A World Atlas." ),
                          KAboutData::License_LGPL, ki18n( "(c) 2007, 2008, 2009, 2010" ),
                          KLocalizedString(),
                          "http://edu.kde.org/marble" );

    // Active Development Team of Marble 0.10
    aboutData.addAuthor( ki18n( "Torsten Rahn" ),
                         ki18n( "Core Developer and Original Author" ),
                         "rahn@kde.org" );
    aboutData.addAuthor( ki18n( "Patrick Spendrin" ),
                         ki18n( "Core Developer: KML and Windows support" ),
                         "pspendrin@gmail.com" );
    aboutData.addAuthor( ki18n( "Jens-Michael Hoffmann" ),
                         ki18n( "OpenStreetMap Integration, OSM Namefinder, Download Management" ),
                         "jmho@c-xx.com", "http://www.c-xx.com" );
    aboutData.addAuthor( ki18n( "Henry de Valence" ),
                         ki18n( "Core Developer: Marble Runners, World-Clock Plasmoid" ),
                         "hdevalence@gmail.com" );
    aboutData.addAuthor( ki18n( "Bastian Holst" ),
                         ki18n( "Online Services support" ),
                         "bastianholst@gmx.de" );
    aboutData.addAuthor( ki18n( "Pino Toscano" ),
                         ki18n( "Network plugins" ),
                         "pino@kde.org" );
    aboutData.addAuthor( ki18n( "Harshit Jain" ),
                         ki18n( "Planet filter" ),
                         "sonu.itbhu@googlemail.com" );
    aboutData.addAuthor( ki18n( "Simon Edwards" ),
                         ki18n( "Marble Python Bindings" ),
                         "simon@simonzone.com" );
    aboutData.addAuthor( ki18n( "Dennis Nienhüser" ),
                         ki18n( "Navigator Float Item" ),
                         "earthwings@gentoo.org" );
    aboutData.addAuthor( ki18n( "Magnus Valle" ),
                         ki18n( "Historical Maps" ),
                         "" );
    aboutData.addAuthor( ki18n( "Médéric Boquien" ),
                         ki18n( "Astronomical Observatories" ),
                         "mboquien@free.fr" );
    aboutData.addAuthor( ki18n( "Eckhart Wörner" ),
                         ki18n( "Bugfixes" ),
                         "kde@ewsoftware.de" );

    // Google Summer of Code
    aboutData.addAuthor( ki18n( "Andrew Manson" ),
                         ki18n( "Google Summer of Code 2009 Project:"
                                " OSM Annotation" ),
                         "g.real.ate@gmail.com" );
    aboutData.addAuthor( ki18n( "Bastian Holst" ),
                         ki18n( "Google Summer of Code 2009 Project:"
                                " Online Services" ),
                         "bastianholst@gmx.de" );
    aboutData.addAuthor( ki18n( "Patrick Spendrin" ),
                         ki18n( "Google Summer of Code 2008 Project:"
                                " Vector Tiles for Marble" ),
                         "pspendrin@gmail.com" );
    aboutData.addAuthor( ki18n( "Shashank Singh" ),
                         ki18n( "Google Summer of Code 2008 Project:"
                                " Panoramio / Wikipedia -photo support for Marble" ),
                         "shashank.personal@gmail.com" );
    aboutData.addAuthor( ki18n( "Carlos Licea" ),
                         ki18n( "Google Summer of Code 2007 Project:"
                                " Equirectangular Projection (\"Flat Map\")" ),
                         "carlos.licea@kdemail.net" );
    aboutData.addAuthor( ki18n( "Andrew Manson" ),
                         ki18n( "Google Summer of Code 2007 Project:"
                                " GPS Support for Marble" ),
                         "g.real.ate@gmail.com" );
    aboutData.addAuthor( ki18n( "Murad Tagirov" ),
                         ki18n( "Google Summer of Code 2007 Project:"
                                " KML Support for Marble" ),
                         "tmurad@gmail.com" );

    // Developers
    aboutData.addAuthor( ki18n( "Inge Wallin" ),
                         ki18n( "Core Developer and Co-Maintainer" ),
                         "inge@lysator.liu.se" );
    aboutData.addAuthor( ki18n( "Simon Schmeisser" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Claudiu Covaci" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "David Roberts" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Nikolas Zimmermann" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Jan Becker" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Stefan Asserhäll" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Laurent Montel" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Prashanth Udupa" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Anne-Marie Mahfouf" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Josef Spillner" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Frerich Raabe" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Frederik Gladhorn" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Fredrik Höglund" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Albert Astals Cid" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Thomas Zander" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Joseph Wenninger" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Kris Thomsen" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Daniel Molkentin" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Tim Sutton" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Christian Ehrlicher" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Ralf Habacker" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Steffen Joeris" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Marcus Czeslinski" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Marcus D. Hanwell" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Chitlesh Goorah" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Nuno Pinheiro" ),
                         ki18n( "Artwork" ));
    aboutData.addAuthor( ki18n( "Torsten Rahn" ),
                         ki18n( "Artwork" ));

    // Credits
    aboutData.addCredit( ki18n( "Luis Silva" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Stefan Jordan" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Robert Scott" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Lubos Petrovic" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Benoit Sigoure" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Martin Konold" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Matthias Welwarsky" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Rainer Endres" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Ralf Gesellensetter" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Tim Alder" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "John Layt" ),
                         ki18n( "Special thanks for providing an"
                                " important source of inspiration by creating"
                                " Marble's predecessor \"Kartographer\"." ));

    QApplication::setGraphicsSystem( readGraphicsSystem( argc, argv, aboutData ) );

    KCmdLineArgs::init( argc, argv, &aboutData );

    // Autodetect profiles
    MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();

    KCmdLineOptions  options;
    options.add( "debug-info", ki18n( "Enable debug output" ) );
    options.add( "timedemo", ki18n( "Make a time measurement to check performance" ) );
    options.add( "gpsdemo", ki18n( "Check speed of gps drawing" ) );
    options.add( "fps", ki18n( "Show frame rate" ) );
    options.add( "enableCurrentLocation", ki18n( "Enable tab to show the current location" ) );
    options.add( "enableFileView",
                 ki18n( "Enable tab to see gpxFileView" ) );
    options.add( "tile-id", ki18n( "Show tile id's" ) );
    options.add( "marbledatapath \<data path>", ki18n( "Use a different directory which contains map data" ) );
    if( profiles & MarbleGlobal::SmallScreen ) {
        options.add( "nosmallscreen", ki18n( "Do not use the interface optimized for small screens" ) );
    }
    else {
        options.add( "smallscreen", ki18n( "Use the interface optimized for small screens" ) );
    }
    if( profiles & MarbleGlobal::HighResolution ) {
        options.add( "nohighresolution", ki18n( "Do not use the interface optimized for high resolutions" ) );
    }
    else {
        options.add( "highresolution", ki18n( "Use the interface optimized for high resolutions" ) );
    }
    options.add( "+[file]", ki18n( "One or more placemark files to be opened" ) );

    KCmdLineArgs::addCmdLineOptions( options );
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    KApplication app;
    KGlobal::locale()->insertCatalog( "marble_qt" );

    if ( args->isSet( "debug-info" ) ) {
        MarbleDebug::enable = true;
    } else {
        MarbleDebug::enable = false;
    }

    if ( args->isSet( "smallscreen" ) ) {
        profiles |= MarbleGlobal::SmallScreen;
    }
    else {
        profiles &= ~MarbleGlobal::SmallScreen;
    }

    if ( args->isSet( "highresolution" ) ) {
        profiles |= MarbleGlobal::HighResolution;
    }
    else {
        profiles &= ~MarbleGlobal::HighResolution;
    }

    MarbleGlobal::getInstance()->setProfiles( profiles );

    QString marbleDataPath = args->getOption( "marbledatapath" );
    if( marbleDataPath.isEmpty() ) {
        marbleDataPath = QString();
    }
    MainWindow *window = new MainWindow( marbleDataPath );
    window->setAttribute( Qt::WA_DeleteOnClose, true );
    window->show();

    if ( args->isSet( "timedemo" ) ) {
        window->resize(900, 640);
        MarbleTest test( window->marbleWidget() );
        test.timeDemo();
        return 0;
    }

    if ( args->isSet( "gpsdemo" ) ) {
        window->resize( 900, 640 );
        MarbleTest test( window->marbleWidget() );
        test.gpsDemo();
        return 0;
    }

    if ( args->isSet( "fps" ) ) {
        window->marbleControl()->marbleWidget()->setShowFrameRate( true );
    }

    if ( args->isSet( "enableCurrentLocation" ) ) {
        window->marbleControl()->setCurrentLocationTabShown( true );
    }

    if ( args->isSet( "enableFileView" ) ) {
        window->marbleControl()->setFileViewTabShown( true );
    }

    if ( args->isSet( "tile-id" ) ) {
	window->marbleControl()->marbleWidget()->setShowTileId( true );
    }

    // Read the files that are given on the command line.
    for ( int i = 0; i < args->count(); ++i ) {

        // FIXME: Use openUrl( args->url(i) ) instead?
        if ( QFile::exists( args->arg( i ) ) )
            window->marbleControl()->addPlacemarkFile( args->arg( i ) );
    }

    return app.exec();
}
<commit_msg>fix compiler warning<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2007      Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
// Copyright 2009      Jens-Michael Hoffmann <jensmh@gmx.de>
//

#include <KApplication>
#include <KLocale>
#include <KAboutData>
#include <KCmdLineArgs>
#include <KConfig>
#include <KConfigGroup>
#include <KGlobal>

#include <QtCore/QFile>

#include "ControlView.h"
#include "KdeMainWindow.h"
#include "MarbleDebug.h"

#include "MarbleTest.h"

#ifdef STATIC_BUILD
 #include <QtCore/QtPlugin>
 Q_IMPORT_PLUGIN(qjpeg)
 Q_IMPORT_PLUGIN(qsvg)
#endif

using namespace Marble;

// The GraphicsSystem needs to be set before the instantiation of the
// QApplication. Therefore we need to parse the current setting
// in this unusual place :-/

QString readGraphicsSystem( int argc, char *argv[], const KAboutData& aboutData )
{
    QCoreApplication app( argc, argv );
    KComponentData componentData( aboutData, KComponentData::SkipMainComponentRegistration );

    KConfigGroup viewGroup( componentData.config(), "View" );
    QString graphicsSystem = viewGroup.readEntry( "graphicsSystem", "NativeGraphics" );

    QString graphicsString( "native" );
    if ( graphicsSystem == QString( "RasterGraphics" ) ) {
        graphicsString = QString( "raster" );
    }
    if ( graphicsSystem == QString( "OpenGLGraphics" ) ) {
        graphicsString = QString( "opengl" );
    }

    return graphicsString;
}

int main ( int argc, char *argv[] )
{
    KAboutData aboutData( "marble", 0,
                          ki18n( "Marble Desktop Globe" ),
                          MARBLE_VERSION_STRING.toLatin1(),
                          ki18n( "A World Atlas." ),
                          KAboutData::License_LGPL, ki18n( "(c) 2007, 2008, 2009, 2010" ),
                          KLocalizedString(),
                          "http://edu.kde.org/marble" );

    // Active Development Team of Marble 0.10
    aboutData.addAuthor( ki18n( "Torsten Rahn" ),
                         ki18n( "Core Developer and Original Author" ),
                         "rahn@kde.org" );
    aboutData.addAuthor( ki18n( "Patrick Spendrin" ),
                         ki18n( "Core Developer: KML and Windows support" ),
                         "pspendrin@gmail.com" );
    aboutData.addAuthor( ki18n( "Jens-Michael Hoffmann" ),
                         ki18n( "OpenStreetMap Integration, OSM Namefinder, Download Management" ),
                         "jmho@c-xx.com", "http://www.c-xx.com" );
    aboutData.addAuthor( ki18n( "Henry de Valence" ),
                         ki18n( "Core Developer: Marble Runners, World-Clock Plasmoid" ),
                         "hdevalence@gmail.com" );
    aboutData.addAuthor( ki18n( "Bastian Holst" ),
                         ki18n( "Online Services support" ),
                         "bastianholst@gmx.de" );
    aboutData.addAuthor( ki18n( "Pino Toscano" ),
                         ki18n( "Network plugins" ),
                         "pino@kde.org" );
    aboutData.addAuthor( ki18n( "Harshit Jain" ),
                         ki18n( "Planet filter" ),
                         "sonu.itbhu@googlemail.com" );
    aboutData.addAuthor( ki18n( "Simon Edwards" ),
                         ki18n( "Marble Python Bindings" ),
                         "simon@simonzone.com" );
    aboutData.addAuthor( ki18n( "Dennis Nienhüser" ),
                         ki18n( "Navigator Float Item" ),
                         "earthwings@gentoo.org" );
    aboutData.addAuthor( ki18n( "Magnus Valle" ),
                         ki18n( "Historical Maps" ),
                         "" );
    aboutData.addAuthor( ki18n( "Médéric Boquien" ),
                         ki18n( "Astronomical Observatories" ),
                         "mboquien@free.fr" );
    aboutData.addAuthor( ki18n( "Eckhart Wörner" ),
                         ki18n( "Bugfixes" ),
                         "kde@ewsoftware.de" );

    // Google Summer of Code
    aboutData.addAuthor( ki18n( "Andrew Manson" ),
                         ki18n( "Google Summer of Code 2009 Project:"
                                " OSM Annotation" ),
                         "g.real.ate@gmail.com" );
    aboutData.addAuthor( ki18n( "Bastian Holst" ),
                         ki18n( "Google Summer of Code 2009 Project:"
                                " Online Services" ),
                         "bastianholst@gmx.de" );
    aboutData.addAuthor( ki18n( "Patrick Spendrin" ),
                         ki18n( "Google Summer of Code 2008 Project:"
                                " Vector Tiles for Marble" ),
                         "pspendrin@gmail.com" );
    aboutData.addAuthor( ki18n( "Shashank Singh" ),
                         ki18n( "Google Summer of Code 2008 Project:"
                                " Panoramio / Wikipedia -photo support for Marble" ),
                         "shashank.personal@gmail.com" );
    aboutData.addAuthor( ki18n( "Carlos Licea" ),
                         ki18n( "Google Summer of Code 2007 Project:"
                                " Equirectangular Projection (\"Flat Map\")" ),
                         "carlos.licea@kdemail.net" );
    aboutData.addAuthor( ki18n( "Andrew Manson" ),
                         ki18n( "Google Summer of Code 2007 Project:"
                                " GPS Support for Marble" ),
                         "g.real.ate@gmail.com" );
    aboutData.addAuthor( ki18n( "Murad Tagirov" ),
                         ki18n( "Google Summer of Code 2007 Project:"
                                " KML Support for Marble" ),
                         "tmurad@gmail.com" );

    // Developers
    aboutData.addAuthor( ki18n( "Inge Wallin" ),
                         ki18n( "Core Developer and Co-Maintainer" ),
                         "inge@lysator.liu.se" );
    aboutData.addAuthor( ki18n( "Simon Schmeisser" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Claudiu Covaci" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "David Roberts" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Nikolas Zimmermann" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Jan Becker" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Stefan Asserhäll" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Laurent Montel" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Prashanth Udupa" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Anne-Marie Mahfouf" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Josef Spillner" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Frerich Raabe" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Frederik Gladhorn" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Fredrik Höglund" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Albert Astals Cid" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Thomas Zander" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Joseph Wenninger" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Kris Thomsen" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Daniel Molkentin" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Tim Sutton" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Christian Ehrlicher" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Ralf Habacker" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Steffen Joeris" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Marcus Czeslinski" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Marcus D. Hanwell" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Chitlesh Goorah" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Nuno Pinheiro" ),
                         ki18n( "Artwork" ));
    aboutData.addAuthor( ki18n( "Torsten Rahn" ),
                         ki18n( "Artwork" ));

    // Credits
    aboutData.addCredit( ki18n( "Luis Silva" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Stefan Jordan" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Robert Scott" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Lubos Petrovic" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Benoit Sigoure" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Martin Konold" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Matthias Welwarsky" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Rainer Endres" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Ralf Gesellensetter" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Tim Alder" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "John Layt" ),
                         ki18n( "Special thanks for providing an"
                                " important source of inspiration by creating"
                                " Marble's predecessor \"Kartographer\"." ));

    QApplication::setGraphicsSystem( readGraphicsSystem( argc, argv, aboutData ) );

    KCmdLineArgs::init( argc, argv, &aboutData );

    // Autodetect profiles
    MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();

    KCmdLineOptions  options;
    options.add( "debug-info", ki18n( "Enable debug output" ) );
    options.add( "timedemo", ki18n( "Make a time measurement to check performance" ) );
    options.add( "gpsdemo", ki18n( "Check speed of gps drawing" ) );
    options.add( "fps", ki18n( "Show frame rate" ) );
    options.add( "enableCurrentLocation", ki18n( "Enable tab to show the current location" ) );
    options.add( "enableFileView",
                 ki18n( "Enable tab to see gpxFileView" ) );
    options.add( "tile-id", ki18n( "Show tile id's" ) );
    options.add( "marbledatapath <data path>", ki18n( "Use a different directory which contains map data" ) );
    if( profiles & MarbleGlobal::SmallScreen ) {
        options.add( "nosmallscreen", ki18n( "Do not use the interface optimized for small screens" ) );
    }
    else {
        options.add( "smallscreen", ki18n( "Use the interface optimized for small screens" ) );
    }
    if( profiles & MarbleGlobal::HighResolution ) {
        options.add( "nohighresolution", ki18n( "Do not use the interface optimized for high resolutions" ) );
    }
    else {
        options.add( "highresolution", ki18n( "Use the interface optimized for high resolutions" ) );
    }
    options.add( "+[file]", ki18n( "One or more placemark files to be opened" ) );

    KCmdLineArgs::addCmdLineOptions( options );
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    KApplication app;
    KGlobal::locale()->insertCatalog( "marble_qt" );

    if ( args->isSet( "debug-info" ) ) {
        MarbleDebug::enable = true;
    } else {
        MarbleDebug::enable = false;
    }

    if ( args->isSet( "smallscreen" ) ) {
        profiles |= MarbleGlobal::SmallScreen;
    }
    else {
        profiles &= ~MarbleGlobal::SmallScreen;
    }

    if ( args->isSet( "highresolution" ) ) {
        profiles |= MarbleGlobal::HighResolution;
    }
    else {
        profiles &= ~MarbleGlobal::HighResolution;
    }

    MarbleGlobal::getInstance()->setProfiles( profiles );

    QString marbleDataPath = args->getOption( "marbledatapath" );
    if( marbleDataPath.isEmpty() ) {
        marbleDataPath = QString();
    }
    MainWindow *window = new MainWindow( marbleDataPath );
    window->setAttribute( Qt::WA_DeleteOnClose, true );
    window->show();

    if ( args->isSet( "timedemo" ) ) {
        window->resize(900, 640);
        MarbleTest test( window->marbleWidget() );
        test.timeDemo();
        return 0;
    }

    if ( args->isSet( "gpsdemo" ) ) {
        window->resize( 900, 640 );
        MarbleTest test( window->marbleWidget() );
        test.gpsDemo();
        return 0;
    }

    if ( args->isSet( "fps" ) ) {
        window->marbleControl()->marbleWidget()->setShowFrameRate( true );
    }

    if ( args->isSet( "enableCurrentLocation" ) ) {
        window->marbleControl()->setCurrentLocationTabShown( true );
    }

    if ( args->isSet( "enableFileView" ) ) {
        window->marbleControl()->setFileViewTabShown( true );
    }

    if ( args->isSet( "tile-id" ) ) {
	window->marbleControl()->marbleWidget()->setShowTileId( true );
    }

    // Read the files that are given on the command line.
    for ( int i = 0; i < args->count(); ++i ) {

        // FIXME: Use openUrl( args->url(i) ) instead?
        if ( QFile::exists( args->arg( i ) ) )
            window->marbleControl()->addPlacemarkFile( args->arg( i ) );
    }

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


<commit_before>#ifndef STAN_MATH_REV_FUNCTOR_ODE_STORE_SENSITIVITIES_HPP
#define STAN_MATH_REV_FUNCTOR_ODE_STORE_SENSITIVITIES_HPP

#include <stan/math/prim/functor/ode_store_sensitivities.hpp>
#include <stan/math/rev/core.hpp>
#include <ostream>
#include <vector>

namespace stan {
namespace math {

/**
 * Build output vars for a state of the ODE solve, storing the sensitivities
 * precomputed using the forward sensitivity problem in precomputed varis.
 *
 * Any combination of y0, t0, ts, and any of the args arguments can have the
 * var scalar type.
 *
 * @tparam F Type of ODE right hand side
 * @tparam T_0 Type of initial time
 * @tparam T_ts Type of output times
 * @tparam T_Args Types of pass-through parameters
 *
 * @param f Right hand side of the ODE
 * @param coupled_state Current state of the coupled_ode_system
 * @param y0 Initial state
 * @param t0 Initial time
 * @param ts Times at which to solve the ODE at
 * @param[in, out] msgs the print stream for warning messages
 * @param args Extra arguments passed unmodified through to ODE right hand side
 * @return ODE state with scalar type var
 */
template <typename F, typename T_y0_t0, typename T_t0, typename T_t,
          typename... Args,
          typename
          = require_any_autodiff_t<T_y0_t0, T_t0, T_t, scalar_type_t<Args>...>>
Eigen::Matrix<var, Eigen::Dynamic, 1> ode_store_sensitivities(
    const F& f, const Eigen::VectorXd& coupled_state,
    const Eigen::Matrix<T_y0_t0, Eigen::Dynamic, 1>& y0, const T_t0& t0,
    const T_t& t, std::ostream* msgs, const Args&... args) {
  const size_t N = y0.size();
  const size_t y0_vars = count_vars(y0);
  const size_t args_vars = count_vars(args...);
  const size_t t0_vars = count_vars(t0);
  const size_t t_vars = count_vars(t);
  Eigen::Matrix<var, Eigen::Dynamic, 1> yt(N);

  Eigen::VectorXd y = coupled_state.head(N);

  Eigen::VectorXd f_y_t;
  if (is_var<T_t>::value)
    f_y_t = f(value_of(t), y, msgs, value_of(args)...);

  Eigen::VectorXd f_y0_t0;
  if (is_var<T_t0>::value)
    f_y0_t0 = f(value_of(t0), value_of(y0), msgs, value_of(args)...);

  for (size_t j = 0; j < N; j++) {
    const size_t total_vars = y0_vars + args_vars + t0_vars + t_vars;

    vari** varis
        = ChainableStack::instance_->memalloc_.alloc_array<vari*>(total_vars);
    double* partials
        = ChainableStack::instance_->memalloc_.alloc_array<double>(total_vars);

    vari** varis_ptr = varis;
    double* partials_ptr = partials;

    // iterate over parameters for each equation
    varis_ptr = save_varis(varis_ptr, y0);
    for (std::size_t k = 0; k < y0_vars; ++k) {
      //*varis_ptr = y0[k].vi_;
      *partials_ptr = coupled_state(N + y0_vars * k + j);
      partials_ptr++;
    }

    varis_ptr = save_varis(varis_ptr, args...);
    for (std::size_t k = 0; k < args_vars; ++k) {
      // dy[j]_dtheta[k]
      // theta[k].vi_
      *partials_ptr = coupled_state(N + N * y0_vars + N * k + j);
      partials_ptr++;
    }

    varis_ptr = save_varis(varis_ptr, t0);
    if (t0_vars > 0) {
      double dyt_dt0 = 0.0;
      for (std::size_t k = 0; k < y0_vars; ++k) {
        // dy[j]_dtheta[k]
        // theta[k].vi_
        dyt_dt0 += -f_y0_t0[k] * coupled_state(N + y0_vars * k + j);
      }
      *partials_ptr = dyt_dt0;
      partials_ptr++;
    }

    varis_ptr = save_varis(varis_ptr, t);
    if (t_vars > 0) {
      *partials_ptr = f_y_t[j];
      partials_ptr++;
    }

    yt(j) = new precomputed_gradients_vari(y(j), total_vars, varis, partials);
  }

  return yt;
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>Added eval statement to handle `value_of` expressions (design-doc #19)<commit_after>#ifndef STAN_MATH_REV_FUNCTOR_ODE_STORE_SENSITIVITIES_HPP
#define STAN_MATH_REV_FUNCTOR_ODE_STORE_SENSITIVITIES_HPP

#include <stan/math/prim/functor/ode_store_sensitivities.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/meta.hpp>
#include <ostream>
#include <vector>

namespace stan {
namespace math {

/**
 * Build output vars for a state of the ODE solve, storing the sensitivities
 * precomputed using the forward sensitivity problem in precomputed varis.
 *
 * Any combination of y0, t0, ts, and any of the args arguments can have the
 * var scalar type.
 *
 * @tparam F Type of ODE right hand side
 * @tparam T_0 Type of initial time
 * @tparam T_ts Type of output times
 * @tparam T_Args Types of pass-through parameters
 *
 * @param f Right hand side of the ODE
 * @param coupled_state Current state of the coupled_ode_system
 * @param y0 Initial state
 * @param t0 Initial time
 * @param ts Times at which to solve the ODE at
 * @param[in, out] msgs the print stream for warning messages
 * @param args Extra arguments passed unmodified through to ODE right hand side
 * @return ODE state with scalar type var
 */
template <typename F, typename T_y0_t0, typename T_t0, typename T_t,
          typename... Args,
          require_any_autodiff_t<T_y0_t0, T_t0, T_t, scalar_type_t<Args>...>* = nullptr>
Eigen::Matrix<var, Eigen::Dynamic, 1> ode_store_sensitivities(
    const F& f, const Eigen::VectorXd& coupled_state,
    const Eigen::Matrix<T_y0_t0, Eigen::Dynamic, 1>& y0, const T_t0& t0,
    const T_t& t, std::ostream* msgs, const Args&... args) {
  const size_t N = y0.size();
  const size_t y0_vars = count_vars(y0);
  const size_t args_vars = count_vars(args...);
  const size_t t0_vars = count_vars(t0);
  const size_t t_vars = count_vars(t);
  Eigen::Matrix<var, Eigen::Dynamic, 1> yt(N);

  Eigen::VectorXd y = coupled_state.head(N);

  Eigen::VectorXd f_y_t;
  if (is_var<T_t>::value)
    f_y_t = f(value_of(t), y, msgs, value_of(args)...);

  Eigen::VectorXd f_y0_t0;
  if (is_var<T_t0>::value)
    f_y0_t0 = f(value_of(t0), value_of(y0).eval(), msgs, value_of(args)...);

  for (size_t j = 0; j < N; j++) {
    const size_t total_vars = y0_vars + args_vars + t0_vars + t_vars;

    vari** varis
        = ChainableStack::instance_->memalloc_.alloc_array<vari*>(total_vars);
    double* partials
        = ChainableStack::instance_->memalloc_.alloc_array<double>(total_vars);

    vari** varis_ptr = varis;
    double* partials_ptr = partials;

    // iterate over parameters for each equation
    varis_ptr = save_varis(varis_ptr, y0);
    for (std::size_t k = 0; k < y0_vars; ++k) {
      //*varis_ptr = y0[k].vi_;
      *partials_ptr = coupled_state(N + y0_vars * k + j);
      partials_ptr++;
    }

    varis_ptr = save_varis(varis_ptr, args...);
    for (std::size_t k = 0; k < args_vars; ++k) {
      // dy[j]_dtheta[k]
      // theta[k].vi_
      *partials_ptr = coupled_state(N + N * y0_vars + N * k + j);
      partials_ptr++;
    }

    varis_ptr = save_varis(varis_ptr, t0);
    if (t0_vars > 0) {
      double dyt_dt0 = 0.0;
      for (std::size_t k = 0; k < y0_vars; ++k) {
        // dy[j]_dtheta[k]
        // theta[k].vi_
        dyt_dt0 += -f_y0_t0[k] * coupled_state(N + y0_vars * k + j);
      }
      *partials_ptr = dyt_dt0;
      partials_ptr++;
    }

    varis_ptr = save_varis(varis_ptr, t);
    if (t_vars > 0) {
      *partials_ptr = f_y_t[j];
      partials_ptr++;
    }

    yt(j) = new precomputed_gradients_vari(y(j), total_vars, varis, partials);
  }

  return yt;
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#ifdef __ANDROID__
#include <android/log.h>
#endif//__ANDROID__

#include "logging.h"

ELogLevel Logging::global_level = LOGLEVEL_ERROR;
FILE* Logging::log_stream = nullptr;

#ifdef __ANDROID__
#define print_func(...) __android_log_print(ANDROID_LOG_INFO, "SeriousProton", __VA_ARGS__)
#else
#define print_func(...) fprintf(Logging::log_stream, __VA_ARGS__)
#endif

Logging::Logging(ELogLevel level, string file, int line, string function_name)
{
    do_logging = level >= global_level;

    if (do_logging)
    {
        if (log_stream == nullptr)
            log_stream = stderr;
        switch(level)
        {
        case LOGLEVEL_DEBUG:
            print_func("[DEBUG] ");
            break;
        case LOGLEVEL_INFO:
            print_func("[INFO]  ");
            break;
        case LOGLEVEL_WARNING:
            print_func("[WARN]  ");
            break;
        case LOGLEVEL_ERROR:
            print_func("[ERROR] ");
            break;
        }
    }
}

Logging::~Logging()
{
    if (do_logging)
        print_func("\n");
}

const Logging& operator<<(const Logging& log, const char* str)
{
    if (log.do_logging)
        print_func("%s", str);
    return log;
}

void Logging::setLogLevel(ELogLevel level)
{
    global_level = level;
}

void Logging::setLogFile(string filename)
{
    log_stream = fopen(filename.c_str(), "wt");
}
<commit_msg>Don't buffer logs on Win32<commit_after>#include <stdio.h>
#ifdef __ANDROID__
#include <android/log.h>
#endif//__ANDROID__

#include "logging.h"

ELogLevel Logging::global_level = LOGLEVEL_ERROR;
FILE* Logging::log_stream = nullptr;

#ifdef __ANDROID__
#define print_func(...) __android_log_print(ANDROID_LOG_INFO, "SeriousProton", __VA_ARGS__)
#else
#define print_func(...) fprintf(Logging::log_stream, __VA_ARGS__)
#endif

Logging::Logging(ELogLevel level, string file, int line, string function_name)
{
    do_logging = level >= global_level;

    if (do_logging)
    {
        if (log_stream == nullptr)
            log_stream = stderr;
        switch(level)
        {
        case LOGLEVEL_DEBUG:
            print_func("[DEBUG] ");
            break;
        case LOGLEVEL_INFO:
            print_func("[INFO]  ");
            break;
        case LOGLEVEL_WARNING:
            print_func("[WARN]  ");
            break;
        case LOGLEVEL_ERROR:
            print_func("[ERROR] ");
            break;
        }
    }
}

Logging::~Logging()
{
    if (do_logging)
        print_func("\n");
}

const Logging& operator<<(const Logging& log, const char* str)
{
    if (log.do_logging)
        print_func("%s", str);
    return log;
}

void Logging::setLogLevel(ELogLevel level)
{
    global_level = level;
}

void Logging::setLogFile(string filename)
{
    log_stream = fopen(filename.c_str(), "wt");
    #ifdef __WIN32__
    // win32 doesn't support line buffering. #1042
    // Instead, don't buffer logging at all on Windows.
    setvbuf(log_stream, NULL, _IONBF, 0);
    #endif//__WIN32__
}
<|endoftext|>


<commit_before>#include "manager.h"
#include "capturer.h"
#include "corrector.h"
#include "debug.h"
#include "recognizer.h"
#include "representer.h"
#include "settingseditor.h"
#include "task.h"
#include "translator.h"
#include "trayicon.h"
#include "updates.h"

#include <QApplication>
#include <QDesktopServices>
#include <QFileInfo>
#include <QMessageBox>
#include <QNetworkProxy>
#include <QThread>

namespace
{
#ifdef DEVELOP
const auto updatesUrl = "http://localhost:8081/updates.json";
#else
const auto updatesUrl =
    "https://raw.githubusercontent.com/OneMoreGres/ScreenTranslator/master/"
    "updates.json";
#endif
}  // namespace

Manager::Manager()
  : settings_(std::make_unique<Settings>())
  , updater_(std::make_unique<update::Loader>(QUrl(updatesUrl)))
  , updateAutoChecker_(std::make_unique<update::AutoChecker>(*updater_))
  , models_(std::make_unique<CommonModels>())
{
  SOFT_ASSERT(settings_, return );

  tray_ = std::make_unique<TrayIcon>(*this, *settings_);
  capturer_ = std::make_unique<Capturer>(*this, *settings_, *models_);
  recognizer_ = std::make_unique<Recognizer>(*this, *settings_);
  translator_ = std::make_unique<Translator>(*this, *settings_);
  corrector_ = std::make_unique<Corrector>(*this, *settings_);
  representer_ =
      std::make_unique<Representer>(*this, *tray_, *settings_, *models_);
  qRegisterMetaType<TaskPtr>();

  settings_->load();
  updateSettings();

  if (settings_->showMessageOnStart)
    tray_->showInformation(QObject::tr("Screen translator started"));

  warnIfOutdated();

  QObject::connect(updater_.get(), &update::Loader::error,  //
                   tray_.get(), &TrayIcon::showError);
  QObject::connect(updater_.get(), &update::Loader::updated,  //
                   tray_.get(), [this] {
                     tray_->showInformation(QObject::tr("Update completed"));
                   });
  QObject::connect(updater_.get(), &update::Loader::updatesAvailable,  //
                   tray_.get(), [this] {
                     tray_->showInformation(QObject::tr("Updates available"));
                   });
}

Manager::~Manager()
{
  SOFT_ASSERT(settings_, return );
  if (updateAutoChecker_ && updateAutoChecker_->isLastCheckDateChanged()) {
    settings_->lastUpdateCheck = updateAutoChecker_->lastCheckDate();
    settings_->saveLastUpdateCheck();
  }
  setupTrace(false);
}

void Manager::warnIfOutdated()
{
  const auto now = QDateTime::currentDateTime();
  const auto binaryInfo = QFileInfo(QApplication::applicationFilePath());
  const auto date = binaryInfo.fileTime(QFile::FileTime::FileBirthTime);
  const auto deadlineDays = 90;
  if (date.daysTo(now) < deadlineDays)
    return;
  const auto updateDate = settings_->lastUpdateCheck;
  if (updateDate.isValid() && updateDate.daysTo(now) < deadlineDays)
    return;
  tray_->showInformation(
      QObject::tr("Current version might be outdated.\n"
                  "Check for updates to silence this warning"));
}

void Manager::updateSettings()
{
  LTRACE() << "updateSettings";
  SOFT_ASSERT(settings_, return );
  setupTrace(settings_->writeTrace);
  setupProxy(*settings_);
  setupUpdates(*settings_);

  models_->update(settings_->tessdataPath);

  tray_->updateSettings();
  capturer_->updateSettings();
  recognizer_->updateSettings();
  translator_->updateSettings();
  representer_->updateSettings();

  tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked());
}

void Manager::setupProxy(const Settings &settings)
{
  if (settings.proxyType == ProxyType::System) {
    QNetworkProxyFactory::setUseSystemConfiguration(true);
    return;
  }

  QNetworkProxyFactory::setUseSystemConfiguration(false);

  if (settings.proxyType == ProxyType::Disabled) {
    QNetworkProxy::setApplicationProxy({});
    return;
  }

  QNetworkProxy proxy;
  using T = QNetworkProxy::ProxyType;
  proxy.setType(settings.proxyType == ProxyType::Socks5 ? T::Socks5Proxy
                                                        : T::HttpProxy);
  proxy.setHostName(settings.proxyHostName);
  proxy.setPort(settings.proxyPort);
  proxy.setUser(settings.proxyUser);
  proxy.setPassword(settings.proxyPassword);
  QNetworkProxy::setApplicationProxy(proxy);
}

void Manager::setupUpdates(const Settings &settings)
{
  updater_->model()->setExpansions({
      {"$translators$", settings.translatorsDir},
      {"$tessdata$", settings.tessdataPath},
  });

  SOFT_ASSERT(updateAutoChecker_, return );
  updateAutoChecker_->setLastCheckDate(settings.lastUpdateCheck);
  updateAutoChecker_->setCheckIntervalDays(settings.autoUpdateIntervalDays);
}

void Manager::setupTrace(bool isOn)
{
  const auto oldFile = debug::traceFileName();

  if (!isOn) {
    debug::setTraceFileName({});
    debug::isTrace = false;

    if (!oldFile.isEmpty())
      QDesktopServices::openUrl(QUrl::fromLocalFile(oldFile));

    return;
  }

  if (!oldFile.isEmpty())
    return;

  const auto traceFile =
      QStandardPaths::writableLocation(QStandardPaths::TempLocation) +
      QLatin1String("/multidir-") +
      QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss");

  if (!debug::setTraceFileName(traceFile)) {
    QMessageBox::warning(
        nullptr, {},
        QObject::tr("Failed to setup log to file: %1").arg(traceFile));
    return;
  }

  debug::isTrace = true;
  QMessageBox::information(
      nullptr, {}, QObject::tr("Started logging to file: %1").arg(traceFile));
}

void Manager::finishTask(const TaskPtr &task)
{
  SOFT_ASSERT(task, return );
  LTRACE() << "finishTask" << task->captured << task->error;

  --activeTaskCount_;
  tray_->setActiveTaskCount(activeTaskCount_);

  if (!task->isValid()) {
    tray_->showError(task->error);
    tray_->setTaskActionsEnabled(false);
    return;
  }

  tray_->showSuccess();
}

void Manager::captured(const TaskPtr &task)
{
  tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked());
  tray_->blockActions(false);

  SOFT_ASSERT(task, return );
  LTRACE() << "captured" << task->captured << task->error;

  ++activeTaskCount_;
  tray_->setActiveTaskCount(activeTaskCount_);

  if (!task->isValid()) {
    finishTask(task);
    return;
  }

  recognizer_->recognize(task);
}

void Manager::captureCanceled()
{
  tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked());
  tray_->blockActions(false);
}

void Manager::recognized(const TaskPtr &task)
{
  SOFT_ASSERT(task, return );
  LTRACE() << "recognized" << task->recognized << task->error;

  if (!task->isValid()) {
    finishTask(task);
    return;
  }

  corrector_->correct(task);
}

void Manager::corrected(const TaskPtr &task)
{
  SOFT_ASSERT(task, return );
  LTRACE() << "corrected" << task->recognized << task->error;

  if (!task->isValid()) {
    finishTask(task);
    return;
  }

  if (!task->targetLanguage.isEmpty())
    translator_->translate(task);
  else
    translated(task);
}

void Manager::translated(const TaskPtr &task)
{
  SOFT_ASSERT(task, return );
  LTRACE() << "translated" << task->recognized << task->error;

  finishTask(task);

  representer_->represent(task);
  tray_->setTaskActionsEnabled(!task->isNull());
}

void Manager::applySettings(const Settings &settings)
{
  SOFT_ASSERT(settings_, return );
  const auto lastUpdate = settings_->lastUpdateCheck;  // not handled in editor

  *settings_ = settings;

  settings_->lastUpdateCheck = lastUpdate;

  settings_->save();
  updateSettings();
}

void Manager::fatalError(const QString &text)
{
  tray_->blockActions(false);
  tray_->showFatalError(text);
}

void Manager::capture()
{
  SOFT_ASSERT(capturer_, return );
  tray_->blockActions(true);
  capturer_->capture();
  tray_->setRepeatCaptureEnabled(true);
}

void Manager::repeatCapture()
{
  SOFT_ASSERT(capturer_, return );
  tray_->blockActions(true);
  capturer_->repeatCapture();
}

void Manager::captureLocked()
{
  SOFT_ASSERT(capturer_, return );

  if (representer_->isVisible()) {
    representer_->hide();
    QThread::usleep(300'000);
  }

  capturer_->captureLocked();
}

void Manager::settings()
{
  SettingsEditor editor(*this, *updater_);

  SOFT_ASSERT(settings_, return );
  editor.setSettings(*settings_);

  tray_->blockActions(true);
  auto result = editor.exec();
  tray_->blockActions(false);

  if (result != QDialog::Accepted)
    return;

  tray_->resetFatalError();

  const auto edited = editor.settings();
  applySettings(edited);
}

void Manager::showLast()
{
  SOFT_ASSERT(representer_, return );
  representer_->showLast();
}

void Manager::showTranslator()
{
  SOFT_ASSERT(translator_, return );
  translator_->show();
}

void Manager::copyLastToClipboard()
{
  SOFT_ASSERT(representer_, return );
  representer_->clipboardLast();
}

void Manager::quit()
{
  QApplication::quit();
}
<commit_msg>Hide result before capture<commit_after>#include "manager.h"
#include "capturer.h"
#include "corrector.h"
#include "debug.h"
#include "recognizer.h"
#include "representer.h"
#include "settingseditor.h"
#include "task.h"
#include "translator.h"
#include "trayicon.h"
#include "updates.h"

#include <QApplication>
#include <QDesktopServices>
#include <QFileInfo>
#include <QMessageBox>
#include <QNetworkProxy>
#include <QThread>

namespace
{
#ifdef DEVELOP
const auto updatesUrl = "http://localhost:8081/updates.json";
#else
const auto updatesUrl =
    "https://raw.githubusercontent.com/OneMoreGres/ScreenTranslator/master/"
    "updates.json";
#endif
const auto resultHideWaitUs = 300'000;
}  // namespace

Manager::Manager()
  : settings_(std::make_unique<Settings>())
  , updater_(std::make_unique<update::Loader>(QUrl(updatesUrl)))
  , updateAutoChecker_(std::make_unique<update::AutoChecker>(*updater_))
  , models_(std::make_unique<CommonModels>())
{
  SOFT_ASSERT(settings_, return );

  tray_ = std::make_unique<TrayIcon>(*this, *settings_);
  capturer_ = std::make_unique<Capturer>(*this, *settings_, *models_);
  recognizer_ = std::make_unique<Recognizer>(*this, *settings_);
  translator_ = std::make_unique<Translator>(*this, *settings_);
  corrector_ = std::make_unique<Corrector>(*this, *settings_);
  representer_ =
      std::make_unique<Representer>(*this, *tray_, *settings_, *models_);
  qRegisterMetaType<TaskPtr>();

  settings_->load();
  updateSettings();

  if (settings_->showMessageOnStart)
    tray_->showInformation(QObject::tr("Screen translator started"));

  warnIfOutdated();

  QObject::connect(updater_.get(), &update::Loader::error,  //
                   tray_.get(), &TrayIcon::showError);
  QObject::connect(updater_.get(), &update::Loader::updated,  //
                   tray_.get(), [this] {
                     tray_->showInformation(QObject::tr("Update completed"));
                   });
  QObject::connect(updater_.get(), &update::Loader::updatesAvailable,  //
                   tray_.get(), [this] {
                     tray_->showInformation(QObject::tr("Updates available"));
                   });
}

Manager::~Manager()
{
  SOFT_ASSERT(settings_, return );
  if (updateAutoChecker_ && updateAutoChecker_->isLastCheckDateChanged()) {
    settings_->lastUpdateCheck = updateAutoChecker_->lastCheckDate();
    settings_->saveLastUpdateCheck();
  }
  setupTrace(false);
}

void Manager::warnIfOutdated()
{
  const auto now = QDateTime::currentDateTime();
  const auto binaryInfo = QFileInfo(QApplication::applicationFilePath());
  const auto date = binaryInfo.fileTime(QFile::FileTime::FileBirthTime);
  const auto deadlineDays = 90;
  if (date.daysTo(now) < deadlineDays)
    return;
  const auto updateDate = settings_->lastUpdateCheck;
  if (updateDate.isValid() && updateDate.daysTo(now) < deadlineDays)
    return;
  tray_->showInformation(
      QObject::tr("Current version might be outdated.\n"
                  "Check for updates to silence this warning"));
}

void Manager::updateSettings()
{
  LTRACE() << "updateSettings";
  SOFT_ASSERT(settings_, return );
  setupTrace(settings_->writeTrace);
  setupProxy(*settings_);
  setupUpdates(*settings_);

  models_->update(settings_->tessdataPath);

  tray_->updateSettings();
  capturer_->updateSettings();
  recognizer_->updateSettings();
  translator_->updateSettings();
  representer_->updateSettings();

  tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked());
}

void Manager::setupProxy(const Settings &settings)
{
  if (settings.proxyType == ProxyType::System) {
    QNetworkProxyFactory::setUseSystemConfiguration(true);
    return;
  }

  QNetworkProxyFactory::setUseSystemConfiguration(false);

  if (settings.proxyType == ProxyType::Disabled) {
    QNetworkProxy::setApplicationProxy({});
    return;
  }

  QNetworkProxy proxy;
  using T = QNetworkProxy::ProxyType;
  proxy.setType(settings.proxyType == ProxyType::Socks5 ? T::Socks5Proxy
                                                        : T::HttpProxy);
  proxy.setHostName(settings.proxyHostName);
  proxy.setPort(settings.proxyPort);
  proxy.setUser(settings.proxyUser);
  proxy.setPassword(settings.proxyPassword);
  QNetworkProxy::setApplicationProxy(proxy);
}

void Manager::setupUpdates(const Settings &settings)
{
  updater_->model()->setExpansions({
      {"$translators$", settings.translatorsDir},
      {"$tessdata$", settings.tessdataPath},
  });

  SOFT_ASSERT(updateAutoChecker_, return );
  updateAutoChecker_->setLastCheckDate(settings.lastUpdateCheck);
  updateAutoChecker_->setCheckIntervalDays(settings.autoUpdateIntervalDays);
}

void Manager::setupTrace(bool isOn)
{
  const auto oldFile = debug::traceFileName();

  if (!isOn) {
    debug::setTraceFileName({});
    debug::isTrace = false;

    if (!oldFile.isEmpty())
      QDesktopServices::openUrl(QUrl::fromLocalFile(oldFile));

    return;
  }

  if (!oldFile.isEmpty())
    return;

  const auto traceFile =
      QStandardPaths::writableLocation(QStandardPaths::TempLocation) +
      QLatin1String("/multidir-") +
      QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss");

  if (!debug::setTraceFileName(traceFile)) {
    QMessageBox::warning(
        nullptr, {},
        QObject::tr("Failed to setup log to file: %1").arg(traceFile));
    return;
  }

  debug::isTrace = true;
  QMessageBox::information(
      nullptr, {}, QObject::tr("Started logging to file: %1").arg(traceFile));
}

void Manager::finishTask(const TaskPtr &task)
{
  SOFT_ASSERT(task, return );
  LTRACE() << "finishTask" << task->captured << task->error;

  --activeTaskCount_;
  tray_->setActiveTaskCount(activeTaskCount_);

  if (!task->isValid()) {
    tray_->showError(task->error);
    tray_->setTaskActionsEnabled(false);
    return;
  }

  tray_->showSuccess();
}

void Manager::captured(const TaskPtr &task)
{
  tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked());
  tray_->blockActions(false);

  SOFT_ASSERT(task, return );
  LTRACE() << "captured" << task->captured << task->error;

  ++activeTaskCount_;
  tray_->setActiveTaskCount(activeTaskCount_);

  if (!task->isValid()) {
    finishTask(task);
    return;
  }

  recognizer_->recognize(task);
}

void Manager::captureCanceled()
{
  tray_->setCaptureLockedEnabled(capturer_->canCaptureLocked());
  tray_->blockActions(false);
}

void Manager::recognized(const TaskPtr &task)
{
  SOFT_ASSERT(task, return );
  LTRACE() << "recognized" << task->recognized << task->error;

  if (!task->isValid()) {
    finishTask(task);
    return;
  }

  corrector_->correct(task);
}

void Manager::corrected(const TaskPtr &task)
{
  SOFT_ASSERT(task, return );
  LTRACE() << "corrected" << task->recognized << task->error;

  if (!task->isValid()) {
    finishTask(task);
    return;
  }

  if (!task->targetLanguage.isEmpty())
    translator_->translate(task);
  else
    translated(task);
}

void Manager::translated(const TaskPtr &task)
{
  SOFT_ASSERT(task, return );
  LTRACE() << "translated" << task->recognized << task->error;

  finishTask(task);

  representer_->represent(task);
  tray_->setTaskActionsEnabled(!task->isNull());
}

void Manager::applySettings(const Settings &settings)
{
  SOFT_ASSERT(settings_, return );
  const auto lastUpdate = settings_->lastUpdateCheck;  // not handled in editor

  *settings_ = settings;

  settings_->lastUpdateCheck = lastUpdate;

  settings_->save();
  updateSettings();
}

void Manager::fatalError(const QString &text)
{
  tray_->blockActions(false);
  tray_->showFatalError(text);
}

void Manager::capture()
{
  SOFT_ASSERT(capturer_, return );

  tray_->blockActions(true);

  if (representer_->isVisible()) {
    representer_->hide();
    QThread::usleep(resultHideWaitUs);
  }

  capturer_->capture();
  tray_->setRepeatCaptureEnabled(true);
}

void Manager::repeatCapture()
{
  SOFT_ASSERT(capturer_, return );
  tray_->blockActions(true);
  capturer_->repeatCapture();
}

void Manager::captureLocked()
{
  SOFT_ASSERT(capturer_, return );

  if (representer_->isVisible()) {
    representer_->hide();
    QThread::usleep(resultHideWaitUs);
  }

  capturer_->captureLocked();
}

void Manager::settings()
{
  SettingsEditor editor(*this, *updater_);

  SOFT_ASSERT(settings_, return );
  editor.setSettings(*settings_);

  tray_->blockActions(true);
  auto result = editor.exec();
  tray_->blockActions(false);

  if (result != QDialog::Accepted)
    return;

  tray_->resetFatalError();

  const auto edited = editor.settings();
  applySettings(edited);
}

void Manager::showLast()
{
  SOFT_ASSERT(representer_, return );
  representer_->showLast();
}

void Manager::showTranslator()
{
  SOFT_ASSERT(translator_, return );
  translator_->show();
}

void Manager::copyLastToClipboard()
{
  SOFT_ASSERT(representer_, return );
  representer_->clipboardLast();
}

void Manager::quit()
{
  QApplication::quit();
}
<|endoftext|>


<commit_before>#ifndef optional_hh_INCLUDED
#define optional_hh_INCLUDED

namespace Kakoune
{

template<typename T>
struct Optional
{
public:
    constexpr Optional() : m_valid(false) {}
    Optional(const T& other) : m_valid(true) { new (&m_value) T(other); }
    Optional(T&& other) : m_valid(true) { new (&m_value) T(std::move(other)); }

    Optional(const Optional& other)
        : m_valid(other.m_valid)
    {
        if (m_valid)
            new (&m_value) T(other.m_value);
    }

    Optional(Optional&& other)
        noexcept(noexcept(new (nullptr) T(std::move(other.m_value))))
        : m_valid(other.m_valid)
    {
        if (m_valid)
            new (&m_value) T(std::move(other.m_value));
    }

    Optional& operator=(const Optional& other)
    {
        destruct_ifn();
        if ((m_valid = other.m_valid))
            new (&m_value) T(other.m_value);
        return *this;
    }

    Optional& operator=(Optional&& other)
    {
        destruct_ifn();
        if ((m_valid = other.m_valid))
            new (&m_value) T(std::move(other.m_value));
        return *this;
    }

    ~Optional() { destruct_ifn(); }

    constexpr explicit operator bool() const noexcept { return m_valid; }

    bool operator==(const Optional& other) const
    {
        if (m_valid == other.m_valid)
        {
            if (m_valid)
                return m_value == other.m_value;
            return true;
        }
        return false;
    }

    T& operator*()
    {
        kak_assert(m_valid);
        return m_value;
    }
    const T& operator*() const { return *const_cast<Optional&>(*this); }

    T* operator->()
    {
        kak_assert(m_valid);
        return &m_value;
    }
    const T* operator->() const { return const_cast<Optional&>(*this).operator->(); }

    template<typename U>
    T value_or(U&& fallback) const { return m_valid ? m_value : T{fallback}; }

private:
    void destruct_ifn() { if (m_valid) m_value.~T(); }

    bool m_valid;
    union { T m_value; };
};

}

#endif // optional_hh_INCLUDED
<commit_msg>Optional: put the bool m_valid after the content to improve packing<commit_after>#ifndef optional_hh_INCLUDED
#define optional_hh_INCLUDED

namespace Kakoune
{

template<typename T>
struct Optional
{
public:
    constexpr Optional() : m_valid(false) {}
    Optional(const T& other) : m_valid(true) { new (&m_value) T(other); }
    Optional(T&& other) : m_valid(true) { new (&m_value) T(std::move(other)); }

    Optional(const Optional& other)
        : m_valid(other.m_valid)
    {
        if (m_valid)
            new (&m_value) T(other.m_value);
    }

    Optional(Optional&& other)
        noexcept(noexcept(new (nullptr) T(std::move(other.m_value))))
        : m_valid(other.m_valid)
    {
        if (m_valid)
            new (&m_value) T(std::move(other.m_value));
    }

    Optional& operator=(const Optional& other)
    {
        destruct_ifn();
        if ((m_valid = other.m_valid))
            new (&m_value) T(other.m_value);
        return *this;
    }

    Optional& operator=(Optional&& other)
    {
        destruct_ifn();
        if ((m_valid = other.m_valid))
            new (&m_value) T(std::move(other.m_value));
        return *this;
    }

    ~Optional() { destruct_ifn(); }

    constexpr explicit operator bool() const noexcept { return m_valid; }

    bool operator==(const Optional& other) const
    {
        if (m_valid == other.m_valid)
        {
            if (m_valid)
                return m_value == other.m_value;
            return true;
        }
        return false;
    }

    T& operator*()
    {
        kak_assert(m_valid);
        return m_value;
    }
    const T& operator*() const { return *const_cast<Optional&>(*this); }

    T* operator->()
    {
        kak_assert(m_valid);
        return &m_value;
    }
    const T* operator->() const { return const_cast<Optional&>(*this).operator->(); }

    template<typename U>
    T value_or(U&& fallback) const { return m_valid ? m_value : T{fallback}; }

private:
    void destruct_ifn() { if (m_valid) m_value.~T(); }

    union { T m_value; };
    bool m_valid;
};

}

#endif // optional_hh_INCLUDED
<|endoftext|>


<commit_before>#include <DrogonControlInterfaceLibrary.h>

using namespace std;

void fillMap(map<string, double> &goal, string filename);
DrogonControlInterface* dci;

int main(int argc, char** argv)
{
	ros::init(argc, argv, "Drogon_Planner");
	if (argc < 2) {
		printf("a file name is required./n");
		return -1;
	}
	cout << "creating DrogonControlInterface" << endl;
	dci = new DrogonControlInterface();
	cout << "created DrogonControlInterface" << endl;
	dci->rosEnable();
	map<string, double> goal;
	fillMap(goal, argv[1]);
//	moveit::planning_interface::MoveGroup::Plan plan = dci->getPlan(goal, drogon::LEFT);
//	dci->executePlan(plan, drogon::LEFT);
	ros::waitForShutdown();
}
void fillMap(map<string, double> &goal, string filename)
{
	ifstream goalInput;
	cout << filename.c_str() << endl;
	goalInput.open(filename.c_str());
	string line;
	while(!goalInput.eof()) {
		getline(goalInput, line);
		cout << line << endl;
		stringstream lineStream(line);
		string key;
		string valueString;
		double value;
		while (lineStream >> key) {
			lineStream >> valueString;
			value = atof(valueString.c_str());
			goal[key] = value;
		}
	}
	goalInput.close();
}
<commit_msg>working on planner<commit_after>#include <DrogonControlInterfaceLibrary.h>

using namespace std;

void fillMap(map<string, double> &goal, string filename);
DrogonControlInterface* dci;

int main(int argc, char** argv)
{
	ros::init(argc, argv, "Drogon_Planner");
	if (argc < 2) {
		printf("a file name is required./n");
		return -1;
	}
	cout << "creating DrogonControlInterface" << endl;
	dci = new DrogonControlInterface();
	cout << "created DrogonControlInterface" << endl;
	dci->rosEnable();
	map<string, double> goal;
	fillMap(goal, argv[1]);
	sleep(5000);
	moveit::planning_interface::MoveGroup::Plan plan = dci->getPlan(goal, drogon::LEFT);
	cout << "plan received" << endl;
	dci->executePlan(plan, drogon::LEFT);
	cout << "plan executed" << endl;
	ros::spin();
}
void fillMap(map<string, double> &goal, string filename)
{
	ifstream goalInput;
	cout << filename.c_str() << endl;
	goalInput.open(filename.c_str());
	string line;
	while(getline(goalInput, line)) {
		cout << "outer loop:: " << endl;
		cout << line << endl;
		stringstream lineStream(line);
		string key;
		string valueString;
		double value;
		while (lineStream >> key) {
			lineStream >> valueString;
			value = atof(valueString.c_str());
			goal[key] = value;
		}
	}
	goalInput.close();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, Christian Menard
 * Copyright (c) 2015, Nils Asmussen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those
 * of the authors and should not be interpreted as representing official policies,
 * either expressed or implied, of the FreeBSD Project.
 */

#include "debug/MemoryWatch.hh"
#include "mem/scratchpad.hh"

Scratchpad::Scratchpad(const ScratchpadParams* p)
  : AbstractMemory(p),
    cpuPort(name() + ".cpu_port", *this),
    dtuPort(name() + ".dtu_port", *this),
    latency(p->latency),
    throughput(p->throughput),
    initFile(p->init_file),
    watchRange(1, 0)
{
    if(p->watch_range_start != p->watch_range_end)
        watchRange = AddrRange(p->watch_range_start, p->watch_range_end - 1);
}

void
Scratchpad::init()
{
    AbstractMemory::init();

    assert(cpuPort.isConnected());
    // assert(dtuPort.isConnected());

    cpuPort.sendRangeChange();
    if(dtuPort.isConnected())
        dtuPort.sendRangeChange();

    if(!initFile.empty()) {
        FILE *f = fopen(initFile.c_str(), "r");
        if(!f)
            panic("Unable to open '%s' for reading", initFile.c_str());

        fseek(f, 0L, SEEK_END);
        size_t sz = ftell(f);
        fseek(f, 0L, SEEK_SET);

        Request::Flags flags;
        auto req = new Request(0, sz, flags, 0);
        auto pkt = new Packet(req, MemCmd::WriteReq);
        auto pktData = new uint8_t[sz];
        fread(pktData, 1, sz, f);
        pkt->dataDynamic(pktData);
        fclose(f);

        this->functionalAccess(pkt);

        delete pkt->req;
        delete pkt;
    }
}

BaseSlavePort &
Scratchpad::getSlavePort(const std::string &if_name, PortID idx)
{
    if (if_name == "cpu_port") {
        return cpuPort;
    }
    else if(if_name == "dtu_port") {
        return dtuPort;
    }
    else {
        return MemObject::getSlavePort(if_name, idx);
    }
}

Tick
Scratchpad::recvAtomic(PacketPtr pkt)
{
    /*
     * TODO
     * So far the Scratchpad has no busy state -> it accepts all requests!
     */

    // let subclass handle the request
    access(pkt);

    if(watchRange.valid())
    {
        AddrRange range(pkt->getAddr(), pkt->getAddr() + pkt->getSize() - 1);
        if(watchRange.intersects(range))
        {
            DPRINTF(MemoryWatch, "%s access to address range %p..%p (watching %p..%p)\n",
                pkt->isRead() ? "read" : "write", range.start(), range.end(),
                watchRange.start(), watchRange.end());
            DDUMP(MemoryWatch, pkt->getPtr<uint8_t>(), pkt->getSize());
        }
    }

    unsigned cyclesNeeded = round(((float) pkt->getSize()) / ((float)throughput));
    unsigned payloadDelay = clockPeriod() * cyclesNeeded;

    // pay the header delay caused by interconnect and add the scratchpad latency
    unsigned totalDelay = pkt->headerDelay + latency * clockPeriod();
    pkt->headerDelay = 0;

    // Pay the payload dalay. The paylaod delay does not accumulate,
    // instead the highest value is taken.
    totalDelay += std::max(payloadDelay, pkt->payloadDelay);
    pkt->payloadDelay = 0;

    return totalDelay;
}

Scratchpad::ScratchpadPort::ScratchpadPort(const std::string& _name,
                                           Scratchpad& _scratchpad)
    : SimpleTimingPort(_name, &_scratchpad), scratchpad(_scratchpad)
{ }

AddrRangeList
Scratchpad::ScratchpadPort::getAddrRanges() const
{
    AddrRangeList ranges;
    ranges.push_back(scratchpad.getAddrRange());
    return ranges;
}

Tick
Scratchpad::ScratchpadPort::recvAtomic(PacketPtr pkt)
{
    return scratchpad.recvAtomic(pkt);
}

Scratchpad*
ScratchpadParams::create()
{
    return new Scratchpad(this);
}
<commit_msg>Scratchpad: fixed warning.<commit_after>/*
 * Copyright (c) 2015, Christian Menard
 * Copyright (c) 2015, Nils Asmussen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those
 * of the authors and should not be interpreted as representing official policies,
 * either expressed or implied, of the FreeBSD Project.
 */

#include "debug/MemoryWatch.hh"
#include "mem/scratchpad.hh"

Scratchpad::Scratchpad(const ScratchpadParams* p)
  : AbstractMemory(p),
    cpuPort(name() + ".cpu_port", *this),
    dtuPort(name() + ".dtu_port", *this),
    latency(p->latency),
    throughput(p->throughput),
    initFile(p->init_file),
    watchRange(1, 0)
{
    if(p->watch_range_start != p->watch_range_end)
        watchRange = AddrRange(p->watch_range_start, p->watch_range_end - 1);
}

void
Scratchpad::init()
{
    AbstractMemory::init();

    assert(cpuPort.isConnected());
    // assert(dtuPort.isConnected());

    cpuPort.sendRangeChange();
    if(dtuPort.isConnected())
        dtuPort.sendRangeChange();

    if(!initFile.empty()) {
        FILE *f = fopen(initFile.c_str(), "r");
        if(!f)
            panic("Unable to open '%s' for reading", initFile.c_str());

        fseek(f, 0L, SEEK_END);
        size_t sz = ftell(f);
        fseek(f, 0L, SEEK_SET);

        Request::Flags flags;
        auto req = new Request(0, sz, flags, 0);
        auto pkt = new Packet(req, MemCmd::WriteReq);
        auto pktData = new uint8_t[sz];
        if(fread(pktData, 1, sz, f) != sz)
            panic("Unable to read '%s'", initFile.c_str());
        pkt->dataDynamic(pktData);
        fclose(f);

        this->functionalAccess(pkt);

        delete pkt->req;
        delete pkt;
    }
}

BaseSlavePort &
Scratchpad::getSlavePort(const std::string &if_name, PortID idx)
{
    if (if_name == "cpu_port") {
        return cpuPort;
    }
    else if(if_name == "dtu_port") {
        return dtuPort;
    }
    else {
        return MemObject::getSlavePort(if_name, idx);
    }
}

Tick
Scratchpad::recvAtomic(PacketPtr pkt)
{
    /*
     * TODO
     * So far the Scratchpad has no busy state -> it accepts all requests!
     */

    // let subclass handle the request
    access(pkt);

    if(watchRange.valid())
    {
        AddrRange range(pkt->getAddr(), pkt->getAddr() + pkt->getSize() - 1);
        if(watchRange.intersects(range))
        {
            DPRINTF(MemoryWatch, "%s access to address range %p..%p (watching %p..%p)\n",
                pkt->isRead() ? "read" : "write", range.start(), range.end(),
                watchRange.start(), watchRange.end());
            DDUMP(MemoryWatch, pkt->getPtr<uint8_t>(), pkt->getSize());
        }
    }

    unsigned cyclesNeeded = round(((float) pkt->getSize()) / ((float)throughput));
    unsigned payloadDelay = clockPeriod() * cyclesNeeded;

    // pay the header delay caused by interconnect and add the scratchpad latency
    unsigned totalDelay = pkt->headerDelay + latency * clockPeriod();
    pkt->headerDelay = 0;

    // Pay the payload dalay. The paylaod delay does not accumulate,
    // instead the highest value is taken.
    totalDelay += std::max(payloadDelay, pkt->payloadDelay);
    pkt->payloadDelay = 0;

    return totalDelay;
}

Scratchpad::ScratchpadPort::ScratchpadPort(const std::string& _name,
                                           Scratchpad& _scratchpad)
    : SimpleTimingPort(_name, &_scratchpad), scratchpad(_scratchpad)
{ }

AddrRangeList
Scratchpad::ScratchpadPort::getAddrRanges() const
{
    AddrRangeList ranges;
    ranges.push_back(scratchpad.getAddrRange());
    return ranges;
}

Tick
Scratchpad::ScratchpadPort::recvAtomic(PacketPtr pkt)
{
    return scratchpad.recvAtomic(pkt);
}

Scratchpad*
ScratchpadParams::create()
{
    return new Scratchpad(this);
}
<|endoftext|>