예제 #1
0
void ProxyManager::unset()
{
    this->_host = QString();
    this->_port = 0;

    qunsetenv("http_proxy");
    qunsetenv("https_proxy");
    qunsetenv("ftp_proxy");
    qunsetenv("rsync_proxy");

    if(QFile::exists(this->_proxyfile))
        QFile::remove(this->_proxyfile);
}
예제 #2
0
void SettingsWidget::applyProxy()
{
	Settings &QMPSettings = QMPlay2Core.getSettings();
	if (!QMPSettings.getBool("Proxy/Use"))
	{
		qunsetenv("http_proxy");
	}
	else
	{
		const QString proxyHostName = QMPSettings.getString("Proxy/Host");
		const quint16 proxyPort = QMPSettings.getInt("Proxy/Port");
		QString proxyUser, proxyPassword;
		if (QMPSettings.getBool("Proxy/Login"))
		{
			proxyUser = QMPSettings.getString("Proxy/User");
			proxyPassword = QByteArray::fromBase64(QMPSettings.getByteArray("Proxy/Password"));
		}

		/* Proxy env for FFmpeg */
		QString proxyEnv = QString("http://" + proxyHostName + ':' + QString::number(proxyPort));
		if (!proxyUser.isEmpty())
		{
			QString auth = proxyUser;
			if (!proxyPassword.isEmpty())
				auth += ':' + proxyPassword;
			auth += '@';
			proxyEnv.insert(7, auth);
		}
		qputenv("http_proxy", proxyEnv.toLocal8Bit());
	}
}
예제 #3
0
void tst_QGetPutEnv::getSetCheck()
{
    const char varName[] = "should_not_exist";

    QVERIFY(!qEnvironmentVariableIsSet(varName));
    QVERIFY(qEnvironmentVariableIsEmpty(varName));
    QByteArray result = qgetenv(varName);
    QCOMPARE(result, QByteArray());

#ifndef Q_OS_WIN
    QVERIFY(qputenv(varName, "")); // deletes varName instead of making it empty, on Windows

    QVERIFY(qEnvironmentVariableIsSet(varName));
    QVERIFY(qEnvironmentVariableIsEmpty(varName));
#endif

    QVERIFY(qputenv(varName, QByteArray("supervalue")));

    QVERIFY(qEnvironmentVariableIsSet(varName));
    QVERIFY(!qEnvironmentVariableIsEmpty(varName));
    result = qgetenv(varName);
    QVERIFY(result == "supervalue");

    qputenv(varName,QByteArray());

    // Now test qunsetenv
    QVERIFY(qunsetenv(varName));
    QVERIFY(!qEnvironmentVariableIsSet(varName));
    QVERIFY(qEnvironmentVariableIsEmpty(varName));
    result = qgetenv(varName);
    QCOMPARE(result, QByteArray());
}
예제 #4
0
void TestsCommon::init()
{
    qunsetenv("VLC_PLUGIN_PATH");

#ifndef Q_OS_DARWIN
    VlcCommon::setPluginPath(QString(LIBVLC_PLUGINS_DIR));
#endif

    _instance = new VlcInstance(VlcCommon::args(), this);
    _instance->setLogLevel(Vlc::DebugLevel);
}
예제 #5
0
MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString appPath = qgetenv("bfcrashreport_apppath");
    QString dumpPath = qgetenv("bfcrashreport_dumppath");
    QString webSite = qgetenv("bfcrashreport_website");

    qunsetenv("bfcrashreport_apppath");
    qunsetenv("bfcrashreport_dumppath");
    qunsetenv("bfcrashreport_website");

    QString appName = QFileInfo(appPath).baseName();
    this->setWindowTitle(appName + " crashed!!!");
    ui->lineEditAppPath->setText(appPath);
    ui->lineEditDumpPath->setText(dumpPath);
    ui->lineEditWebSite->setText(webSite);
}
예제 #6
0
int main(int argc, char **argv)
{
    qunsetenv("QT_DEVICE_PIXEL_RATIO");
    QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);

    KLocalizedString::setApplicationDomain("krunner");

    QQuickWindow::setDefaultAlphaBuffer(true);
    QApplication app(argc, argv);

    KQuickAddons::QtQuickSettings::init();

//     TODO: Make it a QGuiApplication once we don't depend on KDELibs4Support
//     QGuiApplication app(argc, argv);
    app.setApplicationName(QStringLiteral("krunner"));
    app.setOrganizationDomain(QStringLiteral("kde.org"));
    app.setApplicationVersion(QStringLiteral(PROJECT_VERSION));
    app.setQuitOnLastWindowClosed(false);
    parser.setApplicationDescription(i18n("Run Command interface"));

    parser.addHelpOption();
    parser.addVersionOption();
    parser.process(app);

    if (!KAuthorized::authorize(QStringLiteral("run_command"))) {
        return -1;
    }

    KDBusService service(KDBusService::Unique);

    KAboutData aboutData(QStringLiteral("krunner"),
        i18n("krunner"),
        QStringLiteral(PROJECT_VERSION),
        i18n("Run Command interface"),
        KAboutLicense::GPL);

    KAboutData::setApplicationData(aboutData);

    QGuiApplication::setFallbackSessionManagementEnabled(false);

    auto disableSessionManagement = [](QSessionManager &sm) {
        sm.setRestartHint(QSessionManager::RestartNever);
    };
    QObject::connect(&app, &QGuiApplication::commitDataRequest, disableSessionManagement);
    QObject::connect(&app, &QGuiApplication::saveStateRequest, disableSessionManagement);

    View view;
    view.setVisible(false);

    QObject::connect(&service, &KDBusService::activateRequested, &view, &View::display);

    return app.exec();
}
예제 #7
0
void CompositorLauncher::setupEnvironment()
{
    // Make clients run on Wayland
    if (m_hardware == BroadcomHardware) {
        qputenv("QT_QPA_PLATFORM", QByteArray("wayland-brcm"));
        qputenv("QT_WAYLAND_HARDWARE_INTEGRATION", QByteArray("brcm-egl"));
        qputenv("QT_WAYLAND_CLIENT_BUFFER_INTEGRATION", QByteArray("brcm-egl"));
    } else {
        qputenv("QT_QPA_PLATFORM", QByteArray("wayland"));
    }
    qputenv("GDK_BACKEND", QByteArray("wayland"));
    
    qunsetenv("WAYLAND_DISPLAY");
}
예제 #8
0
void NetworkAccessManager::setProxy(const QString &proxyType, const QString &proxy, int port)
{
    if (proxyType == "no" || proxy.isEmpty())
    {
        // Set proxy for this access manager
        QNetworkAccessManager::setProxy(QNetworkProxy(QNetworkProxy::NoProxy));
        // QWebEngine uses application proxy
        QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::NoProxy));
        // libmpv uses proxy from environment
        qunsetenv("http_proxy");
    }
    else if (proxyType == "socks5")
    {
        QNetworkAccessManager::setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, proxy, port));
        QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, proxy, port));
        qunsetenv("http_proxy");
    }
    else if (proxyType == "http")
    {
        QNetworkAccessManager::setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, port));
        QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, port));
        qputenv("http_proxy", QString("http://%1:%2").arg(proxy, QString::number(port)).toUtf8());
    }
    else if (proxyType == "http_unblockcn")
    {
        // this access manager does not use proxy
        QNetworkAccessManager::setProxy(QNetworkProxy(QNetworkProxy::NoProxy));
        // QWebEngine uses proxy to parse videos
        QNetworkProxy::setApplicationProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, port));
        // libmpv does not use proxy
        qunsetenv("http_proxy");
        // access manager for unblocking
        if (amForUnblock == NULL)
            amForUnblock = new QNetworkAccessManager(this);
        amForUnblock->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, port));
    }
}
예제 #9
0
파일: main.cpp 프로젝트: tsuibin/dde-dock
// let startdde know that we've already started.
void RegisterDdeSession()
{
    QString envName("DDE_SESSION_PROCESS_COOKIE_ID");

    QByteArray cookie = qgetenv(envName.toUtf8().data());
    qunsetenv(envName.toUtf8().data());

    if (!cookie.isEmpty()) {
        QDBusInterface iface("com.deepin.SessionManager",
                             "/com/deepin/SessionManager",
                             "com.deepin.SessionManager",
                             QDBusConnection::sessionBus());
        iface.asyncCall("Register", QString(cookie));
    }
}
예제 #10
0
파일: main.cpp 프로젝트: openmv/openmv-swd
int main(int argc, char **argv)
{
    const char *highDpiEnvironmentVariable = setHighDpiEnvironmentVariable();

#ifdef Q_OS_MAC
    // increase the number of file that can be opened.
    struct rlimit rl;
    getrlimit(RLIMIT_NOFILE, &rl);

    rl.rlim_cur = qMin((rlim_t)OPEN_MAX, rl.rlim_max);
    setrlimit(RLIMIT_NOFILE, &rl);
#endif

    SharedTools::QtSingleApplication app(QLatin1String("OpenMV SWD"), argc, argv);

    if (app.sendMessage(QLatin1String("Hello World!"))) {
        return 0;
    }

    if (highDpiEnvironmentVariable)
        qunsetenv(highDpiEnvironmentVariable);

#if defined(Q_OS_WIN)
    if(!qFuzzyCompare(qApp->devicePixelRatio(), 1.0)
            && QApplication::style()->objectName().startsWith(
                QLatin1String("windows"), Qt::CaseInsensitive)) {
        QApplication::setStyle(QLatin1String("fusion"));
    }
#endif

    const int threadCount = QThreadPool::globalInstance()->maxThreadCount();
    QThreadPool::globalInstance()->setMaxThreadCount(qMax(4, 2 * threadCount));

    app.setAttribute(Qt::AA_UseHighDpiPixmaps);

    // Make sure we honor the system's proxy settings
    QNetworkProxyFactory::setUseSystemConfiguration(true);

    OpenMVSWD *w = new OpenMVSWD();
    app.setActivationWindow(w);

    QTimer::singleShot(1, w, [w] {w->show();});
    return app.exec();
}
예제 #11
0
int main(int argc, char *argv[])
{
    // Disable it because we already support HDPI display natively
    qunsetenv("QT_DEVICE_PIXEL_RATIO");

    QGuiApplication app(argc, argv);
    app.setOrganizationName("KDE");
    app.setApplicationName(GCOMPRIS_APPLICATION_NAME);
    app.setOrganizationDomain("kde.org");
    app.setApplicationVersion(ApplicationInfo::GCVersion());

    // Local scope for config
    QSettings config(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) +
                     "/gcompris/" + GCOMPRIS_APPLICATION_NAME + ".conf",
                     QSettings::IniFormat);

    // Load translations
    QTranslator translator;
    QString locale = loadTranslation(config, translator);
    // Apply translation
    app.installTranslator(&translator);

    QCommandLineParser parser;
    parser.setApplicationDescription("GCompris is an educational software for children 2 to 10");
    parser.addHelpOption();
    parser.addVersionOption();
    QCommandLineOption exportActivitiesAsSQL("export-activities-as-sql", "Export activities as SQL");
    parser.addOption(exportActivitiesAsSQL);
	QCommandLineOption clDefaultCursor(QStringList() << "c" << "cursor",
                                       QObject::tr("Run GCompris with the default system cursor."));
	parser.addOption(clDefaultCursor);
    QCommandLineOption clNoCursor(QStringList() << "C" << "nocursor",
                                       QObject::tr("Run GCompris without cursor (touch screen mode)."));
    parser.addOption(clNoCursor);
    QCommandLineOption clFullscreen(QStringList() << "f" << "fullscreen",
                                       QObject::tr("Run GCompris in fullscreen mode."));
    parser.addOption(clFullscreen);
    QCommandLineOption clWindow(QStringList() << "w" << "window",
                                       QObject::tr("Run GCompris in window mode."));
    parser.addOption(clWindow);
    QCommandLineOption clSound(QStringList() << "s" << "sound",
                                       QObject::tr("Run GCompris with sound enabled."));
    parser.addOption(clSound);
    QCommandLineOption clMute(QStringList() << "m" << "mute",
                                       QObject::tr("Run GCompris without sound."));
    parser.addOption(clMute);
    QCommandLineOption clWithoutConfig(QStringList() << "disable-config",
                                       QObject::tr("Disable the configuration button."));
    parser.addOption(clWithoutConfig);
    QCommandLineOption clWithConfig(QStringList() << "enable-config",
                                       QObject::tr("Enable the configuration button (default)."));
    parser.addOption(clWithConfig);
    parser.process(app);


    ApplicationInfo::init();
	ActivityInfoTree::init();
    ApplicationSettings::init();
	File::init();
	DownloadManager::init();

    // Tell media players to stop playing, it's GCompris time
    ApplicationInfo::getInstance()->requestAudioFocus();

    // Must be done after ApplicationSettings is constructed because we get an
    // async callback from the payment system
    ApplicationSettings::getInstance()->checkPayment();

    // Getting fullscreen mode from config if exist, else true is default value
    bool isFullscreen = true;
    {

        if(config.contains("General/fullscreen")) {
            isFullscreen = config.value("General/fullscreen").toBool();
        }

		// Set the cursor image
		bool defaultCursor = false;
		if(config.contains("General/defaultCursor")) {
			defaultCursor = config.value("General/defaultCursor").toBool();
		}
		if(!defaultCursor && !parser.isSet(clDefaultCursor))
			QGuiApplication::setOverrideCursor(
						QCursor(QPixmap(":/gcompris/src/core/resource/cursor.svg"),
								0, 0));

		// Hide the cursor
		bool noCursor = false;
		if(config.contains("General/noCursor")) {
			noCursor = config.value("General/noCursor").toBool();
		}
		if(noCursor || parser.isSet(clNoCursor))
			QGuiApplication::setOverrideCursor(QCursor(Qt::BlankCursor));
    }

    // Update execution counter
    ApplicationSettings::getInstance()->setExeCount(ApplicationSettings::getInstance()->exeCount() + 1);

    // Register voices-resources for current locale, updates/downloads only if
    // not prohibited by the settings
    if(!DownloadManager::getInstance()->areVoicesRegistered())
        DownloadManager::getInstance()->updateResource(DownloadManager::getInstance()
            ->getVoicesResourceForLocale(locale));

    if(parser.isSet(clFullscreen)) {
        isFullscreen = true;
    }
    if(parser.isSet(clWindow)) {
        isFullscreen = false;
    }
    if(parser.isSet(clMute)) {
        ApplicationSettings::getInstance()->setIsAudioEffectsEnabled(false);
        ApplicationSettings::getInstance()->setIsAudioVoicesEnabled(false);
    }
    if(parser.isSet(clSound)) {
        ApplicationSettings::getInstance()->setIsAudioEffectsEnabled(true);
        ApplicationSettings::getInstance()->setIsAudioVoicesEnabled(true);
    }
    if(parser.isSet(clWithConfig)) {
        ApplicationSettings::getInstance()->setKioskMode(false);
    }
    if(parser.isSet(clWithoutConfig)) {
        ApplicationSettings::getInstance()->setKioskMode(true);
    }

    QQmlApplicationEngine engine(QUrl("qrc:/gcompris/src/core/main.qml"));
    QObject::connect(&engine, SIGNAL(quit()), DownloadManager::getInstance(),
                     SLOT(shutdown()));
    // add import path for shipped qml modules:
#ifdef SAILFISHOS
    engine.addImportPath(QStringLiteral("%1/../share/%2/lib/qml")
                         .arg(QCoreApplication::applicationDirPath()).arg(GCOMPRIS_APPLICATION_NAME));
#else
    engine.addImportPath(QStringLiteral("%1/../lib/qml")
                         .arg(QCoreApplication::applicationDirPath()));
#endif

    if(parser.isSet(exportActivitiesAsSQL)) {
        ActivityInfoTree *menuTree(qobject_cast<ActivityInfoTree*>(ActivityInfoTree::menuTreeProvider(&engine, NULL)));
        menuTree->exportAsSQL();
        exit(0);
    }

    QObject *topLevel = engine.rootObjects().value(0);

    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
    if (!window) {
		qWarning("Error: Your root item has to be a Window.");
		return -1;
	}

    ApplicationInfo::setWindow(window);

    window->setIcon(QIcon(QPixmap(QString::fromUtf8(":/gcompris/src/core/resource/gcompris-icon.png"))));

    if(isFullscreen) {
        window->showFullScreen();
    }
    else {
        window->show();
    }

	return app.exec();

}
예제 #12
0
파일: main.cpp 프로젝트: Artiom-M/xpiks
int main(int argc, char *argv[]) {
    const QString runGuardName = getRunGuardName();
    Helpers::RunGuard guard(runGuardName);
    if (!guard.tryToRun()) {
        std::cerr << "Xpiks is already running";
        return -1;
    }

    // will call curl_global_init and cleanup
    Conectivity::CurlInitHelper curlInitHelper;
    Q_UNUSED(curlInitHelper);

    // will init thread-unsafe XMP toolkit
    MetadataIO::Exiv2InitHelper exiv2InitHelper;
    Q_UNUSED(exiv2InitHelper);

    const char *highDpiEnvironmentVariable = setHighDpiEnvironmentVariable();
    qRegisterMetaTypeStreamOperators<Models::ProxySettings>("ProxySettings");
    qRegisterMetaType<Common::SpellCheckFlags>("Common::SpellCheckFlags");
    initQSettings();
    Helpers::AppSettings appSettings;
    ensureUserIdExists(&appSettings);

    Suggestion::LocalLibrary localLibrary;

    QString appDataPath = XPIKS_USERDATA_PATH;
    if (!appDataPath.isEmpty()) {
        QDir appDataDir(appDataPath);

        QString libraryFilePath = appDataDir.filePath(Constants::LIBRARY_FILENAME);
        localLibrary.setLibraryPath(libraryFilePath);
    } else {
        std::cerr << "AppDataPath is empty!";
    }

#ifdef WITH_LOGS
    const QString &logFileDir = QDir::cleanPath(appDataPath + QDir::separator() + "logs");
    if (!logFileDir.isEmpty()) {
        QDir dir(logFileDir);
        if (!dir.exists()) {
            bool created = QDir().mkpath(logFileDir);
            Q_UNUSED(created);
        }

        QString time = QDateTime::currentDateTimeUtc().toString("ddMMyyyy-hhmmss-zzz");
        QString logFilename = QString("xpiks-qt-%1.log").arg(time);

        QString logFilePath = dir.filePath(logFilename);

        Helpers::Logger &logger = Helpers::Logger::getInstance();
        logger.setLogFilePath(logFilePath);
    }

#endif

    QMLExtensions::ColorsModel colorsModel;
    Models::LogsModel logsModel(&colorsModel);
    logsModel.startLogging();

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
    qSetMessagePattern("%{time hh:mm:ss.zzz} %{type} T#%{threadid} %{function} - %{message}");
#endif

    qInstallMessageHandler(myMessageHandler);

    LOG_INFO << "Log started. Today is" << QDateTime::currentDateTimeUtc().toString("dd.MM.yyyy");
    LOG_INFO << "Xpiks" << XPIKS_VERSION_STRING << "-" << STRINGIZE(BUILDNUMBER);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
    LOG_INFO << QSysInfo::productType() << QSysInfo::productVersion() << QSysInfo::currentCpuArchitecture();
#else
#ifdef Q_OS_WIN
    LOG_INFO << QLatin1String("Windows Qt<5.4");
#elsif Q_OS_DARWIN
    LOG_INFO << QLatin1String("OS X Qt<5.4");
#else
    LOG_INFO << QLatin1String("LINUX Qt<5.4");
#endif
#endif

    QApplication app(argc, argv);

    LOG_INFO << "Working directory of Xpiks is:" << QDir::currentPath();
    LOG_DEBUG << "Extra files search locations:" << QStandardPaths::standardLocations(XPIKS_DATA_LOCATION_TYPE);

    if (highDpiEnvironmentVariable) {
        qunsetenv(highDpiEnvironmentVariable);
    }

    localLibrary.loadLibraryAsync();

    QString userId = appSettings.value(QLatin1String(Constants::USER_AGENT_ID)).toString();
    userId.remove(QRegExp("[{}-]."));

    Models::ArtworksRepository artworkRepository;
    Models::ArtItemsModel artItemsModel;
    Models::CombinedArtworksModel combinedArtworksModel;
    Models::UploadInfoRepository uploadInfoRepository;
    Warnings::WarningsService warningsService;
    Models::SettingsModel settingsModel;
    settingsModel.readAllValues();
    Encryption::SecretsManager secretsManager;
    UndoRedo::UndoRedoManager undoRedoManager;
    Models::ZipArchiver zipArchiver;
    Suggestion::KeywordsSuggestor keywordsSuggestor(&localLibrary);
    Models::FilteredArtItemsProxyModel filteredArtItemsModel;
    filteredArtItemsModel.setSourceModel(&artItemsModel);
    Models::RecentDirectoriesModel recentDirectorieModel;
    Conectivity::FtpCoordinator *ftpCoordinator = new Conectivity::FtpCoordinator(settingsModel.getMaxParallelUploads());
    Models::ArtworkUploader artworkUploader(ftpCoordinator);
    SpellCheck::SpellCheckerService spellCheckerService;
    SpellCheck::SpellCheckSuggestionModel spellCheckSuggestionModel;
    MetadataIO::BackupSaverService metadataSaverService;
    Warnings::WarningsModel warningsModel;
    warningsModel.setSourceModel(&artItemsModel);
    warningsModel.setWarningsSettingsModel(warningsService.getWarningsSettingsModel());
    Models::LanguagesModel languagesModel;
    AutoComplete::AutoCompleteModel autoCompleteModel;
    AutoComplete::AutoCompleteService autoCompleteService(&autoCompleteModel);
    QMLExtensions::ImageCachingService imageCachingService;
    Models::FindAndReplaceModel replaceModel(&colorsModel);
    Models::DeleteKeywordsViewModel deleteKeywordsModel;

    Conectivity::UpdateService updateService(&settingsModel);

    MetadataIO::MetadataIOCoordinator metadataIOCoordinator;

#if defined(QT_NO_DEBUG) && !defined(TELEMETRY_DISABLED)
    const bool telemetryEnabled = appSettings.value(Constants::USER_STATISTICS, true).toBool();
#else
    const bool telemetryEnabled = false;
#endif
    Conectivity::TelemetryService telemetryService(userId, telemetryEnabled);

    Plugins::PluginManager pluginManager;
    Plugins::PluginsWithActionsModel pluginsWithActions;
    pluginsWithActions.setSourceModel(&pluginManager);

    Helpers::HelpersQmlWrapper helpersQmlWrapper;

    LOG_INFO << "Models created";

    Commands::CommandManager commandManager;
    commandManager.InjectDependency(&artworkRepository);
    commandManager.InjectDependency(&artItemsModel);
    commandManager.InjectDependency(&filteredArtItemsModel);
    commandManager.InjectDependency(&combinedArtworksModel);
    commandManager.InjectDependency(&artworkUploader);
    commandManager.InjectDependency(&uploadInfoRepository);
    commandManager.InjectDependency(&warningsService);
    commandManager.InjectDependency(&secretsManager);
    commandManager.InjectDependency(&undoRedoManager);
    commandManager.InjectDependency(&zipArchiver);
    commandManager.InjectDependency(&keywordsSuggestor);
    commandManager.InjectDependency(&settingsModel);
    commandManager.InjectDependency(&recentDirectorieModel);
    commandManager.InjectDependency(&spellCheckerService);
    commandManager.InjectDependency(&spellCheckSuggestionModel);
    commandManager.InjectDependency(&metadataSaverService);
    commandManager.InjectDependency(&telemetryService);
    commandManager.InjectDependency(&updateService);
    commandManager.InjectDependency(&logsModel);
    commandManager.InjectDependency(&localLibrary);
    commandManager.InjectDependency(&metadataIOCoordinator);
    commandManager.InjectDependency(&pluginManager);
    commandManager.InjectDependency(&languagesModel);
    commandManager.InjectDependency(&colorsModel);
    commandManager.InjectDependency(&autoCompleteService);
    commandManager.InjectDependency(&imageCachingService);
    commandManager.InjectDependency(&replaceModel);
    commandManager.InjectDependency(&deleteKeywordsModel);
    commandManager.InjectDependency(&helpersQmlWrapper);

    commandManager.ensureDependenciesInjected();

    keywordsSuggestor.initSuggestionEngines();

    // other initializations
    secretsManager.setMasterPasswordHash(appSettings.value(Constants::MASTER_PASSWORD_HASH, "").toString());
    uploadInfoRepository.initFromString(appSettings.value(Constants::UPLOAD_HOSTS, "").toString());
    recentDirectorieModel.deserializeFromSettings(appSettings.value(Constants::RECENT_DIRECTORIES, "").toString());

    commandManager.connectEntitiesSignalsSlots();

    languagesModel.initFirstLanguage();
    languagesModel.loadLanguages();

    telemetryService.setInterfaceLanguage(languagesModel.getCurrentLanguage());

    qmlRegisterType<Helpers::ClipboardHelper>("xpiks", 1, 0, "ClipboardHelper");
    qmlRegisterType<QMLExtensions::TriangleElement>("xpiks", 1, 0, "TriangleElement");

    QQmlApplicationEngine engine;
    Helpers::GlobalImageProvider *globalProvider = new Helpers::GlobalImageProvider(QQmlImageProviderBase::Image);
    QMLExtensions::CachingImageProvider *cachingProvider = new QMLExtensions::CachingImageProvider(QQmlImageProviderBase::Image);
    cachingProvider->setImageCachingService(&imageCachingService);

    QQmlContext *rootContext = engine.rootContext();
    rootContext->setContextProperty("artItemsModel", &artItemsModel);
    rootContext->setContextProperty("artworkRepository", &artworkRepository);
    rootContext->setContextProperty("combinedArtworks", &combinedArtworksModel);
    rootContext->setContextProperty("appSettings", &appSettings);
    rootContext->setContextProperty("secretsManager", &secretsManager);
    rootContext->setContextProperty("undoRedoManager", &undoRedoManager);
    rootContext->setContextProperty("keywordsSuggestor", &keywordsSuggestor);
    rootContext->setContextProperty("settingsModel", &settingsModel);
    rootContext->setContextProperty("filteredArtItemsModel", &filteredArtItemsModel);
    rootContext->setContextProperty("helpersWrapper", &helpersQmlWrapper);
    rootContext->setContextProperty("recentDirectories", &recentDirectorieModel);
    rootContext->setContextProperty("metadataIOCoordinator", &metadataIOCoordinator);
    rootContext->setContextProperty("pluginManager", &pluginManager);
    rootContext->setContextProperty("pluginsWithActions", &pluginsWithActions);
    rootContext->setContextProperty("warningsModel", &warningsModel);
    rootContext->setContextProperty("languagesModel", &languagesModel);
    rootContext->setContextProperty("i18", &languagesModel);
    rootContext->setContextProperty("Colors", &colorsModel);
    rootContext->setContextProperty("acSource", &autoCompleteModel);
    rootContext->setContextProperty("replaceModel", &replaceModel);

#ifdef QT_DEBUG
    QVariant isDebug(true);
#else
    QVariant isDebug(false);
#endif
    rootContext->setContextProperty("debug", isDebug);

    engine.addImageProvider("global", globalProvider);
    engine.addImageProvider("cached", cachingProvider);

    LOG_DEBUG << "About to load main view...";
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    LOG_DEBUG << "Main view loaded";

    pluginManager.getUIProvider()->setQmlEngine(&engine);
    QQuickWindow *window = qobject_cast<QQuickWindow *>(engine.rootObjects().at(0));
    pluginManager.getUIProvider()->setRoot(window->contentItem());

#ifdef QT_DEBUG
    if (argc > 1) {
        QList<QUrl> pathes;
        for (int i = 1; i < argc; ++i) {
            pathes.append(QUrl::fromLocalFile(QString::fromUtf8(argv[i])));
        }

        commandManager.addInitialArtworks(pathes);
    }

#endif

    commandManager.afterConstructionCallback();

    return app.exec();
}
예제 #13
0
extern "C" Q_DECL_EXPORT int kdemain(int argc, char **argv)
{
#ifndef Q_OS_WIN
    // Started via kdeinit.
    int launcherFd;
    if (argc != 2 || memcmp(argv[1], "--fd=", 5) || !(launcherFd = atoi(argv[1] + 5))) {
        fprintf(stderr, "%s", i18n("klauncher: This program is not supposed to be started manually.\n"
                                   "klauncher: It is started automatically by kdeinit5.\n").toLocal8Bit().data());
        return 1;
    }
#endif

#if defined(Q_OS_DARWIN)
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    if (mainBundle) {
        // get the application's Info Dictionary. For app bundles this would live in the bundle's Info.plist,
        // for regular executables it is obtained in another way.
        CFMutableDictionaryRef infoDict = (CFMutableDictionaryRef) CFBundleGetInfoDictionary(mainBundle);
        if (infoDict) {
            // Add or set the "LSUIElement" key with/to value "1". This can simply be a CFString.
            CFDictionarySetValue(infoDict, CFSTR("LSUIElement"), CFSTR("1"));
            // That's it. We're now considered as an "agent" by the window server, and thus will have
            // neither menubar nor presence in the Dock or App Switcher.
        }
    }
    mac_initialize_dbus();
#endif

    // WABA: Make sure not to enable session management.
    qunsetenv("SESSION_MANAGER");

    // Disable the GLib event loop (rh#983110)
    const bool wasQtNoGlibSet = !qEnvironmentVariableIsEmpty("QT_NO_GLIB");
    if (!wasQtNoGlibSet) {
       qputenv("QT_NO_GLIB", "1");
    }

    // We need a QGuiApplication as we use X11
    QGuiApplication app(argc, argv);
    app.setApplicationName(QStringLiteral("klauncher"));

    // Now get rid of QT_NO_GLIB again so launched processes don't inherit it
    if (!wasQtNoGlibSet) {
       qunsetenv("QT_NO_GLIB");
    }

    int maxTry = 3;
    while (true) {
        QString service(QStringLiteral("org.kde.klauncher5")); // same as ktoolinvocation.cpp
        if (!QDBusConnection::sessionBus().isConnected()) {
            qWarning() << "No DBUS session-bus found. Check if you have started the DBUS server.";
            return 1;
        }
        QDBusReply<QDBusConnectionInterface::RegisterServiceReply> reply =
            QDBusConnection::sessionBus().interface()->registerService(service);
        if (!reply.isValid()) {
            qWarning() << "DBUS communication problem!";
            return 1;
        }
        if (reply == QDBusConnectionInterface::ServiceRegistered) {
            break;
        }

        if (--maxTry == 0) {
            qWarning() << "Another instance of klauncher is already running!";
            return 1;
        }

        // Wait a bit...
        qWarning() << "Waiting for already running klauncher to exit.";
        QThread::sleep(1);

        // Try again...
    }

#ifndef USE_KPROCESS_FOR_KIOSLAVES
    KLauncher *launcher = new KLauncher(launcherFd);
#else
    KLauncher *launcher = new KLauncher();
#endif
    QDBusConnection::sessionBus().registerObject(QStringLiteral("/"), launcher);

#ifndef USE_KPROCESS_FOR_KIOSLAVES
    if (pipe(sigpipe) != 0) {
        perror("klauncher: pipe failed.");
        return 1;
    }
    QSocketNotifier *signotif = new QSocketNotifier(sigpipe[ 0 ], QSocketNotifier::Read, launcher);
    QObject::connect(signotif, SIGNAL(activated(int)), launcher, SLOT(destruct()));
    KCrash::setEmergencySaveFunction(sig_handler);
    signal(SIGHUP, sig_handler);
    signal(SIGPIPE, SIG_IGN);
    signal(SIGTERM, sig_handler);
#endif

    return app.exec();
}
예제 #14
0
int main(int argc, char *argv[])
{
    // Disable it because we already support HDPI display natively
    qunsetenv("QT_DEVICE_PIXEL_RATIO");

    QApplication app(argc, argv);
    app.setOrganizationName("KDE");
    app.setApplicationName(GCOMPRIS_APPLICATION_NAME);
    app.setOrganizationDomain("kde.org");
    app.setApplicationVersion(ApplicationInfo::GCVersion());
    
    //add a variable to disable default fullscreen on Mac, see below..
#if defined(Q_OS_MAC)
    // Sandboxing on MacOSX as documented in:
    // http://doc.qt.io/qt-5/osx-deployment.html
    QDir dir(QGuiApplication::applicationDirPath());
    dir.cdUp();
    dir.cd("Plugins");
    QGuiApplication::setLibraryPaths(QStringList(dir.absolutePath()));
#endif

    // Local scope for config
    QSettings config(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) +
                     "/gcompris/" + GCOMPRIS_APPLICATION_NAME + ".conf",
                     QSettings::IniFormat);

    // Load translations
    QTranslator translator;
    loadTranslation(config, translator);
    // Apply translation
    app.installTranslator(&translator);

    QCommandLineParser parser;
    parser.setApplicationDescription("GCompris is an educational software for children 2 to 10");
    parser.addHelpOption();
    parser.addVersionOption();
    QCommandLineOption exportActivitiesAsSQL("export-activities-as-sql", "Export activities as SQL");
    parser.addOption(exportActivitiesAsSQL);
    QCommandLineOption clDefaultCursor(QStringList() << "c" << "cursor",
                                       QObject::tr("Run GCompris with the default system cursor."));
    parser.addOption(clDefaultCursor);
    QCommandLineOption clNoCursor(QStringList() << "C" << "nocursor",
                                       QObject::tr("Run GCompris without cursor (touch screen mode)."));
    parser.addOption(clNoCursor);
    QCommandLineOption clFullscreen(QStringList() << "f" << "fullscreen",
                                       QObject::tr("Run GCompris in fullscreen mode."));
    parser.addOption(clFullscreen);
    QCommandLineOption clWindow(QStringList() << "w" << "window",
                                       QObject::tr("Run GCompris in window mode."));
    parser.addOption(clWindow);
    QCommandLineOption clSound(QStringList() << "s" << "sound",
                                       QObject::tr("Run GCompris with sound enabled."));
    parser.addOption(clSound);
    QCommandLineOption clMute(QStringList() << "m" << "mute",
                                       QObject::tr("Run GCompris without sound."));
    parser.addOption(clMute);
    QCommandLineOption clWithoutKioskMode(QStringList() << "disable-kioskmode",
                                       QObject::tr("Disable the kiosk mode (default)."));
    parser.addOption(clWithoutKioskMode);
    QCommandLineOption clWithKioskMode(QStringList() << "enable-kioskmode",
                                       QObject::tr("Enable the kiosk mode."));
    parser.addOption(clWithKioskMode);

    QCommandLineOption clSoftwareRenderer(QStringList() << "software-renderer",
                                       QObject::tr("Use software renderer instead of openGL (slower but should run with any graphical card, needs Qt 5.8 minimum)."));
    parser.addOption(clSoftwareRenderer);
    QCommandLineOption clOpenGLRenderer(QStringList() << "opengl-renderer",
                                       QObject::tr("Use openGL renderer instead of software (faster but crash potentially depending on your graphical card)."));
    parser.addOption(clOpenGLRenderer);

    parser.process(app);

    GComprisPlugin plugin;
    plugin.registerTypes("GCompris");
    ActivityInfoTree::registerResources();

    // Tell media players to stop playing, it's GCompris time
    ApplicationInfo::getInstance()->requestAudioFocus();

    // Must be done after ApplicationSettings is constructed because we get an
    // async callback from the payment system
    ApplicationSettings::getInstance()->checkPayment();

    // Disable default fullscreen launch on Mac as it's a bit broken, window is behind desktop bars
#if defined(Q_OS_MAC)
    bool isFullscreen = false;
#else
    // for other platforms, fullscreen is the default value
    bool isFullscreen = true;
#endif
    {
        isFullscreen = config.value("General/fullscreen", isFullscreen).toBool();

        // Set the cursor image
        bool defaultCursor = config.value("General/defaultCursor", false).toBool();

        if(!defaultCursor && !parser.isSet(clDefaultCursor))
            QGuiApplication::setOverrideCursor(
                                               QCursor(QPixmap(":/gcompris/src/core/resource/cursor.svg"),
                                                       0, 0));

        // Hide the cursor
        bool noCursor = config.value("General/noCursor", false).toBool();

        if(noCursor || parser.isSet(clNoCursor))
            QGuiApplication::setOverrideCursor(QCursor(Qt::BlankCursor));
    }

    // Update execution counter
    ApplicationSettings::getInstance()->setExeCount(ApplicationSettings::getInstance()->exeCount() + 1);

    if(parser.isSet(clFullscreen)) {
        isFullscreen = true;
    }
    if(parser.isSet(clWindow)) {
        isFullscreen = false;
    }
    if(parser.isSet(clMute)) {
        ApplicationSettings::getInstance()->setIsAudioEffectsEnabled(false);
        ApplicationSettings::getInstance()->setIsAudioVoicesEnabled(false);
    }
    if(parser.isSet(clSound)) {
        ApplicationSettings::getInstance()->setIsAudioEffectsEnabled(true);
        ApplicationSettings::getInstance()->setIsAudioVoicesEnabled(true);
    }
    if(parser.isSet(clWithoutKioskMode)) {
        ApplicationSettings::getInstance()->setKioskMode(false);
    }
    if(parser.isSet(clWithKioskMode)) {
        ApplicationSettings::getInstance()->setKioskMode(true);
    }
    if(parser.isSet(clSoftwareRenderer)) {
        ApplicationSettings::getInstance()->setRenderer(QStringLiteral("software"));
    }
    if(parser.isSet(clOpenGLRenderer)) {
        ApplicationSettings::getInstance()->setRenderer(QStringLiteral("opengl"));
    }

    // Set the renderer used
    const QString &renderer = ApplicationSettings::getInstance()->renderer();
    ApplicationInfo::getInstance()->setUseOpenGL(renderer != QLatin1String("software"));

#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
    if(renderer == QLatin1String("software"))
       QQuickWindow::setSceneGraphBackend(QSGRendererInterface::Software);
    else if(renderer == QLatin1String("opengl"))
       QQuickWindow::setSceneGraphBackend(QSGRendererInterface::OpenGL);
#endif

    QQmlApplicationEngine engine(QUrl("qrc:/gcompris/src/core/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::quit, DownloadManager::getInstance(),
                     &DownloadManager::shutdown);
    // add import path for shipped qml modules:
#ifdef SAILFISHOS
    engine.addImportPath(QStringLiteral("%1/../share/%2/lib/qml")
                         .arg(QCoreApplication::applicationDirPath()).arg(GCOMPRIS_APPLICATION_NAME));
#else
    engine.addImportPath(QStringLiteral("%1/../lib/qml")
                         .arg(QCoreApplication::applicationDirPath()));
#endif

    ApplicationInfo::getInstance()->setBox2DInstalled(engine);

    if(parser.isSet(exportActivitiesAsSQL)) {
        ActivityInfoTree *menuTree(qobject_cast<ActivityInfoTree*>(ActivityInfoTree::menuTreeProvider(&engine, nullptr)));
        menuTree->exportAsSQL();
        exit(0);
    }

    QObject *topLevel = engine.rootObjects().value(0);

    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
    if (window == nullptr) {
        qWarning("Error: Your root item has to be a Window.");
        return -1;
    }
    ApplicationInfo::setWindow(window);

    window->setIcon(QIcon(QPixmap(QString::fromUtf8(":/gcompris/src/core/resource/gcompris-icon.png"))));

    if(isFullscreen) {
        window->showFullScreen();
    }
    else {
        window->show();
    }

    return app.exec();
}
예제 #15
0
GLXFBConfig qglx_findConfig(Display *display, int screen , const QSurfaceFormat &format, int drawableBit)
{
    // Allow forcing LIBGL_ALWAYS_SOFTWARE for Qt 5 applications only.
    // This is most useful with drivers that only support OpenGL 1.
    // We need OpenGL 2, but the user probably doesn't want
    // LIBGL_ALWAYS_SOFTWARE in OpenGL 1 apps.
    static bool checkedForceSoftwareOpenGL = false;
    static bool forceSoftwareOpenGL = false;
    if (!checkedForceSoftwareOpenGL) {
        // If LIBGL_ALWAYS_SOFTWARE is already set, don't mess with it.
        // We want to unset LIBGL_ALWAYS_SOFTWARE at the end so it does not
        // get inherited by other processes, of course only if it wasn't
        // already set before.
        if (!qEnvironmentVariableIsEmpty("QT_XCB_FORCE_SOFTWARE_OPENGL")
            && !qEnvironmentVariableIsSet("LIBGL_ALWAYS_SOFTWARE"))
            forceSoftwareOpenGL = true;

        checkedForceSoftwareOpenGL = true;
    }

    if (forceSoftwareOpenGL)
        qputenv("LIBGL_ALWAYS_SOFTWARE", QByteArrayLiteral("1"));

    bool reduced = true;
    GLXFBConfig chosenConfig = 0;
    QSurfaceFormat reducedFormat = format;
    while (!chosenConfig && reduced) {
        QVector<int> spec = qglx_buildSpec(reducedFormat, drawableBit);
        int confcount = 0;
        GLXFBConfig *configs;
        configs = glXChooseFBConfig(display, screen,spec.constData(),&confcount);
        if (confcount)
        {
            for (int i = 0; i < confcount; i++) {
                chosenConfig = configs[i];
                // Make sure we try to get an ARGB visual if the format asked for an alpha:
                if (reducedFormat.hasAlpha()) {
                    int alphaSize;
                    glXGetFBConfigAttrib(display,configs[i],GLX_ALPHA_SIZE,&alphaSize);
                    if (alphaSize > 0) {
                        XVisualInfo *visual = glXGetVisualFromFBConfig(display, chosenConfig);
                        bool hasAlpha = false;

#if !defined(QT_NO_XRENDER)
                        XRenderPictFormat *pictFormat = XRenderFindVisualFormat(display, visual->visual);
                        hasAlpha = pictFormat->direct.alphaMask > 0;
#else
                        hasAlpha = visual->depth == 32;
#endif

                        XFree(visual);

                        if (hasAlpha)
                            break;
                    }
                } else {
                    break; // Just choose the first in the list if there's no alpha requested
                }
            }

            XFree(configs);
        }
        if (!chosenConfig)
            reducedFormat = qglx_reduceSurfaceFormat(reducedFormat,&reduced);
    }

    // unset LIBGL_ALWAYS_SOFTWARE now so other processes don't inherit it
    if (forceSoftwareOpenGL)
        qunsetenv("LIBGL_ALWAYS_SOFTWARE");

    return chosenConfig;
}
예제 #16
0
extern "C" Q_DECL_EXPORT int kdemain( int argc, char* argv[] )
{
    sanity_check(argc, argv);

    putenv((char*)"SESSION_MANAGER=");
    checkComposite();

    // force xcb QPA plugin as ksmserver is very X11 specific
    const QByteArray origQpaPlatform = qgetenv("QT_QPA_PLATFORM");
    qputenv("QT_QPA_PLATFORM", QByteArrayLiteral("xcb"));

    QQuickWindow::setDefaultAlphaBuffer(true);
    QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
    QApplication *a = new QApplication(argc, argv);

    // now the QPA platform is set, unset variable again to not launch apps with incorrect environment
    if (origQpaPlatform.isEmpty()) {
        qunsetenv("QT_QPA_PLATFORM");
    } else {
        qputenv("QT_QPA_PLATFORM", origQpaPlatform);
    }

    QApplication::setApplicationName( QStringLiteral( "ksmserver") );
    QApplication::setApplicationVersion( QString::fromLatin1( version ) );
    QApplication::setOrganizationDomain( QStringLiteral( "kde.org") );

    fcntl(ConnectionNumber(QX11Info::display()), F_SETFD, 1);

    a->setQuitOnLastWindowClosed(false); // #169486

    QCommandLineParser parser;
    parser.setApplicationDescription(i18n(description));
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption restoreOption(QStringList() << QStringLiteral("r") << QStringLiteral("restore"),
                                     i18n("Restores the saved user session if available"));
    parser.addOption(restoreOption);

    QCommandLineOption wmOption(QStringList() << QStringLiteral("w") << QStringLiteral("windowmanager"),
                                i18n("Starts <wm> in case no other window manager is \nparticipating in the session. Default is 'kwin'"),
                                i18n("wm"));
    parser.addOption(wmOption);

    QCommandLineOption nolocalOption(QStringLiteral("nolocal"),
                                     i18n("Also allow remote connections"));
    parser.addOption(nolocalOption);

    QCommandLineOption lockscreenOption(QStringLiteral("lockscreen"),
                                        i18n("Starts the session in locked mode"));
    parser.addOption(lockscreenOption);

    QCommandLineOption noLockscreenOption(QStringLiteral("no-lockscreen"),
                                         i18n("Starts without lock screen support. Only needed if other component provides the lock screen."));
    parser.addOption(noLockscreenOption);

    parser.process(*a);

//TODO: should we still use this?
//    if( !QDBusConnection::sessionBus().interface()->
//            registerService( QStringLiteral( "org.kde.ksmserver" ),
//                             QDBusConnectionInterface::DontQueueService ) )
//    {
//        qCWarning(KSMSERVER, "Could not register with D-BUS. Aborting.");
//        return 1;
//    }

    QString wm = parser.value(wmOption);

    bool only_local = !parser.isSet(nolocalOption);
#ifndef HAVE__ICETRANSNOLISTEN
    /* this seems strange, but the default is only_local, so if !only_local
     * the option --nolocal was given, and we warn (the option --nolocal
     * does nothing on this platform, as here the default is reversed)
     */
    if (!only_local) {
        qCWarning(KSMSERVER, "--nolocal is not supported on your platform. Sorry.");
    }
    only_local = false;
#endif

    KSMServer::InitFlags flags = KSMServer::InitFlag::None;
    if (only_local) {
        flags |= KSMServer::InitFlag::OnlyLocal;
    }
    if (parser.isSet(lockscreenOption)) {
        flags |= KSMServer::InitFlag::ImmediateLockScreen;
    }
    if (parser.isSet(noLockscreenOption)) {
        flags |= KSMServer::InitFlag::NoLockScreen;
    }

    KSMServer *server = new KSMServer( wm, flags);

    // for the KDE-already-running check in startkde
    KSelectionOwner kde_running( "_KDE_RUNNING", 0 );
    kde_running.claim( false );

    IceSetIOErrorHandler( IoErrorHandler );

    KConfigGroup config(KSharedConfig::openConfig(), "General");

    int realScreenCount = ScreenCount( QX11Info::display() );
    bool screenCountChanged =
         ( config.readEntry( "screenCount", realScreenCount ) != realScreenCount );

    QString loginMode = config.readEntry( "loginMode", "restorePreviousLogout" );

    if ( parser.isSet( restoreOption ) && ! screenCountChanged )
        server->restoreSession( QStringLiteral( SESSION_BY_USER ) );
    else if ( loginMode == QStringLiteral( "default" ) || screenCountChanged )
        server->startDefaultSession();
    else if ( loginMode == QStringLiteral( "restorePreviousLogout" ) )
        server->restoreSession( QStringLiteral( SESSION_PREVIOUS_LOGOUT ) );
    else if ( loginMode == QStringLiteral( "restoreSavedSession" ) )
        server->restoreSession( QStringLiteral( SESSION_BY_USER ) );
    else
        server->startDefaultSession();

    KDBusService service(KDBusService::Unique);

    int ret = a->exec();
    kde_running.release(); // needs to be done before QApplication destruction
    delete a;
    return ret;
}