Example #1
0
int main(int argc, char *argv[])
{
    qSetMessagePattern(QLatin1String(
        "%{if-warning}\x1b[35m%{endif}"
        "%{if-critical}\x1b[31m%{endif}"
        "%{if-fatal}\x1b[1;31m%{endif}"
        "%{time HH:mm:ss.zzz} "
      //"%{appname} %{pid} %{threadid} "
        "%{type} "
      //"%{file}:%{line} %{function} "
        "%{if-category}%{category} %{endif}%{message}"
        "\x1b[0m"
    ));

    QCoreApplication app(argc, argv);

    const QString accessKeyId = QString::fromLocal8Bit(qgetenv("AWS_ACCESS_KEY_ID"));
    const QString secretAccessKey = QString::fromLocal8Bit(qgetenv("AWS_SECRET_ACCESS_KEY"));
    if ((accessKeyId.isEmpty()) || (secretAccessKey.isEmpty())) {
        std::cerr << "Missing credentials" << std::endl;
        exit(1);
    }

    AwsBasicCredentials credentials(accessKeyId, secretAccessKey);

    QNetworkAccessManager manager;

    SqsClient sqs(AwsRegion::AP_Southeast_2, &credentials, &manager);

    SqsCreateQueueResponse * response =
        sqs.createQueue(QLatin1String("libqtaws-test-queue"));
    QObject::connect(response, SIGNAL(finished()), &app, SLOT(quit()));
    return (response) ? app.exec() : 1;
}
Example #2
0
int main(int argc, char **argv)
{
    QQuickWindow::setDefaultAlphaBuffer(true);
    
    QApplication app(argc, argv);
    app.setApplicationVersion(version);
    app.setOrganizationDomain(QStringLiteral("audoban"));
    app.setApplicationName(QStringLiteral("CandilDock"));
    
    //! set pattern for debug messages
    //! [%{type}] [%{function}:%{line}] - %{message} [%{backtrace}]
    qSetMessagePattern(QStringLiteral(
                           CIGREEN "[%{type} " CGREEN "%{time h:mm:ss.zzzz}" CIGREEN "]" CNORMAL
#ifndef QT_NO_DEBUG
                           CIRED " [" CCYAN "%{function}" CIRED ":" CCYAN "%{line}" CIRED "]"
#endif
                           CICYAN " - " CNORMAL "%{message}"
                           CIRED "%{if-fatal}\n%{backtrace depth=" DEPTH " separator=\"\n\"}%{endif}"
                           "%{if-warning}\n%{backtrace depth=" DEPTH " separator=\"\n\"}%{endif}"
                           "%{if-critical}\n%{backtrace depth=" DEPTH " separator=\"\n\"}%{endif}" CNORMAL));
                           
    qputenv("QT_QUICK_CONTROLS_1_STYLE", "Desktop");
    Candil::DockCorona corona;
    
    return app.exec();
}
Example #3
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    app.setApplicationName("tst_qlogging");

    qSetMessagePattern("[%{type}] %{message}");

    qDebug("qDebug");
    qWarning("qWarning");
    qCritical("qCritical");

    qSetMessagePattern(QString());

    qDebug("qDebug2");

    return 0;
}
Example #4
0
void DkUtils::initializeDebug() {

	if (Settings::param().app().useLogFile)
		qInstallMessageHandler(qtMessageOutput);

	// format console
	QString p = "%{if-info}[INFO] %{endif}%{if-warning}[WARNING] %{endif}%{if-critical}[CRITICAL] %{endif}%{if-fatal}[ERROR] %{endif}%{message}";
	qSetMessagePattern(p);
}
Example #5
0
void adjustLog()
{
    auto msg_pattern = "["\
            "%{if-debug}D%{endif}"\
            "%{if-warning}W%{endif}"\
            "%{if-critical}C%{endif}"\
            "%{if-fatal}F%{endif}]"\
            "%{file}:%{line} - %{message}";
    qSetMessagePattern(msg_pattern);
}
int main(int argc, char* argv[])
{
    qSetMessagePattern("%{type} %{threadid} %{message}");
    NetworkViewerApp app(argc,argv);
    app.init();

    qInstallMessageHandler(myMessageOutput);

    //See also void qSetMessagePattern(const QString & pattern)
    return app.exec();
}
Example #7
0
Logger::Logger( QObject* parent) : QObject(parent),
  _showTime(true), _doLogging(false), _doFileFlush(false), _logExpire(0)
{
#ifndef NO_MSG_HANDLER
#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)
    qSetMessagePattern("%{time MM-dd hh:mm:ss:zzz} %{threadid} %{function}: %{message}");
#endif
    qInstallMessageHandler(mirallLogCatcher);
#else
    Q_UNUSED(mirallLogCatcher)
#endif
}
Example #8
0
File: main.cpp Project: Gu1/Phoenix
int main(int argc, char *argv[])
{
#ifdef Q_OS_LINUX
    // When using QAudioOutput on linux/ALSA, we need to
    // block SIGIO on all threads except the audio thread
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGIO);
    pthread_sigmask(SIG_BLOCK, &set, nullptr);
#endif

    qSetMessagePattern("[%{if-debug}D%{endif}%{if-warning}W%{endif}"
                       "%{if-critical}C%{endif}%{if-fatal}F%{endif}]"
                       "%{if-category} [%{category}]:%{endif} %{message}");

    QGuiApplication a(argc, argv);
    a.setApplicationName("Phoenix");
    a.setApplicationVersion(PHOENIX_VERSION);
    a.setOrganizationName("Phoenix");
//    a.setOrganizationDomain("phoenix-emu.org");
    QSettings settings;


    qmlRegisterType<PhoenixWindow>("phoenix.window", 1, 0, "PhoenixWindow");
    qmlRegisterType<CachedImage>("phoenix.image", 1, 0, "CachedImage");
    qmlRegisterType<VideoItem>("phoenix.video", 1, 0, "VideoItem");
    qmlRegisterType<GameLibraryModel>();
    qmlRegisterType<PhoenixLibrary>("phoenix.library", 1, 0, "PhoenixLibrary");
    qmlRegisterType<InputDeviceMapping>();
    qmlRegisterType<InputDevice>();
    qRegisterMetaType<retro_device_id>("retro_device_id");
    qRegisterMetaType<int16_t>("int16_t");
    qRegisterMetaType<InputDeviceEvent *>();

    QQmlApplicationEngine engine;

    // first, set the context properties
    QQmlContext *rctx = engine.rootContext();
    rctx->setContextProperty("inputmanager", &input_manager);

    // then, load qml and display the window
    engine.load(QUrl("qrc:/qml/main.qml"));
    QObject *topLevel = engine.rootObjects().value(0);
    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);

    window->show();

    input_manager.scanDevices();

    return a.exec();
}
Example #9
0
void MTest::initMTest()
{
    qSetMessagePattern("%{function}: %{message}");
    initMyResources();
//      DPI  = 120;
//      PDPI = 120;
    MScore::noGui = true;

    synti  = new MasterSynthesizer();
    mscore = new MScore;
    new MuseScoreCore;
    mscore->init();
    preferences.shortestNote = MScore::division / 4; // midi quantization: 1/16

    root = TESTROOT "/mtest";
    loadInstrumentTemplates(":/instruments.xml");
    score = readScore("test.mscx");
}
Example #10
0
CReporterLogger::CReporterLogger(const QString type)
{
    // save ourself in a static variable
    CReporterLogger::sm_Instance = this;

    if (type == CREPORTER_LOGGER_FILE) {
        CReporterLogger::sm_LogType = CReporter::LogFile;
    } else if (type == CREPORTER_LOGGER_SYSLOG) {
        CReporterLogger::sm_LogType = CReporter::LogSyslog;
    }

    switch (CReporterLogger::sm_LogType) {
    // Initialize logging.
    case CReporter::LogSyslog:
        // Init syslog.
        openlog(NULL, LOG_PID, LOG_USER);
        break;
    case CReporter::LogFile:
        m_file.setFileName(CReporter::DefaultLogFile);
        // Open file for appending.
        if (!m_file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
            std::cerr << __PRETTY_FUNCTION__ << "Failed to open log file: " << qPrintable(CReporter::DefaultLogFile)
                      << " for appending." << std::endl;
            m_old_msg_handler = 0;
            return;
        }
        // Set stream.
        m_stream.setDevice(&m_file);
        // Set default message pattern
        qSetMessagePattern(QStringLiteral("%{time} %{appname}: ["
                                          "%{if-debug}D%{endif}"
                                          "%{if-info}I%{endif}"
                                          "%{if-warning}W%{endif}"
                                          "%{if-critical}C%{endif}"
                                          "%{if-fatal}F%{endif}"
                                          "] %{function}:%{line} - %{message}"));
        break;
    case CReporter::LogNone: // TODO Means rather LogDefault than LogNone
        return;
    };
    // Register ourselves as a debug message handler
    m_old_msg_handler = qInstallMessageHandler(CReporterLogger::messageHandler);
}
Example #11
0
int main(int argc, char** argv)
{

   // Logging settings.
   qSetMessagePattern("[%{type}] | %{category} | %{function}@%{line} | %{message}");
   QLoggingCategory::setFilterRules(QStringLiteral("*.debug=false\n \
                                                    *.warning=false\n \
                                                    *.critical=false\n"));

   int status = 0;
   {
      DigitalScratchApi_Test tc;
      status |= QTest::qExec(&tc, argc, argv);
   }
   {
      DigitalScratch_Test tc;
      status |= QTest::qExec(&tc, argc, argv);
   }
   return status;
}
Example #12
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    app.setOrganizationName(ORGANIZATION_NAME);
    app.setOrganizationDomain(ORGANIZATION_DOMAIN);
    app.setApplicationName(APPLICATION_NAME);

    qSetMessagePattern("%{type} %{function}: %{message}");

    QSettings settings;
    QString language = settings.value("PatternPaint/language", DEFAULT_LANGUAGE).toString();

    QString locale;

    if(language == "<System Language>") {
        locale = QLocale::system().name();
    }
    else {
        locale = language;
    }

    qDebug() << "Loading translators for locale:" << locale;

    // Translator for the Qt library
    QTranslator qtTranslator;
    qtTranslator.load("qt_" + locale,
            QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app.installTranslator(&qtTranslator);

    // Translator for PatternPaint
    QTranslator appTranslator;
    appTranslator.load("patternpaint_" + locale,
                       ":/translations");
    app.installTranslator(&appTranslator);

    MainWindow w;
    w.show();

    return app.exec();
}
Example #13
0
int main(int argc, char **argv)
{
    if (IS_DEBUG_BUILD) {
        // see http://doc.qt.io/qt-5/qtglobal.html#qSetMessagePattern
        // also allows environment variable QT_MESSAGE_PATTERN
        qSetMessagePattern(
            "[%{time} %{threadid}] %{type} in %{function} (at %{file}:%{line}): %{message}");
    }

    QApplication app(argc, argv);
    Q_INIT_RESOURCE(mmapper2);
    tryInitDrMingw();
    tryUseHighDpi(app);
    auto tryLoadingWinSock = std::make_unique<WinSock>();

    const auto &config = getConfig();
    if (config.canvas.softwareOpenGL) {
        app.setAttribute(Qt::AA_UseSoftwareOpenGL);
        if (CURRENT_PLATFORM == Platform::Linux) {
            qputenv("LIBGL_ALWAYS_SOFTWARE", "1");
        }
    } else {
        // Windows Intel drivers cause black screens if we don't specify OpenGL
        app.setAttribute(Qt::AA_UseDesktopOpenGL);
    }

    std::unique_ptr<ISplash> splash = !config.general.noSplash
                                          ? static_upcast<ISplash>(std::make_unique<Splash>())
                                          : static_upcast<ISplash>(std::make_unique<FakeSplash>());
    auto mw = std::make_unique<MainWindow>();
    tryAutoLoad(*mw);
    mw->show();
    splash->finish(mw.get());
    splash.reset();

    mw->startServices();
    const int ret = app.exec();
    mw.reset();
    config.write();
    return ret;
}
Example #14
0
void MTest::initMTest()
      {
      qputenv("QML_DISABLE_DISK_CACHE", "true");
      qSetMessagePattern("%{function}: %{message}");
      initMyResources();
//      DPI  = 120;
//      PDPI = 120;
      MScore::noGui = true;

      synti  = new MasterSynthesizer();
      mscore = new MScore;
      new MuseScoreCore;
      mscore->init();
      ed.init();

      preferences.init(true);

      root = TESTROOT "/mtest";
      loadInstrumentTemplates(":/instruments.xml");
      score = readScore("test.mscx");
      }
dfs::core::DDebugInitialiser::
DDebugInitialiser()
{
#ifdef DFS_COPY_DEBUG_OUTPUT_TO_FILE
    // redirect all debug stuff to file
    QString filePath = DFS_COPY_DEBUG_OUTPUT_TO_FILE;
    if(editDebugOutputFile(filePath).open(QFile::Truncate | QFile::Text | QFile::WriteOnly))
    {
        std::cerr << "Redirecting Debug output to a file \"" << DFS_COPY_DEBUG_OUTPUT_TO_FILE << "\" with full path \"" << QFileInfo(editDebugOutputFile()).absoluteFilePath().toStdString() << "\"" << std::endl;
        // we could open the file - now install the handler
        editFormerMessageHandler() = qInstallMessageHandler(myMessageHandler);
    }
    else
    {
        qDebug() << "Could not open the debug file for writing";
    }
#endif

#ifdef DFS_CUSTOM_DEBUG_FORMAT
    qSetMessagePattern(DFS_CUSTOM_DEBUG_FORMAT);
#endif
}
Example #16
0
void LoggingConfig::readConfigurationSection(QSettings *settings)
{
  QString defaultPattern("[%{time yyyy-MM-dd h:mm:ss.zzz} %{category} "
                         "%{if-debug}DEBUG%{endif}"
                         "%{if-info}INFO %{endif}"
                         "%{if-warning}WARN %{endif}"
                         "%{if-critical}CRIT %{endif}"
                         "%{if-fatal}FATAL%{endif}]: %{message}");

  // Set the configured message pattern
  qSetMessagePattern(settings->value("configuration/messagepattern", QVariant(defaultPattern)).toString());

  QString filesParameter = settings->value("configuration/files").toString();
  if(filesParameter == "truncate" || filesParameter == "roll")
    mode = QIODevice::WriteOnly | QIODevice::Text;
  else if(filesParameter == "append")
    mode = QIODevice::Append | QIODevice::Text;
  else
  {
    qWarning() << "Invalid value for configuration/files:" << filesParameter
               << "use either truncate, append or roll.";
    mode = QIODevice::WriteOnly | QIODevice::Text;
  }

  rolling = settings->value("configuration/files").toString() == "roll";
  maxFiles = settings->value("configuration/maxfiles").toInt();

  QString abortOn = settings->value("configuration/abort", QVariant("fatal")).toString();
  if(abortOn == "warning")
    abortType = QtWarningMsg;
  else if(abortOn == "critical")
    abortType = QtCriticalMsg;
  else if(abortOn == "fatal")
    abortType = QtFatalMsg;
  else
    qWarning() << "Invalid value for configuration/abort:" << abortOn
               << "use either warning, critical or fatal (default).";
}
Example #17
0
int main( int argc , char *argv[] )
{
    QString messagePattern = QString("%1[%{time yyyyMMdd h:mm:ss.zzz}] "
                                     "%{if-debug}%2DEB %{endif}%{if-info}%3%{endif}%{if-warning}%4WAR %{endif}%{if-critical}%5CRIT%{endif} %1"
                                     "%3 %{file}:%{line} %6 %{message} %1")
            .arg(NO_COLOR)
            .arg(DEBUG_COLOR)
            .arg(INFO_COLOR)
            .arg(WARNING_COLOR)
            .arg(CRITICAL_COLOR)
            .arg(MESSAGE_COLOR);
    
    qSetMessagePattern(messagePattern);
    QApplication app(argc, argv);
    
    Dicom dcm;
    dcm.setWindowIcon(QIcon(":Images/dicom.xpm"));
    dcm.show();
    
    int ret = app.exec();
    QtDcmManager::destroy();
    
    return ret;
}
Example #18
0
CMainWindow::CMainWindow(int argc, char *argv[], QWidget *parent)
    : QMainWindow(parent)
{
    //======================================================================================================================================
    QStringList arguments;

    for (int i = 0; i < argc; i++)
    {
        arguments.append(argv[i]);

        arguments[i].remove("-");
    }
    //======================================================================================================================================
    qSetMessagePattern("[%{time h:mm:ss:zzz} %{if-category}%{category}%{endif} %{type}] %{function}: - %{message}");
    //======================================================================================================================================
    ui.setupUi(this);
    QSettings settings;
    m_EventFilter = CEventFilter::Signleton();
    m_Data = new CData;
    //======================================================================================================================================
    if (arguments.contains("ip"))
    {
        m_WebSocketClient = new CWebSocketClient(QUrl(QString("ws://%1").arg((arguments.at(arguments.indexOf("ip") + 1)))), m_Data);
        settings.setValue("IPAdress", arguments.at(arguments.indexOf("ip") + 1).split(":").first());
        settings.setValue("Port", arguments.at(arguments.indexOf("ip") + 1).split(":").last());
    }
    else
        m_WebSocketClient = new CWebSocketClient(QUrl(QString("ws://%1:%2").arg(settings.value("IPAdress").toString()).arg(settings.value("Port").toString())), m_Data);
    //======================================================================================================================================
    ////Actions
    //QAction *action_Close = new QAction(QIcon(QString::fromUtf8(":/Resources/cancel.png")), "Close", this);
    //QAction *action_FullScreen = new QAction(QIcon(QString::fromUtf8(":/Resources/slideshow_full_screen.png")), "Fullsreen", this);
    //QAction *action_HomePage = new QAction(QIcon(QString::fromUtf8(":/Resources/home_page.png")), "Home Page", this);
    //QAction *action_Plotter = new QAction(QIcon(QString::fromUtf8(":/Resources/chart_curve.png")), "Plotter", this);
    ////======================================================================================================================================
    ////Toolbar
    //ui.toolBar->addAction(action_Close);
    //ui.toolBar->addAction(action_FullScreen);
    //ui.toolBar->addSeparator();
    //ui.toolBar->setIconSize(QSize(20, 20));
    //ui.toolBar->addAction(action_HomePage);
    //ui.toolBar->addAction(action_Plotter);
    //======================================================================================================================================
    //StartPage
    m_StartPage = new CStartPage(this);
    ui.stackedWidget->addWidget(m_StartPage->getView());
    //======================================================================================================================================
    //Plotter
    m_Plotter = new CPlotter(this);
    ui.stackedWidget->addWidget(m_Plotter->getView());
    //======================================================================================================================================
    //Settings
    m_Settings = new CSettings(this);
    ui.stackedWidget->addWidget(m_Settings);
    //======================================================================================================================================
    //======================================================================================================================================
    connect(m_EventFilter,		SIGNAL(reciveClick()),							this,		SLOT(showNextPage()));
    connect(m_EventFilter,		SIGNAL(reciveDoubleClick()),					this,		SLOT(showSettings()));

    connect(m_Data,				SIGNAL(NewDataRecieved()),						this,		SLOT(onNewData()));

    connect(m_Settings,			SIGNAL(reciveNewURL(QString)),					this,		SLOT(onNewURL(QString)));
    connect(m_Settings,			SIGNAL(ready()),								this,		SLOT(showStartpage()));

    connect(m_WebSocketClient,	SIGNAL(serverConnected(QString)),				m_Settings, SLOT(onServerConnected(QString)));
    connect(m_WebSocketClient,	SIGNAL(serverDisconnected()),					m_Settings, SLOT(onServerDisconnected()));

    connect(m_WebSocketClient,	SIGNAL(recievedInitialScript(QJsonObject)),		m_Data,		SLOT(recievedInitialScript(QJsonObject)));
    connect(m_WebSocketClient,	SIGNAL(recievedDataScript(QJsonObject)),		m_Data,		SLOT(recievedDataScript(QJsonObject)));

    //======================================================================================================================================
    //======================================================================================================================================
    resize(480, 320);

    ui.stackedWidget->setCurrentIndex(0);
}
Example #19
0
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();
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

//![2]
    QLoggingCategory::setFilterRules(QStringLiteral("qt.driver.usb.debug=true"));
//![2]

//![22]

// ...
oldCategoryFilter = QLoggingCategory::installFilter(myCategoryFilter);
//![22]

//![3]
    qSetMessagePattern("%{category} %{message}");
//![3]

//![4]
    // usbEntries() will only be called if QT_DRIVER_USB category is enabled
    qCDebug(QT_DRIVER_USB) << "devices: " << usbEntries();
//![4]

    {
//![10]
    QLoggingCategory category("qt.driver.usb");
    qCDebug(category) << "a debug message";
//![10]
    }

    {
//![11]
    QLoggingCategory category("qt.driver.usb");
    qCWarning(category) << "a warning message";
//![11]
    }

    {
//![12]
    QLoggingCategory category("qt.driver.usb");
    qCCritical(category) << "a critical message";
//![12]
    }

    {
//![13]
    QLoggingCategory category("qt.driver.usb");
    qCDebug(category, "a debug message logged into category %s", category.categoryName());
//![13]
    }

    {
//![14]
    QLoggingCategory category("qt.driver.usb");
    qCWarning(category, "a warning message logged into category %s", category.categoryName());
//![14]
    }

    {
//![15]
    QLoggingCategory category("qt.driver.usb");
    qCCritical(category, "a critical message logged into category %s", category.categoryName());
//![15]
    }

    return 0;
}
Example #21
0
int main(int argc, char *argv[])
{
    QCoreApplication::setApplicationName("Embedded IDE");
    QCoreApplication::setOrganizationName("none");
    QCoreApplication::setOrganizationDomain("unknown.tk");

    QApplication app(argc, argv);
    QApplication::setWindowIcon(QIcon(":/images/embedded-ide.svg"));
    QTranslator tr;
    for(const auto& p: AppConfig::langPaths()) {
        if (tr.load(QLocale::system().name(), p)) {
            if (app.installTranslator(&tr)) {
                qDebug() << "load translations" << QLocale::system().name();
                break;
            }
        }
    }

    auto checkConfig = [&app, &tr](AppConfig *config) {
        app.setStyleSheet( config->useDarkStyle()?
            AppConfig::readEntireTextFile(":/qdarkstyle/style.qss"): ""
        );
        auto selectedLang = config->language();
        if (!selectedLang.isEmpty()) {
            for(const auto& p: AppConfig::langPaths()) {
                if (tr.load(selectedLang, p)) {
                    if (app.installTranslator(&tr)) {
                        qDebug() << "load translations" << QLocale::system().name();
                        break;
                    }
                }
            }
        }
    };
    QObject::connect(&AppConfig::instance(), &AppConfig::configChanged, [&checkConfig](AppConfig *config)
    {
        checkConfig(config);
        switch (config->networkProxyType()) {
        case AppConfig::NetworkProxyType::None:
            QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
            break;
        case AppConfig::NetworkProxyType::System:
            QNetworkProxyFactory::setUseSystemConfiguration(true);
            break;
        case AppConfig::NetworkProxyType::Custom:
            QNetworkProxy proxy(
                        QNetworkProxy::HttpProxy, config->networkProxyHost(),
                        static_cast<quint16>(config->networkProxyPort().toInt()));
            if (config->networkProxyUseCredentials()) {
                proxy.setUser(config->networkProxyUsername());
                proxy.setPassword(config->networkProxyPassword());
            }
            QNetworkProxy::setApplicationProxy(proxy);
            break;
        }
    });
    AppConfig::instance().load();
    checkConfig(&AppConfig::instance());


    QCommandLineParser opt;
    opt.addHelpOption();
    opt.addVersionOption();
    opt.addPositionalArgument("filename", "Makefile filename");
    opt.addOptions({
                       { { "e", "exec" }, "Execute stript or file", "execname" },
                       { { "d", "debug"}, "Enable debug" },
                       { { "s", "stacktrace" }, "Add stack trace to debug" }
                   });
    opt.process(app);

    if (opt.isSet("exec")) {
        QString execname = opt.value("exec");
        QProcess::startDetached(execname);
        return 0;
    }

    if (opt.isSet("debug")) {
        QString debugString = "[%{type}] %{appname} (%{file}:%{line}) - %{message}";
        if (opt.isSet("stacktrace"))
            debugString += "\n\t%{backtrace separator=\"\n\t\"}";
        qSetMessagePattern(debugString);
    } else
        qSetMessagePattern("");

    MainWindow w;
    w.show();

    if (!opt.positionalArguments().isEmpty()) {
        QString path = opt.positionalArguments().first();
        QTimer::singleShot(0, [path, &w]() { w.openProject(path); });
    }

    return QApplication::exec();
}
Example #22
0
LoggingSystem::LoggingSystem()
    : QObject()
{
    qInstallMessageHandler(LoggingSystem::qtMessage);
    qSetMessagePattern("[%{time h:mm:ss.zzz}] %{if-debug}%{file}:%{line} - %{endif}%{message}");
}