int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QTextStream QErr(stderr); //! This is need for libq4wine-core.so import; typedef void *CoreLibPrototype (bool); CoreLibPrototype *CoreLibClassPointer; std::auto_ptr<corelib> CoreLib; QLibrary libq4wine; // Loading libq4wine-core.so #ifdef RELEASE libq4wine.setFileName(_CORELIB_PATH_); #else libq4wine.setFileName(QString("%1/q4wine-lib/libq4wine-core").arg(APP_BUILD)); #endif if (!libq4wine.load()){ libq4wine.load(); } // Getting corelib calss pointer CoreLibClassPointer = (CoreLibPrototype *) libq4wine.resolve("createCoreLib"); CoreLib.reset((corelib *)CoreLibClassPointer(false)); if (!CoreLib.get()){ QErr<<"[EE] Can't load shared library."<<endl; return -1; } DataBase db; if (!db.checkDb()){ QErr<<"[EE] Can't init database engine."<<endl; return -1; } QTranslator qtt; #ifdef RELEASE #ifdef _OS_DARWIN_ QString i18nPath = QString("%1/%2.app/Contents/i18n").arg(QDir::currentPath()).arg(APP_SHORT_NAME); #else QString i18nPath = QString("%1/share/%2/i18n").arg(APP_PREF).arg(APP_SHORT_NAME); #endif #else QString i18nPath = QString("%1/i18n").arg(APP_BUILD); #endif qtt.load(CoreLib->getTranslationLang(), i18nPath); app.installTranslator(&qtt); if (!CoreLib->isConfigured()){ QErr<<"[EE] App not configured! Re run wizard, or delete q4wine broken config files."<<endl; return -1; } QTextStream Qcout(stdout); WineObject wineObject; if (argc==1){ app.arguments().append("-h"); argc++; } for (int i=1; i<argc; i++){ qDebug()<<app.arguments().at(i); if ((app.arguments().at(1)=="--version") or (app.arguments().at(1)=="-v")){ Qcout<<QString("%1-helper %2").arg(APP_SHORT_NAME).arg(APP_VERS)<<endl; Qcout<<QString("(Copyright (C) 2008-2009, brezblock core team.")<<endl; Qcout<<QString("License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.")<<endl; Qcout<<QObject::tr("This is free software: you are free to change and redistribute it.")<<endl; Qcout<<QObject::tr("There is NO WARRANTY, to the extent permitted by law.")<<endl; CoreLib->getBuildFlags(); Qcout<<QObject::tr("Author: %1.").arg("Malakhov Alexey aka John Brezerk")<<endl; return 0; } else if (app.arguments().at(i)=="--prefix"){ i++; if (i<argc) wineObject.setPrefix(app.arguments().at(i)); } else if (app.arguments().at(i)=="--wine-debug"){ i++; if (i<argc) wineObject.setProgramDebug(app.arguments().at(i)); } else if (app.arguments().at(i)=="--console"){ i++; if (i<argc) wineObject.setUseConsole(app.arguments().at(i).toInt()); } else if (app.arguments().at(i)=="--display"){ i++; if (i<argc) wineObject.setProgramDisplay(app.arguments().at(i)); } else if (app.arguments().at(i)=="--nice"){ i++; if (i<argc) wineObject.setProgramNice(app.arguments().at(i).toInt()); } else if (app.arguments().at(i)=="--desktop"){ i++; if (i<argc) wineObject.setProgramDesktop(app.arguments().at(i)); } else if (app.arguments().at(i)=="--program-bin") { i++; if (i<argc) wineObject.setProgramBinary(app.arguments().at(i)); } else if (app.arguments().at(i)=="--program-args") { i++; if (i<argc) wineObject.setProgramArgs(app.arguments().at(i)); } else if (app.arguments().at(i)=="--wrkdir") { i++; if (i<argc) wineObject.setProgramWrkdir(app.arguments().at(i)); } else if (app.arguments().at(i)=="--program-lang") { i++; if (i<argc) wineObject.setProgramLang(app.arguments().at(i)); } else if (app.arguments().at(i)=="--override") { i++; if (i<argc) wineObject.setProgramOverride(app.arguments().at(i)); } else if (app.arguments().at(i)=="--prerun") { i++; if (i<argc) wineObject.setPreRun(app.arguments().at(i)); } else if (app.arguments().at(i)=="--postrun") { i++; if (i<argc) wineObject.setPostRun(app.arguments().at(i)); } else { Qcout<<QObject::tr("Usage:")<<endl; Qcout<<QObject::tr(" %1-helper [KEYs]...").arg(APP_SHORT_NAME)<<endl; Qcout<<QObject::tr("Console utility for q4wine which helps to handle wine application exit status and it's stdout\\stderr output logging.")<<endl<<endl; Qcout<<QObject::tr("KEYs list:")<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --prefix"<<QObject::tr("sets the current prefix name")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --wine-debug"<<QObject::tr("sets WINEDEBUG variable")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --console"<<QObject::tr("run with output in console")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --display"<<QObject::tr("sets DISPLAY variable")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --nice"<<QObject::tr("sets program nicenes")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --desktop"<<QObject::tr("sets program virtual desktop resolution")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --program-bin"<<QObject::tr("sets program binary")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --program-args"<<QObject::tr("sets program args")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --wrkdir"<<QObject::tr("sets program working directory")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --program-lang"<<QObject::tr("sets program LANG variable")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --override"<<QObject::tr("sets WINEDLLOVERRIDES variable")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --prerun"<<QObject::tr("execute script before run program")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" --postrun"<<QObject::tr("execute script after program run")<<qSetFieldWidth(0)<<endl; Qcout<<endl; Qcout<<QObject::tr("Report %1 bugs to %2").arg(APP_SHORT_NAME).arg(APP_BUG_EMAIL)<<endl; Qcout<<QObject::tr("%1 homepage: <%2>").arg(APP_SHORT_NAME).arg(APP_WEBSITTE)<<endl; Qcout<<QObject::tr("General help using GNU software: <http://www.gnu.org/gethelp/>")<<endl; return 0; } } return wineObject.runSys(); /* if (app.arguments().count()>1){ if ((app.arguments().at(1)=="--version") or (app.arguments().at(1)=="-v")){ Qcout<<QString("%1-helper %2").arg(APP_SHORT_NAME).arg(APP_VERS)<<endl; Qcout<<QString("(Copyright (C) 2008-2009, brezblock core team.")<<endl; Qcout<<QString("License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.")<<endl; Qcout<<QObject::tr("This is free software: you are free to change and redistribute it.")<<endl; Qcout<<QObject::tr("There is NO WARRANTY, to the extent permitted by law.")<<endl; CoreLib->getBuildFlags(); Qcout<<QObject::tr("Author: %1.").arg("Malakhov Alexey aka John Brezerk")<<endl; return 0; } else if ((app.arguments().at(1)=="--binary") or (app.arguments().at(1)=="-b")) { //startState = 1; } else { Qcout<<QObject::tr("Usage:")<<endl; Qcout<<QString(" %1 -b <unix_path_to_windown_binary>").arg(APP_SHORT_NAME)<<endl; Qcout<<QObject::tr(" %1 [KEY]...").arg(APP_SHORT_NAME)<<endl; Qcout<<QObject::tr("GUI utility for wine applications and prefixes management.")<<endl<<endl; Qcout<<QObject::tr("KEYs list:")<<endl; Qcout<<qSetFieldWidth(25)<<left<<" -h, --help"<<QObject::tr("display this help and exit")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" -v, --version"<<QObject::tr("output version information and exit")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" -b, --binary"<<QObject::tr("Open q4wine run dialog for windows binary")<<qSetFieldWidth(0)<<endl; Qcout<<qSetFieldWidth(25)<<left<<" -m, --minimize"<<QObject::tr("minimize %1 main window on startup").arg(APP_SHORT_NAME)<<qSetFieldWidth(0)<<endl; Qcout<<endl; Qcout<<QObject::tr("Report %1 bugs to %2").arg(APP_SHORT_NAME).arg(APP_BUG_EMAIL)<<endl; Qcout<<QObject::tr("%1 homepage: <%2>").arg(APP_SHORT_NAME).arg(APP_WEBSITTE)<<endl; Qcout<<QObject::tr("General help using GNU software: <http://www.gnu.org/gethelp/>")<<endl; return 0; } } */ }
/*! Processes the qdoc config file \a fileName. This is the controller for all of qdoc. */ static void processQdocconfFile(const QString &fileName) { QList<QTranslator *> translators; /* The Config instance represents the configuration data for qdoc. All the other classes are initialized with the config. Here we initialize the configuration with some default values. */ Config config(tr("qdoc")); int i = 0; while (defaults[i].key) { config.setStringList(defaults[i].key, QStringList() << defaults[i].value); ++i; } config.setStringList(CONFIG_SLOW, QStringList(slow ? "true" : "false")); config.setStringList(CONFIG_SHOWINTERNAL, QStringList(showInternal ? "true" : "false")); config.setStringList(CONFIG_OBSOLETELINKS, QStringList(obsoleteLinks ? "true" : "false")); /* With the default configuration values in place, load the qdoc configuration file. Note that the configuration file may include other configuration files. The Location class keeps track of the current location in the file being processed, mainly for error reporting purposes. */ Location::initialize(config); config.load(fileName); /* Add the defines to the configuration variables. */ QStringList defs = defines + config.getStringList(CONFIG_DEFINES); config.setStringList(CONFIG_DEFINES,defs); Location::terminate(); QString prevCurrentDir = QDir::currentPath(); QString dir = QFileInfo(fileName).path(); if (!dir.isEmpty()) QDir::setCurrent(dir); /* Initialize all the classes and data structures with the qdoc configuration. */ Location::initialize(config); Tokenizer::initialize(config); Doc::initialize(config); CppToQsConverter::initialize(config); CodeMarker::initialize(config); CodeParser::initialize(config); Generator::initialize(config); /* Load the language translators, if the configuration specifies any. */ QStringList fileNames = config.getStringList(CONFIG_TRANSLATORS); QStringList::Iterator fn = fileNames.begin(); while (fn != fileNames.end()) { QTranslator *translator = new QTranslator(0); if (!translator->load(*fn)) config.lastLocation().error(tr("Cannot load translator '%1'") .arg(*fn)); QCoreApplication::instance()->installTranslator(translator); translators.append(translator); ++fn; } //QSet<QString> outputLanguages = config.getStringSet(CONFIG_OUTPUTLANGUAGES); /* Get the source language (Cpp) from the configuration and the location in the configuration file where the source language was set. */ QString lang = config.getString(CONFIG_LANGUAGE); Location langLocation = config.lastLocation(); /* Initialize the tree where all the parsed sources will be stored. The tree gets built as the source files are parsed, and then the documentation output is generated by traversing the tree. */ Tree *tree = new Tree; tree->setVersion(config.getString(CONFIG_VERSION)); /* There must be a code parser for the source code language, e.g. C++. If there isn't one, give up. */ CodeParser *codeParser = CodeParser::parserForLanguage(lang); if (codeParser == 0) config.lastLocation().fatal(tr("Cannot parse programming language '%1'").arg(lang)); /* By default, the only output format is HTML. */ QSet<QString> outputFormats = config.getStringSet(CONFIG_OUTPUTFORMATS); Location outputFormatsLocation = config.lastLocation(); /* There must be a code marker for the source code language, e.g. C++. If there isn't one, give up. */ CodeMarker *marker = CodeMarker::markerForLanguage(lang); if (!marker && !outputFormats.isEmpty()) langLocation.fatal(tr("Cannot output documentation for programming language '%1'").arg(lang)); /* Read some XML indexes. What are they??? */ QStringList indexFiles = config.getStringList(CONFIG_INDEXES); tree->readIndexes(indexFiles); /* Get all the header files: "*.ch *.h *.h++ *.hh *.hpp *.hxx" Put them in a set. */ QSet<QString> excludedDirs; QStringList excludedDirsList = config.getStringList(CONFIG_EXCLUDEDIRS); foreach (const QString &excludeDir, excludedDirsList) excludedDirs.insert(QDir::fromNativeSeparators(excludeDir)); QSet<QString> headers = QSet<QString>::fromList( config.getAllFiles(CONFIG_HEADERS, CONFIG_HEADERDIRS, codeParser->headerFileNameFilter(), excludedDirs)); /* Parse each header file in the set and add it to the big tree. */ QSet<QString>::ConstIterator h = headers.begin(); while (h != headers.end()) { codeParser->parseHeaderFile(config.location(), *h, tree); ++h; } codeParser->doneParsingHeaderFiles(tree); /* Get all the source text files: "*.cpp *.qdoc *.mm" Put them in a set. */ QSet<QString> sources = QSet<QString>::fromList( config.getAllFiles(CONFIG_SOURCES, CONFIG_SOURCEDIRS, codeParser->sourceFileNameFilter(), excludedDirs)); /* Parse each source text file in the set and add it to the big tree. */ QSet<QString>::ConstIterator s = sources.begin(); while (s != sources.end()) { codeParser->parseSourceFile(config.location(), *s, tree); ++s; } codeParser->doneParsingSourceFiles(tree); /* Now the big tree has been built from all the header and source files. Resolve all the class names, function names, targets, URLs, links, and other stuff that needs resolving. */ tree->resolveGroups(); tree->resolveTargets(); /* Now the tree has been built, and all the stuff that needed resolving has been resolved. Now it is time to traverse the big tree and generate the documentation output. */ QSet<QString>::ConstIterator of = outputFormats.begin(); while (of != outputFormats.end()) { Generator *generator = Generator::generatorForFormat(*of); if (generator == 0) outputFormatsLocation.fatal(tr("Unknown output format '%1'") .arg(*of)); generator->generateTree(tree, marker); ++of; } /* Generate the XML tag file, if it was requested. */ QString tagFile = config.getString(CONFIG_TAGFILE); if (!tagFile.isEmpty()) tree->generateTagFile(tagFile); tree->setVersion(""); Generator::terminate(); CodeParser::terminate(); CodeMarker::terminate(); CppToQsConverter::terminate(); Doc::terminate(); Tokenizer::terminate(); Location::terminate(); QDir::setCurrent(prevCurrentDir); foreach (QTranslator *translator, translators) delete translator; delete tree; }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); #ifndef Q_OS_WIN32 QTranslator translator; QTranslator qtTranslator; QString sysLocale = QLocale::system().name(); QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir) && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) { app.installTranslator(&translator); app.installTranslator(&qtTranslator); } #endif // Q_OS_WIN32 QStringList args = app.arguments(); QList<File> inFiles; QString inFormat(QLatin1String("auto")); QString outFileName; QString outFormat(QLatin1String("auto")); QString targetLanguage; QString sourceLanguage; bool dropTranslations = false; bool noObsolete = false; bool noFinished = false; bool verbose = false; bool noUiLines = false; Translator::LocationsType locations = Translator::DefaultLocations; ConversionData cd; Translator tr; for (int i = 1; i < args.size(); ++i) { if (args[i].startsWith(QLatin1String("--"))) args[i].remove(0, 1); if (args[i] == QLatin1String("-o") || args[i] == QLatin1String("-output-file")) { if (++i >= args.size()) return usage(args); outFileName = args[i]; } else if (args[i] == QLatin1String("-of") || args[i] == QLatin1String("-output-format")) { if (++i >= args.size()) return usage(args); outFormat = args[i]; } else if (args[i] == QLatin1String("-i") || args[i] == QLatin1String("-input-file")) { if (++i >= args.size()) return usage(args); File file; file.name = args[i]; file.format = inFormat; inFiles.append(file); } else if (args[i] == QLatin1String("-if") || args[i] == QLatin1String("-input-format")) { if (++i >= args.size()) return usage(args); inFormat = args[i]; } else if (args[i] == QLatin1String("-input-codec")) { if (++i >= args.size()) return usage(args); cd.m_codecForSource = args[i].toLatin1(); } else if (args[i] == QLatin1String("-output-codec")) { if (++i >= args.size()) return usage(args); cd.m_outputCodec = args[i].toLatin1(); } else if (args[i] == QLatin1String("-drop-tag")) { if (++i >= args.size()) return usage(args); cd.m_dropTags.append(args[i]); } else if (args[i] == QLatin1String("-drop-translations")) { dropTranslations = true; } else if (args[i] == QLatin1String("-target-language")) { if (++i >= args.size()) return usage(args); targetLanguage = args[i]; } else if (args[i] == QLatin1String("-source-language")) { if (++i >= args.size()) return usage(args); sourceLanguage = args[i]; } else if (args[i].startsWith(QLatin1String("-h"))) { usage(args); return 0; } else if (args[i] == QLatin1String("-no-obsolete")) { noObsolete = true; } else if (args[i] == QLatin1String("-no-finished")) { noFinished = true; } else if (args[i] == QLatin1String("-sort-contexts")) { cd.m_sortContexts = true; } else if (args[i] == QLatin1String("-locations")) { if (++i >= args.size()) return usage(args); if (args[i] == QLatin1String("none")) locations = Translator::NoLocations; else if (args[i] == QLatin1String("relative")) locations = Translator::RelativeLocations; else if (args[i] == QLatin1String("absolute")) locations = Translator::AbsoluteLocations; else return usage(args); } else if (args[i] == QLatin1String("-no-ui-lines")) { noUiLines = true; } else if (args[i] == QLatin1String("-verbose")) { verbose = true; } else if (args[i].startsWith(QLatin1Char('-'))) { return usage(args); } else { File file; file.name = args[i]; file.format = inFormat; inFiles.append(file); } } if (inFiles.isEmpty()) return usage(args); tr.setLanguageCode(Translator::guessLanguageCodeFromFileName(inFiles[0].name)); if (!tr.load(inFiles[0].name, cd, inFiles[0].format)) { std::cerr << qPrintable(cd.error()); return 2; } tr.reportDuplicates(tr.resolveDuplicates(), inFiles[0].name, verbose); for (int i = 1; i < inFiles.size(); ++i) { Translator tr2; if (!tr2.load(inFiles[i].name, cd, inFiles[i].format)) { std::cerr << qPrintable(cd.error()); return 2; } tr2.reportDuplicates(tr2.resolveDuplicates(), inFiles[i].name, verbose); for (int j = 0; j < tr2.messageCount(); ++j) tr.replaceSorted(tr2.message(j)); } if (!targetLanguage.isEmpty()) tr.setLanguageCode(targetLanguage); if (!sourceLanguage.isEmpty()) tr.setSourceLanguageCode(sourceLanguage); if (noObsolete) tr.stripObsoleteMessages(); if (noFinished) tr.stripFinishedMessages(); if (dropTranslations) tr.dropTranslations(); if (noUiLines) tr.dropUiLines(); if (locations != Translator::DefaultLocations) tr.setLocationsType(locations); tr.normalizeTranslations(cd); if (!cd.errors().isEmpty()) { std::cerr << qPrintable(cd.error()); cd.clearErrors(); } if (!tr.save(outFileName, cd, outFormat)) { std::cerr << qPrintable(cd.error()); return 3; } return 0; }
int main(int argc, char *argv[]) { QString error; QString arg; QString collectionFile; QString configFile; QString basePath; bool showHelp = false; bool showVersion = false; // don't require a window manager even though we're a QGuiApplication qputenv("QT_QPA_PLATFORM", QByteArrayLiteral("minimal")); QGuiApplication app(argc, argv); #ifndef Q_OS_WIN32 QTranslator translator; QTranslator qtTranslator; QTranslator qt_helpTranslator; QString sysLocale = QLocale::system().name(); QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); if (translator.load(QLatin1String("assistant_") + sysLocale, resourceDir) && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir) && qt_helpTranslator.load(QLatin1String("qt_help_") + sysLocale, resourceDir)) { app.installTranslator(&translator); app.installTranslator(&qtTranslator); app.installTranslator(&qt_helpTranslator); } #endif // Q_OS_WIN32 for (int i=1; i<argc; ++i) { arg = QString::fromLocal8Bit(argv[i]); if (arg == QLatin1String("-o")) { if (++i < argc) { QFileInfo fi(QString::fromLocal8Bit(argv[i])); collectionFile = fi.absoluteFilePath(); } else { error = QCG::tr("Missing output file name."); } } else if (arg == QLatin1String("-h")) { showHelp = true; } else if (arg == QLatin1String("-v")) { showVersion = true; } else { QFileInfo fi(arg); configFile = fi.absoluteFilePath(); basePath = fi.absolutePath(); } } if (showVersion) { fputs(qPrintable(QCG::tr("Qt Collection Generator version 1.0 (Qt %1)\n") .arg(QT_VERSION_STR)), stdout); return 0; } if (configFile.isEmpty() && !showHelp) error = QCG::tr("Missing collection config file."); QString help = QCG::tr("\nUsage:\n\n" "qcollectiongenerator <collection-config-file> [options]\n\n" " -o <collection-file> Generates a collection file\n" " called <collection-file>. If\n" " this option is not specified\n" " a default name will be used.\n" " -v Displays the version of\n" " qcollectiongenerator.\n\n"); if (showHelp) { fputs(qPrintable(help), stdout); return 0; } else if (!error.isEmpty()) { fprintf(stderr, "%s\n\n%s", qPrintable(error), qPrintable(help)); return -1; } QFile file(configFile); if (!file.open(QIODevice::ReadOnly)) { fputs(qPrintable(QCG::tr("Could not open %1.\n").arg(configFile)), stderr); return -1; } if (collectionFile.isEmpty()) { QFileInfo fi(configFile); collectionFile = basePath + QDir::separator() + fi.baseName() + QLatin1String(".qhc"); } fputs(qPrintable(QCG::tr("Reading collection config file...\n")), stdout); CollectionConfigReader config; config.readData(file.readAll()); if (config.hasError()) { fputs(qPrintable(QCG::tr("Collection config file error: %1\n") .arg(config.errorString())), stderr); return -1; } QMap<QString, QString>::const_iterator it = config.filesToGenerate().constBegin(); while (it != config.filesToGenerate().constEnd()) { fputs(qPrintable(QCG::tr("Generating help for %1...\n").arg(it.key())), stdout); QHelpProjectData helpData; if (!helpData.readData(absoluteFileName(basePath, it.key()))) { fprintf(stderr, "%s\n", qPrintable(helpData.errorMessage())); return -1; } HelpGenerator helpGenerator; if (!helpGenerator.generate(&helpData, absoluteFileName(basePath, it.value()))) { fprintf(stderr, "%s\n", qPrintable(helpGenerator.error())); return -1; } ++it; } fputs(qPrintable(QCG::tr("Creating collection file...\n")), stdout); QFileInfo colFi(collectionFile); if (colFi.exists()) { if (!colFi.dir().remove(colFi.fileName())) { fputs(qPrintable(QCG::tr("The file %1 cannot be overwritten.\n") .arg(collectionFile)), stderr); return -1; } } QHelpEngineCore helpEngine(collectionFile); if (!helpEngine.setupData()) { fprintf(stderr, "%s\n", qPrintable(helpEngine.error())); return -1; } foreach (const QString &file, config.filesToRegister()) { if (!helpEngine.registerDocumentation(absoluteFileName(basePath, file))) { fprintf(stderr, "%s\n", qPrintable(helpEngine.error())); return -1; } } if (!config.filesToRegister().isEmpty()) CollectionConfiguration::updateLastRegisterTime(helpEngine); if (!config.title().isEmpty()) CollectionConfiguration::setWindowTitle(helpEngine, config.title()); if (!config.homePage().isEmpty()) { CollectionConfiguration::setDefaultHomePage(helpEngine, config.homePage()); } if (!config.startPage().isEmpty()) { CollectionConfiguration::setLastShownPages(helpEngine, QStringList(config.startPage())); } if (!config.currentFilter().isEmpty()) { helpEngine.setCurrentFilter(config.currentFilter()); } if (!config.cacheDirectory().isEmpty()) { CollectionConfiguration::setCacheDir(helpEngine, config.cacheDirectory(), config.cacheDirRelativeToCollection()); } CollectionConfiguration::setFilterFunctionalityEnabled(helpEngine, config.enableFilterFunctionality()); CollectionConfiguration::setFilterToolbarVisible(helpEngine, !config.hideFilterFunctionality()); CollectionConfiguration::setDocumentationManagerEnabled(helpEngine, config.enableDocumentationManager()); CollectionConfiguration::setAddressBarEnabled(helpEngine, config.enableAddressBar()); CollectionConfiguration::setAddressBarVisible(helpEngine, !config.hideAddressBar()); CollectionConfiguration::setCreationTime(helpEngine, QDateTime::currentDateTime().toTime_t()); CollectionConfiguration::setFullTextSearchFallbackEnabled(helpEngine, config.fullTextSearchFallbackEnabled()); if (!config.applicationIcon().isEmpty()) { QFile icon(absoluteFileName(basePath, config.applicationIcon())); if (!icon.open(QIODevice::ReadOnly)) { fputs(qPrintable(QCG::tr("Cannot open %1.\n").arg(icon.fileName())), stderr); return -1; } CollectionConfiguration::setApplicationIcon(helpEngine, icon.readAll()); } if (config.aboutMenuTexts().count()) { QByteArray ba; QDataStream s(&ba, QIODevice::WriteOnly); QMap<QString, QString>::const_iterator it = config.aboutMenuTexts().constBegin(); while (it != config.aboutMenuTexts().constEnd()) { s << it.key(); s << it.value(); ++it; } CollectionConfiguration::setAboutMenuTexts(helpEngine, ba); } if (!config.aboutIcon().isEmpty()) { QFile icon(absoluteFileName(basePath, config.aboutIcon())); if (!icon.open(QIODevice::ReadOnly)) { fputs(qPrintable(QCG::tr("Cannot open %1.\n").arg(icon.fileName())), stderr); return -1; } CollectionConfiguration::setAboutIcon(helpEngine, icon.readAll()); } if (config.aboutTextFiles().count()) { QByteArray ba; QDataStream s(&ba, QIODevice::WriteOnly); QMap<QString, QString>::const_iterator it = config.aboutTextFiles().constBegin(); QMap<QString, QByteArray> imgData; QRegExp srcRegExp(QLatin1String("src=(\"(.+)\"|([^\"\\s]+)).*>")); srcRegExp.setMinimal(true); QRegExp imgRegExp(QLatin1String("(<img[^>]+>)")); imgRegExp.setMinimal(true); while (it != config.aboutTextFiles().constEnd()) { s << it.key(); QFileInfo fi(absoluteFileName(basePath, it.value())); QFile f(fi.absoluteFilePath()); if (!f.open(QIODevice::ReadOnly)) { fputs(qPrintable(QCG::tr("Cannot open %1.\n").arg(f.fileName())), stderr); return -1; } QByteArray data = f.readAll(); s << data; QString contents = QString::fromUtf8(data); int pos = 0; while ((pos = imgRegExp.indexIn(contents, pos)) != -1) { QString imgTag = imgRegExp.cap(1); pos += imgRegExp.matchedLength(); if (srcRegExp.indexIn(imgTag, 0) != -1) { QString src = srcRegExp.cap(2); if (src.isEmpty()) src = srcRegExp.cap(3); QFile img(fi.absolutePath() + QDir::separator() + src); if (img.open(QIODevice::ReadOnly)) { if (!imgData.contains(src)) imgData.insert(src, img.readAll()); } else { fputs(qPrintable(QCG::tr("Cannot open referenced image file %1.\n") .arg(img.fileName())), stderr); } } } ++it; } CollectionConfiguration::setAboutTexts(helpEngine, ba); if (imgData.count()) { QByteArray imageData; QBuffer buffer(&imageData); buffer.open(QIODevice::WriteOnly); QDataStream out(&buffer); out << imgData; CollectionConfiguration::setAboutImages(helpEngine, imageData); } } return 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(); }
/*! Processes the qdoc config file \a fileName. This is the controller for all of qdoc. */ static void processQdocconfFile(const QString &fileName) { #ifndef QT_NO_TRANSLATION QList<QTranslator *> translators; #endif /* The Config instance represents the configuration data for qdoc. All the other classes are initialized with the config. Here we initialize the configuration with some default values. */ Config config(tr("qdoc")); int i = 0; while (defaults[i].key) { config.setStringList(defaults[i].key, QStringList() << defaults[i].value); ++i; } config.setStringList(CONFIG_SYNTAXHIGHLIGHTING, QStringList(highlighting ? "true" : "false")); config.setStringList(CONFIG_SHOWINTERNAL, QStringList(showInternal ? "true" : "false")); config.setStringList(CONFIG_NOLINKERRORS, QStringList(noLinkErrors ? "true" : "false")); config.setStringList(CONFIG_OBSOLETELINKS, QStringList(obsoleteLinks ? "true" : "false")); QString documentationPath = QLibraryInfo::rawLocation(QLibraryInfo::DocumentationPath, QLibraryInfo::EffectivePaths); // Set a few environment variables that can be used from the qdocconf file qputenv("QT_INSTALL_DOCS", documentationPath.toLatin1()); /* With the default configuration values in place, load the qdoc configuration file. Note that the configuration file may include other configuration files. The Location class keeps track of the current location in the file being processed, mainly for error reporting purposes. */ Location::initialize(config); config.load(fileName); /* Add the defines to the configuration variables. */ QStringList defs = defines + config.getStringList(CONFIG_DEFINES); config.setStringList(CONFIG_DEFINES,defs); Location::terminate(); QString prevCurrentDir = QDir::currentPath(); QString dir = QFileInfo(fileName).path(); if (!dir.isEmpty()) QDir::setCurrent(dir); /* Initialize all the classes and data structures with the qdoc configuration. */ Location::initialize(config); Tokenizer::initialize(config); Doc::initialize(config); CodeMarker::initialize(config); CodeParser::initialize(config); Generator::initialize(config); #ifndef QT_NO_TRANSLATION /* Load the language translators, if the configuration specifies any. */ QStringList fileNames = config.getStringList(CONFIG_TRANSLATORS); QStringList::Iterator fn = fileNames.constBegin(); while (fn != fileNames.constEnd()) { QTranslator *translator = new QTranslator(0); if (!translator->load(*fn)) config.lastLocation().error(tr("Cannot load translator '%1'") .arg(*fn)); QCoreApplication::instance()->installTranslator(translator); translators.append(translator); ++fn; } #endif //QSet<QString> outputLanguages = config.getStringSet(CONFIG_OUTPUTLANGUAGES); /* Get the source language (Cpp) from the configuration and the location in the configuration file where the source language was set. */ QString lang = config.getString(CONFIG_LANGUAGE); Location langLocation = config.lastLocation(); /* Initialize the qdoc database, where all the parsed source files will be stored. The database includes a tree of nodes, which gets built as the source files are parsed. The documentation output is generated by traversing that tree. */ QDocDatabase* qdb = QDocDatabase::qdocDB(); qdb->setVersion(config.getString(CONFIG_VERSION)); /* By default, the only output format is HTML. */ QSet<QString> outputFormats = config.getOutputFormats(); Location outputFormatsLocation = config.lastLocation(); /* Read some XML indexes containing definitions from other documentation sets. */ QStringList indexFiles = config.getStringList(CONFIG_INDEXES); dependModules += config.getStringList(CONFIG_DEPENDS); // Allow modules and third-party application/libraries to link // to the Qt docs without having to explicitly pass --indexdir. if (!indexDirs.contains(documentationPath)) indexDirs.append(documentationPath); if (dependModules.size() > 0) { if (indexDirs.size() > 0) { for (int i = 0; i < indexDirs.size(); i++) { if (indexDirs[i].startsWith("..")) { const QString prefix(QDir(dir).relativeFilePath(prevCurrentDir)); if (!prefix.isEmpty()) indexDirs[i].prepend(prefix + QLatin1Char('/')); } } /* Add all subdirectories of the indexdirs as dependModules when an asterisk is used in the 'depends' list. */ if (dependModules.contains("*")) { dependModules.removeOne("*"); for (int i = 0; i < indexDirs.size(); i++) { QDir scanDir = QDir(indexDirs[i]); scanDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); QFileInfoList dirList = scanDir.entryInfoList(); for (int j = 0; j < dirList.size(); j++) { if (dirList[j].fileName().toLower() != config.getString(CONFIG_PROJECT).toLower()) dependModules.append(dirList[j].fileName()); } } } for (int i = 0; i < dependModules.size(); i++) { QString indexToAdd; QList<QFileInfo> foundIndices; for (int j = 0; j < indexDirs.size(); j++) { QString fileToLookFor = indexDirs[j] + QLatin1Char('/') + dependModules[i] + QLatin1Char('/') + dependModules[i] + QLatin1String(".index"); if (QFile::exists(fileToLookFor)) { QFileInfo tempFileInfo(fileToLookFor); if (!foundIndices.contains(tempFileInfo)) foundIndices.append(tempFileInfo); } } qSort(foundIndices.begin(), foundIndices.end(), creationTimeBefore); if (foundIndices.size() > 1) { /* QDoc should always use the last entry in the multimap when there are multiple index files for a module, since the last modified file has the highest UNIX timestamp. */ qDebug() << "Multiple indices found for dependency:" << dependModules[i] << "\nFound:"; for (int k = 0; k < foundIndices.size(); k++) qDebug() << foundIndices[k].absoluteFilePath(); qDebug() << "Using" << foundIndices[foundIndices.size() - 1].absoluteFilePath() << "as index for" << dependModules[i]; indexToAdd = foundIndices[foundIndices.size() - 1].absoluteFilePath(); } else if (foundIndices.size() == 1) { indexToAdd = foundIndices[0].absoluteFilePath(); } else { qDebug() << "No indices for" << dependModules[i] << "could be found in the specified index directories."; } if (!indexToAdd.isEmpty() && !indexFiles.contains(indexToAdd)) indexFiles << indexToAdd; } } else { qDebug() << "Dependant modules specified, but no index directories or install directory were set." << "There will probably be errors for missing links."; } } qdb->readIndexes(indexFiles); QSet<QString> excludedDirs; QSet<QString> excludedFiles; QStringList headerList; QStringList sourceList; QStringList excludedDirsList; QStringList excludedFilesList; Generator::debugSegfault("Reading excludedirs"); excludedDirsList = config.getCanonicalRelativePathList(CONFIG_EXCLUDEDIRS); foreach (const QString &excludeDir, excludedDirsList) { QString p = QDir::fromNativeSeparators(excludeDir); excludedDirs.insert(p); }
/// \fn int main(int argc, char *argv[]) /// \brief Entry point of the application. /// /// \file main.cpp /// \brief Entry point for the GUI application /// /// This file contains main(). /////////////////// /// \brief main /// \param argc /// \param argv /// \return /// int main(int argc, char *argv[]) { #if QT_DEBUG // logger creation #endif // initialize resources at startup (qrc file loading) #if defined(Q_OS_MAC) Q_INIT_RESOURCE(eddypro_mac); #elif defined(Q_OS_WIN) Q_INIT_RESOURCE(eddypro_win); #else Q_INIT_RESOURCE(eddypro_lin); #endif qApp->setAttribute(Qt::AA_UseHighDpiPixmaps); #if defined(Q_OS_MAC) qApp->setAttribute(Qt::AA_DontShowIconsInMenus); // workaround necessary in case of widget painting issues // qApp->setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); #endif QApplication::setColorSpec(QApplication::ManyColor); // QApplication::setDesktopSettingsAware(false); QApplication::setEffectEnabled(Qt::UI_AnimateMenu); QApplication::setEffectEnabled(Qt::UI_FadeMenu); QApplication::setEffectEnabled(Qt::UI_AnimateCombo); QApplication::setEffectEnabled(Qt::UI_AnimateTooltip); QApplication::setEffectEnabled(Qt::UI_FadeTooltip); /// /// A set of flags to workaroud issues in specific cases /// // QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); QCoreApplication::setAttribute(Qt::AA_UseOpenGLES); // QCoreApplication::setAttribute(Qt::AA_UseSoftwareOpenGL); // QCoreApplication::setAttribute(Qt::AA_ForceRasterWidgets); // QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); // QCoreApplication::setAttribute(Qt::AA_SetPalette); // QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling); QApplication app(argc, argv); app.setApplicationName(Defs::APP_NAME); app.setApplicationDisplayName(Defs::APP_NAME); app.setOrganizationName(Defs::ORG_NAME); app.setOrganizationDomain(Defs::ORG_DOMAIN); qDebug() << "currentUnicodeVersion" << QChar::currentUnicodeVersion(); // fix order of library paths // see https://bugreports.qt-project.org/browse/QTBUG-40738 QString executable = QLatin1String(argv[0]); QtHelper::prependApplicationPathToLibraryPaths(executable); qDebug() << "library paths" << QApplication::libraryPaths(); #if defined(Q_OS_MAC) // file to open at start auto fileToOpen = QString(); // install event filter to open clicked files in Mac OS X OpenFileFilter openFileFilter; app.installEventFilter(&openFileFilter); app.processEvents(); auto requestedFile = openFileFilter.fileRequested(); if (requestedFile.endsWith(QStringLiteral(".eddypro"))) { fileToOpen = requestedFile; } #endif // custom ttf setup int fontId_1 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-Regular.ttf")); Q_ASSERT(fontId_1 != -1); qDebug() << QFontDatabase::applicationFontFamilies(fontId_1); int fontId_2 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-Italic.ttf")); Q_ASSERT(fontId_2 != -1); qDebug() << QFontDatabase::applicationFontFamilies(fontId_2); int fontId_3 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-Bold.ttf")); Q_ASSERT(fontId_3 != -1); qDebug() << QFontDatabase::applicationFontFamilies(fontId_3); int fontId_4 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-Semibold.ttf")); Q_ASSERT(fontId_4 != -1); qDebug() << QFontDatabase::applicationFontFamilies(fontId_4); int fontId_5 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-BoldItalic.ttf")); Q_ASSERT(fontId_5 != -1); qDebug() << QFontDatabase::applicationFontFamilies(fontId_5); // load translation file embedded in resources QTranslator appTranslator; bool ok = appTranslator.load(QStringLiteral(":/tra/en")); qDebug() << "loading translation:" << ok; app.installTranslator(&appTranslator); // working dir QDir dir = QDir::current(); qDebug() << "current dir" << dir.absolutePath(); QString currentWorkingDir = QDir::currentPath(); QString installationDir = qApp->applicationDirPath(); qDebug() << "currentWorkingDir" << currentWorkingDir; qDebug() << "installationDir" << installationDir; if (currentWorkingDir != installationDir) { QDir::setCurrent(installationDir); } qDebug() << "currentWorkingDir" << QDir::currentPath(); qDebug() << "currentWorkingDir" << QCoreApplication::applicationDirPath(); // styles qDebug() << "------------------------------------------------------------"; qDebug() << "Default Style: " << app.style()->metaObject()->className(); MyStyle myStyle(app.style()->objectName()); app.setStyle(&myStyle); #if defined(Q_OS_WIN) FileUtils::loadStyleSheetFile(QStringLiteral(":/css/winstyle")); #elif defined(Q_OS_MAC) FileUtils::loadStyleSheetFile(QStringLiteral(":/css/macstyle")); #elif defined(Q_OS_LINUX) FileUtils::loadStyleSheetFile(QStringLiteral(":/css/linstyle")); #endif QString appEnvPath = FileUtils::setupEnv(); if (appEnvPath.isEmpty()) { WidgetUtils::critical(nullptr, QObject::tr("Cannot proceed"), QObject::tr("Home Path not available.")); return 1000; } qDebug() << "appEnvPath" << appEnvPath; // check for command line arguments QTextStream stream(stdout); //#ifdef QT_DEBUG // bool getLogFile = true; //#else bool getLogFile = false; //#endif QString filename = doArgs(app.arguments(), stream, &getLogFile); qDebug() << "filename:" << filename; qDebug() << "getLogFile:" << getLogFile; #if defined(Q_OS_MAC) if (!fileToOpen.isEmpty()) { filename = fileToOpen; } #endif // log file QFile logFile(appEnvPath + QLatin1Char('/') + Defs::LOG_FILE_DIR + QLatin1Char('/') + Defs::APP_NAME_LCASE + QStringLiteral("_gui.") + Defs::LOG_FILE_EXT); if (getLogFile) { if (logFile.size() > 1048576) logFile.remove(); if (logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { outputStream = new QTextStream(&logFile); QtMessageHandler oldMsgHandler(qInstallMessageHandler(logOutput)); Q_UNUSED(oldMsgHandler); } else { qDebug() << "Error opening logFile file '" << Defs::APP_NAME_LCASE << "'. All debug output redirected to console."; } } // create and show splash screen QPixmap pixmap(QStringLiteral(":/icons/splash-img")); #if defined(Q_OS_MAC) pixmap.setDevicePixelRatio(2.0); #endif CustomSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint); auto show_splash = GlobalSettings::getFirstAppPersistentSettings(Defs::CONFGROUP_GENERAL, Defs::CONF_GEN_SHOW_SPLASH, true).toBool(); #if defined(Q_OS_MAC) auto is_full_screen_set = GlobalSettings::getFirstAppPersistentSettings(Defs::CONFGROUP_WINDOW, Defs::CONF_WIN_FULLSCREEN, true).toBool(); if (is_full_screen_set) { show_splash = false; } #endif qDebug() << "show_splash:" << show_splash; if (show_splash) { QFont splashFont; splashFont.setFamily(QStringLiteral("Open Sans")); splashFont.setBold(false); splashFont.setPixelSize(12); splash.setFont(splashFont); splash.setMessageRect(QRect(0, 427, 600, 25), Qt::AlignCenter); // Setting the message position. splash.show(); splash.showStatusMessage(QObject::tr("Initializing...")); } qApp->processEvents(); QLocale::setDefault(QLocale::C); if (show_splash) { splash.showStatusMessage(QObject::tr("Loading...")); splash.setProgressValue(20); splash.setProgressValue(30); splash.repaint(); } qApp->processEvents(); //#if defined(Q_OS_MAC) // MainWindow mainWin(filename, appEnvPath, &splash, 0, // Qt::WindowFlags() // Window|WindowTitleHint|WindowSystemMenuHint|WindowMinMaxButtonsHint|WindowCloseButtonHint|WindowFullscreenButtonHint // Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint // ); //#elif defined(Q_OS_WIN) MainWindow mainWin(filename, appEnvPath, &splash); //#endif if (show_splash) { splash.setProgressValue(40); splash.setProgressValue(50); splash.setProgressValue(60); } mainWin.show(); if (show_splash) { splash.setProgressValue(70); splash.setProgressValue(80); splash.clearMessage(); splash.showStatusMessage(QObject::tr("Loading complete.")); splash.setProgressValue(90); splash.setProgressValue(100); splash.repaint(); } // qApp->processEvents(); qDebug() << "applicationDisplayName" << qApp->applicationDisplayName(); #if defined(Q_OS_MAC) qDebug() << "____________________________________________________"; auto docExtraction = extractDocs(installationDir); qDebug() << "docs.zip extraction:" << docExtraction; qDebug() << "____________________________________________________"; #endif qDebug() << "++++++++++++++++++++++++++++++++++++++++++++++++++++"; const int returnVal = app.exec(); // cleanup // if (logFile) // { // logFile->close(); // delete logFile; // } if (outputStream) { delete outputStream; } return returnVal; }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug()<<"launch"; QFile file("D:\\mifmaster.txt"); //if (file.exists()){file.remove();} qInstallMsgHandler(myMessageHandler); S60AutoStart::SetAutoStart(ETrue); QTranslator myTranslator; myTranslator.load("mifmaster_" + QLocale::system().name()); a.installTranslator(&myTranslator); const QString INSTALL_REBOOT_MULTIPLE=Application::tr("Install MIF-files? Device will reboot multiple times."); const QString OPEN4ALL_NOT_ACTIVE=Application::tr("Open4All patch is not activated (it is recomended apply it to autostart), MIF files can not be installed without patch. Continue?"); const QString DELETE_MIFMASTER_CONF=Application::tr("You're deleting MIFMaster, remove mif replacement patch (device will reboot)?"); const QString PATCH_DELETED=Application::tr("Patch deleted! Remove application one more time :)"); const QString INSTALL_REBOOT_ONCE=Application::tr("Install MIF-files? Phone will reboot."); const QString NO_MIF_FOUND=Application::tr("No *.mif files found!"); const QString INSTALL_PATCH=Application::tr("MIF-files replacement patch is not installed, install it (reboot required)?"); const QString ALL_DONE=Application::tr("All done!"); const QString PATCH_INSTALLED=Application::tr("Patch installed! Copy MIF-files to E drive root folder and run an app"); bool wasAutostart= argc > 1; qDebug()<<"autostart"<<wasAutostart; if (wasAutostart) User::After(5000000); if (wasAutostart&&Application::getAutoStartReason()==EUndefined) return 0; if ((!Application::checkRoot())){ if (!Application::confNote((OPEN4ALL_NOT_ACTIVE))) return 0; } if (Application::isUninstalling()&&Application::isPatchInstalled()){ if (Application::confNote((DELETE_MIFMASTER_CONF))) { Application::renameAknIcon(false); Application::setAutoStartReason(EUninstallingApp); Application::reset(); } } qDebug()<<"main"; if (wasAutostart&&Application::getAutoStartReason()==EUninstallingApp){ Application::removePatchAndPreparedMIFs(); Application::setAutoStartReason(EUndefined); Application::note((PATCH_DELETED)); return 0; } if (Application::isPatchInstalled()&&(!Application::isUninstalling())) { if (!Application::isAvkonReplacementNeeded()&&(!wasAutostart)){ if (Application::confNote((INSTALL_REBOOT_ONCE))) { int mifs=Application::copyMIFs(); Application::switchCache(); qDebug()<<mifs; if (mifs!=0) Application::reset(); else if (mifs==0) Application::note(NO_MIF_FOUND); } return 0; } if (Application::isAknIconRenamed()) { Application::copyMIFs(); Application::renameAknIcon(true); Application::setAutoStartReason(EAllDone); Application::reset(); } else { if (wasAutostart) { if (Application::getAutoStartReason()==EAllDone){ Application::note((ALL_DONE)); Application::setAutoStartReason(EUndefined); return 0;} if (Application::getAutoStartReason()==EPatchInstalled) { Application::note((PATCH_INSTALLED)); Application::setAutoStartReason(EUndefined); return 0;} else return 0; } if (Application::getMifFilesCountReadyToReplace()==0) {Application::note(NO_MIF_FOUND); return 0;} QString reqString=(Application::getS60Version()==EBelleRefresh|| Application::getS60Version()==EFeaturePack1)?INSTALL_REBOOT_ONCE:INSTALL_REBOOT_MULTIPLE; if (Application::confNote((reqString))) { if (Application::getS60Version()==EBelleRefresh|| Application::getS60Version()==EFeaturePack1){ // one reboot way for refresh/FP1 devices Application::copyMIFs(); // and kill aknicon on copying Application::setAutoStartReason(EAllDone); Application::reset(); } else{ Application::renameAknIcon(false); Application::setAutoStartReason(EInstallingMifs); Application::reset(); } } } } else if (!Application::isUninstalling()) { if (Application::confNote((INSTALL_PATCH))) { Application::installPatch(Application::getS60Version()); Application::prepareMIFsForPatch("C"); Application::prepareMIFsForPatch("Z"); Application::copyMIFs(); Application::setAutoStartReason(EPatchInstalled); Application::reset(); } } return 0; }
int main(int argc, char *argv[]) { int ret=2; // return code from qapplication, default to error // // PROCESS COMMAND LINE SWITCHES // // snaffle arguments into a stringlist we can play with into sargs // and only keep non-switch args in the args string list QStringList sargs, args; for (int i=0; i<argc; i++) sargs << argv[i]; #ifdef GC_DEBUG bool debug = true; #else bool debug = false; #endif bool help = false; // honour command line switches foreach (QString arg, sargs) { // help or version requested if (arg == "--help" || arg == "--version") { help = true; fprintf(stderr, "GoldenCheetah %s (%d)\nusage: GoldenCheetah [[directory] athlete]\n\n", VERSION_STRING, VERSION_LATEST); fprintf(stderr, "--help or --version to print this message and exit\n"); #ifdef GC_DEBUG fprintf(stderr, "--debug to turn on redirection of messages to goldencheetah.log [debug build]\n"); #else fprintf(stderr, "--debug to direct diagnostic messages to the terminal instead of goldencheetah.log\n"); #endif fprintf (stderr, "\nSpecify the folder and/or athlete to open on startup\n"); fprintf(stderr, "If no parameters are passed it will reopen the last athlete.\n\n"); } else if (arg == "--debug") { #ifdef GC_DEBUG // debug, so don't redirect stderr! debug = false; #else debug = true; #endif } else { // not switches ! args << arg; } } // help or version printed so just exit now if (help) { exit(0); } // // INITIALISE ONE TIME OBJECTS // #ifdef Q_OS_X11 XInitThreads(); #endif #ifdef Q_OS_MACX if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) { // fix Mac OS X 10.9 (mavericks) font issue // https://bugreports.qt-project.org/browse/QTBUG-32789 QFont::insertSubstitution("LucidaGrande", "Lucida Grande"); } #endif // create the application -- only ever ONE regardless of restarts QApplication *application = new QApplication(argc, argv); #ifdef Q_OS_MAC // get an autorelease pool setup static CocoaInitializer cocoaInitializer; #endif // set defaultfont QFont font; font.fromString(appsettings->value(NULL, GC_FONT_DEFAULT, QFont().toString()).toString()); font.setPointSize(appsettings->value(NULL, GC_FONT_DEFAULT_SIZE, 10).toInt()); application->setFont(font); // set default font // set default colors GCColor::setupColors(); GCColor::readConfig(); // // OPEN FIRST MAINWINDOW // do { // lets not restart endlessly restarting = false; //this is the path within the current directory where GC will look for //files to allow USB stick support QString localLibraryPath="Library/GoldenCheetah"; //this is the path that used to be used for all platforms //now different platforms will use their own path //this path is checked first to make things easier for long-time users QString oldLibraryPath=QDir::home().canonicalPath()+"/Library/GoldenCheetah"; //these are the new platform-dependent library paths #if defined(Q_OS_MACX) QString libraryPath="Library/GoldenCheetah"; #elif defined(Q_OS_WIN) #if QT_VERSION > 0x050000 // windows and qt5 QStringList paths=QStandardPaths::standardLocations(QStandardPaths::DataLocation); QString libraryPath = paths.at(0); #else // windows not qt5 QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/GoldenCheetah"; #endif // qt5 #else // not windows or osx (must be Linux or OpenBSD) // Q_OS_LINUX et al QString libraryPath=".goldencheetah"; #endif // // or did we override in settings? QString sh; if ((sh=appsettings->value(NULL, GC_HOMEDIR, "").toString()) != QString("")) localLibraryPath = sh; // lets try the local library we've worked out... QDir home = QDir(); if(QDir(localLibraryPath).exists() || home.exists(localLibraryPath)) { home.cd(localLibraryPath); } else { // YIKES !! The directory we should be using doesn't exist! home = QDir::home(); if (home.exists(oldLibraryPath)) { // there is an old style path, lets fo there home.cd(oldLibraryPath); } else { if (!home.exists(libraryPath)) { if (!home.mkpath(libraryPath)) { // tell user why we aborted ! QMessageBox::critical(NULL, "Exiting", QString("Cannot create library directory (%1)").arg(libraryPath)); exit(0); } } home.cd(libraryPath); } } // set global root directory gcroot = home.canonicalPath(); // now redirect stderr #ifndef WIN32 if (!debug) nostderr(home.canonicalPath()); #endif // install QT Translator to enable QT Dialogs translation // we may have restarted JUST to get this! QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); application->installTranslator(&qtTranslator); // Language setting (default to system locale) QVariant lang = appsettings->value(NULL, GC_LANG, QLocale::system().name()); // Load specific translation QTranslator gcTranslator; gcTranslator.load(":translations/gc_" + lang.toString() + ".qm"); application->installTranslator(&gcTranslator); // Initialize metrics once the translator is installed RideMetricFactory::instance().initialize(); // Initialize global registry once the translator is installed GcWindowRegistry::initialize(); // initialise the trainDB trainDB = new TrainDB(home); // lets do what the command line says ... QVariant lastOpened; if(args.count() == 2) { // $ ./GoldenCheetah Mark // athlete lastOpened = args.at(1); } else if (args.count() == 3) { // $ ./GoldenCheetah ~/Athletes Mark // first parameter is a folder that exists? if (QFileInfo(args.at(1)).isDir()) { home.cd(args.at(1)); } // folder and athlete lastOpened = args.at(2); } else { // no parameters passed lets open the last athlete we worked with lastOpened = appsettings->value(NULL, GC_SETTINGS_LAST); // but hang on, did they crash? if so we need to open with a menu if(appsettings->cvalue(lastOpened.toString(), GC_SAFEEXIT, true).toBool() != true) lastOpened = QVariant(); } // lets attempt to open as asked/remembered bool anyOpened = false; if (lastOpened != QVariant()) { QStringList list = lastOpened.toStringList(); QStringListIterator i(list); while (i.hasNext()) { QString cyclist = i.next(); if (home.cd(cyclist)) { GcUpgrade v3; if (v3.upgradeConfirmedByUser(home)) { MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); mainWindow->ridesAutoImport(); home.cdUp(); anyOpened = true; } else { delete trainDB; return ret; } } } } // ack, didn't manage to open an athlete // and the upgradeWarning was // lets ask the user which / create a new one if (!anyOpened) { ChooseCyclistDialog d(home, true); d.setModal(true); // choose cancel? if ((ret=d.exec()) != QDialog::Accepted) { delete trainDB; return ret; } // chosen, so lets get the choice.. home.cd(d.choice()); if (!home.exists()) { delete trainDB; exit(0); } // .. and open a mainwindow GcUpgrade v3; if (v3.upgradeConfirmedByUser(home)) { MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); mainWindow->ridesAutoImport(); } else { delete trainDB; return ret; } } ret=application->exec(); // close trainDB delete trainDB; // clear web caches (stop warning of WebKit leaks) QWebSettings::clearMemoryCaches(); } while (restarting); return ret; }
int main(int argc, char *argv[]) { QApplication app(argc, argv); //this is the path within the current directory where GC will look for //files to allow USB stick support QString localLibraryPath="Library/GoldenCheetah"; //this is the path that used to be used for all platforms //now different platforms will use their own path //this path is checked first to make things easier for long-time users QString oldLibraryPath=QDir::home().path()+"/Library/GoldenCheetah"; //these are the new platform-dependent library paths #if defined(Q_OS_MACX) QString libraryPath="Library/GoldenCheetah"; #elif defined(Q_OS_WIN) QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/GoldenCheetah"; #else // Q_OS_LINUX et al QString libraryPath=".goldencheetah"; #endif //First check to see if the Library folder exists where the executable is (for USB sticks) QDir home = QDir(); //if it does, create an ini file for settings and cd into the library if(home.exists(localLibraryPath)) { home.cd(localLibraryPath); } //if it does not exist, let QSettings handle storing settings //also cd to the home directory and look for libraries else { home = QDir::home(); //check if this users previously stored files in the old library path //if they did, use the existing library if (home.exists(oldLibraryPath)) { home.cd(oldLibraryPath); } //otherwise use the new library path else { //first create the path if it does not exist if (!home.exists(libraryPath)) { if (!home.mkpath(libraryPath)) { qDebug()<<"Failed to create library path\n"; assert(false); } } home.cd(libraryPath); } } boost::shared_ptr<QSettings> settings; settings = GetApplicationSettings(); #ifdef ENABLE_METRICS_TRANSLATION // install QT Translator to enable QT Dialogs translation QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); #endif // Language setting (default to system locale) QVariant lang = settings->value(GC_LANG, QLocale::system().name()); // Load specific translation QTranslator gcTranslator; gcTranslator.load(":translations/gc_" + lang.toString() + ".qm"); app.installTranslator(&gcTranslator); #ifdef ENABLE_METRICS_TRANSLATION RideMetricFactory::instance().initialize(); #endif QVariant lastOpened = settings->value(GC_SETTINGS_LAST); QVariant unit = settings->value(GC_UNIT); #ifdef ENABLE_METRICS_TRANSLATION if (unit.isNull()) { // Default to system locale unit = QLocale::system().measurementSystem() == QLocale::MetricSystem ? "Metric" : "Imperial"; settings->setValue(GC_UNIT, unit); } #endif double crankLength = settings->value(GC_CRANKLENGTH).toDouble(); if(crankLength<=0) { settings->setValue(GC_CRANKLENGTH,172.5); } bool anyOpened = false; if (lastOpened != QVariant()) { QStringList list = lastOpened.toStringList(); QStringListIterator i(list); while (i.hasNext()) { QString cyclist = i.next(); if (home.cd(cyclist)) { // used by WkoRideFileReader to store notes WKO_HOMEDIR = home.absolutePath(); MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); home.cdUp(); anyOpened = true; } } } if (!anyOpened) { ChooseCyclistDialog d(home, true); d.setModal(true); if (d.exec() != QDialog::Accepted) return 0; home.cd(d.choice()); if (!home.exists()) assert(false); // used by WkoRideFileReader to store notes WKO_HOMEDIR = home.absolutePath(); MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); } return app.exec(); }
Q_DECL_EXPORT int main(int argc, char *argv[]) { int currentExitCode = 0; QScopedPointer<QSymbianApplication> app(new QSymbianApplication(argc, argv)); // Set App Info: app->setApplicationName("Battery Status"); app->setOrganizationName("Motaz Alnuweiri"); app->setApplicationVersion(APP_Version); // QT_DEBUG or QT_NO_DEBUG // #ifdef QT_DEBUG // // Install Debug Msgs Handler: // ClearDebugFile(); // qInstallMsgHandler(DebugFileHandler); // #endif // Install EventFilter in QApplication: //app->installEventFilter(new myEventFilter); // Set App Splash Screen: QSplashScreen *splash = new QSplashScreen(QPixmap(":qml/Images/JPG/Splash_Screen.jpg"), Qt::WindowStaysOnTopHint); splash->show(); // Check System Language & Load App Translator: QString systemLang = QLocale::system().name(); QTranslator appTranslator; systemLang.truncate(2); //truncate(2) to ignore the country code if (QFile::exists("Languages/batterystatus_" + systemLang + ".qm")) { appTranslator.load("batterystatus_" + systemLang, "Languages"); } else { appTranslator.load("batterystatus_en", "Languages"); } // Install QTranslator to QApplication: app->installTranslator(&appTranslator); // Hide The App If Deactive: if (!app->foreground()) QSymbianHelper::hideInBackground(); // Register QSettings: QAppSettings appSettings; // Register QmlApplicationViewer: QmlApplicationViewer *viewer = new QmlApplicationViewer(); //viewer.setResizeMode(QmlApplicationViewer::SizeRootObjectToView); //viewer.setAutoFillBackground(false); //viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait); // Register App HSWidget: QBatteryHSWidget *batteryHSWidget = new QBatteryHSWidget(); batteryHSWidget->setBackgroundOpacity(appSettings.getWidgetOpacity()); // Register QDeviceName: QDeviceName deviceName; // Register Class to QML: qmlRegisterType<QPSMode>("PSMode", 1, 0, "PSMode"); qmlRegisterType<QGlobalNote>("GlobalNote", 1, 0, "GlobalNote"); qmlRegisterType<QCBatteryInfo>("CBatteryInfo", 1, 0, "CBatteryInfo"); qmlRegisterType<CommonType>("CommonType", 1, 0, "CommonType"); // Set Propertys to QML: viewer->rootContext()->setContextProperty("APPName", QObject::tr("Battery Status")); viewer->rootContext()->setContextProperty("APPVersion", app->applicationVersion()); viewer->rootContext()->setContextProperty("AppPath", app->applicationDirPath()); viewer->rootContext()->setContextProperty("SymbianHelper", new QSymbianHelper); viewer->rootContext()->setContextProperty("AppSettings", &appSettings); viewer->rootContext()->setContextProperty("HSWidget", batteryHSWidget); viewer->rootContext()->setContextProperty("DeviceName", &deviceName); viewer->rootContext()->setContextProperty("QApp", app->instance()); viewer->setSource(QUrl(QLatin1String("qrc:qml/main.qml"))); //viewer.setSource(QUrl::fromLocalFile("qrc:qml/main.qml")); // Lock screen orientation in portrait only //viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait); //viewer.setGeometry(app->desktop()->screenGeometry()); viewer->showFullScreen(); // Stop Splash Screen & Delete It: splash->finish(viewer); splash->deleteLater(); //viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto); // Enter App Event Loop: currentExitCode = app->exec(); // Cleun Pointers: delete viewer; delete batteryHSWidget; // Check If App Is Restarting: if(app->isRestarting()) { // Workround for my app to restart it self QProcess::startDetached(qApp->applicationFilePath()); } return currentExitCode; }
int main(int argc, char *argv[]) { QApplication::setApplicationName("photoqt"); // This string holds the current version QString globVersion = QString::fromStdString(VERSION); // A help message for the command line QString hlp = "\nPhotoQt v" + globVersion + " - Copyright (C) 2013, Lukas Spies ([email protected]), License: GPLv2 (or later)\n"; hlp += "PhotoQt is a fast, simple, good looking, yet powerfull and highly configurable image viewer.\n\n"; hlp += "Usage: photoqt [options|file]\n\n"; hlp += "Options:\n"; hlp += "\t--h, --help\t\tThis help message\n\n"; hlp += ">> Start-up options:\n\n"; hlp += "\t--start-in-tray\t\tStart PhotoQt hidden to the system tray\n"; hlp += "\t--no-thumbs\t\tDon't load thumbnails (Navigation through folder is still possible)\n\n"; hlp += ">> Remote Controlling:\n\n"; hlp += "\t--open\t\t\tOpens the open file dialog (also shows PhotoQt if hidden)\n"; hlp += "\t--toggle\t\tToggles PhotoQt - hides PhotoQt if visible, shows if hidden\n"; hlp += "\t--show\t\t\tShows PhotoQt (does nothing if already shown)\n"; hlp += "\t--hide\t\t\tHides PhotoQt (does nothing if already hidden)\n\n"; hlp += ">> Remote controlling w/ filename needed:\n\n"; hlp += "\t--no-thumbs [filename]\tDon't load thumbnails (Navigation through folder is still possible)\n"; hlp += "\t--thumbs [filename]\tReversing a '--no-thumbs' (thumbnails are enabled by default)\n\n"; hlp += ">> Debuging:\n\n"; hlp += "\t--v, --verbose\t\tEnabling debug messages\n\n"; hlp += "\n Enjoy PhotoQt :-)\n\n\n"; // This file is updated by a running instance of PhotoQt every 500 milliseconds - check QFile chk(QDir::homePath() + "/.photoqt/running"); QString all = ""; if(chk.open(QIODevice::ReadOnly)) { QTextStream in(&chk); all = in.readAll(); } QStringList allArgs; for(int i = 0; i < argc; ++i) allArgs.append(argv[i]); if(QFile(QDir::homePath()+"/.photoqt/verbose").exists()) allArgs.append("--v"); QStringList knownArgs; knownArgs << "--open"; knownArgs << "--no-thumbs"; knownArgs << "--thumbs"; knownArgs << "--toggle"; knownArgs << "--show"; knownArgs << "--hide"; knownArgs << "--start-in-tray"; knownArgs << "--verbose"; knownArgs << "--v"; /****************************************************/ // DEVELOPMENT ONLY knownArgs << "--update" << "--install"; // DEVELOPMENT ONLY /****************************************************/ // If PhotoQt was started with "--h" or "--help", show help message if(allArgs.contains("--help") || allArgs.contains("-help") || allArgs.contains("--h") || allArgs.contains("-h")) { std::cout << hlp.toStdString(); return 0; // If an instance of PhotoQt is running, we check for command line arguments } else if(QDateTime::currentMSecsSinceEpoch() - all.toLongLong() < qint64(1020)) { // We need to initiate it here to, because we check for the applicationFilePath() later-on QApplication a(argc, argv); std::cout << "Running instance of PhotoQt detected..." << std::endl; // This is the content of the file used to communicate with running PhotoQt instance QString cont = ""; // This boolean is set to true if an unknown command is used bool err = false; for(int i = 1; i < allArgs.length(); ++i) { // We ignore the verbose switch when an instance is already running if(allArgs.at(i) != "--v" && allArgs.at(i) != "--verbose") { if(knownArgs.contains(allArgs.at(i))) cont += allArgs.at(i) + "\n"; else if(allArgs.at(i).startsWith("-")) { err = true; } else { QString filename = allArgs.at(i); if(!filename.startsWith("/")) filename = QFileInfo(filename).absoluteFilePath(); if(filename != a.applicationFilePath()) cont += "-f-" + filename; } } } // If PhotoQt is called without any arguments, "show" is used if(allArgs.length() == 1 || (allArgs.length() == 2 && allArgs.contains("--v"))) cont = "--show"; // If only correct arguments were used if(!err) { // Write the commands into this file, which is checked regularly by a running instance of PhotoQt QFile f(QDir::homePath() + "/.photoqt/cmd"); f.remove(); if(f.open(QIODevice::WriteOnly)) { QTextStream out(&f); out << cont; f.close(); } else std::cerr << "ERROR! Couldn't write to file '~/.photoqt/cmd'. Unable to communicate with running process" << std::endl; // If an uncorrect argument was used } else std::cout << hlp.toStdString(); return 0; // If PhotoQt isn't running and no command line argument (besides filename and "--start-in.tray") was used } else { bool verbose = (allArgs.contains("--v") || allArgs.contains("--verbose") || QFile(QDir::homePath() + "/.photoqt/verbose").exists() || (!QDir(QDir::homePath() + "/.photoqt").exists() && QFile(QDir::homePath() + "/.photo/verbose").exists())); bool migrated = false; // Ensure that the config folder exists, and move from ~/.photo to ~/.photoqt QDir dir(QDir::homePath() + "/.photoqt"); if(!dir.exists()) { QDir dir_old(QDir::homePath() + "/.photo"); if(dir_old.exists()) { if(verbose) std::clog << "Moving ~/.photo to ~/.photoqt" << std::endl; dir.mkdir(QDir::homePath() + "/.photoqt"); QFile file(QDir::homePath() + "/.photo/contextmenu"); if(file.exists()) { file.copy(QDir::homePath() + "/.photoqt/contextmenu"); file.remove(); } file.setFileName(QDir::homePath() + "/.photo/fileformats"); if(file.exists()) { file.copy(QDir::homePath() + "/.photoqt/fileformats"); file.remove(); } file.setFileName(QDir::homePath() + "/.photo/running"); if(file.exists()) { file.copy(QDir::homePath() + "/.photoqt/running"); file.remove(); } file.setFileName(QDir::homePath() + "/.photo/settings"); if(file.exists()) { file.copy(QDir::homePath() + "/.photoqt/settings"); file.remove(); } file.setFileName(QDir::homePath() + "/.photo/shortcuts"); if(file.exists()) { file.copy(QDir::homePath() + "/.photoqt/shortcuts"); file.remove(); } file.setFileName(QDir::homePath() + "/.photo/thumbnails"); if(file.exists()) { file.copy(QDir::homePath() + "/.photoqt/thumbnails"); file.remove(); } file.setFileName(QDir::homePath() + "/.photo/verbose"); if(file.exists()) { file.copy(QDir::homePath() + "/.photoqt/verbose"); file.remove(); } dir_old.rmdir(dir_old.absolutePath()); migrated = true; } else { if(verbose) std::clog << "Creating ~/.photoqt/" << std::endl; dir.mkdir(QDir::homePath() + "/.photoqt"); } } bool err = false; for(int i = 0; i < allArgs.length(); ++i) { if(allArgs.at(i).startsWith("-") && !knownArgs.contains(allArgs.at(i))) err = true; } if(err == true) { std::cout << hlp.toStdString(); // Nothing after this return will be executed (PhotoQt will simply quit) return 0; } // This int holds 1 if PhotoQt was updated and 2 if it's newly installed int update = 0; QString settingsFileTxt = ""; // Check if the settings file exists. If not, create a file with default settings (i.e. empty file, settings and defaults are handled by globalsettings.h) QFile file(QDir::homePath() + "/.photoqt/settings"); if(!file.exists()) { if(!file.open(QIODevice::WriteOnly)) std::cerr << "ERROR: Couldn't write settings file! Please ensure that you have read&write access to home directory" << std::endl; else { if(verbose) std::clog << "Creating basic settings file" << std::endl; QTextStream out(&file); out << "Version=" + globVersion + "\n"; file.close(); } update = 2; // If file does exist, check if it is from a previous version -> PhotoQt was updated } else { if(!file.open(QIODevice::ReadWrite)) std::cerr << "ERROR: Couldn't read settings file! Please ensure that you have read&write access to home directory" << std::endl; else { QTextStream in(&file); settingsFileTxt = in.readAll(); if(verbose) std::clog << "Checking if first run of new version" << std::endl; // If it doesn't contain current version (some previous version) if(!settingsFileTxt.contains("Version=" + globVersion + "\n")) { file.close(); file.remove(); file.open(QIODevice::ReadWrite); QStringList allSplit = settingsFileTxt.split("\n"); allSplit.removeFirst(); QString allFile = "Version=" + globVersion + "\n" + allSplit.join("\n"); in << allFile; update = 1; } file.close(); } } /****************************************************/ // DEVELOPMENT ONLY if(allArgs.contains("--update")) update = 1; if(allArgs.contains("--install")) update = 2; // DEVELOPMENT ONLY /****************************************************/ #ifdef GM Magick::InitializeMagick(*argv); #endif if(QFile(QDir::homePath()+"/.photoqt/cmd").exists()) QFile(QDir::homePath()+"/.photoqt/cmd").remove(); // This boolean stores if PhotoQt needs to be minimized to the tray bool startintray = allArgs.contains("--start-in-tray"); // If PhotoQt is supposed to be started minimized in system tray if(startintray) { if(verbose) std::clog << "Starting minimised to tray" << std::endl; // If the option "Use Tray Icon" in the settings is not set, we set it QFile set(QDir::homePath() + "/.photoqt/settings"); if(set.open(QIODevice::ReadOnly)) { QTextStream in(&set); QString all = in.readAll(); if(!all.contains("TrayIcon=1")) { if(all.contains("TrayIcon=0")) all.replace("TrayIcon=0","TrayIcon=1"); else all += "\n[Temporary Appended]\nTrayIcon=1\n"; set.close(); set.remove(); if(!set.open(QIODevice::WriteOnly)) std::cerr << "ERROR: Can't enable tray icon setting!" << std::endl; QTextStream out(&set); out << all; set.close(); } else set.close(); } else std::cerr << "Unable to ensure TrayIcon is enabled - make sure it is enabled!!" << std::endl; } QApplication a(argc, argv); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) // Opt-in to High DPI usage of Pixmaps for larger screens with larger font DPI a.setAttribute(Qt::AA_UseHighDpiPixmaps, true); #endif // LOAD THE TRANSLATOR QTranslator trans; // We use two strings, since the system locale usually is of the form e.g. "de_DE" // and some translations only come with the first part, i.e. "de", // and some with the full string. We need to be able to find both! if(verbose) std::clog << "Checking for translation" << std::endl; QString code1 = ""; QString code2 = ""; if(settingsFileTxt.contains("Language=") && !settingsFileTxt.contains("Language=en") && !settingsFileTxt.contains("Language=\n")) { code1 = settingsFileTxt.split("Language=").at(1).split("\n").at(0).trimmed(); code2 = code1; } else if(!settingsFileTxt.contains("Language=en")) { code1 = QLocale::system().name(); code2 = QLocale::system().name().split("_").at(0); } if(verbose) std::clog << "Found following language: " << code1.toStdString() << "/" << code2.toStdString() << std::endl; if(QFile(":/lang/photoqt_" + code1 + ".qm").exists()) { std::clog << "Loading Translation:" << code1.toStdString() << std::endl; trans.load(":/lang/photoqt_" + code1); a.installTranslator(&trans); code2 = code1; } else if(QFile(":/lang/photoqt_" + code2 + ".qm").exists()) { std::clog << "Loading Translation:" << code2.toStdString() << std::endl; trans.load(":/lang/photoqt_" + code2); a.installTranslator(&trans); code1 = code2; } // Check if thumbnail database exists. If not, create it QFile database(QDir::homePath() + "/.photoqt/thumbnails"); if(!database.exists()) { if(verbose) std::clog << "Create Thumbnail Database" << std::endl; QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "thumbDB"); db.setDatabaseName(QDir::homePath() + "/.photoqt/thumbnails"); if(!db.open()) std::cerr << "ERROR: Couldn't open thumbnail database:" << db.lastError().text().trimmed().toStdString() << std::endl; QSqlQuery query(db); query.prepare("CREATE TABLE Thumbnails (filepath TEXT,thumbnail BLOB, filelastmod INT, thumbcreated INT, origwidth INT, origheight INT)"); query.exec(); if(query.lastError().text().trimmed().length()) std::cerr << "ERROR (Creating Thumbnail Datbase):" << query.lastError().text().trimmed().toStdString() << std::endl; query.clear(); } else { if(verbose) std::clog << "Opening Thumbnail Database" << std::endl; // Opening the thumbnail database QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","thumbDB"); db.setDatabaseName(QDir::homePath() + "/.photoqt/thumbnails"); if(!db.open()) std::cerr << "ERROR: Couldn't open thumbnail database:" << db.lastError().text().trimmed().toStdString() << std::endl; if(migrated) { QSqlQuery query(db); query.prepare("ALTER TABLE Thumbnails ADD COLUMN origwidth INT"); query.exec(); if(query.lastError().text().trimmed().length()) std::cerr << "ERROR (Adding origwidth to Thumbnail Database):" << query.lastError().text().trimmed().toStdString() << std::endl; query.clear(); query.prepare("ALTER TABLE Thumbnails ADD COLUMN origheight INT"); query.exec(); if(query.lastError().text().trimmed().length()) std::cerr << "ERROR (Adding origheight to Thumbnail Database):" << query.lastError().text().trimmed().toStdString() << std::endl; query.clear(); } } // Previous versions of PhotoQt checked here also for the shortcuts file. We don't need to do that anymore, since all shortcuts including the defaults are handled by shortcuts.h /*************************** ***************************/ // The Window has to be initialised *AFTER* the checks above to ensure that the settings exist and are updated and can be loaded MainWindow w(0,verbose); /*************************** ***************************/ // We move from old way of handling image formats to new way // We can't do it before here, since we need access to global settings QFile old_qt(QDir::homePath() + "/.photoqt/fileformatsQt"); QFile old_gm(QDir::homePath() + "/.photoqt/fileformatsGm"); QFile new_file(QDir::homePath() + "/.photoqt/fileformats.disabled"); if((old_qt.exists() || old_gm.exists()) && !new_file.exists()) { // These will be the sets of known file formats QStringList new_qt; QStringList new_gm; // Read in formats supported by qt if(old_qt.exists()) { if(!old_qt.open(QIODevice::ReadOnly)) std::cerr << "[migrate fileformats] ERROR: Can't open old file with qt file formats"; else { QTextStream in(&old_qt); QString line = in.readLine(); while (!line.isNull()) { if(line.trimmed().length() != 0) new_qt << "*" + line.trimmed(); line = in.readLine(); } old_qt.close(); } // Remove old and redundant file if(!old_qt.remove()) std::cerr << "[migrate fileformats] WARNING: Can't remove old (redundant) file with qt file formats"; } // Read in formats supported by gm if(old_gm.exists()) { if(!old_gm.open(QIODevice::ReadOnly)) std::cerr << "[migrate fileformats] ERROR: Can't open old file with gm file formats"; else { QTextStream in(&old_gm); QString line = in.readLine(); while (!line.isNull()) { if(line.trimmed().length() != 0) new_gm << "*" + line.trimmed(); line = in.readLine(); } old_gm.close(); } // Remove old and redundant file if(!old_gm.remove()) std::cerr << "[migrate fileformats] WARNING: Can't remove old (redundant) file with gm file formats"; } // File content of disabled fileformats QString fileformatsDisabled = ""; // New fileformats that were not part of previous versions of PhotoQt QStringList newfileformats; newfileformats << "*.cin"; newfileformats << "*.mono"; newfileformats << "*.sfw"; newfileformats << "*.txt"; newfileformats << "*.wpg"; // QT: If not supported, it is disabled QStringList qtDef; qtDef << "*.bmp, *.bitmap" << "*.dds" << "*.gif" << "*.ico, *.icns" << "*.jpg, *.jpeg" << "*.jpeg2000, *.jp2, *.jpc, *.j2k, *.jpf, *.jpx, *.jpm, *.mj2" << "*.mng" << "*.png" << "*.pbm" << "*.pgm" << "*.ppm" << "*.svg, *.svgz" << "*.tif, *.tiff" << "*.wbmp, *.webp" << "*.xbm" << "*.xpm"; QList<QByteArray> qtSup = QImageReader::supportedImageFormats(); foreach(QString q, qtDef) { QStringList parts = q.split(", "); bool disabled = true; foreach(QString p, parts) { if(qtSup.contains(p.remove(0,2).toLower().trimmed().toLatin1())) { disabled = false; break; } } if(disabled) fileformatsDisabled += parts.join("\n") + "\n"; } // GM: If not enabled, it is disabled - new fileformats are ENabled by default QStringList gmDef = w.globSet->fileFormats->formatsGmEnabled; foreach(QString g, gmDef) { if(!new_gm.contains(g) && !newfileformats.contains(g)) fileformatsDisabled += g + "\n"; } // Extras are disabled by default fileformatsDisabled += "**.xcf\n**.psd\n**.psb\n"; // Untested are disabled by default if(!fileformatsDisabled.contains("*.hp\n")) fileformatsDisabled += "*.hp\n"; if(!fileformatsDisabled.contains("*.hpgl\n")) fileformatsDisabled += "*.hpgl\n"; if(!fileformatsDisabled.contains("*.jbig\n")) fileformatsDisabled += "*.jbig\n"; if(!fileformatsDisabled.contains("*.jbg\n")) fileformatsDisabled += "*.jbg\n"; if(!fileformatsDisabled.contains("*.pwp\n")) fileformatsDisabled += "*.pwp\n"; if(!fileformatsDisabled.contains("*.rast\n")) fileformatsDisabled += "*.rast\n"; if(!fileformatsDisabled.contains("*.rla\n")) fileformatsDisabled += "*.rla\n"; if(!fileformatsDisabled.contains("*.rle\n")) fileformatsDisabled += "*.rle\n"; if(!fileformatsDisabled.contains("*.sct\n")) fileformatsDisabled += "*.sct\n"; if(!fileformatsDisabled.contains("*.tim\n")) fileformatsDisabled += "*.tim\n"; // Write 'disabled filetypes' file if(new_file.open(QIODevice::WriteOnly)) { QTextStream out(&new_file); out << fileformatsDisabled; new_file.close(); } else std::cerr << "ERROR: Can't write default disabled fileformats file" << std::endl; // Update settings with new values w.globSet->fileFormats->getFormats(); }
int main(int argc, char *argv[]) { QString error; QString arg; QString compressedFile; QString projectFile; QString basePath; bool showHelp = false; bool showVersion = false; bool checkLinks = false; // don't require a window manager even though we're a QGuiApplication qputenv("QT_QPA_PLATFORM", QByteArrayLiteral("minimal")); QGuiApplication app(argc, argv); #ifndef Q_OS_WIN32 QTranslator translator; QTranslator qtTranslator; QTranslator qt_helpTranslator; QString sysLocale = QLocale::system().name(); QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); if (translator.load(QLatin1String("assistant_") + sysLocale, resourceDir) && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir) && qt_helpTranslator.load(QLatin1String("qt_help_") + sysLocale, resourceDir)) { app.installTranslator(&translator); app.installTranslator(&qtTranslator); app.installTranslator(&qt_helpTranslator); } #endif // Q_OS_WIN32 for (int i = 1; i < argc; ++i) { arg = QString::fromLocal8Bit(argv[i]); if (arg == QLatin1String("-o")) { if (++i < argc) { QFileInfo fi(QString::fromLocal8Bit(argv[i])); compressedFile = fi.absoluteFilePath(); } else { error = QHG::tr("Missing output file name."); } } else if (arg == QLatin1String("-v")) { showVersion = true; } else if (arg == QLatin1String("-h")) { showHelp = true; } else if (arg == QLatin1String("-c")) { checkLinks = true; } else { QFileInfo fi(arg); projectFile = fi.absoluteFilePath(); basePath = fi.absolutePath(); } } if (showVersion) { fputs(qPrintable(QHG::tr("Qt Help Generator version 1.0 (Qt %1)\n") .arg(QT_VERSION_STR)), stdout); return 0; } if (projectFile.isEmpty() && !showHelp) error = QHG::tr("Missing Qt help project file."); QString help = QHG::tr("\nUsage:\n\n" "qhelpgenerator <help-project-file> [options]\n\n" " -o <compressed-file> Generates a Qt compressed help\n" " file called <compressed-file>.\n" " If this option is not specified\n" " a default name will be used.\n" " -c Checks whether all links in HTML files\n" " point to files in this help project.\n" " -v Displays the version of \n" " qhelpgenerator.\n\n"); if (showHelp) { fputs(qPrintable(help), stdout); return 0; }else if (!error.isEmpty()) { fprintf(stderr, "%s\n\n%s", qPrintable(error), qPrintable(help)); return -1; } QFile file(projectFile); if (!file.open(QIODevice::ReadOnly)) { fputs(qPrintable(QHG::tr("Could not open %1.\n").arg(projectFile)), stderr); return -1; } if (compressedFile.isEmpty()) { if (!checkLinks) { QFileInfo fi(projectFile); compressedFile = basePath + QDir::separator() + fi.baseName() + QLatin1String(".qch"); } } else { // check if the output dir exists -- create if it doesn't QFileInfo fi(compressedFile); QDir parentDir = fi.dir(); if (!parentDir.exists()) { if (!parentDir.mkpath(QLatin1String("."))) { fputs(qPrintable(QHG::tr("Could not create output directory: %1\n") .arg(parentDir.path())), stderr); } } } QHelpProjectData *helpData = new QHelpProjectData(); if (!helpData->readData(projectFile)) { fprintf(stderr, "%s\n", qPrintable(helpData->errorMessage())); return -1; } HelpGenerator generator; bool success = true; if (checkLinks) success = generator.checkLinks(*helpData); if (success && !compressedFile.isEmpty()) success = generator.generate(helpData, compressedFile); delete helpData; if (!success) { fprintf(stderr, "%s\n", qPrintable(generator.error())); return -1; } return 0; }
int main(int argc, char** argv) { Q_INIT_RESOURCE(resource); QString nextTranslator; //const char* argv_2[]={"OpenBrf"}; int argc_2=1; //QApplication app(argc_2,argv_2); //argc, argv); QApplication app(argc, argv); QStringList arguments = QCoreApplication::arguments(); app.setApplicationVersion(applVersion); app.setApplicationName("OpenBrf"); app.setOrganizationName("Marco Tarini"); app.setOrganizationDomain("Marco Tarini"); bool useAlphaC = false; if ((arguments.size()>1)&&(arguments[1].startsWith("-"))) { if ((arguments[1] == "--dump")&&(arguments.size()==4)) { switch (MainWindow().loadModAndDump(arguments[2],arguments[3])) { case -1: printf("OpenBRF: invalid module folder\n"); break; case -2: printf("OpenBRF: error scanning brf data or ini file\n"); break; case -3: printf("OpenBRF: error writing output file\n"); break; default: return 0; } return -1; } else if ((arguments[1] == "--useAlphaCommands")&&(arguments.size()==2)) { useAlphaC = true; arguments.clear(); } else { showUsage(); return -1; } } while (1){ QTranslator translator; QTranslator qtTranslator; if (nextTranslator.isEmpty()){ QString loc; switch (MainWindow::getLanguageOption()) { default: loc = QLocale::system().name(); break; case 1: loc = QString("en");break; case 2: loc = QString("zh_CN");break; case 3: loc = QString("es");break; case 4: loc = QString("de");break; } translator.load(QString(":/translations/openbrf_%1.qm").arg(loc)); qtTranslator.load(QString(":/translations/qt_%1.qm").arg(loc)); } else { translator.load(nextTranslator); } app.installTranslator(&translator); app.installTranslator(&qtTranslator); MainWindow w; w.setUseAlphaCommands(useAlphaC); w.show(); if (arguments.size()>1) w.loadFile(arguments[1]); arguments.clear(); if (app.exec()==101) { nextTranslator = w.getNextTranslatorFilename(); continue; // just changed language! another run } break; } return 0; }
int main(int argc, char *argv[]) { VSingleInstanceGuard guard; bool canRun = guard.tryRun(); QTextCodec *codec = QTextCodec::codecForName("UTF8"); if (codec) { QTextCodec::setCodecForLocale(codec); } QApplication app(argc, argv); // The file path passed via command line arguments. QStringList filePaths = VUtils::filterFilePathsToOpen(app.arguments().mid(1)); if (!canRun) { // Ask another instance to open files passed in. if (!filePaths.isEmpty()) { guard.openExternalFiles(filePaths); } else { guard.showInstance(); } return 0; } VConfigManager vconfig; vconfig.initialize(); g_config = &vconfig; #if defined(QT_NO_DEBUG) for (int i = 1; i < argc; ++i) { if (!qstrcmp(argv[i], "-d")) { g_debugLog = true; break; } } initLogFile(vconfig.getLogFilePath()); #endif qInstallMessageHandler(VLogger); QString locale = VUtils::getLocale(); // Set default locale. if (locale == "zh_CN") { QLocale::setDefault(QLocale(QLocale::Chinese, QLocale::China)); } qDebug() << "command line arguments" << app.arguments(); qDebug() << "files to open from arguments" << filePaths; // Check the openSSL. qDebug() << "openSSL" << QSslSocket::sslLibraryBuildVersionString() << QSslSocket::sslLibraryVersionNumber(); // Load missing translation for Qt (QTextEdit/QPlainTextEdit/QTextBrowser). QTranslator qtTranslator1; if (qtTranslator1.load("widgets_" + locale, ":/translations")) { app.installTranslator(&qtTranslator1); } QTranslator qtTranslator2; if (qtTranslator2.load("qdialogbuttonbox_" + locale, ":/translations")) { app.installTranslator(&qtTranslator2); } QTranslator qtTranslator3; if (qtTranslator3.load("qwebengine_" + locale, ":/translations")) { app.installTranslator(&qtTranslator3); } // Load translation for Qt from resource. QTranslator qtTranslator; if (qtTranslator.load("qt_" + locale, ":/translations")) { app.installTranslator(&qtTranslator); } // Load translation for Qt from env. QTranslator qtTranslatorEnv; if (qtTranslatorEnv.load("qt_" + locale, "translations")) { app.installTranslator(&qtTranslatorEnv); } // Load translation for vnote. QTranslator translator; if (translator.load("vnote_" + locale, ":/translations")) { app.installTranslator(&translator); } VPalette palette(g_config->getThemeFile()); g_palette = &palette; VMainWindow w(&guard); QString style = palette.fetchQtStyleSheet(); if (!style.isEmpty()) { app.setStyleSheet(style); } w.show(); w.openStartupPages(); w.openFiles(filePaths); w.promptNewNotebookIfEmpty(); return app.exec(); }
int main(int argc, char *argv[]) { ArgumentList *argList = new ArgumentList(argc, argv); #if QT_VERSION < 0x050000 QApplication::setGraphicsSystem(QLatin1String("raster")); #endif QString packagesToInstall; QString arg; for (int c=1; c<argc; c++) { arg = argv[c]; if (arg.contains("pkg.tar*")) { packagesToInstall += arg + ","; } } QtSingleApplication app( StrConstants::getApplicationName(), argc, argv ); if (app.isRunning()) { if (argList->getSwitch("-sysupgrade")) { app.sendMessage("SYSUPGRADE"); } else if (argList->getSwitch("-sysupgrade-noconfirm")) { app.sendMessage("SYSUPGRADE_NOCONFIRM"); } else if (argList->getSwitch("-close")) { app.sendMessage("CLOSE"); } else if (argList->getSwitch("-hide")) { app.sendMessage("HIDE"); } else if (!packagesToInstall.isEmpty()) { app.sendMessage(packagesToInstall); } else { app.sendMessage("RAISE"); } return 0; } //This sends a message just to enable the socket-based QtSingleApplication engine app.sendMessage("RAISE"); QTranslator appTranslator; appTranslator.load(":/resources/translations/octopi_" + QLocale::system().name()); app.installTranslator(&appTranslator); if (argList->getSwitch("-help")){ std::cout << StrConstants::getApplicationCliHelp().toLatin1().data() << std::endl; return(0); } else if (argList->getSwitch("-version")){ std::cout << "\n" << StrConstants::getApplicationName().toLatin1().data() << " " << StrConstants::getApplicationVersion().toLatin1().data() << "\n" << std::endl; return(0); } if (UnixCommand::isRootRunning() && !WMHelper::isKDERunning()){ QMessageBox::critical( 0, StrConstants::getApplicationName(), StrConstants::getErrorRunningWithRoot()); return ( -2 ); } MainWindow w; app.setActivationWindow(&w); app.setQuitOnLastWindowClosed(false); #if QT_VERSION < 0x050000 #ifndef NO_GTK_STYLE if (!argList->getSwitch("-style")) { if (UnixCommand::getLinuxDistro() == ectn_MANJAROLINUX && (!WMHelper::isKDERunning() && (!WMHelper::isRazorQtRunning()) && (!WMHelper::isLXQTRunning()))) { app.setStyle(new QGtkStyle()); } else if(UnixCommand::getLinuxDistro() != ectn_CHAKRA) { app.setStyle(new QCleanlooksStyle()); } } #endif #endif if (argList->getSwitch("-sysupgrade-noconfirm")) { w.setCallSystemUpgradeNoConfirm(); } else if (argList->getSwitch("-sysupgrade")) { w.setCallSystemUpgrade(); } if (!packagesToInstall.isEmpty()) { QStringList packagesToInstallList = packagesToInstall.split(",", QString::SkipEmptyParts); w.setPackagesToInstallList(packagesToInstallList); } w.setRemoveCommand("Rcs"); //argList->getSwitchArg("-removecmd", "Rcs")); w.show(); QResource::registerResource("./resources.qrc"); return app.exec(); }
void setLanguage(QCoreApplication& qapplication, QWidget* parent) { static int cntTranslators=0; if(cntTranslators>0){ qapplication.removeTranslator(&translator); cntTranslators=0; } //translator stuff QDir d("/usr/share/fet/translations"); bool translation_loaded=false; //this is one place (out of 2) in which you need to add a new language if(FET_LANGUAGE=="ar" || FET_LANGUAGE=="ca" || FET_LANGUAGE=="de" || FET_LANGUAGE=="es" || FET_LANGUAGE=="el" || FET_LANGUAGE=="fr" || FET_LANGUAGE=="hu" || FET_LANGUAGE=="mk" || FET_LANGUAGE=="ms" || FET_LANGUAGE=="nl" || FET_LANGUAGE=="pl" || FET_LANGUAGE=="ro" || FET_LANGUAGE=="tr" || FET_LANGUAGE=="id" || FET_LANGUAGE=="it" || FET_LANGUAGE=="lt" || FET_LANGUAGE=="ru" || FET_LANGUAGE=="fa" || FET_LANGUAGE=="uk" || FET_LANGUAGE=="pt_BR" || FET_LANGUAGE=="da" || FET_LANGUAGE=="si" || FET_LANGUAGE=="sk" || FET_LANGUAGE=="he" || FET_LANGUAGE=="sr" || FET_LANGUAGE=="gl" || FET_LANGUAGE=="vi" || FET_LANGUAGE=="uz"){ translation_loaded=translator.load("fet_"+FET_LANGUAGE, qapplication.applicationDirPath()); if(!translation_loaded){ translation_loaded=translator.load("fet_"+FET_LANGUAGE, qapplication.applicationDirPath()+"/translations"); if(!translation_loaded){ if(d.exists()){ translation_loaded=translator.load("fet_"+FET_LANGUAGE, "/usr/share/fet/translations"); } } } } else{ if(FET_LANGUAGE!="en_US"){ /* QMessageBox::warning(parent, QString("FET warning"), QString("Specified language is incorrect - making it en_US (US English)")); FET_LANGUAGE="en_US"; */ } assert(FET_LANGUAGE=="en_US"); translation_loaded=true; } if(!translation_loaded){ /* QMessageBox::warning(parent, QString("FET warning"), QString("Translation for specified language not loaded - maybe the translation file is missing - setting the language to en_US (US English)") +"\n\n"+ QString("FET searched for the translation file %1 in the directory %2, then in the directory %3 and " "then in the directory %4 (under systems that support such a directory), but could not find it.") .arg("fet_"+FET_LANGUAGE+".qm") .arg(QDir::toNativeSeparators(qapplication.applicationDirPath())) .arg(QDir::toNativeSeparators(qapplication.applicationDirPath()+"/translations")) .arg("/usr/share/fet/translations") ); FET_LANGUAGE="en_US"; */ } if(FET_LANGUAGE=="ar" || FET_LANGUAGE=="he" || FET_LANGUAGE=="fa" || FET_LANGUAGE=="ur" /* and others? */){ LANGUAGE_STYLE_RIGHT_TO_LEFT=true; } else{ LANGUAGE_STYLE_RIGHT_TO_LEFT=false; } if(FET_LANGUAGE=="zh_CN"){ LANGUAGE_FOR_HTML="zh-Hans"; } else if(FET_LANGUAGE=="zh_TW"){ LANGUAGE_FOR_HTML="zh-Hant"; } else if(FET_LANGUAGE=="en_US"){ LANGUAGE_FOR_HTML=FET_LANGUAGE.left(2); } else{ LANGUAGE_FOR_HTML=FET_LANGUAGE; LANGUAGE_FOR_HTML.replace(QString("_"), QString("-")); } assert(cntTranslators==0); if(FET_LANGUAGE!="en_US"){ qapplication.installTranslator(&translator); cntTranslators=1; } /* if(LANGUAGE_STYLE_RIGHT_TO_LEFT==true) qapplication.setLayoutDirection(Qt::RightToLeft); */ //retranslate /* QList<QWidget*> tlwl=qapplication.topLevelWidgets(); foreach(QWidget* wi, tlwl) if(wi->isVisible()){ FetMainForm* mainform=qobject_cast<FetMainForm*>(wi); if(mainform!=NULL){ mainform->retranslateUi(mainform); continue; } //help HelpAboutForm* aboutf=qobject_cast<HelpAboutForm*>(wi); if(aboutf!=NULL){ aboutf->retranslateUi(aboutf); continue; } HelpFaqForm* faqf=qobject_cast<HelpFaqForm*>(wi); if(faqf!=NULL){ faqf->retranslateUi(faqf); faqf->setText(); continue; } HelpTipsForm* tipsf=qobject_cast<HelpTipsForm*>(wi); if(tipsf!=NULL){ tipsf->retranslateUi(tipsf); tipsf->setText(); continue; } HelpInstructionsForm* instrf=qobject_cast<HelpInstructionsForm*>(wi); if(instrf!=NULL){ instrf->retranslateUi(instrf); instrf->setText(); continue; } ////// //timetable TimetableViewStudentsForm* vsf=qobject_cast<TimetableViewStudentsForm*>(wi); if(vsf!=NULL){ vsf->retranslateUi(vsf); vsf->updateStudentsTimetableTable(); continue; } TimetableViewTeachersForm* vtchf=qobject_cast<TimetableViewTeachersForm*>(wi); if(vtchf!=NULL){ vtchf->retranslateUi(vtchf); vtchf->updateTeachersTimetableTable(); continue; } TimetableViewRoomsForm* vrf=qobject_cast<TimetableViewRoomsForm*>(wi); if(vrf!=NULL){ vrf->retranslateUi(vrf); vrf->updateRoomsTimetableTable(); continue; } TimetableShowConflictsForm* scf=qobject_cast<TimetableShowConflictsForm*>(wi); if(scf!=NULL){ scf->retranslateUi(scf); continue; } } */ }
int main(int argc, char *argv[]) { #ifdef WITH_IMAGEMAGICK Magick::InitializeMagick(*argv); #endif QCoreApplication *a = (argc == 1) ? new QApplication(argc, argv) : new QCoreApplication(argc, argv); if(a) { /* we need nice getDataHome */ #if defined(Q_OS_WIN32) || defined(Q_OS_WIN64) QCoreApplication::setApplicationName("luckygps"); QCoreApplication::setOrganizationName("."); #endif QLocale locale = QLocale::system(); QString locale_name = locale.name(); QTranslator translator; /* Detect if luckyGPS is executed in "local mode" (no installation) */ int local = 0; QDir dir(QCoreApplication::applicationDirPath()); QFileInfoList fileList = dir.entryInfoList(QStringList("luckygps_*.qm"), QDir::AllEntries | QDir::NoDot | QDir::NoDotDot); if(fileList.length() > 0) local = 1; #if defined(Q_OS_LINUX) translator.load(QString("luckygps_") + locale_name, "/usr/share/luckygps"); #else translator.load(QString("luckygps_") + locale_name, getDataHome(local)); #endif a->installTranslator(&translator); setlocale(LC_NUMERIC, "C"); if(argc == 1) { MainWindow w(0, local); w.show(); a->exec(); } #ifdef WITH_ROUTING else { /* check if 1 argument is given */ if(argc > 3) { printf("\nUsage: luckygps FILE.osm.pbf [SETTINGS.spp]\n"); } else { QString settingsFile; if(argc == 2) settingsFile = ":/data/motorcar.spp"; else settingsFile = QString(argv[2]); /* import osm file into routing database */ if(importOsmPbf(a, argv[1], settingsFile, local)) qWarning() << "Import successfully."; else qWarning() << "Import failed."; } } #endif delete a; } return true; }
int main(int argc, char **argv) { QApplication app(argc, argv, true); QTranslator custranldr; QTranslator translator; QString tnapplang; QString tnappcoun; QString clangcode = ""; QStringList allappargs = app.arguments(); QList<QPair<QString, QString> > oppairs; for (QList<QString>::const_iterator i = allappargs.constBegin(); i < allappargs.constEnd(); ++i) { if (i->count('=') == 1) oppairs.append(QPair<QString, QString>(i->section('=', 0, 0).simplified(), i->section('=',1, 1).simplified())); } for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i) { if (i->first.contains("lang", Qt::CaseInsensitive)) { clangcode = i->second; tnapplang = clangcode.left(2); if (clangcode.contains('_') && clangcode.size() == 5) { tnappcoun = clangcode.section('_', -1, -1); } break; } } if (clangcode.isEmpty()) { clangcode = QLocale::system().name(); tnapplang = clangcode.left(2); if (clangcode.contains('_') && clangcode.size() == 5) { tnappcoun = clangcode.section('_', -1, -1); } } QDir applocdir(app.applicationDirPath()); QStringList applocfiles = applocdir.entryList(QStringList() << "*.qm", QDir::Files); if (!applocfiles.isEmpty()) { QString custqmfilepath = applocfiles.at(0); if (!applocfiles.filter("unetbootin").isEmpty()) { custqmfilepath = applocfiles.filter("unetbootin").at(0); if (!applocfiles.filter("unetbootin").filter(tnapplang).isEmpty()) { custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).at(0); if (!tnappcoun.isEmpty() && !applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).isEmpty()) custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).at(0); } } if (custranldr.load(custqmfilepath, app.applicationDirPath())) app.installTranslator(&custranldr); } if (!tnappcoun.isEmpty() && QFile::exists(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun)) && translator.load(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (!tnappcoun.isEmpty() && QFile::exists(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (!tnappcoun.isEmpty() && QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (QFile::exists(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang)) && translator.load(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang))) { app.installTranslator(&translator); } else if (QFile::exists(QString(":/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString(":/unetbootin_%1.qm").arg(tnapplang))) { app.installTranslator(&translator); } else if (QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang))) { app.installTranslator(&translator); } else { tnapplang = "en"; tnappcoun = "US"; clangcode = "en_US"; } app.installTranslator(&translator); if (QObject::tr("LeftToRight") == "RightToLeft") app.setLayoutDirection(Qt::RightToLeft); #ifdef Q_OS_UNIX bool disabledrootcheck = false; for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i) { if (i->first.contains("rootcheck", Qt::CaseInsensitive)) { if (i->second.contains('n', Qt::CaseInsensitive)) disabledrootcheck = true; break; } } if (!disabledrootcheck) { QProcess whoamip; whoamip.start("whoami"); whoamip.waitForFinished(); if (QString(whoamip.readAll()).remove("\r").remove("\n") != "root") { QString argsconc = ""; QString argsconcSingleQuote = ""; for (int i = 1; i < allappargs.size(); ++i) { argsconc += QString("\"%1\" ").arg(allappargs.at(i)); argsconcSingleQuote += QString("'%1' ").arg(allappargs.at(i)); } argsconc += "\"rootcheck=no\""; argsconcSingleQuote += "'rootcheck=no'"; #ifdef Q_OS_LINUX QString gksuarg1; gksuarg1 += QString("bash -c 'QT_X11_NO_MITSHM=1 "); gksuarg1 += QString("%1 %2").arg(app.applicationFilePath()).arg(argsconc); gksuarg1 += QString("'"); QStringList gksuargs; gksuargs.append(gksuarg1); QString gksulocation = checkforgraphicalsu("gksu"); if (gksulocation != "REQCNOTFOUND") { //QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc)); QProcess::startDetached(gksulocation, gksuargs); return 0; } QString kdesulocation = checkforgraphicalsu("kdesu"); if (kdesulocation != "REQCNOTFOUND") { //QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc)); QProcess::startDetached(kdesulocation, gksuargs); return 0; } QString gnomesulocation = checkforgraphicalsu("gnomesu"); if (gnomesulocation != "REQCNOTFOUND") { //QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc)); QProcess::startDetached(gnomesulocation, gksuargs); return 0; } QString kdesudolocation = checkforgraphicalsu("kdesudo"); if (kdesudolocation != "REQCNOTFOUND") { //QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc)); QProcess::startDetached(kdesudolocation, gksuargs); return 0; } QMessageBox rootmsgb; rootmsgb.setIcon(QMessageBox::Warning); rootmsgb.setWindowTitle(uninstaller::tr("Must run as root")); rootmsgb.setTextFormat(Qt::RichText); rootmsgb.setText(uninstaller::tr("%2 must be run as root. Run it from the command line using:<br/><b>sudo QT_X11_NO_MITSHM=1 %1</b><br/>").arg(app.applicationFilePath()).arg(UNETBOOTINB)); rootmsgb.setStandardButtons(QMessageBox::Ok); switch (rootmsgb.exec()) { case QMessageBox::Ok: break; default: break; } return 0; /* QString pkexeclocation = checkforgraphicalsu("pkexec"); if (pkexeclocation != "REQCNOTFOUND" && app.applicationFilePath() == "/usr/bin/unetbootin" && QFile::exists("/usr/share/polkit-1/actions/org.unetbootin.pkexec.unetbootin.policy")) { QProcess::startDetached(QString("%1 %2").arg(pkexeclocation).arg(app.applicationFilePath())); //QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc)); //QProcess::startDetached(QString("%1 %2 %3").arg(pkexeclocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } */ #endif #ifdef Q_OS_MAC /* QProcess osascriptProc; osascriptProc.start("osascript"); osascriptProc.write(QString("do shell script \""+app.applicationFilePath()+"\" with administrator privileges\n").toAscii().data()); osascriptProc.closeWriteChannel(); osascriptProc.waitForFinished(-1); */ //qDebug() << QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc); //QProcess::startDetached(QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc)); QProcess::startDetached("osascript", QStringList() << "-e" << QString("do shell script \"'%1' %2\" with administrator privileges").arg(app.applicationFilePath()).arg(argsconcSingleQuote)); return 0; #endif } } #endif #ifdef Q_OS_WIN32 QSettings chkinst("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\UNetbootin", QSettings::NativeFormat); #endif #ifdef Q_OS_LINUX QSettings chkinst(QSettings::SystemScope, "UNetbootin"); #endif #ifndef Q_OS_MAC if (chkinst.contains("Location")) { QMessageBox uninstmsgb; uninstmsgb.setIcon(QMessageBox::Information); uninstmsgb.setWindowTitle(uninstaller::tr("%1 Uninstaller").arg(UNETBOOTINB)); uninstmsgb.setText(uninstaller::tr("%1 is currently installed. Remove the existing version?").arg(UNETBOOTINB)); uninstmsgb.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); switch (uninstmsgb.exec()) { case QMessageBox::Ok: { ubnUninst(); } case QMessageBox::Cancel: break; default: break; } return 0; } #endif unetbootin unetbootin; unetbootin.appNlang = tnapplang; unetbootin.appDir = QDir::toNativeSeparators(QString("%1/").arg(app.applicationDirPath())); unetbootin.appLoc = app.applicationFilePath(); QIcon icon; icon.addFile(":/unetbootin_16.png", QSize(16,16)); icon.addFile(":/unetbootin_22.png", QSize(22,22)); icon.addFile(":/unetbootin_24.png", QSize(24,24)); icon.addFile(":/unetbootin_32.png", QSize(32,32)); icon.addFile(":/unetbootin_48.png", QSize(48,48)); #ifdef Q_OS_LINUX icon.addFile("/usr/share/pixmaps/unetbootin.png"); icon.addFile("/usr/share/pixmaps/unetbootin.xpm"); #endif unetbootin.setWindowIcon(icon); QObject::connect(&app, SIGNAL(lastWindowClosed()), &unetbootin, SLOT(killApplication())); bool automate = unetbootin.ubninitialize(oppairs); unetbootin.show(); if (automate) QTimer::singleShot(0, &unetbootin, SLOT(on_okbutton_clicked())); return app.exec(); }
int main(int argc, char **argv) { int do_help = 0; LOG_LEVEL verbosity = LOG_DEFAULT; QString config_path = ""; QApplication app(argc, argv); #ifndef Q_OS_MACX /* Don't override the higher quality OS X .icns file */ app.setWindowIcon(QIcon(":/resources/icons/128x128/qtscrob.png")); #endif app.setApplicationName("QTScrobbler"); QTranslator translator; if (QFile::exists(":/language.qm")) { translator.load(":/language"); app.installTranslator(&translator); } QTextStream out(stdout); while (1) { static struct option long_options[] = { {"help", no_argument, &do_help, 1}, {"config", required_argument, 0, 'c'}, {"verbose", required_argument, 0, 'v'}, {0, 0, 0, 0} }; int option_index = 0; int c = getopt_long(argc, argv, "c:hv:", long_options, &option_index); if (c == -1) break; switch (c) { case 0: //long option break; case 'c': config_path = optarg; break; case 'h': do_help = 1; break; case 'v': verbosity = (LOG_LEVEL)QString(optarg).toInt(); break; case '?': break; default: abort (); } } if (optind < argc) { out << "Unknown option argument:"; while (optind < argc) out << " " << argv[optind++]; out << endl; exit(1); } if (do_help) { printusage(); exit(0); } QTScrob mainWin; if (!config_path.isEmpty()) mainWin.scrob->conf->set_custom_location(config_path); mainWin.scrob->set_log_level(verbosity); mainWin.setupWindow(); mainWin.show(); return app.exec(); }
// // By default will open last athlete, but will also provide // a dialog to select an athlete if not found, and then upgrade // the athlete one selected before opening a mainwindow // // It will also respawn mainwindows when restarting for changes // to application settings (athlete folder, language) // // Also creates singleton instances prior to application launching // int main(int argc, char *argv[]) { int ret=2; // return code from qapplication, default to error // // PROCESS COMMAND LINE SWITCHES // // snaffle arguments into a stringlist we can play with into sargs // and only keep non-switch args in the args string list QStringList sargs, args; for (int i=0; i<argc; i++) sargs << argv[i]; #ifdef GC_DEBUG bool debug = true; #else bool debug = false; #endif bool server = false; nogui = false; bool help = false; // honour command line switches foreach (QString arg, sargs) { // help or version requested if (arg == "--help" || arg == "--version") { help = true; fprintf(stderr, "GoldenCheetah %s (%d)\nusage: GoldenCheetah [[directory] athlete]\n\n", VERSION_STRING, VERSION_LATEST); fprintf(stderr, "--help or --version to print this message and exit\n"); #ifdef GC_WANT_HTTP fprintf(stderr, "--server to run as an API server\n"); #endif #ifdef GC_DEBUG fprintf(stderr, "--debug to turn on redirection of messages to goldencheetah.log [debug build]\n"); #else fprintf(stderr, "--debug to direct diagnostic messages to the terminal instead of goldencheetah.log\n"); #endif #ifdef GC_HAS_CLOUD_DB fprintf(stderr, "--clouddbcurator to add CloudDB curator specific functions to the menus\n"); #endif fprintf (stderr, "\nSpecify the folder and/or athlete to open on startup\n"); fprintf(stderr, "If no parameters are passed it will reopen the last athlete.\n\n"); } else if (arg == "--server") { #ifdef GC_WANT_HTTP nogui = server = true; #else fprintf(stderr, "HTTP support not compiled in, exiting.\n"); exit(1); #endif } else if (arg == "--debug") { #ifdef GC_DEBUG // debug, so don't redirect stderr! debug = false; #else debug = true; #endif } else if (arg == "--clouddbcurator") { #ifdef GC_HAS_CLOUD_DB CloudDBCommon::addCuratorFeatures = true; #else fprintf(stderr, "CloudDB support not compiled in, exiting.\n"); exit(1); #endif } else { // not switches ! args << arg; } } // help or version printed so just exit now if (help) { exit(0); } // // INITIALISE ONE TIME OBJECTS // #ifdef GC_WANT_HTTP listener = NULL; #endif #ifdef Q_OS_X11 XInitThreads(); #endif #ifdef Q_OS_MACX if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) { // fix Mac OS X 10.9 (mavericks) font issue // https://bugreports.qt-project.org/browse/QTBUG-32789 QFont::insertSubstitution("LucidaGrande", "Lucida Grande"); } #endif #ifdef GC_WANT_R // create the singleton in the main thread // will be shared by all athletes and all charts (!!) rtool = new RTool(argc,argv); #endif // create the application -- only ever ONE regardless of restarts application = new QApplication(argc, argv); //XXXIdleEventFilter idleFilter; //XXXapplication->installEventFilter(&idleFilter); #ifdef Q_OS_MAC // get an autorelease pool setup static CocoaInitializer cocoaInitializer; #endif // set default colors GCColor::setupColors(); appsettings->migrateQSettingsSystem(); // colors must be setup before migration can take place, but reading has to be from the migrated ones GCColor::readConfig(); // set defaultfont QFont font; font.fromString(appsettings->value(NULL, GC_FONT_DEFAULT, QFont().toString()).toString()); font.setPointSize(appsettings->value(NULL, GC_FONT_DEFAULT_SIZE, 10).toInt()); application->setFont(font); // set default font // // OPEN FIRST MAINWINDOW // do { // lets not restart endlessly restarting = false; //this is the path within the current directory where GC will look for //files to allow USB stick support QString localLibraryPath="Library/GoldenCheetah"; //this is the path that used to be used for all platforms //now different platforms will use their own path //this path is checked first to make things easier for long-time users QString oldLibraryPath=QDir::home().canonicalPath()+"/Library/GoldenCheetah"; //these are the new platform-dependent library paths #if defined(Q_OS_MACX) QString libraryPath="Library/GoldenCheetah"; #elif defined(Q_OS_WIN) #if QT_VERSION > 0x050000 // windows and qt5 QStringList paths=QStandardPaths::standardLocations(QStandardPaths::DataLocation); QString libraryPath = paths.at(0); #else // windows not qt5 QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/GoldenCheetah"; #endif // qt5 #else // not windows or osx (must be Linux or OpenBSD) // Q_OS_LINUX et al QString libraryPath=".goldencheetah"; #endif // // or did we override in settings? QString sh; if ((sh=appsettings->value(NULL, GC_HOMEDIR, "").toString()) != QString("")) localLibraryPath = sh; // lets try the local library we've worked out... QDir home = QDir(); if(QDir(localLibraryPath).exists() || home.exists(localLibraryPath)) { home.cd(localLibraryPath); } else { // YIKES !! The directory we should be using doesn't exist! home = QDir::home(); if (home.exists(oldLibraryPath)) { // there is an old style path, lets fo there home.cd(oldLibraryPath); } else { if (!home.exists(libraryPath)) { if (!home.mkpath(libraryPath)) { // tell user why we aborted ! QMessageBox::critical(NULL, "Exiting", QString("Cannot create library directory (%1)").arg(libraryPath)); exit(0); } } home.cd(libraryPath); } } // set global root directory gcroot = home.canonicalPath(); appsettings->initializeQSettingsGlobal(gcroot); // now redirect stderr #ifndef WIN32 if (!debug) nostderr(home.canonicalPath()); #else Q_UNUSED(debug) #endif // install QT Translator to enable QT Dialogs translation // we may have restarted JUST to get this! QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); application->installTranslator(&qtTranslator); // Language setting (default to system locale) QVariant lang = appsettings->value(NULL, GC_LANG, QLocale::system().name()); // Load specific translation, try from GCROOT otherwise from binary QTranslator gcTranslator; QString translation_file = "/gc_" + lang.toString() + ".qm"; if (gcTranslator.load(gcroot + translation_file)) qDebug() << "Loaded translation from"+gcroot+translation_file; else gcTranslator.load(":translations" + translation_file); application->installTranslator(&gcTranslator); // Initialize metrics once the translator is installed RideMetricFactory::instance().initialize(); // Initialize global registry once the translator is installed GcWindowRegistry::initialize(); // initialise the trainDB trainDB = new TrainDB(home); #ifdef GC_WANT_R (*(rtool->R))["GC.home"] = home.absolutePath().toStdString(); #endif // lets do what the command line says ... QVariant lastOpened; if(args.count() == 2) { // $ ./GoldenCheetah Mark -or- ./GoldenCheetah --server ~/athletedir // athlete if (!server) lastOpened = args.at(1); else home.cd(args.at(1)); } else if (args.count() == 3) { // $ ./GoldenCheetah ~/Athletes Mark // first parameter is a folder that exists? if (QFileInfo(args.at(1)).isDir()) { home.cd(args.at(1)); } // folder and athlete lastOpened = args.at(2); } else { // no parameters passed lets open the last athlete we worked with lastOpened = appsettings->value(NULL, GC_SETTINGS_LAST); // does lastopened Directory exists at all QDir lastOpenedDir(gcroot+"/"+lastOpened.toString()); if (lastOpenedDir.exists()) { // but hang on, did they crash? if so we need to open with a menu appsettings->initializeQSettingsAthlete(gcroot, lastOpened.toString()); if(appsettings->cvalue(lastOpened.toString(), GC_SAFEEXIT, true).toBool() != true) lastOpened = QVariant(); } else { lastOpened = QVariant(); } } #ifdef GC_WANT_HTTP // The API server offers webservices (default port 12021, see httpserver.ini) // This is to enable integration with R and similar if (appsettings->value(NULL, GC_START_HTTP, true).toBool() || server) { // notifications etc if (nogui) { qDebug()<<"Starting GoldenCheetah API web-services... (hit ^C to close)"; qDebug()<<"Athlete directory:"<<home.absolutePath(); } else { // switch off warnings if in gui mode #ifndef GC_WANT_ALLDEBUG #if QT_VERSION > 0x50000 qInstallMessageHandler(myMessageOutput); #else qInstallMsgHandler(myMessageOutput); #endif #endif } QString httpini = home.absolutePath() + "/httpserver.ini"; if (!QFile(httpini).exists()) { // read default ini file QFile file(":webservice/httpserver.ini"); QString content; if (file.open(QIODevice::ReadOnly)) { content = file.readAll(); file.close(); } // write default ini file QFile out(httpini); if (out.open(QIODevice::WriteOnly)) { out.resize(0); QTextStream stream(&out); stream << content; out.close(); } } // use the default handler (just get an error page) QSettings* settings=new QSettings(httpini,QSettings::IniFormat,application); if (listener) { // when changing the Athlete Directory, there is already a listener running // close first to avoid errors listener->close(); } listener=new HttpListener(settings,new APIWebService(home, application),application); // if not going on to launch a gui... if (nogui) { // catch ^C exit signal(SIGINT, sigabort); ret = application->exec(); // stop web server if running qDebug()<<"Stopping GoldenCheetah API web-services..."; listener->close(); // and done terminate(0); } } #endif // lets attempt to open as asked/remembered bool anyOpened = false; if (lastOpened != QVariant()) { QStringList list = lastOpened.toStringList(); QStringListIterator i(list); while (i.hasNext()) { QString cyclist = i.next(); QString homeDir = home.canonicalPath(); if (home.cd(cyclist)) { appsettings->initializeQSettingsAthlete(homeDir, cyclist); GcUpgrade v3; if (v3.upgradeConfirmedByUser(home)) { MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); mainWindow->ridesAutoImport(); gc_opened++; home.cdUp(); anyOpened = true; } else { delete trainDB; terminate(0); } } } } // ack, didn't manage to open an athlete // and the upgradeWarning was // lets ask the user which / create a new one if (!anyOpened) { ChooseCyclistDialog d(home, true); d.setModal(true); // choose cancel? if ((ret=d.exec()) != QDialog::Accepted) { delete trainDB; terminate(0); } // chosen, so lets get the choice.. QString homeDir = home.canonicalPath(); home.cd(d.choice()); if (!home.exists()) { delete trainDB; terminate(0); } appsettings->initializeQSettingsAthlete(homeDir, d.choice()); // .. and open a mainwindow GcUpgrade v3; if (v3.upgradeConfirmedByUser(home)) { MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); mainWindow->ridesAutoImport(); gc_opened++; } else { delete trainDB; terminate(0); } } ret=application->exec(); // close trainDB delete trainDB; // reset QSettings (global & Athlete) appsettings->clearGlobalAndAthletes(); #ifndef NOWEBKIT // clear web caches (stop warning of WebKit leaks) QWebSettings::clearMemoryCaches(); #endif } while (restarting); return ret; }
int main(int argc, char *argv[]) { // Под Windows устанавливаем кодировку cp1251 #ifdef Q_WS_WIN QTextCodec *codec = QTextCodec::codecForName("Windows-1251"); // Под остальными ОС - utf8 #else QTextCodec *codec = QTextCodec::codecForName("UTF-8"); #endif QString param; QString org_file_name; org_file_name = "org_name.conf"; for (int i = 0; i<argc; i++) { param = codec->toUnicode(argv[i]); if (check_extention(param, ".conf")) { //ключ c - передается файл с названием организации org_file_name = param; } } bool get_name = false; QString org_name = "IP_Volkov"; QString app_name = "CenGen"; QFile *file = new QFile(org_file_name); if (!file->exists()) get_name = true; file->open(QFile::ReadOnly); if (!file->isOpen()) get_name = true; if (get_name) { //открываем диалоговое окно, вводим название организации //сохраняем полученный результат в файл file->open(QFile::WriteOnly); QTextStream out(file); out << "org_name = " + org_name + "\n"; out << "app_name = " + app_name + "\n"; } else { //читаем название организации из файла QString name; QByteArray line; while (!file->atEnd()) { line = file->readLine(); if (line.at(0) != '#') { if (line.contains("org_name")) { name = line; if (name.split("=").count()>1) { name = name.split("=").at(1).trimmed(); org_name = name; } } if (line.contains("app_name")) { name = line; if (name.split("=").count()>1) { name = name.split("=").at(1).trimmed(); app_name = name; } } } } } file->close(); //qDebug() << "Org name " << org_name; //устанавливаем название организации QCoreApplication::setOrganizationName(org_name); QCoreApplication::setApplicationName(app_name); QFileInfo *fi = new QFileInfo; fi->setFile(org_file_name); QString path = fi->absolutePath(); QApplication a(argc, argv); QTranslator myTranslator; myTranslator.load("cengen_ru.qm", path); a.installTranslator(&myTranslator); cengen w; w.set_org_name(org_name, app_name); for (int i = 0; i<argc; i++) { param = codec->toUnicode(argv[i]); if (check_extention(param, ".tov")) { w.open_tovar_list(param); } if (check_extention(param, ".fli")) { w.turn_filter_ON(); w.load_filter_settings_file(param); } if (check_extention(param, ".das")) { w.load_source_settings_file(param); } if (check_extention(param, ".dbf")) { qDebug() << "Trying to load dbf file"; w.save_source_settings_file("_$tmp.das"); bool good = w.set_source_from_dbf(param); if (good) w.load_all_records(); w.load_source_settings_file("_$tmp.das"); w.repaint(); } if (check_extention(param, "frf")) { w.set_ext_shablon_name(param); } if (check_extention(param, "csf")) { QLabel *lbl = new QLabel("Please wait! Executing scenarium file"); lbl->show(); lbl->repaint(); w.execute_macro_file(param); lbl->hide(); } } w.show(); return a.exec(); }
/*! * \brief 该函数最初是在子线程中完成的,但是由于在子线程中完成创建对象的任务后,还需要将该对象moveToThread到 * 主线,给很多操作带来不小的麻烦,所以这里还是在主线程中完成的。 * \param[] receiver 用来传输数据 * \return 返回0表示成功 */ int loadPluginThread(MainApp *receiver) { QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, QCoreApplication::applicationDirPath() + QLatin1String(SHARE_PATH)); QSettings::setDefaultFormat(QSettings::IniFormat); QSettings *settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, QLatin1String(Core::Constants::TOTEM_SETTINGSVARIANT_STR), QLatin1String("Totem")); QSettings *globalSettings = new QSettings(QSettings::IniFormat, QSettings::SystemScope, QLatin1String(Core::Constants::TOTEM_SETTINGSVARIANT_STR), QLatin1String("Totem")); ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); pm->setFileExtension(QLatin1String(PLUGINSPEC_FILE_EXTENTION)); pm->setGlobalSettings(globalSettings); pm->setSettings(settings); QTranslator translator; QTranslator qtTranslator; QStringList uiLanguages; #if (QT_VERSION >= 0x040801) || (QT_VERSION >= 0x040800 && !defined(Q_OS_WIN)) uiLanguages = QLocale::system().uiLanguages(); #else uiLanguages << QLocale::system().name(); #endif // QString overrideLanguage = settings->value("General/OverrideLanguage").toString(); // if (!overrideLanguage.isEmpty()) // uiLanguages.prepend(overrideLanguage); const QString &totemTrPath = QCoreApplication::applicationDirPath() + QLatin1String(SHARE_PATH "/translations"); foreach (const QString &locale, uiLanguages) { if (translator.load(QLatin1String("totem_") + locale, totemTrPath)) { const QString &qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath); const QString &qtTrFile = QLatin1String("qt_") + locale; if (qtTranslator.load(qtTrFile, qtTrPath) || qtTranslator.load(qtTrFile, totemTrPath)) { receiver->app.installTranslator(&translator); receiver->app.installTranslator(&qtTranslator); receiver->app.setProperty("qtc_locale", locale); break; } translator.load(QString()); // unload() } else if (locale == QLatin1String("C") /* overrideLanguage == "English" */) { break; } else if (locale.startsWith(QLatin1String("en")) /* "English" is built-in */) { break; } } //这里没有考虑MacOS,Unix QNetworkProxyFactory::setUseSystemConfiguration(true); //设置插件搜索路径 const QStringList pluginPaths = getPluginPaths(); pm->setPluginPaths(pluginPaths); //检查核心插件 const PluginSpecSet plugins = pm->plugins(); ExtensionSystem::PluginSpec *coreplugin = 0; foreach(ExtensionSystem::PluginSpec *spec, plugins) { if(spec->name() == QLatin1String(corePluginNameC)) { coreplugin = spec; break; } } int status; if( status = checkPlugin(coreplugin, QLatin1String(corePluginNameC)))//如果核心插件检查有问题 { return status; } //载入皮肤 receiver->loadSkin(defaultQssFileC); QList<ExtensionSystem::PluginSpec *> queue = pm->loadQueue(); receiver->m_futureInterface->setProgressRange(0, queue.size()); QMetaObject::invokeMethod(receiver, "onStart", Qt::QueuedConnection); receiver->m_futureInterface->reportStarted(); foreach(ExtensionSystem::PluginSpec *spec, queue) { pm->loadPlugin(spec,ExtensionSystem::PluginSpec::Loaded); receiver->m_futureInterface->setProgressValue( receiver->m_futureInterface->progressValue() + 1); }
int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("SRFGames"); QCoreApplication::setOrganizationDomain("sol-online.org"), QCoreApplication::setApplicationName("TrackYourTime"); #ifdef Q_OS_MAC QDir dir(argv[0]); dir.cdUp(); QString currentDir = dir.absolutePath(); dir.cdUp(); dir.cd("PlugIns"); QCoreApplication::setLibraryPaths(QStringList(dir.absolutePath())); #endif QApplication a(argc, argv); QApplication::setQuitOnLastWindowClosed(false); #ifdef Q_OS_MAC QDir::setCurrent(currentDir); #endif QSettings settings; QString Language = QLocale::system().name(); Language.truncate(Language.lastIndexOf('_')); Language = settings.value(cDataManager::CONF_LANGUAGE_ID,Language).toString(); if (settings.value(cDataManager::CONF_FIRST_LAUNCH_ID,true).toBool()){ settings.setValue(cDataManager::CONF_FIRST_LAUNCH_ID,false); settings.setValue(cDataManager::CONF_LANGUAGE_ID,Language); settings.setValue(cDataManager::CONF_AUTORUN_ID,true); setAutorun(); settings.sync(); } QTranslator translator; translator.load("lang_" + Language,QDir::currentPath()+"/data/languages"); QApplication::installTranslator(&translator); cDataManager datamanager; cTrayIcon trIcon(&datamanager); QObject::connect(&datamanager, SIGNAL(trayActive()), &trIcon, SLOT(setActive())); QObject::connect(&datamanager, SIGNAL(traySleep()), &trIcon, SLOT(setInactive())); QObject::connect(&datamanager, SIGNAL(trayShowHint(QString)), &trIcon, SLOT(showHint(QString))); QObject::connect(&datamanager, SIGNAL(profilesChanged()), &trIcon, SLOT(onProfilesChange())); ApplicationsWindow applicationsWindow(&datamanager); QObject::connect(&trIcon, SIGNAL(showApplications()), &applicationsWindow, SLOT(show())); QObject::connect(&datamanager, SIGNAL(profilesChanged()), &applicationsWindow, SLOT(onProfilesChange())); QObject::connect(&datamanager, SIGNAL(applicationsChanged()), &applicationsWindow, SLOT(onApplicationsChange())); ProfilesWindow profilesWindow(&datamanager); QObject::connect(&applicationsWindow, SIGNAL(showProfiles()), &profilesWindow, SLOT(show())); App_SettingsWindow app_settingsWindow(&datamanager); QObject::connect(&applicationsWindow, SIGNAL(showAppSettings(int)), &app_settingsWindow, SLOT(showApp(int))); QObject::connect(&datamanager, SIGNAL(debugScriptResult(QString,sSysInfo)), &app_settingsWindow, SLOT(onScriptResult(QString,sSysInfo))); SettingsWindow settingsWindow(&datamanager); QObject::connect(&trIcon, SIGNAL(showSettings()), &settingsWindow, SLOT(show())); QObject::connect(&settingsWindow, SIGNAL(preferencesChange()), &datamanager, SLOT(onPreferencesChanged())); StatisticWindow statisticWindow(&datamanager); QObject::connect(&trIcon, SIGNAL(showStatistic()), &statisticWindow, SLOT(show())); AboutWindow aboutWindow; QObject::connect(&trIcon, SIGNAL(showAbout()), &aboutWindow, SLOT(show())); int result = a.exec(); return result; }
int main(int argc, char *argv[]) { QDir clamDir; QFile dbFile, confFile; QApplication app(argc, argv); QTranslator myappTranslator; QString locale = QLocale::system().name(); QString defaultLanguage = QString(APP_NAME) + "_" + locale + ".qm"; // Falls die Sprache manuell gesetzt wurde. QSettings clamui_conf(QSettings::NativeFormat, QSettings::UserScope, APP_TITLE, APP_NAME); clamui_conf.beginGroup("ClamUI"); bool languageSet = clamui_conf.value("Language_Manually", false).toBool(); QString currLanguage = clamui_conf.value( "languageFileName", defaultLanguage).toString(); bool hideWindow =clamui_conf.value("Hide_Window", false).toBool(); clamui_conf.endGroup(); // Systemsprache aus der Umgebungsvariable des Systems lesen. // Read the system language from the system environment. QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); if (languageSet == false) { // Langauge from system settings myappTranslator.load(LANG_PATH + APP_NAME + "_" + locale + ".qm"); app.installTranslator(&myappTranslator); } else { // Language manually. myappTranslator.load(LANG_PATH + currLanguage); app.installTranslator(&myappTranslator); } /* * Check if there is a ClamAV directory. * In this directory are the config files stored. */ if (!clamDir.exists(CLAMAV_PATH)) clamDir.mkdir(CLAMAV_PATH); /* * The default quarantine folder. */ if (!clamDir.exists(CLAMAV_PATH + "quarantine")) clamDir.mkdir(CLAMAV_PATH + "quarantine"); /* * The directory for the virus definition stored. */ if (!clamDir.exists(CLAMAV_VDB_PATH)) clamDir.mkdir(CLAMAV_VDB_PATH); /* * Check for an existing SQLite3 database. */ if (!dbFile.exists(APP_CONFIG_PATH + SQLITE_DB_NAME)){ SQLite_DB sqliteDB; sqliteDB.connectDB(); } /* * Check for an existing config file. * * If not run the wizard. */ if (!confFile.exists(APP_CONFIG_PATH + APP_NAME + ".conf")){ FirstRunWizard startWizard; startWizard.show(); return app.exec(); } /* * If exists run clamui. */ if (confFile.exists(APP_CONFIG_PATH + APP_NAME + ".conf")){ ClamUI startClamUI; if (hideWindow){ startClamUI.hide(); return app.exec(); } else { startClamUI.show(); return app.exec(); } } } // main end
int main(int argc, char** argv) { QApplication app(argc, argv); app.setApplicationName(CLIENT_FANCY_NAME); app.setApplicationVersion(CLIENT_VERSION); QString locale = QLocale::system().name(); #ifdef Q_OS_WIN32 app.setStyle(QStyleFactory::create("Fusion")); #endif QString settingsFile; QStringList args = app.arguments(); if (args.count() > 1) { QString arg(args[1]); if (arg == "testmarkup") return testMarkup(argc > 2 ? args[2] : ""); else if (arg == "testfeedint") { qDebug() << PumpaSettingsDialog::feedIntToComboIndex(args[2].toInt()); return 0; } else if (arg == "autotestfeedint") { int (*f)(int) = PumpaSettingsDialog::feedIntToComboIndex; (void) f; Q_ASSERT(f(0) == 0); Q_ASSERT(f(1) == 0); Q_ASSERT(f(2) == 1); Q_ASSERT(f(3) == 0); Q_ASSERT(f(4) == 0); Q_ASSERT(f(5) == 0); Q_ASSERT(f(6) == 2); Q_ASSERT(f(11) == 0); Q_ASSERT(f(12) == 0); Q_ASSERT(f(14) == 3); Q_ASSERT(f(15) == 4); Q_ASSERT(f(16) == 0); Q_ASSERT(f(255) == 0); return 0; } else if (arg == "autotestcomboindex") { int (*f)(int) = PumpaSettingsDialog::comboIndexToFeedInt; (void) f; Q_ASSERT(f(0) == 0); Q_ASSERT(f(1) == 2); Q_ASSERT(f(2) == 6); Q_ASSERT(f(3) == 14); Q_ASSERT(f(4) == 15); Q_ASSERT(f(255) == 0); return 0; } else if (arg == "-l" && argc == 3) { locale = args[2]; } else if (arg == "-c" && argc == 3) { settingsFile = args[2]; } else { qDebug() << "Usage: ./pumpa [-c alternative.conf] [-l locale]"; return 0; } } qDebug() << "Using locale" << locale; QTranslator qtTranslator; qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); QTranslator translator; bool ok = translator.load(QString("pumpa_%1").arg(locale), ":/translations"); app.installTranslator(&translator); if (ok) qDebug() << "Successfully loaded translation"; PumpApp papp(settingsFile, locale); return app.exec(); }
int main(int argc, char *argv[]) { // SailfishApp::main() will display "qml/template.qml", if you need more // control over initialization, you can use: // // - SailfishApp::application(int, char *[]) to get the QGuiApplication * // - SailfishApp::createView() to get a new QQuickView * instance // - SailfishApp::pathTo(QString) to get a QUrl to a resource file // QProcess appinfo; QString appversion; // read app version from rpm database on startup appinfo.start("/bin/rpm", QStringList() << "-qa" << "--queryformat" << "%{version}-%{RELEASE}" << "harbour-worldclock"); appinfo.waitForFinished(-1); if (appinfo.bytesAvailable() > 0) { appversion = appinfo.readAll(); } QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QQuickView* view = SailfishApp::createView(); qmlRegisterType<TimeZone>("harbour.worldclock.TimeZone", 1 , 0 , "TZ"); qmlRegisterType<Launcher>("harbour.worldclock.Launcher", 1 , 0 , "App"); qmlRegisterType<Settings>("harbour.worldclock.Settings", 1 , 0 , "MySettings"); qmlRegisterType<settingsPublic::Languages>("harbour.worldclock.Settings", 1, 0, "Languages"); // QString locale_appname = "harbour-worldclock-" + QLocale::system().name(); // qDebug() << "Translations:" << SailfishApp::pathTo("translations").toLocalFile() + "/" + locale_appname + ".qm"; // Check if user has set language explicitly to be used in the app QString locale = QLocale::system().name(); QSettings mySets; int languageNbr = mySets.value("language","0").toInt(); QTranslator translator; if (settingsPublic::Languages::SYSTEM_DEFAULT != languageNbr) { switch (languageNbr) { // Swedish case settingsPublic::Languages::SV: translator.load("harbour-worldclock-sv.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // Dutch case settingsPublic::Languages::NL: translator.load("harbour-worldclock-nl.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // German case settingsPublic::Languages::DE: translator.load("harbour-worldclock-de.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // Russian case settingsPublic::Languages::RU: translator.load("harbour-worldclock-ru.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // Hungarian case settingsPublic::Languages::HU_HU: translator.load("harbour-worldclock-hu_HU.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // Polish case settingsPublic::Languages::PL_PL: translator.load("harbour-worldclock-pl_PL.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // French case settingsPublic::Languages::FR_FR: translator.load("harbour-worldclock-fr_FR.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // Italian case settingsPublic::Languages::IT: translator.load("harbour-worldclock-it.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // Greek case settingsPublic::Languages::EL: translator.load("harbour-worldclock-el.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // Arabic case settingsPublic::Languages::AR: translator.load("harbour-worldclock-ar.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; // English default: translator.load("harbour-worldclock.qm", SailfishApp::pathTo(QString("translations")).toLocalFile()); break; } // install translator for specific language // otherwise the system language will be set by SailfishApp app->installTranslator(&translator); } view->rootContext()->setContextProperty("DebugLocale",QVariant(locale)); view->rootContext()->setContextProperty("version", appversion); view->setSource(SailfishApp::pathTo("qml/worldclock.qml")); view->showFullScreen(); return app->exec(); }
/** * Start point of the program which executes the main window * @param argc Slots of command line parameter * @param argv Values of command line parameter * @return The executing main window */ int main(int argc, char *argv[]) { QApplication a(argc, argv); #ifdef LOGFILE QString fileName = QCoreApplication::applicationFilePath() + ".log"; QFile *log = new QFile(fileName); if (log->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { out = new QTextStream(log); qInstallMessageHandler(messageOutput); } else { qDebug() << "Error opening log file '" << fileName << "'. All debug output redirected to console."; } #endif // Check language QTranslator translator; QString current = QLocale::system().name(); if ( current.contains("de_DE") ) { translator.load("scribo_de", ":/translations"); a.installTranslator(&translator); } // Load splash screen QSplashScreen *splash = new QSplashScreen; splash->setPixmap( QPixmap(":/img/splash.jpg") ); splash->show(); Qt::Alignment topRight = Qt::AlignRight | Qt::AlignTop; splash->setStyleSheet("font-size: 10px;"); splash->showMessage(QObject::tr("Loading modules..."), topRight, Qt::white); QCoreApplication::setApplicationName("Scribo"); QCoreApplication::setApplicationVersion("0.1"); // Create directories QString scriboDir = QDir::home().absolutePath() + QDir::separator() + "scribo"; if ( !QDir(scriboDir).exists() ) QDir().mkdir(scriboDir); splash->showMessage(QObject::tr("Establishing connections..."), topRight, Qt::white); // Create database connection Database db; if ( !db.open() ) { qDebug() << "Failed to open the database.\n" "Please check the database settings"; } else { qDebug() << "Connected to the database"; } splash->showMessage(QObject::tr("Loading..."), topRight, Qt::white); MainWindow w; QTimer::singleShot(3000, splash, SLOT(close())); QTimer::singleShot(3000, &w, SLOT(show())); //w.show(); qDebug() << "Application started..."; return a.exec(); }
Q_DECL_EXPORT int main(int argc, char* argv[]) { //QApplication::setGraphicsSystem("native"); QApplication app(argc, argv); app.setOrganizationDomain("meecast.omweather.com"); app.setApplicationName("MeeCast"); QValueSpace::initValueSpaceServer(); app.setProperty("NoMStyle", true); QDir::setCurrent(app.applicationDirPath()); textdomain("omweather"); bindtextdomain("omweather", "/opt/com.meecast.omweather/share/locale"); /* //Set up a graphics scene with a QGraphicsWidget and Layout QGraphicsView view; QGraphicsScene scene; QGraphicsWidget *widget = new QGraphicsWidget(); QGraphicsGridLayout *layout = new QGraphicsGridLayout; layout->setSpacing(0); widget->setLayout(layout); scene.addItem(widget); view.setScene(&scene); */ //Add the QML snippet into the layout //QString locale = QLocale::system().name(); //std::cerr<<"locale: "<<locale.toStdString()<<std::endl; //ConfigQml *config; Controller *controller; QTranslator translator; translator.load("ru.qml", "i18n"); app.installTranslator(&translator); controller = new Controller(); /* D-BUS */ DbusAdaptor* dadapt = new DbusAdaptor(controller); QDBusConnection connection = QDBusConnection::sessionBus(); connection.registerService("org.meego.omweather"); connection.registerObject("/org/meego/omweather", controller); //config = controller->config(); //std::cerr<<"iconpath = "<<config->imagespath().toStdString() << std::endl; //update_weather_forecast(config); QDeclarativeView *qview; qview = controller->qview(); std::cerr << "qml path = " << Core::AbstractConfig::layoutqml << std::endl; qview->setSource(QUrl::fromLocalFile(QString::fromStdString(Core::AbstractConfig::prefix + Core::AbstractConfig::sharePath + Core::AbstractConfig::layoutqml))); QObject::connect((QObject*)qview->engine(), SIGNAL(quit()), &app, SLOT(quit())); qview->showFullScreen(); /*This code provides Segmantation fault delete dadapt; delete controller; */ return app.exec(); }
//--------------------------------------------------------------------------------------------------------------------- int main(int argc, char *argv[]) { Q_INIT_RESOURCE(cursor); Q_INIT_RESOURCE(icon); Q_INIT_RESOURCE(schema); Q_INIT_RESOURCE(theme); QT_REQUIRE_VERSION(argc, argv, "5.2.1"); VApplication app(argc, argv); #ifdef QT_DEBUG // Because our "noisy" message handler uses the GUI subsystem for message // boxes, we can't install it until after the QApplication is constructed. But it // is good to be the very next thing to run, to start catching warnings ASAP. { qInstallMessageHandler(noisyFailureMsgHandler); } #endif app.setApplicationDisplayName(VER_PRODUCTNAME_STR); app.setApplicationName(VER_INTERNALNAME_STR); app.setOrganizationName(VER_COMPANYNAME_STR); app.setOrganizationDomain(VER_COMPANYDOMAIN_STR); // Setting the Application version app.setApplicationVersion(APP_VERSION); QSettings settings(QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(), QApplication::applicationName()); QString defaultLocale = QLocale::system().name(); // e.g. "de_DE" defaultLocale.truncate(defaultLocale.lastIndexOf('_')); // e.g. "de" QString checkedLocale = settings.value("configuration/locale", defaultLocale).toString(); QTranslator qtTranslator; qtTranslator.load("qt_" + checkedLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); QTranslator appTranslator; appTranslator.load("valentina_" + checkedLocale, qApp->translationsPath()); app.installTranslator(&appTranslator); static const char * GENERIC_ICON_TO_CHECK = "document-open"; if (QIcon::hasThemeIcon(GENERIC_ICON_TO_CHECK) == false) { //If there is no default working icon theme then we should //use an icon theme that we provide via a .qrc file //This case happens under Windows and Mac OS X //This does not happen under GNOME or KDE QIcon::setThemeName("win.icon.theme"); } MainWindow w; w.setWindowState(w.windowState() ^ Qt::WindowMaximized); app.setWindowIcon(QIcon(":/icon/64x64/icon64x64.png")); TableWindow table; QObject::connect(&w, &MainWindow::ModelChosen, &table, &TableWindow::ModelChosen); QObject::connect(&table, &TableWindow::closed, &w, &MainWindow::tableClosed); QCommandLineParser parser; parser.setApplicationDescription(QCoreApplication::translate("main", "Pattern making program.")); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("filename", QCoreApplication::translate("main", "Pattern file.")); parser.process(app); const QStringList args = parser.positionalArguments(); if (args.size() > 0) { w.LoadPattern(args.at(0)); } w.show(); return app.exec(); }