void tst_QProcessEnvironment::emptyNull()
{
    QProcessEnvironment e;

    e.insert("FOO", "");
    QVERIFY(e.contains("FOO"));
    QVERIFY(e.value("FOO").isEmpty());
    QVERIFY(!e.value("FOO").isNull());

    e.insert("FOO", QString());
    QVERIFY(e.contains("FOO"));
    QVERIFY(e.value("FOO").isEmpty());
    // don't test if it's NULL, since we shall not make a guarantee

    e.remove("FOO");
    QVERIFY(!e.contains("FOO"));
}
Esempio n. 2
0
    bool Backend::openSession() {
        struct passwd *pw;
        pw = getpwnam(qPrintable(qobject_cast<HelperApp*>(parent())->user()));
        if (pw) {
            QProcessEnvironment env = m_app->session()->processEnvironment();
            env.insert("HOME", pw->pw_dir);
            env.insert("PWD", pw->pw_dir);
            env.insert("SHELL", pw->pw_shell);
            env.insert("USER", pw->pw_name);
            env.insert("LOGNAME", pw->pw_name);
            if (env.contains("DISPLAY") && !env.contains("XAUTHORITY"))
                env.insert("XAUTHORITY", QString("%1/.Xauthority").arg(pw->pw_dir));
            // TODO: I'm fairly sure this shouldn't be done for PAM sessions, investigate!
            m_app->session()->setProcessEnvironment(env);

            // redirect standard error to a file
            m_app->session()->setStandardErrorFile(QString("%1/.xsession-errors").arg(pw->pw_dir));
        }
        return m_app->session()->start();
    }
Esempio n. 3
0
bool UserModel::autoLoginEnabled() const
{
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    if (env.contains("MOBAPP_AUTO_LOGIN")) {
        QString value = env.value("MOBAPP_AUTO_LOGIN").toLower().trimmed();

        if (value == "true" || value == "1")
            return true;
    }

    return false;
}
Esempio n. 4
0
void tst_QProcessEnvironment::putenv()
{
#ifdef Q_WS_WINCE
    QSKIP("Windows CE has no environment", SkipAll);
#else
    static const char envname[] = "WE_RE_SETTING_THIS_ENVIRONMENT_VARIABLE";
    static bool testRan = false;

    if (testRan)
        QFAIL("You cannot run this test more than once, since we modify the environment");
    testRan = true;

    QByteArray valBefore = qgetenv(envname);
    if (!valBefore.isNull())
        QFAIL("The environment variable we set in the environment is already set! -- please correct the test environment");
    QProcessEnvironment eBefore = QProcessEnvironment::systemEnvironment();

    qputenv(envname, "Hello, World");
    QByteArray valAfter = qgetenv(envname);
    if (valAfter != "Hello, World")
        QSKIP("Could not test: qputenv did not do its job", SkipAll);

    QProcessEnvironment eAfter = QProcessEnvironment::systemEnvironment();

    QVERIFY(!eBefore.contains(envname));
    QVERIFY(eAfter.contains(envname));
    QCOMPARE(eAfter.value(envname), QString("Hello, World"));

# ifdef Q_OS_WIN
    // check case-insensitive too
    QString lower = envname;
    lower = lower.toLower();
    QVERIFY(!eBefore.contains(lower));
    QVERIFY(eAfter.contains(lower));
    QCOMPARE(eAfter.value(lower), QString("Hello, World"));
# endif
#endif
}
void tst_QProcessEnvironment::caseSensitivity()
{
    QProcessEnvironment e;
    e.insert("foo", "bar");

#ifdef Q_OS_WIN
    // Windows is case-insensitive, but case-preserving
    QVERIFY(e.contains("foo"));
    QVERIFY(e.contains("FOO"));
    QVERIFY(e.contains("FoO"));

    QCOMPARE(e.value("foo"), QString("bar"));
    QCOMPARE(e.value("FOO"), QString("bar"));
    QCOMPARE(e.value("FoO"), QString("bar"));

    // Per Windows, this overwrites the value, but keeps the name's original capitalization
    e.insert("Foo", "Bar");

    QStringList list = e.toStringList();
    QCOMPARE(list.length(), 1);
    QCOMPARE(list.at(0), QString("foo=Bar"));
#else
    // otherwise, it's case sensitive
    QVERIFY(e.contains("foo"));
    QVERIFY(!e.contains("FOO"));

    e.insert("FOO", "baz");
    QVERIFY(e.contains("FOO"));
    QCOMPARE(e.value("FOO"), QString("baz"));
    QCOMPARE(e.value("foo"), QString("bar"));

    QStringList list = e.toStringList();
    QCOMPARE(list.length(), 2);
    QVERIFY(list.contains("foo=bar"));
    QVERIFY(list.contains("FOO=baz"));
#endif
}
Esempio n. 6
0
/*
void runProgram(QString path, QString args) {

	SHELLEXECUTEINFO ShExecInfo;
	bool elevated = (GetKeyState(VK_SHIFT) & 0x80000000) != 0 && (GetKeyState(VK_CONTROL) & 0x80000000) != 0;

	ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
	ShExecInfo.fMask = SEE_MASK_FLAG_NO_UI;
	ShExecInfo.hwnd = NULL;
	ShExecInfo.lpVerb = elevated ? L"runas" : NULL;
	ShExecInfo.lpFile = (LPCTSTR)path.utf16();
	if (args != "") {
		ShExecInfo.lpParameters = (LPCTSTR)args.utf16();
	} else {
		ShExecInfo.lpParameters = NULL;
	}
	QDir dir(path);
	QFileInfo info(path);
	if (!info.isDir() && info.isFile())
		dir.cdUp();	
	QString filePath = QDir::toNativeSeparators(dir.absolutePath());
	ShExecInfo.lpDirectory = (LPCTSTR)filePath.utf16();
	ShExecInfo.nShow = SW_NORMAL;
	ShExecInfo.hInstApp = NULL;

	ShellExecuteEx(&ShExecInfo);	
}
*/
void runProgram(QString path, QString args) {

	QProcessEnvironment env = QProcessEnvironment::systemEnvironment ();
	QString pf32 = env.value("PROGRAMFILES");
	QString pf64 = env.value("PROGRAMW6432");

	// On 64 bit windows, 64 bit shortcuts don't resolve correctly from 32 bit executables, fix it here
	QFileInfo pInfo(path);

	if (env.contains("PROGRAMW6432") && pInfo.isSymLink() &&
		pf32 != pf64 && QDir::toNativeSeparators(pInfo.symLinkTarget()).contains(pf32))
	{
		QString path64 = QDir::toNativeSeparators(pInfo.symLinkTarget());
		path64.replace(pf32, pf64);
		if (QFileInfo(path64).exists()) {
			path = path64;
		}
	}

	SHELLEXECUTEINFO ShExecInfo;
	bool elevated = (GetKeyState(VK_SHIFT) & 0x80000000) != 0 && (GetKeyState(VK_CONTROL) & 0x80000000) != 0;

	ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
	ShExecInfo.fMask = SEE_MASK_FLAG_NO_UI;
	ShExecInfo.hwnd = NULL;
	ShExecInfo.lpVerb = elevated ? L"runas" : NULL;
	ShExecInfo.lpFile = (LPCTSTR)path.utf16();
	if (args != "") {
		ShExecInfo.lpParameters = (LPCTSTR)args.utf16();
	} else {
		ShExecInfo.lpParameters = NULL;
	}


	QDir dir(path);
	QFileInfo info(path);
	if (!info.isDir() && info.isFile())
		dir.cdUp();
	QString filePath = QDir::toNativeSeparators(dir.absolutePath());
	ShExecInfo.lpDirectory = (LPCTSTR)filePath.utf16();
	ShExecInfo.nShow = SW_NORMAL;
	ShExecInfo.hInstApp = NULL;

	ShellExecuteEx(&ShExecInfo);	
}
Esempio n. 7
0
Preferences::Preferences( QObject * parent )
  : QObject( parent )
  , m_environmentEnabled( true )
  , m_normalsLineLength( 1.f )
  , m_transparencyMode( static_cast<unsigned int>(dp::sg::renderer::rix::gl::TransparencyMode::ORDER_INDEPENDENT_ALL) )
{
  load();

  QProcessEnvironment pe = QProcessEnvironment::systemEnvironment();
  QString home = pe.contains( "DPHOME" ) ? pe.value( "DPHOME" ) : QString( "." );

  // Add the DPHOME media folders if m_searchPath is empty
  // which is the case on the very first program run.
  // Different paths can be added inside the Preferences Dialog.
  if ( !m_searchPaths.count() )
  {
    m_searchPaths.append( home + QString( "/media/dpfx" ) );
    m_searchPaths.append( home + QString("/media/effects") );
    m_searchPaths.append( home + QString("/media/effects/xml") );
    m_searchPaths.append( home + QString("/media/textures") );
    m_searchPaths.append( home + QString("/media/textures/maxbench") );
  }

  if ( m_environmentTextureName.isEmpty() )
  {
    m_environmentTextureName = home + "/media/textures/spheremaps/spherical_checker.png";
  }
  if ( m_materialCatalogPath.isEmpty() )
  {
    m_materialCatalogPath = home + "/media/effects";
  }
  if ( m_sceneSelectionPath.isEmpty() )
  {
    m_sceneSelectionPath = home + QString( "/media/scenes" );
  }
  if ( m_textureSelectionPath.isEmpty() )
  {
    m_textureSelectionPath = home + QString( "/media/textures" );
  }
}
Esempio n. 8
0
void Env::loadEnvFile(QIODevice *dev)
{
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    m_orgEnvLines.clear();
#ifdef Q_OS_WIN
    QRegExp rx("\\%([\\w]+)\\%");
#else
    QRegExp rx("\\$([\\w]+)");
#endif
    while (!dev->atEnd()) {
        QString line = dev->readLine().trimmed();
        if (line.indexOf("#") == 0) {
            continue;
        }
        int pos = line.indexOf("=");
        if (pos == -1) {
            continue;
        }
        m_orgEnvLines.append(line);
        QString key = line.left(pos).trimmed();
        QString value = line.right(line.length()-pos-1).trimmed();
        QStringList cap0;
        QStringList cap1;
        pos = 0;
        while ((pos = rx.indexIn(value, pos)) != -1) {
             cap0 << rx.cap(0);
             cap1 << rx.cap(1);
             pos += rx.matchedLength();
        }
        for (int i = 0; i < cap0.size(); i++) {
            if (env.contains(cap1.at(i))) {
                value.replace(cap0.at(i),env.value(cap1.at(i)));
            }
        }
        env.insert(key,value);
    }
    m_env = env;
}
Esempio n. 9
0
int main( int argc, char** argv )
{
#ifdef Q_OS_WIN
    SetErrorMode(SEM_NOGPFAULTERRORBOX); 
#endif

    QString version = CalligraVersionWrapper::versionString(true);

    K4AboutData aboutData("calligrageminithumbnailer",
                         "calligrawords",
                         ki18n("Calligra Gemini Thumbnailer"),
                         version.toLatin1(),
                         ki18n("Calligra Gemini: Writing and Presenting at Home and on the Go"),
                         K4AboutData::License_GPL,
                         ki18n("(c) 1999-%1 The Calligra team and KO GmbH.\n").subs(CalligraVersionWrapper::versionYear()),
                         KLocalizedString(),
                         "http://www.calligra.org",
                         "*****@*****.**");

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

    KCmdLineOptions options;
    options.add( "in <local-url>", ki18n( "Document to thumbnail" ) );
    options.add( "out <local-url>", ki18n( "The full path for the thumbnail file" ) );
    options.add( "width <pixels>", ki18n( "The width in pixels of the thumbnail" ) );
    options.add( "height <pixels>", ki18n( "The height in pixels of the thumbnail" ) );
    KCmdLineArgs::addCmdLineOptions( options );

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

    KApplication app;
    app.setApplicationName("calligrageminithumbnailer");

#ifdef Q_OS_WIN
    QDir appdir(app.applicationDirPath());
    appdir.cdUp();

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    if (!env.contains("KDESYCOCA")) {
        _putenv_s("KDESYCOCA", QString(appdir.absolutePath() + "/sycoca").toLocal8Bit());
    }
    if (!env.contains("XDG_DATA_DIRS")) {
        _putenv_s("XDG_DATA_DIRS", QString(appdir.absolutePath() + "/share").toLocal8Bit());
    }
    _putenv_s("PATH", QString(appdir.absolutePath() + "/bin" + ";"
              + appdir.absolutePath() + "/lib" + ";"
              + appdir.absolutePath() + "/lib"  +  "/kde4" + ";"
              + appdir.absolutePath()).toLocal8Bit());

    app.addLibraryPath(appdir.absolutePath());
    app.addLibraryPath(appdir.absolutePath() + "/bin");
    app.addLibraryPath(appdir.absolutePath() + "/lib");
    app.addLibraryPath(appdir.absolutePath() + "/lib/kde4");
#endif

#if defined HAVE_X11
    QApplication::setAttribute(Qt::AA_X11InitThreads);
#endif

    QString inFile = args->getOption("in");
    QString outFile = args->getOption("out");
    // Only create the thunbnail if:
    // 1) The infile exists and
    // 2) The outfile does /not/ exist
    if(!QFile::exists(inFile)) {
        qDebug() << "The document you are attempting to create a thumbnail of does not exist on disk:" << inFile;
    }
    else if(QFile::exists(outFile)) {
        qDebug() << "The thumbnail file you are asking to have used already exists on disk. We will refuse to overwrite it." << outFile;
    }
    else {
        ThumbnailHelperImpl helper;
        helper.convert(inFile, outFile, args->getOption("width").toInt(), args->getOption("height").toInt());
    }
    QTimer::singleShot(0, &app, SLOT(quit()));

    return app.exec();
}
Esempio n. 10
0
bool HttpServer::initialize()
{
  if(m_IsInitialized)
  {
    LOG_DEBUG("Already initialized");
    return false;
  }

  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  if(env.contains(QTTP_HOME_ENV_VAR))
  {
    QDir::setCurrent(env.value(QTTP_HOME_ENV_VAR));
    LOG_DEBUG("Working directory from $" << QTTP_HOME_ENV_VAR << QDir::currentPath());
  }
  else
  {
    // Just a quirk for mac, but I wonder if we can apply to all in general.
    #ifdef Q_OS_MAC
    QDir::setCurrent(qApp->applicationDirPath());
    LOG_DEBUG("Working directory" << QDir::currentPath());
    #else
    LOG_DEBUG("Working directory" << QDir::currentPath());
    #endif
  }

  QCoreApplication* app = QCoreApplication::instance();
  Q_ASSERT(app);

  m_CmdLineParser.addOptions({
    {{"i", "ip"},
     QCoreApplication::translate("main", "ip of the target interface"),
     QCoreApplication::translate("main", "ip")},
    {{"p", "port"},
     QCoreApplication::translate("main", "port to listen on"),
     QCoreApplication::translate("main", "port")},
    {{"m", "meta"},
     QCoreApplication::translate("main", "appends metadata to responses")},
    {{"c", "config"},
     QCoreApplication::translate("main", "absolute path to the global config file (json)"),
     QCoreApplication::translate("main", "config")},
    {{"r", "routes"},
     QCoreApplication::translate("main", "absolute path to the routes config file (json)"),
     QCoreApplication::translate("main", "routes")},
    {{"d", "dir"},
     QCoreApplication::translate("main", "absolute path to the config directory, don't combine with -c or -r args"),
     QCoreApplication::translate("main", "dir")},
    {{"w", "www"},
     QCoreApplication::translate("main", "absolute path to the www folder to serve http files"),
     QCoreApplication::translate("main", "www")},
    {{"s", "swagger"},
     QCoreApplication::translate("main", "exposes swagger-api json responses for the path /swagger/")},
  });

  m_CmdLineParser.addHelpOption();
  m_CmdLineParser.process(*app);

  if(env.contains(CONFIG_DIRECTORY_ENV_VAR))
  {
    QString var = env.value(CONFIG_DIRECTORY_ENV_VAR);
    if(!var.isNull() && !var.trimmed().isEmpty())
    {
      LOG_INFO("Processing ENVIRONMENT VARIABLE [" << var << "]");
      initConfigDirectory(var);
    }
    else
    {
      LOG_WARN("Invalid ENVIRONMENT VARIABLE [" << CONFIG_DIRECTORY_ENV_VAR << "]");
    }
  }

  QJsonValue d = m_CmdLineParser.value("d");
  if(d.isString() && !d.isNull() && !d.toString().trimmed().isEmpty())
  {
    initConfigDirectory(d.toString());
  }
  else
  {
    QJsonValue c = m_CmdLineParser.value("c");
    if(c.isString() && !c.isNull() && !c.toString().trimmed().isEmpty())
    {
      initGlobal(c.toString());
    }
    else
    {
      initGlobal(GLOBAL_CONFIG_FILE_PATH);
    }

    QJsonValue r = m_CmdLineParser.value("r");
    if(r.isString() && !r.isNull() && !r.toString().trimmed().isEmpty())
    {
      initRoutes(r.toString());
    }
    else
    {
      initRoutes(ROUTES_CONFIG_FILE_PATH);
    }
  }

  if(!m_SendRequestMetadata)
  {
    m_SendRequestMetadata = m_CmdLineParser.isSet("m");
    LOG_DEBUG("CmdLine meta-data" << m_SendRequestMetadata);
  }

  if(!m_IsSwaggerEnabled)
  {
    initSwagger(m_CmdLineParser.isSet("s"));
    LOG_DEBUG("CmdLine swagger" << m_IsSwaggerEnabled);
  }

  QJsonValue i = m_CmdLineParser.value("i");
  if((i.isString() || i.isDouble()) && !i.toString().trimmed().isEmpty())
  {
    QString ip = i.toString();
    m_GlobalConfig["bindIp"] = ip;
    LOG_DEBUG("CmdLine ip" << ip);
  }

  QJsonValue p = m_CmdLineParser.value("p");
  if((p.isString() || p.isDouble()) && !p.toString().trimmed().isEmpty())
  {
    qint32 port = p.toInt();
    m_GlobalConfig["bindPort"] = port;
    LOG_DEBUG("CmdLine port" << port);
  }

  QJsonValue w = m_CmdLineParser.value("w");
  if(w.isString() && !w.isNull() && !w.toString().trimmed().isEmpty())
  {
    initHttpDirectory(w.toString());
    LOG_DEBUG("CmdLine www/web/http-files" << w);
  }

  m_IsInitialized = true;

  return true;
}
Esempio n. 11
0
int main( int argc, char** argv )
{
    QString calligraVersion(CALLIGRA_VERSION_STRING);
    QString version;


#ifdef CALLIGRA_GIT_SHA1_STRING
    QString gitVersion(CALLIGRA_GIT_SHA1_STRING);
    version = QString("%1 (git %2)").arg(calligraVersion).arg(gitVersion).toLatin1();
#else
    version = calligraVersion;
#endif


    KAboutData aboutData("kritagemini",
                         "krita",
                         ki18n("Krita Gemini"),
                         version.toLatin1(),
                         ki18n("Krita Gemini: Painting at Home and on the Go for Artists"),
                         KAboutData::License_GPL,
                         ki18n("(c) 1999-%1 The Krita team and KO GmbH.\n").subs(CALLIGRA_YEAR),
                         KLocalizedString(),
                         "http://www.kritastudio.com",
                         "*****@*****.**");

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

    KCmdLineOptions options;
    options.add( "+[files]", ki18n( "Images to open" ) );
    options.add( "vkb", ki18n( "Use the virtual keyboard" ) );
    options.add( "fullscreen", ki18n( "Use full-screen display" ) );
    KCmdLineArgs::addCmdLineOptions( options );

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
    QStringList fileNames;
    if (args->count() > 0) {
        for (int i = 0; i < args->count(); ++i) {
            QString fileName = args->arg(i);
            if (QFile::exists(fileName)) {
                fileNames << fileName;
            }
        }
    }

    KApplication app;
    app.setApplicationName("kritagemini");
    KIconLoader::global()->addAppDir("krita");
    KIconLoader::global()->addAppDir("kritasketch");

#ifdef Q_OS_WIN
    QDir appdir(app.applicationDirPath());
    appdir.cdUp();

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    // If there's no kdehome, set it and restart the process.
    //QMessageBox::information(0, "krita sketch", "KDEHOME: " + env.value("KDEHOME"));
    if (!env.contains("KDEHOME") ) {
        _putenv_s("KDEHOME", QDesktopServices::storageLocation(QDesktopServices::DataLocation).toLocal8Bit());
    }
    if (!env.contains("KDESYCOCA")) {
        _putenv_s("KDESYCOCA", QString(appdir.absolutePath() + "/sycoca").toLocal8Bit());
    }
    if (!env.contains("XDG_DATA_DIRS")) {
        _putenv_s("XDG_DATA_DIRS", QString(appdir.absolutePath() + "/share").toLocal8Bit());
    }
    if (!env.contains("KDEDIR")) {
        _putenv_s("KDEDIR", appdir.absolutePath().toLocal8Bit());
    }
    if (!env.contains("KDEDIRS")) {
        _putenv_s("KDEDIRS", appdir.absolutePath().toLocal8Bit());
    }
    _putenv_s("PATH", QString(appdir.absolutePath() + "/bin" + ";"
              + appdir.absolutePath() + "/lib" + ";"
              + appdir.absolutePath() + "/lib"  +  "/kde4" + ";"
              + appdir.absolutePath()).toLocal8Bit());

    app.addLibraryPath(appdir.absolutePath());
    app.addLibraryPath(appdir.absolutePath() + "/bin");
    app.addLibraryPath(appdir.absolutePath() + "/lib");
    app.addLibraryPath(appdir.absolutePath() + "/lib/kde4");
#endif

#if defined Q_OS_WIN
    KisTabletSupportWin::init();
    app.setEventFilter(&KisTabletSupportWin::eventFilter);
#elif defined Q_WS_X11
    KisTabletSupportX11::init();
    app.setEventFilter(&KisTabletSupportX11::eventFilter);
#endif
	
	if (qgetenv("KDE_FULL_SESSION").isEmpty()) {
        // There are two themes that work for Krita, oxygen and plastique. Try to set plastique first, then oxygen
        qobject_cast<QApplication*>(QApplication::instance())->setStyle("Plastique");
		qobject_cast<QApplication*>(QApplication::instance())->setStyle("Oxygen");
    }

	bool showFullscreen = false;
	if (args->isSet("fullscreen")) {
        showFullscreen = true;
    }

    // then create the pixmap from an xpm: we cannot get the
    // location of our datadir before we've started our components,
    // so use an xpm.
    // If fullscreen, hide splash screen
    QPixmap pm(splash_screen_xpm);
    QSplashScreen splash(pm);
    if (!showFullscreen) {
        splash.show();
        splash.showMessage(".");
        app.processEvents();
    }

#if defined Q_WS_X11 && QT_VERSION >= 0x040800
    QApplication::setAttribute(Qt::AA_X11InitThreads);
#endif

    MainWindow window(fileNames);

    if (args->isSet("vkb")) {
        app.setInputContext(new SketchInputContext(&app));
    }

    if (showFullscreen) {
        window.showFullScreen();
    } else {
#ifdef Q_OS_WIN
		window.showMaximized();
#else
		window.show();
#endif
	}
    splash.finish(&window);

    return app.exec();
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
#if QT_VERSION < 0x050000
    // The GraphicsSystem needs to be set before the instantiation of the
    // QApplication. Therefore we need to parse the current setting
    // in this unusual place :-/
    QSettings graphicsSettings("KDE", "Marble Virtual Globe"); // keep the parameters here
    QString const graphicsString = graphicsSettings.value("View/graphicsSystem", "raster").toString();
    QApplication::setGraphicsSystem( graphicsString );
#endif

    QApplication app(argc, argv);
    app.setApplicationName( "Marble Virtual Globe" );
    app.setOrganizationName( "KDE" );
    app.setOrganizationDomain( "kde.org" );
    // Widget translation

#ifdef Q_WS_MAEMO_5
    // Work around http://bugreports.qt-project.org/browse/QTBUG-1313
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    QString lang( "C" );
    QStringList const locales = QStringList() << "LC_ALL" << "LC_MESSAGES" << "LANG" << "LANGUAGE";
    foreach( const QString &locale, locales ) {
        if ( env.contains( locale ) && !env.value( locale ).isEmpty() ) {
            lang = env.value( locale, "C" );
            break;
        }
    }

    lang = lang.section( '_', 0, 0 );
#else
    QString      lang = QLocale::system().name().section('_', 0, 0);
#endif
    QTranslator  translator;
    translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) );
    app.installTranslator(&translator);

    // For non static builds on mac and win
    // we need to be sure we can find the qt image
    // plugins. In mac be sure to look in the
    // application bundle...

#ifdef Q_WS_WIN
    QApplication::addLibraryPath( QApplication::applicationDirPath()
                                  + QDir::separator() + "plugins" );
#endif
#ifdef Q_OS_MACX
    QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);
    qDebug("Adding qt image plugins to plugin search path...");
    CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
    const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
    CFRelease(myBundleRef);
    CFRelease(myMacPath);
    QString myPath(mypPathPtr);
    // if we are not in a bundle assume that the app is built
    // as a non bundle app and that image plugins will be
    // in system Qt frameworks. If the app is a bundle
    // lets try to set the qt plugin search path...
    if (myPath.contains(".app"))
    {
        myPath += "/Contents/plugins";
        QApplication::addLibraryPath( myPath );
        qDebug( "Added %s to plugin search path", qPrintable( myPath ) );
    }
#endif

    QString marbleDataPath;
    int dataPathIndex=0;
    QString mapThemeId;
    QString coordinatesString;
    QString distanceString;
    const MarbleGlobal::Profiles profiles = MarbleGlobal::SmallScreen | MarbleGlobal::HighResolution;

    QStringList args = QApplication::arguments();

    if ( args.contains( "-h" ) || args.contains( "--help" ) ) {
        qWarning() << "Usage: marble [options] [files]";
        qWarning();
        qWarning() << "[files] can be zero, one or more .kml and/or .gpx files to load and show.";
        qWarning();
        qWarning() << "general options:";
        qWarning() << "  --marbledatapath=<path> .... Overwrite the compile-time path to map themes and other data";
        qWarning() << "  --latlon=<coordinates> ..... Show map at given lat lon coordinates";
        qWarning() << "  --distance=<value> ......... Set the distance of the observer to the globe (in km)";
        qWarning() << "  --map=<id> ................. Use map id (e.g. \"earth/openstreetmap/openstreetmap.dgml\")";
        qWarning();
        qWarning() << "debug options:";
        qWarning() << "  --debug-info ............... write (more) debugging information to the console";
        qWarning() << "  --fps ...................... Show the paint performance (paint rate) in the top left corner";
        qWarning() << "  --runtimeTrace.............. Show the time spent and other debug info of each layer";
        qWarning() << "  --tile-id................... Write the identifier of texture tiles on top of them";
        qWarning() << "  --timedemo ................. Measure the paint performance while moving the map and quit";

        return 0;
    }

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);

        if ( arg == QLatin1String( "--debug-info" ) )
        {
            MarbleDebug::setEnabled( true );
        }
        else if ( arg.startsWith( QLatin1String( "--marbledatapath=" ), Qt::CaseInsensitive ) )
        {
            marbleDataPath = args.at(i).mid(17);
        }
        else if ( arg.compare( QLatin1String( "--marbledatapath" ), Qt::CaseInsensitive ) == 0 ) {
            dataPathIndex = i + 1;
            marbleDataPath = args.value( dataPathIndex );
            ++i;
        }
        else if ( arg.startsWith( QLatin1String( "--latlon=" ), Qt::CaseInsensitive ) )
        {
            coordinatesString = arg.mid(9);
        }
        else if ( arg.compare( QLatin1String( "--latlon" ), Qt::CaseInsensitive ) == 0 ) {
            ++i;
            // TODO: misses an error check if there is a value at all
            // and error reporting to user (problem also exists with marbledatapath)
            coordinatesString = args.value( i );
        }
        else if ( arg.startsWith( QLatin1String( "--distance=" ), Qt::CaseInsensitive ) )
        {
            distanceString = arg.mid(11);
        }
        else if ( arg.compare( QLatin1String( "--distance" ), Qt::CaseInsensitive ) == 0 ) {
            ++i;
            // TODO: misses an error check if there is a value at all
            // and error reporting to user (problem also exists with marbledatapath)
            distanceString = args.value( i );
        }
        else if ( arg.startsWith( QLatin1String( "--map=" ), Qt::CaseInsensitive ) )
        {
            mapThemeId = arg.mid(6);
        }
        else if ( arg.compare( QLatin1String( "--map" ), Qt::CaseInsensitive ) == 0 ) {
            ++i;
            // TODO: misses an error check if there is a value at all
            // and error reporting to user (problem also exists with marbledatapath)
            mapThemeId = args.value( i );
        }
    }
    MarbleGlobal::getInstance()->setProfiles( profiles );

    QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem();
    MarbleGlobal::getInstance()->locale()->setMeasurementSystem( measurement );

    QVariantMap cmdLineSettings;
    if ( !mapThemeId.isEmpty() ) {
        cmdLineSettings.insert( QLatin1String("mapTheme"), QVariant(mapThemeId) );
    }

    if ( !coordinatesString.isEmpty() ) {
        bool success = false;
        const GeoDataCoordinates coordinates = GeoDataCoordinates::fromString(coordinatesString, success);
        if ( success ) {
            QVariantList lonLat;
            lonLat << QVariant( coordinates.longitude(GeoDataCoordinates::Degree) )
                   << QVariant( coordinates.latitude(GeoDataCoordinates::Degree) );
            cmdLineSettings.insert( QLatin1String("lonlat"), QVariant(lonLat) );
        }
    }
    if ( !distanceString.isEmpty() ) {
        bool success = false;
        const qreal distance = distanceString.toDouble(&success);
        if ( success ) {
            cmdLineSettings.insert( QLatin1String("distance"), QVariant(distance) );
        }
    }

    MainWindow *window = new MainWindow( marbleDataPath, cmdLineSettings );
    window->setAttribute( Qt::WA_DeleteOnClose, true );

//    window->marbleWidget()->rotateTo( 0, 0, -90 );
//    window->show();

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);
        if ( arg == "--timedemo" )
        {
            window->resize(900, 640);
            MarbleTest marbleTest( window->marbleWidget() );
            marbleTest.timeDemo();
            return 0;
        }
        else if( arg == "--fps" ) {
            window->marbleWidget()->setShowFrameRate( true );
        }
        else if ( arg == "--tile-id" )
        {
            window->marbleWidget()->setShowTileId(true);
        }
        else if( arg == "--runtimeTrace" ) {
            window->marbleWidget()->setShowRuntimeTrace( true );
        }
        else if ( i != dataPathIndex && QFile::exists( arg ) ) {
            window->addGeoDataFile( QFileInfo( arg ).absoluteFilePath() );
        }
    }

    return app.exec();
}
Esempio n. 13
0
int main( int argc, char** argv )
{
    KAboutData aboutData("kritasketch",
                         "krita",
                         ki18n("Krita Sketch"),
                         "0.1",
                         ki18n("Krita Sketch: Painting on the Go for Artists"),
                         KAboutData::License_GPL,
                         ki18n("(c) 1999-2014 The Krita team and KO GmbH.\n"),
                         KLocalizedString(),
                         "http://www.krita.org",
                         "*****@*****.**");

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

    KCmdLineOptions options;
    options.add( "+[files]", ki18n( "Images to open" ) );
    options.add( "vkb", ki18n( "Use the virtual keyboard" ) );
    options.add( "windowed", ki18n( "Open sketch in a window, otherwise defaults to full-screen" ) );
    KCmdLineArgs::addCmdLineOptions( options );

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
    QStringList fileNames;
    if (args->count() > 0) {
        for (int i = 0; i < args->count(); ++i) {
            QString fileName = args->arg(i);
            if (QFile::exists(fileName)) {
                fileNames << fileName;
            }
        }
    }

    KApplication app;
    app.setApplicationName("kritasketch");
    KIconLoader::global()->addAppDir("krita");
    QDir appdir(app.applicationDirPath());
    appdir.cdUp();

#ifdef Q_OS_WIN
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    // If there's no kdehome, set it and restart the process.
    //QMessageBox::information(0, "krita sketch", "KDEHOME: " + env.value("KDEHOME"));
    if (!env.contains("KDEHOME") ) {
        _putenv_s("KDEHOME", QDesktopServices::storageLocation(QDesktopServices::DataLocation).toLocal8Bit());
    }
    if (!env.contains("KDESYCOCA")) {
        _putenv_s("KDESYCOCA", QString(appdir.absolutePath() + "/sycoca").toLocal8Bit());
    }
    if (!env.contains("XDG_DATA_DIRS")) {
        _putenv_s("XDG_DATA_DIRS", QString(appdir.absolutePath() + "/share").toLocal8Bit());
    }
    if (!env.contains("KDEDIR")) {
        _putenv_s("KDEDIR", appdir.absolutePath().toLocal8Bit());
    }
    if (!env.contains("KDEDIRS")) {
        _putenv_s("KDEDIRS", appdir.absolutePath().toLocal8Bit());
    }
    _putenv_s("PATH", QString(appdir.absolutePath() + "/bin" + ";"
              + appdir.absolutePath() + "/lib" + ";"
              + appdir.absolutePath() + "/lib"  +  "/kde4" + ";"
              + appdir.absolutePath()).toLocal8Bit());

    app.addLibraryPath(appdir.absolutePath());
    app.addLibraryPath(appdir.absolutePath() + "/bin");
    app.addLibraryPath(appdir.absolutePath() + "/lib");
    app.addLibraryPath(appdir.absolutePath() + "/lib/kde4");
#endif

#if defined Q_OS_WIN
    KisTabletSupportWin::init();
    app.setEventFilter(&KisTabletSupportWin::eventFilter);
#elif defined Q_WS_X11
    KisTabletSupportX11::init();
    app.setEventFilter(&KisTabletSupportX11::eventFilter);
#endif

#if defined Q_WS_X11 && QT_VERSION >= 0x040800
    QApplication::setAttribute(Qt::AA_X11InitThreads);
#endif

    MainWindow window(fileNames);

    if (args->isSet("vkb")) {
        app.setInputContext(new SketchInputContext(&app));
    }

    if (args->isSet("windowed")) {
        window.show();
    } else {
        window.showFullScreen();
    }

    return app.exec();
}
Esempio n. 14
0
int main( int argc, char** argv )
{
    QString calligraVersion(CALLIGRA_VERSION_STRING);
    QString version;


#ifdef CALLIGRA_GIT_SHA1_STRING
    QString gitVersion(CALLIGRA_GIT_SHA1_STRING);
    version = QString("%1 (git %2)").arg(calligraVersion).arg(gitVersion).toLatin1();
#else
    version = calligraVersion;
#endif

    KLocalizedString::setApplicationDomain("krita");

    KAboutData aboutData(QStringLiteral("kritasketch"),
                         i18n("Krita Sketch"),
                         QStringLiteral("0.1"),
                         i18n("Krita Sketch: Painting on the Go for Artists"),
                         KAboutLicense::GPL,
                         i18n("(c) 1999-%1 The Krita team.\n").arg(CALLIGRA_YEAR),
                         QString(),
                         QStringLiteral("https://www.krita.org"),
                         QStringLiteral("*****@*****.**"));

#if defined HAVE_X11
    QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
#endif
    QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
    QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);
    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true);

    SketchApplication app(argc, argv);
    KAboutData::setApplicationData( aboutData );
    app.setWindowIcon(KisIconUtils::loadIcon("kritasketch"));

    QCommandLineParser parser;
    aboutData.setupCommandLine(&parser);
    parser.addHelpOption();
    parser.addVersionOption();

    parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("vkb"), i18n("Use the virtual keyboard")));
    parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("windowed"), i18n("Open sketch in a window, otherwise defaults to full-screen")));

    parser.addPositionalArgument(QStringLiteral("[file(s)]"), i18n("Images to open"));

    parser.process(app);

    aboutData.processCommandLine(&parser);

    QStringList fileNames;
    Q_FOREACH (const QString &fileName, parser.positionalArguments()) {
        const QString absoluteFilePath = QDir::current().absoluteFilePath(fileName);
        if (QFile::exists(absoluteFilePath)) {
            fileNames << absoluteFilePath;
        }
    }

    // QT5TODO: untested replacement of KIconLoader::global()->addAppDir("krita");
    QStringList themeSearchPaths = QIcon::themeSearchPaths();
    themeSearchPaths.append(QStandardPaths::locate(QStandardPaths::GenericDataLocation, "krita/pics", QStandardPaths::LocateDirectory));
    QIcon::setThemeSearchPaths(themeSearchPaths);

    // Initialize all Calligra directories etc.
    KoGlobal::initialize();

    // for cursors
    KoResourcePaths::addResourceType("kis_pics", "data", "krita/pics/");

    // for images in the paintop box
    KoResourcePaths::addResourceType("kis_images", "data", "krita/images/");

    KoResourcePaths::addResourceType("icc_profiles", "data", "krita/profiles/");

    KisOpenGL::initialize();

    QDir appdir(app.applicationDirPath());
    appdir.cdUp();

#ifdef Q_OS_WIN
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    // If there's no kdehome, set it and restart the process.
    //QMessageBox::information(0, i18nc("@title:window", "Krita sketch", "KDEHOME: " + env.value("KDEHOME"));
    if (!env.contains("KDEHOME") ) {
        _putenv_s("KDEHOME", QDesktopServices::storageLocation(QDesktopServices::DataLocation).toLocal8Bit());
    }
    if (!env.contains("KDESYCOCA")) {
        _putenv_s("KDESYCOCA", QString(appdir.absolutePath() + "/sycoca").toLocal8Bit());
    }
    if (!env.contains("XDG_DATA_DIRS")) {
        _putenv_s("XDG_DATA_DIRS", QString(appdir.absolutePath() + "/share").toLocal8Bit());
    }
    if (!env.contains("KDEDIR")) {
        _putenv_s("KDEDIR", appdir.absolutePath().toLocal8Bit());
    }
    if (!env.contains("KDEDIRS")) {
        _putenv_s("KDEDIRS", appdir.absolutePath().toLocal8Bit());
    }
    _putenv_s("PATH", QString(appdir.absolutePath() + "/bin" + ";"
              + appdir.absolutePath() + "/lib" + ";"
              + appdir.absolutePath() + "/lib"  +  "/kde4" + ";"
              + appdir.absolutePath()).toLocal8Bit());

    app.addLibraryPath(appdir.absolutePath());
    app.addLibraryPath(appdir.absolutePath() + "/bin");
    app.addLibraryPath(appdir.absolutePath() + "/lib");
    app.addLibraryPath(appdir.absolutePath() + "/lib/kde4");
#endif

#if defined Q_OS_WIN
    KisTabletSupportWin::init();
#elif defined HAVE_X11
    KisTabletSupportX11::init();
    // TODO: who owns the filter object?
    app.installNativeEventFilter(new KisTabletSupportX11());
#endif

    app.start();

    MainWindow window(fileNames);

// QT5TODO
//     if (parser.isSet("vkb")) {
//         app.setInputContext(new SketchInputContext(&app));
//     }

    if (parser.isSet("windowed")) {
        window.show();
    } else {
        window.showFullScreen();
    }

    return app.exec();
}
Esempio n. 15
0
int main( int argc, char** argv )
{
    QString version = CalligraVersionWrapper::versionString(true);

    K4AboutData aboutData("calligragemini",
                         "calligrawords",
                         ki18n("Calligra Gemini"),
                         version.toLatin1(),
                         ki18n("Calligra Gemini: Writing and Presenting at Home and on the Go"),
                         K4AboutData::License_GPL,
                         ki18n("(c) 1999-%1 The Calligra team and KO GmbH.\n").subs(CalligraVersionWrapper::versionYear()),
                         KLocalizedString(),
                         "http://www.calligra.org",
                         "*****@*****.**");

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

    KCmdLineOptions options;
    options.add( "+[files]", ki18n( "Document to open" ) );
    options.add( "vkb", ki18n( "Use the virtual keyboard" ) );
    KCmdLineArgs::addCmdLineOptions( options );

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
    QStringList fileNames;
    if (args->count() > 0) {
        for (int i = 0; i < args->count(); ++i) {
            QString fileName = args->arg(i);
            if (QFile::exists(fileName)) {
                fileNames << fileName;
            }
        }
    }

    KApplication app;
    app.setApplicationName("calligragemini");
    KIconLoader::global()->addAppDir("calligrawords");
    KIconLoader::global()->addAppDir("words");
    KIconLoader::global()->addAppDir("calligrastage");
    KIconLoader::global()->addAppDir("stage");

#ifdef Q_OS_WIN
    QDir appdir(app.applicationDirPath());
    appdir.cdUp();

    QString envStringSet;
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    if (!env.contains("KDESYCOCA")) {
        _putenv_s("KDESYCOCA", QString(appdir.absolutePath() + "/sycoca").toLocal8Bit());
        envStringSet.append("KDESYCOCA ");
    }
    if (!env.contains("XDG_DATA_DIRS")) {
        _putenv_s("XDG_DATA_DIRS", QString(appdir.absolutePath() + "/share").toLocal8Bit());
        envStringSet.append("XDG_DATA_DIRS ");
    }
    _putenv_s("PATH", QString(appdir.absolutePath() + "/bin" + ";"
              + appdir.absolutePath() + "/lib" + ";"
              + appdir.absolutePath() + "/lib"  +  "/kde4" + ";"
              + appdir.absolutePath()).toLocal8Bit());

    if(envStringSet.length() > 0) {
        qDebug() << envStringSet << "were set from main, restarting application in new environment!";
        // Pass all the arguments along, but don't include the application name...
        QProcess::startDetached(app.applicationFilePath(), KCmdLineArgs::allArguments().mid(1));
        exit(0);
    }

    app.addLibraryPath(appdir.absolutePath());
    app.addLibraryPath(appdir.absolutePath() + "/bin");
    app.addLibraryPath(appdir.absolutePath() + "/lib");
    app.addLibraryPath(appdir.absolutePath() + "/lib/kde4");

    QStringList iconThemePaths;
    iconThemePaths << appdir.absolutePath() + "/share/icons";
    QIcon::setThemeSearchPaths(iconThemePaths);
    QIcon::setThemeName("oxygen");
#endif

    if (qgetenv("KDE_FULL_SESSION").isEmpty()) {
        // There are two themes that work for Krita, oxygen and plastique. Try to set plastique first, then oxygen
        qobject_cast<QApplication*>(QApplication::instance())->setStyle("Plastique");
        qobject_cast<QApplication*>(QApplication::instance())->setStyle("Oxygen");
    }

    // then create the pixmap from an xpm: we cannot get the
    // location of our datadir before we've started our components,
    // so use an xpm.
//     QPixmap pm(splash_screen_xpm);
//     QSplashScreen splash(pm);
//     splash.show();
//     splash.showMessage(".");
    app.processEvents();

#if defined HAVE_X11
    QApplication::setAttribute(Qt::AA_X11InitThreads);
#endif

    MainWindow window(fileNames);

    if (args->isSet("vkb")) {
//        app.setInputContext(new SketchInputContext(&app));
    }

#ifdef Q_OS_WIN
    window.showMaximized();
#else
    window.show();
#endif
//    splash.finish(&window);

    return app.exec();
}
Esempio n. 16
0
void HttpServer::initGlobal(const QString &filepath)
{
  LOG_INFO("Processing filepath [" << filepath << "]");

  m_GlobalConfig = Utils::readJson(QDir(filepath).absolutePath());

  LOG_INFO(m_GlobalConfig["bindIp"]);
  LOG_INFO(m_GlobalConfig["bindPort"]);

  QJsonValueRef loggingValue = m_GlobalConfig["logfile"];
  if(loggingValue.isObject())
  {
    QJsonObject logging = loggingValue.toObject();
    if(logging["isEnabled"].toBool(true))
    {
      QString filename;
      if(logging["filename"].isString())
      {
        filename = logging["filename"].toString();
      }
      if(logging["writeFrequency"].isDouble())
      {
        m_LoggingUtils.initializeFile(filename, logging["writeFrequency"].toInt());
      }
      else
      {
        m_LoggingUtils.initializeFile(filename);
      }
    }
  }

  QJsonValueRef httpFilesValue = m_GlobalConfig["httpFiles"];
  if(httpFilesValue.isObject())
  {
    QJsonObject httpFiles = httpFilesValue.toObject();
    m_ShouldServeFiles = httpFiles["isEnabled"].toBool(false);
    if(m_ShouldServeFiles)
    {
      QString directory = httpFiles["directory"].toString().trimmed();
      if(directory == "$QTTP_HOME")
      {
        QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
        if(env.contains(QTTP_HOME_ENV_VAR))
        {
          m_ServeFilesDirectory = QDir::cleanPath(env.value(QTTP_HOME_ENV_VAR));
          m_ServeFilesDirectory = m_ServeFilesDirectory.absoluteFilePath("www");
          LOG_DEBUG("Using $QTTP_HOME" << m_ServeFilesDirectory.absolutePath());
        }
        else
        {
          m_ServeFilesDirectory = QDir::current().absoluteFilePath("www");
          LOG_DEBUG("QTTP_HOME not found, using current directory" << m_ServeFilesDirectory.absolutePath());
        }
      }
      else if(directory.isEmpty())
      {
        m_ServeFilesDirectory = QDir::current().absoluteFilePath("www");
        LOG_DEBUG("Default to using current directory" << m_ServeFilesDirectory.absolutePath());
      }
      else
      {
        m_ServeFilesDirectory = QDir::cleanPath(directory);
        LOG_DEBUG("Using directory in config" << m_ServeFilesDirectory.absolutePath());
      }
      if(!m_ServeFilesDirectory.exists())
      {
        LOG_ERROR("Unable to serve files from invalid directory [" << m_ServeFilesDirectory.absolutePath() << "]");
        m_ShouldServeFiles = false;
      }
    }
  }

  if(m_ShouldServeFiles)
  {
    m_FileLookup.populateFiles(m_ServeFilesDirectory);
  }

  QJsonObject headers = m_GlobalConfig["defaultHeaders"].toObject();
  QStringList keys = headers.keys();

  if(!keys.isEmpty())
  {
    Global::DEFAULT_HEADERS.clear();
    for(QString key : keys)
    {
      QString value = headers.value(key).toString();
      Global::DEFAULT_HEADERS.push_back({ key, value });
      LOG_DEBUG("Adding default-header [" << key << ", " << value << "]");
    }

    // We'll always force the QttpServer version in here.
    Global::DEFAULT_HEADERS.push_back({ "Server", QTTP_SERVER_VERSION });
  }
  else
  {
    LOG_DEBUG("Did not read headers in config file, using default headers");
  }

  QJsonObject serverConfig = m_GlobalConfig["server"].toObject();
  m_SendRequestMetadata = serverConfig["metadata"].toBool(false);
  m_StrictHttpMethod = serverConfig["strictHttpMethod"].toBool(false);

  QJsonObject processors = serverConfig["processors"].toObject();
  keys = processors.keys();
  for(QString key : keys)
  {
    bool isEnabled = processors.value(key).toBool(false);

    LOG_DEBUG("Processor [" << key << "] is " <<
              (isEnabled ? "ENABLED" : "NOT ENABLED"));

    if(isEnabled)
    {
      m_EnabledProcessors.append(key);
    }
  }

  QJsonObject swagger = m_GlobalConfig["swagger"].toObject();
  initSwagger(swagger["isEnabled"].toBool(false));

#ifndef ASSIGN_SWAGGER
#  define ASSIGN_SWAGER(X) m_ServerInfo.X = swagger[#X].toString()
#endif

  ASSIGN_SWAGER(host);
  ASSIGN_SWAGER(basePath);
  ASSIGN_SWAGER(version);
  ASSIGN_SWAGER(title);
  ASSIGN_SWAGER(description);
  ASSIGN_SWAGER(termsOfService);

  QJsonObject company = swagger["company"].toObject();
  m_ServerInfo.companyName = company["name"].toString();
  m_ServerInfo.companyUrl = company["url"].toString();

  QJsonObject contact = swagger["contact"].toObject();
  m_ServerInfo.contactEmail = contact["email"].toString();

  QJsonObject license = swagger["license"].toObject();
  m_ServerInfo.licenseName = license["name"].toString();
  m_ServerInfo.licenseUrl = license["url"].toString();

  m_ServerInfo.schemes = swagger["schemes"].toArray();
  m_ServerInfo.consumes = swagger["consumes"].toArray();
  m_ServerInfo.produces = swagger["produces"].toArray();
}
Esempio n. 17
0
void Mapviz::Initialize()
{
  if (!initialized_)
  {
    if (is_standalone_)
    {
      // If this Mapviz is running as a standalone application, it needs to init
      // ROS and start spinning.  If it's running as an rqt plugin, rqt will
      // take care of that.
      ros::init(argc_, argv_, "mapviz", ros::init_options::AnonymousName);

      spin_timer_.start(30);
      connect(&spin_timer_, SIGNAL(timeout()), this, SLOT(SpinOnce()));
    }

    node_ = new ros::NodeHandle("~");

    // Create a sub-menu that lists all available Image Transports
    image_transport::ImageTransport it(*node_);
    std::vector<std::string> transports = it.getLoadableTransports();
    QActionGroup* group = new QActionGroup(image_transport_menu_);
    for (std::vector<std::string>::iterator iter = transports.begin(); iter != transports.end(); iter++)
    {
      QString transport = QString::fromStdString(*iter).replace(
          QString::fromStdString(IMAGE_TRANSPORT_PARAM) + "/", "");
      QAction* action = image_transport_menu_->addAction(transport);
      action->setCheckable(true);
      group->addAction(action);
    }

    connect(group, SIGNAL(triggered(QAction*)), this, SLOT(SetImageTransport(QAction*)));

    tf_ = boost::make_shared<tf::TransformListener>();
    tf_manager_ = boost::make_shared<swri_transform_util::TransformManager>();
    tf_manager_->Initialize(tf_);

    loader_ = new pluginlib::ClassLoader<MapvizPlugin>(
        "mapviz", "mapviz::MapvizPlugin");

    std::vector<std::string> plugins = loader_->getDeclaredClasses();
    for (unsigned int i = 0; i < plugins.size(); i++)
    {
      ROS_INFO("Found mapviz plugin: %s", plugins[i].c_str());
    }

    canvas_->InitializeTf(tf_);
    canvas_->SetFixedFrame(ui_.fixedframe->currentText().toStdString());
    canvas_->SetTargetFrame(ui_.targetframe->currentText().toStdString());

    ros::NodeHandle priv("~");

    add_display_srv_ = node_->advertiseService("add_mapviz_display", &Mapviz::AddDisplay, this);

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    QString default_path = QDir::homePath();
    if (env.contains(ROS_WORKSPACE_VAR))
    {
      // If the ROS_WORKSPACE environment variable is defined, try to read our
      // config file out of that.  If we can't read it, fall back to trying to
      // read one from the user's home directory.
      QString ws_path = env.value(ROS_WORKSPACE_VAR, default_path);
      if (QFileInfo(ws_path + MAPVIZ_CONFIG_FILE).isReadable())
      {
        default_path = ws_path;
      }
      else
      {
        ROS_WARN("Could not load config file from ROS_WORKSPACE at %s; trying home directory...",
                 ws_path.toStdString().c_str());
      }
    }
    default_path += MAPVIZ_CONFIG_FILE;


    std::string config;
    priv.param("config", config, default_path.toStdString());

    bool auto_save;
    priv.param("auto_save_backup", auto_save, true);

    Open(config);

    UpdateFrames();
    frame_timer_.start(1000);
    connect(&frame_timer_, SIGNAL(timeout()), this, SLOT(UpdateFrames()));

    if (auto_save)
    {
      save_timer_.start(10000);
      connect(&save_timer_, SIGNAL(timeout()), this, SLOT(AutoSave()));
    }

    connect(&record_timer_, SIGNAL(timeout()), this, SLOT(CaptureVideoFrame()));

    bool print_profile_data;
    priv.param("print_profile_data", print_profile_data, false);
    if (print_profile_data)
    {
      profile_timer_.start(2000);
      connect(&profile_timer_, SIGNAL(timeout()), this, SLOT(HandleProfileTimer()));
    }

    initialized_ = true;
  }
}