コード例 #1
0
ファイル: main.cpp プロジェクト: geolffrey/ve
int main(int argc, char *argv[])
{
    int dummy = errno;
    QApplication a(argc, argv);
    Debug::init(0);
    //mediaPipeline::init(argc, argv);

	// Set the Application Language
#if 0
	//if (QLocale::system().name() == "zh_CN")
	{
		QTranslator *translator = new QTranslator(&a);
		bool ok = translator->load("vscloudnode_zh.qm",
			QCoreApplication::applicationDirPath() + "/translations");
		
		if (ok)
		{
			qDebug("Translation Files loaded.");
			a.installTranslator(translator);
		}
	}
#endif

    QPixmap pixmap(":/logo/resources/splash.png");
    QSplashScreen *splash = new QSplashScreen(pixmap);
    QFont splashFont;
    //splashFont.setFamily("Arial");
    splashFont.setBold(true);

    splash->setStyleSheet(QStringLiteral("color : red;"));
    splash->setFont(splashFont);
    
    splash->show();

    //QApplication::setStyle(QStyleFactory::create("Fusion"));
	//QApplication::setStyle(QStyleFactory::create("Plastique"));
    //QApplication::setStyle("WindowsVista"); 
#if 0
	QFile f(":qdarkstyle/style.qss");
	if (!f.exists())
	{
		printf("Unable to set stylesheet, file not found\n");
	}
	else 
	{
		f.open(QFile::ReadOnly | QFile::Text);
		QTextStream ts(&f);
		a.setStyleSheet(ts.readAll());
	}
#endif


    gFactory = new Factory;
    splash->showMessage("Starting ...");

   if (gFactory->Init() == FALSE)
   {
#ifdef WIN32
       astring strPath = "C:\\";//TODO get the hdd from hdd
       VSCHddDevice hdd;
       hdd.show();
       hdd.exec();
       s32 size = hdd.GetDiskSize();
       hdd.GetDiskPath(strPath);
#else

	astring strPath = "ve/";//TODO get the hdd from hdd
	s32 size = 2;
#endif
       gFactory->SetSystemPath(strPath);
       splash->showMessage("Create Video Database ...");
       gFactory->Init();
#ifndef WIN32
	//gFactory->AddHDD(strPath, size);
#endif
   }

   VEvent::Init(*gFactory);
   VServiceMgr *pServiceMgr = VServiceMgr::CreateObject(*gFactory);

    VSCMainWindows w;
    //w.setWindowIcon(QIcon(":/logo/resources/vscsmall.jpg"));
    //w.show();
    //Sleep(1000);
    //w.setWindowFlags(Qt::FramelessWindowHint );
    //w.setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::CustomizeWindowHint );
    w.showMaximized();
    //w.showFullScreen();
    splash->finish(&w);

	//stacked s;
	//s.show();

    delete splash;
    /* Every thread is ready, start the factory thread */
    gFactory->start();
    return a.exec();
}
コード例 #2
0
ファイル: udav_wnd.cpp プロジェクト: svn2github/MathGL
//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
	QString lang="";
	QSettings settings("udav","UDAV");
	settings.setPath(QSettings::IniFormat, QSettings::UserScope, "UDAV");
	settings.beginGroup("/UDAV");
	pathHelp = settings.value("/helpPath", MGL_DOC_DIR).toString();
	pathFont = settings.value("/userFont", "").toString();
	lang = settings.value("/udavLang", "").toString();
	
	const char *loc="";
	if(lang=="en")	loc = "C.UTF8";
#if WIN32
	if(lang=="ru")	loc = "ru_RU.cp1251";
#else
	if(lang=="ru")	loc = "ru_RU.utf8";
#endif
	if(lang=="es")	{	loc = "es_ES.utf8";	lang="en";	}	// TODO remove lang="en"; then Spanish translation is ready !
	mgl_textdomain(argv?argv[0]:NULL,loc);
	
	bool showHint = settings.value("/showHint", true).toBool();
	mglCompleter = settings.value("/completer",  true).toBool();
	settings.endGroup();

	mgl_suppress_warn(true);
	QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
#ifdef WIN32
	QCoreApplication::addLibraryPath("c:/plugins/");
	QCoreApplication::addLibraryPath(QFileInfo(QString::fromLocal8Bit(argv[0])).absolutePath().append("/plugins/"));
#endif
	mgl_ask_func = mgl_ask_qt;
	QApplication a(argc, argv);
	QTranslator translator;
//QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
#if defined(WIN32)
	if(pathHelp.isEmpty())	pathHelp = a.applicationDirPath()+"\\";
#else
	if(pathHelp.isEmpty())	pathHelp=MGL_DOC_DIR;
#endif

	if(!lang.isEmpty())
	{
		if(!translator.load("udav_"+lang, UDAV_DIR))
			translator.load("udav_"+lang, pathHelp);
		a.installTranslator(&translator);
	}

	udavLoadDefCommands();
	parser.AllowSetSize(true);
	MainWindow *mw = new MainWindow();
	if(argc>1)
	{
		QTextCodec *codec = QTextCodec::codecForLocale();
		mw->load(codec->toUnicode(argv[1]), true);
	}
	mw->show();
	mw->edit->edit->setFocus();
	a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
	if(showHint)	udavShowHint(mw);
	return a.exec();
}
コード例 #3
0
/* \brief To set the current language
\param newLanguage Should be short name code found into informations.xml of language file */
void LanguagesManager::setCurrentLanguage(const QString &newLanguage)
{
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"start: "+newLanguage);
    //protection for re-set the same language
    if(currentLanguage==newLanguage)
        return;
    //store the language
    PluginsManager::pluginsManager->setLanguage(newLanguage);
    //unload the old language
    if(currentLanguage!="en")
    {
        int indexTranslator=0;
        while(indexTranslator<installedTranslator.size())
        {
            QCoreApplication::removeTranslator(installedTranslator[indexTranslator]);
            delete installedTranslator[indexTranslator];
            indexTranslator++;
        }
        installedTranslator.clear();
    }
    int index=0;
    while(index<LanguagesAvailableList.size())
    {
        if(LanguagesAvailableList.at(index).mainShortName==newLanguage)
        {
            //load the new language
            if(newLanguage!="en")
            {
                QTranslator *temp;
                QStringList fileToLoad;
                //load the language main
                if(newLanguage=="en")
                    fileToLoad<<":/Languages/en/translation.qm";
                else
                    fileToLoad<<LanguagesAvailableList.at(index).path+"translation.qm";
                //load the language plugin
                QList<PluginsAvailable> listLoadedPlugins=PluginsManager::pluginsManager->getPlugins();
                int indexPluginIndex=0;
                while(indexPluginIndex<listLoadedPlugins.size())
                {
                    if(listLoadedPlugins.at(indexPluginIndex).category!=PluginType_Languages)
                    {
                        QString tempPath=listLoadedPlugins.at(indexPluginIndex).path+"Languages"+QDir::separator()+LanguagesAvailableList.at(index).mainShortName+QDir::separator()+"translation.qm";
                        if(QFile::exists(tempPath))
                            fileToLoad<<tempPath;
                    }
                    indexPluginIndex++;
                }
                int indexTranslationFile=0;
                while(indexTranslationFile<fileToLoad.size())
                {
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"Translation to load: "+fileToLoad.at(indexTranslationFile));
                    temp=new QTranslator();
                    if(!temp->load(fileToLoad.at(indexTranslationFile)) || temp->isEmpty())
                    {
                        delete temp;
                        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to load the translation file: "+fileToLoad.at(indexTranslationFile));
                    }
                    else
                    {
                        QCoreApplication::installTranslator(temp);
                        installedTranslator<<temp;
                    }
                    indexTranslationFile++;
                }
                temp=new QTranslator();
                if(temp->load(QString("qt_")+newLanguage, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) && !temp->isEmpty())
                {
                    QCoreApplication::installTranslator(temp);
                    installedTranslator<<temp;
                }
                else
                {
                    if(!temp->load(LanguagesAvailableList.at(index).path+"qt.qm") || temp->isEmpty())
                    {
                        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"Unable to load the translation file: qt.qm, into: "+LanguagesAvailableList.at(index).path);
                        delete temp;
                    }
                    else
                    {
                        QCoreApplication::installTranslator(temp);
                        installedTranslator<<temp;
                    }
                }
            }
            currentLanguage=newLanguage;
            FacilityEngine::facilityEngine.retranslate();
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"emit newLanguageLoaded()");
            emit newLanguageLoaded(currentLanguage);
            return;
        }
        index++;
    }
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"unable to found language: "+newLanguage+", LanguagesAvailableList.size(): "+QString::number(LanguagesAvailableList.size()));
}
コード例 #4
0
ファイル: browserapplication.cpp プロジェクト: Andreas665/qt
void BrowserApplication::installTranslator(const QString &name)
{
    QTranslator *translator = new QTranslator(this);
    translator->load(name, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    QApplication::installTranslator(translator);
}
コード例 #5
0
ファイル: main.cpp プロジェクト: cdaffara/symbiandump-ossapps
int main(int argc, char * argv[])
{
#ifdef NO_NETWORK_ACCESS_MANAGER
    QNetworkProxyFactory::setApplicationProxyFactory(&proxies);
#endif //NO_NETWORK_ACCESS_MANAGER
    int res=0;

#ifdef HARDWARE_DEBUG_TRACE
    initDebugOutput();
    qInstallMsgHandler(debugOutput);
#endif

//    qDebug() << "main - before app, argc=" << argc;
//    for (int i = 0; i < argc; ++i)
//        {
//        qDebug() << "main - argv[" << i << "] = " << argv[i];
//        }

/* openurl should only work in Orbit UI application. */
#ifdef ORBIT_UI
#ifdef OPENURL
#ifdef NO_QSTM_GESTURE
    HbApplication app(AppFactoryL, argc, argv);
#else
    BrowserApp app(AppFactoryL, argc, argv);
#endif
#else /* !OPENURL */
#ifdef NO_QSTM_GESTURE
  HbApplication app(argc, argv);
#else // ORBIT_UI
  BrowserApp app(argc, argv);
#endif
#endif /* OPENURL */
#else
#ifdef NO_QSTM_GESTURE
  QApplication app(argc, argv);
#else
  BrowserApp app(argc, argv);
#endif
#endif // ORBIT_UI

#ifdef QTHIGHWAY
    //qDebug() << "ServiceInfo:" << (XQServiceUtil::isService() ? "Service" : "Normal") << "launch";
    //qDebug() << "  Embedded=" << XQServiceUtil::isEmbedded() << "Interface=" << XQServiceUtil::interfaceName() << "Operation=" << XQServiceUtil::operationName();

    // provide service for html mime type
    FileService *fileServiceProvider = new FileService();
#endif

//  qDebug() << "main - after app";
#ifdef Q_OS_SYMBIAN
    //Object cache settings. NB: these need to be tuned per device
    QWebSettings::globalSettings()->setObjectCacheCapacities(128*1024, 1024*1024, 1024*1024);
#endif

    if (BEDROCK_PROVISIONING::BedrockProvisioning::createBedrockProvisioning()->value("DnsPrefetchEnabled").toBool())
	{
	// Specifies whether QtWebkit will try to pre-fetch DNS entries to speed up browsing.
	// Without this technique, the DNS lookup is performed only when you click on the link,
	// adding a wait of 250ms (on average) before the page even starts to show up.
	// This only works as a global attribute.
	   QWebSettings::globalSettings()->setAttribute(QWebSettings::DnsPrefetchEnabled, true);
	}

    configureHtml5OfflineStorage();

    QString lang = QLocale::system().name();

    //install the common translator from platform
    QTranslator common;
    common.load("z:/resource/qt/translations/common_" + lang);
    QApplication::installTranslator(&common);


    //install the translator from Browser
    QTranslator translator;
    QString transFilePath = "Z:/resource/qt/translations/";
    QString transFile = QLatin1String("browserloc_") +  lang;
    translator.load(transFile, transFilePath);
    QApplication::installTranslator(&translator);

// To make the native urlsearch bar selection visible, the following lines have to be removed
// The keypad navigation still works for ginebra2 even without enabling keypad navigation
/*
#ifdef Q_OS_SYMBIAN
    QApplication::setKeypadNavigationEnabled(true);
#endif
*/
#ifdef OPENURL
    // Handle QDesktopServices.openUrl (when browser wasn't already running)
    QString url = CBrowserMainAppSingleton::Instance().InitialUrl();
    GinebraBrowser * browser = new GinebraBrowser(0, &url); // Pass the initial url so it will be loaded as soon as the browser chrome finishes
    // Set things up to handle QDesktopServices.openUrl calls when browser is already running
    CBrowserMainAppSingleton::Instance().setUrlHandler(browser);
#else
    GinebraBrowser * browser = new GinebraBrowser();
#endif


#ifdef ENABLE_PERF_TRACE
#if defined(NO_NETWORK_ACCESS_MANAGER)
    PERF_TRACE_OUT() << "NO_NETWORK_ACCESS_MANAGER\n";
#endif
#if defined(NO_RESIZE_ON_LOAD)
    PERF_TRACE_OUT() << "NO_RESIZE_ON_LOAD\n";
#endif
#if defined(NO_QSTM_GESTURE)
    PERF_TRACE_OUT() << "NO_QSTM_GESTURE\n";
#endif
#if defined(__gva_no_chrome__)
    PERF_TRACE_OUT() << "__gva_no_chrome__\n";
#endif
#if defined(NO_HISTORY)
    PERF_TRACE_OUT() << "NO_HISTORY\n";
#endif

#endif //ENABLE_PERF_TRACE

    browser->show();
    res = app.exec();
    delete browser;

#ifdef QTHIGHWAY
    delete fileServiceProvider;
#endif

#ifdef ENABLE_PERF_TRACE
      WrtPerfTracer::tracer()->close();
#endif //ENABLE_PERF_TRACE

    return res;
}
コード例 #6
0
ファイル: main.cpp プロジェクト: GENIVI/navigation
int main(int  argc , char**  argv )
{
    GMainLoop * mainloop ;

    // Set the global C and C++ locale to the user-configured locale,
    // so we can use std::cout with UTF-8, via Glib::ustring, without exceptions.
    std::locale::global(std::locale(""));

    //index used for argument analysis
    int next_option;

    /* Valid letters for short options. */
    const char* const short_options = "hf:i:";
    /* Valid string for long options. */
    const struct option long_options[] = {
        { "help",     0, NULL, 'h' },
        { "file", 1, NULL, 'f' },
        { "internationalisation", 2, NULL, 'i' },
        { NULL,       0, NULL, 0   }   /* Always at the end of the table.  */
    };
    char* database_filename = NULL; //database filename
    QString language = "en"; //english by default

    program_name = argv[0];

    do {
        next_option = getopt_long (argc, argv, short_options,
                                  long_options, NULL);
        switch (next_option)
        {
        case 'h':   /* -h --help */
            print_usage (stdout, 0);
            break;
        case 'f':   /* -f --file database */
            database_filename = argv[2];
            if (!is_readable(database_filename))
                print_usage (stderr, 1);
            break;
        case 'i':   /* -i --internationalisation language */
            language = argv[4];
            break;
        case '?':   /* Invalid option. */
            print_usage (stderr, 1);
        case -1:    /* End of options.  */
            break;
        default:    /* Error  */
            print_usage (stderr, 1);
        }
    }
    while (next_option != -1);

    QApplication a(argc, argv);
    QTranslator translator;
    if (QResource::registerResource("poi-client-resource.rcc",QDir::currentPath()))
    {
        if (translator.load("poi-contentaccess-module_"+ language))
        {
            a.installTranslator(&translator);
            MainWindow mainWindow;

            // creating the dispatcher
            dispatcher = new DBus::Glib::BusDispatcher();
            DBus::default_dispatcher = dispatcher;
            dispatcher->attach(NULL);

            // create a connection on the session bus
            dbusConnection = new DBus::Connection(DBus::Connection::SessionBus());
            dbusConnection->setup(dispatcher);

            // create the server for contentAccessModule
            dbusConnection->request_name(contentAccessModule_SERVICE_NAME);
            servercontentAccessModule=new contentAccessModuleServer(*dbusConnection,database_filename);

            // connect it to the HMI panel
            mainWindow.ConnectTocontentAccessModuleServer(servercontentAccessModule);

            // connect the HMI panel to it
            servercontentAccessModule->connectToHMI(&mainWindow);

            // create a client for poiContentAccess
            clientpoiContentAccess = new poiContentAccess(*dbusConnection);

            // connect it to the HMI panel
            mainWindow.ConnectTopoiContentAccessClient(clientpoiContentAccess);

            // Create a new GMainLoop with default context and initial state of "not running "
            mainloop = g_main_loop_new (g_main_context_default() , FALSE );

           // loop listening
            mainWindow.InitUi();
            mainWindow.show();

            int ret = a.exec();

            // clean memory
            delete servercontentAccessModule;
            delete dbusConnection;
            delete dispatcher;
        }
        else
        {
            print_usage (stderr, 2);
        }
    }
    else
    {
        print_usage (stderr, 3);
    }
    return EXIT_SUCCESS;
}
コード例 #7
0
ファイル: application.cpp プロジェクト: mjkent/mirall
Application::Application(int &argc, char **argv) :
    SharedTools::QtSingleApplication(argc, argv),
    _tray(0),
#if QT_VERSION >= 0x040700
    _networkMgr(new QNetworkConfigurationManager(this)),
#endif
    _sslErrorDialog(0),
    _contextMenu(0),
    _theme(Theme::instance()),
    _updateDetector(0),
    _logBrowser(0),
    _showLogWindow(false),
    _logFlush(false),
    _helpOnly(false),
    _fileItemDialog(0)
{
    setApplicationName( _theme->appName() );
    setWindowIcon( _theme->applicationIcon() );

    parseOptions(arguments());
    setupLogBrowser();
    //no need to waste time;
    if ( _helpOnly ) return;

    QString locale = Theme::instance()->enforcedLocale();
    if (locale.isEmpty()) locale = QLocale::system().name();

    QTranslator *qtTranslator = new QTranslator(this);
#if defined(Q_OS_MAC)
    qtTranslator->load(QLatin1String("qt_") + locale, applicationDirPath()+QLatin1String("/../translations") ); // path defaults to app dir.
#elif defined(Q_OS_WIN32)
    qtTranslator->load(QLatin1String("qt_") + locale, applicationDirPath());
#endif
    if (qtTranslator->isEmpty()) {
        qtTranslator->load(QLatin1String("qt_") + QLocale::system().name(),
                           QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    }
    installTranslator(qtTranslator);

    QTranslator *mirallTranslator = new QTranslator(this);

#ifdef Q_OS_LINUX
    // FIXME - proper path!
    mirallTranslator->load(QLatin1String("mirall_") + locale, QLatin1String("/usr/share/mirall/i18n/"));
#endif
#ifdef Q_OS_MAC
    mirallTranslator->load(QLatin1String("mirall_") + locale, applicationDirPath()+QLatin1String("/../translations") ); // path defaults to app dir.
#endif
#ifdef Q_OS_WIN32
    mirallTranslator->load(QLatin1String("mirall_") + locale, applicationDirPath());
#endif

    installTranslator(mirallTranslator);

    connect( this, SIGNAL(messageReceived(QString)), SLOT(slotParseOptions(QString)));
    connect( Logger::instance(), SIGNAL(guiLog(QString,QString)),
             this, SLOT(slotShowTrayMessage(QString,QString)));
    // create folder manager for sync folder management
    _folderMan = new FolderMan(this);
    connect( _folderMan, SIGNAL(folderSyncStateChange(QString)),
             this,SLOT(slotSyncStateChange(QString)));

    /* use a signal mapper to map the open requests to the alias names */
    _folderOpenActionMapper = new QSignalMapper(this);
    connect(_folderOpenActionMapper, SIGNAL(mapped(const QString &)),
            this, SLOT(slotFolderOpenAction(const QString &)));

    setQuitOnLastWindowClosed(false);

    _folderWizard = new FolderWizard;

    _owncloudSetupWizard = new OwncloudSetupWizard( _folderMan, _theme, this );
    connect( _owncloudSetupWizard, SIGNAL(ownCloudWizardDone(int)),
             this, SLOT(slotownCloudWizardDone(int)));

    _statusDialog = new StatusDialog( _theme );
    connect( _statusDialog, SIGNAL(addASync()), this, SLOT(slotAddFolder()) );

    connect( _statusDialog, SIGNAL(removeFolderAlias( const QString&)),
             SLOT(slotRemoveFolder(const QString&)));

    connect( _statusDialog, SIGNAL(openLogBrowser()), this, SLOT(slotOpenLogBrowser()));

    connect( _statusDialog, SIGNAL(enableFolderAlias(QString,bool)),
             SLOT(slotEnableFolder(QString,bool)));
    connect( _statusDialog, SIGNAL(infoFolderAlias(const QString&)),
             SLOT(slotInfoFolder( const QString&)));
    connect( _statusDialog, SIGNAL(openFolderAlias(const QString&)),
             SLOT(slotFolderOpenAction(QString)));

#if 0
#if QT_VERSION >= 0x040700
    qDebug() << "* Network is" << (_networkMgr->isOnline() ? "online" : "offline");
    foreach (const QNetworkConfiguration& netCfg, _networkMgr->allConfigurations(QNetworkConfiguration::Active)) {
        //qDebug() << "Network:" << netCfg.identifier();
    }
#endif
#endif
    setupActions();
    setupSystemTray();
    setupProxy();

    QObject::connect( this, SIGNAL(messageReceived(QString)),
                      this, SLOT(slotOpenStatus()) );

    QTimer::singleShot( 0, this, SLOT( slotStartFolderSetup() ));

    MirallConfigFile cfg;
    if( !cfg.ownCloudSkipUpdateCheck() ) {
        QTimer::singleShot( 3000, this, SLOT( slotStartUpdateDetector() ));
    }

    connect( ownCloudInfo::instance(), SIGNAL(sslFailed(QNetworkReply*, QList<QSslError>)),
             this,SLOT(slotSSLFailed(QNetworkReply*, QList<QSslError>)));

    qDebug() << "Network Location: " << NetworkLocation::currentLocation().encoded();
}
コード例 #8
0
ファイル: main.cpp プロジェクト: DoctorCannibal/DSView
int main(int argc, char *argv[])
{
	int ret = 0;
	struct sr_context *sr_ctx = NULL;
	const char *open_file = NULL;

	QApplication a(argc, argv);

    // Language
#ifdef LANGUAGE_ZH_CN
    QTranslator qtTrans;
    qtTrans.load(":/qt_zh_CN");
    a.installTranslator(&qtTrans);

    QTranslator DSViewTrans;
    DSViewTrans.load(":/DSView_zh");
    a.installTranslator(&DSViewTrans);
#endif

    // Set some application metadata
    QApplication::setApplicationVersion(DS_VERSION_STRING);
    QApplication::setApplicationName("DSView(Beta)");
    QApplication::setOrganizationDomain("http://www.DreamSourceLab.com");

	// Parse arguments
	while (1) {
		static const struct option long_options[] = {
			{"loglevel", required_argument, 0, 'l'},
			{"version", no_argument, 0, 'V'},
			{"help", no_argument, 0, 'h'},
			{0, 0, 0, 0}
		};

		const int c = getopt_long(argc, argv,
			"l:Vh?", long_options, NULL);
		if (c == -1)
			break;

		switch (c) {
		case 'l':
		{
			const int loglevel = atoi(optarg);
			sr_log_loglevel_set(loglevel);

#ifdef ENABLE_DECODE
			srd_log_loglevel_set(loglevel);
#endif

			break;
		}

		case 'V':
			// Print version info
			fprintf(stdout, "%s %s\n", DS_TITLE, DS_VERSION_STRING);
			return 0;

		case 'h':
		case '?':
			usage();
			return 0;
		}
	}

	if (argc - optind > 1) {
		fprintf(stderr, "Only one file can be openened.\n");
		return 1;
	} else if (argc - optind == 1)
		open_file = argv[argc - 1];

	// Initialise libsigrok
	if (sr_init(&sr_ctx) != SR_OK) {
		qDebug() << "ERROR: libsigrok init failed.";
		return 1;
	}

	do {

#ifdef ENABLE_DECODE
		// Initialise libsigrokdecode
		if (srd_init(NULL) != SRD_OK) {
			qDebug() << "ERROR: libsigrokdecode init failed.";
			break;
		}

		// Load the protocol decoders
		srd_decoder_load_all();
#endif

		try {
			// Create the device manager, initialise the drivers
			pv::DeviceManager device_manager(sr_ctx);

			// Initialise the main window
            		pv::MainWindow w(device_manager, open_file);
            		QFile qss(":/stylesheet.qss");
            		qss.open(QFile::ReadOnly);
            		a.setStyleSheet(qss.readAll());
            		qss.close();
			w.show();

			// Run the application
			ret = a.exec();

		} catch(std::exception e) {
			qDebug() << e.what();
		}

#ifdef ENABLE_DECODE
		// Destroy libsigrokdecode
		srd_exit();
#endif

	} while (0);

	// Destroy libsigrok
	if (sr_ctx)
		sr_exit(sr_ctx);

	return ret;
}
コード例 #9
0
ファイル: main.cpp プロジェクト: Iownnoname/qt
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    //Check if another instance has been started already
    QSharedMemory sharedMemory;
    sharedMemory.setKey("neu");

    if (!sharedMemory.create(1))
    {
        QMessageBox::warning(nullptr, QObject::tr("Warning!"), QObject::tr("An instance of this application is running!"));
        exit(0); // Exit process immediately
    }

    QSettings settings("neuPlayer.ini", QSettings::IniFormat);

    // Init Trad engine
    QString locale = QLocale::system().name().section('_', 0, 0);
    QTranslator translator;
    //Load correct translation based on system locale
    translator.load("neuplayer_" + locale);
    a.installTranslator(&translator);
    //Setup actual window
    qApp->setStyle(QStyleFactory::create("Fusion")); //base theme fusion

    if(settings.value("skin", 1).toInt() == 1 || settings.value("skin", 1).toInt() == 3)
    {
        Skin HoloFusion(1, nullptr);
        HoloFusion.load();
    }

    else
    {
        Skin CleanFusion(0, nullptr);
        CleanFusion.load();
    }
    //Ready to show
    //Create the helper so it isn't destroyed right away
    NcFramelessHelper helper(nullptr);
    QFile fileHandler(".configdone"); //So you config before anything else
    if(!fileHandler.exists()) //If there is the config to do, the config will launch the app when done
    {
        QPointer <InitialConfig> config = new InitialConfig();
        config->show();
    }
    else
    {
        Player *neuPlayer = new Player(nullptr);
        if(settings.value("Additional_Features/framelessWindow", false).toBool())
        {
            if(settings.value("visibilite").toBool())
                helper.activateOn(neuPlayer, true);
            else
                helper.activateOn(neuPlayer);
        }
        neuPlayer->show();
    }
    fileHandler.close();

    return a.exec();
}
コード例 #10
0
ファイル: main.cpp プロジェクト: rabbor/cmst
int main(int argc, char *argv[])
{  
  QApplication::setApplicationName(LONG_NAME);
  QApplication::setApplicationVersion(VERSION);
  QApplication::setOrganizationName(ORG); 
  QApplication::setDesktopSettingsAware(true);
  QApplication app(argc, argv);   
  
  // make sure only one instance is running
  QLocalSocket* socket = new QLocalSocket();
  socket->connectToServer(SOCKET_NAME);
  bool b_connected = socket->waitForConnected(500);
  socket->abort();
  delete socket;  
  if (b_connected) { 
    qDebug() <<  QCoreApplication::translate("main.cpp", "Another running instance of CMST has been detected.  This instance is aborting");  
    return 1;
  }

  // setup the command line parser
  QCommandLineParser parser;
  parser.setApplicationDescription(QApplication::translate("main.cpp", "Connman System Tray.") );
  
  QCommandLineOption bypassState(QStringList() << "b" << "bypass-restore-state",
		QCoreApplication::translate("main.cpp", "Bypass restoring the window state if restoring window state is specified in the settings file.") );
  parser.addOption(bypassState);   
  
  QCommandLineOption bypassStartOptions(QStringList() << "B" << "bypass-start-options",
		QCoreApplication::translate("main.cpp", "Bypass restoring any start options in the settings file.") );
  parser.addOption(bypassStartOptions);  
  
  QCommandLineOption disableCounters(QStringList() << "c" << "disable-counters",
		QCoreApplication::translate("main.cpp", "[Experimental] Disable data counters.  May be used to minimize load on your system.") );
  parser.addOption(disableCounters);  
  
  QCommandLineOption disableTrayIcon(QStringList() << "d" << "disable-tray-icon",
		QCoreApplication::translate("main.cpp", "Disable the system tray icon.  May be needed for system trays not compliant with the Freedesktop.org system tray specification.") );
  parser.addOption(disableTrayIcon);  
 
  parser.addHelpOption();
  
  QCommandLineOption useIconTheme(QStringList() << "i" << "icon-theme",
		QCoreApplication::translate("main.cpp", "Use an icon theme from your system."),
		QCoreApplication::translate("main.cpp", "Icon Theme Name"),
		QString() );
  parser.addOption(useIconTheme); 
  
  QCommandLineOption logInputRequest(QStringList() << "l" << "log-input-request",
		QCoreApplication::translate("main.cpp", "Log the connman inputRequest for debugging purposes.") );
  parser.addOption(logInputRequest);

  QCommandLineOption startMinimized(QStringList() << "m" << "minimized",
		QCoreApplication::translate("main.cpp", "Start the GUI minimized in the system tray.") );
  parser.addOption(startMinimized);
     
  parser.addVersionOption();  
    
  QCommandLineOption waitTime(QStringList() << "w" << "wait-time",
		QCoreApplication::translate("main.cpp", "Specify the wait time in seconds before starting the system tray icon."),
		QCoreApplication::translate("main.cpp", "seconds"),
		"0");
  parser.addOption(waitTime); 

  QCommandLineOption counterUpdateKb (QStringList() << "counter-update-kb",
		QCoreApplication::translate("main.cpp", "[Experimental] The number of kb that have to be transmitted before the counter updates."),
		QCoreApplication::translate("main.cpp", "KB"),
		"1024" );
  parser.addOption(counterUpdateKb);

  QCommandLineOption counterUpdateRate (QStringList() << "counter-update-rate",
		QCoreApplication::translate("main.cpp", "[Experimental] The interval in seconds between counter updates."),
		QCoreApplication::translate("main.cpp", "seconds"),
		"10" );
  parser.addOption(counterUpdateRate);

	// Added on 2015.01.04 to work around QT5.4 bug with transparency not always working
  QCommandLineOption fakeTransparency(QStringList() << "fake-transparency",
		QCoreApplication::translate("main.cpp", "If tray icon fake transparency is required, specify the background color to use (format: 0xRRGGBB)"),
		QCoreApplication::translate("main.cpp", "RRGGBB"),
		"0x222222" );
  parser.addOption(fakeTransparency); 

  // Added on 2014.11.24 to work around a bug where QT5.3 won't show an icon in XFCE,  My fix may not work, but keep it in for now.  If this gets fixed in 
  // QT5.4 keep the command line option so users start up commands don't break, but make it a NOP. 
  QCommandLineOption useXFCE(QStringList() << "use-xfce",
		QCoreApplication::translate("main.cpp", "Use XFCE specific code.") );
  parser.addOption(useXFCE);   
  
  // Added on 2014.12.16 to work around a similar bug where QT5.3 won't show an icon in MATE.   
  QCommandLineOption useMATE(QStringList() << "use-mate",
		QCoreApplication::translate("main.cpp", "Use MATE DE specific code.") );
  parser.addOption(useMATE); 
  
  // Setup translations   
  QTranslator qtTranslator;
  qtTranslator.load("qt_" + QLocale::system().name(),
  QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  app.installTranslator(&qtTranslator);

  QTranslator cmstTranslator;
  if (cmstTranslator.load("cmst_" + QLocale::system().name(), ":/translations/translations" ) ) {  
		app.installTranslator(&cmstTranslator);	
	}
	// else use en_US as it contains Connman strings properized and some singular/plural strings
	else if (cmstTranslator.load("cmst_en_US", ":/translations/translations" ) ) {
		app.installTranslator(&cmstTranslator);	
	}
 	
  // Make sure all the command lines can be parsed 
  // using parse() instead of process() as process stops on an error if an option needs a value
  // and it is not specified, even if we provide a default.  We're supposed to catch errors if we
  // use parse(), but parse.errorText() returns an empty string on this.  Bag the error checking
  // for now.
  parser.parse(QCoreApplication::arguments() );   
  QStringList sl = parser.unknownOptionNames();
  if (sl.size() > 0 ) parser.showHelp(1);
  if (parser.isSet("help") ) parser.showHelp(1);
                
  // signal handler             
  signal(SIGINT, signalhandler);                
             
  // Showing the dialog (or not) is controlled in the createSystemTrayIcon() function
  // called from the ControlBox constructor.  We don't show it from here.             
  ControlBox ctlbox(parser);
  return app.exec(); 
}
コード例 #11
0
ファイル: mainwindow.cpp プロジェクト: jwotswonit/osmc
void MainWindow::install()
{
    ui->statusLabel->setFont(getFont(ui->statusLabel, FONT_STATUSLABEL_RATIO));
    ui->statusProgressBar->setFont(getFont(ui->statusProgressBar, FONT_PROGRESSBAR_RATIO));

    qApp->processEvents();
    /* Find out what device we are running on */
    logger->addLine("Detecting device we are running on");
    device = targetList->getTarget(utils->getOSMCDev());
    if (device == NULL)
    {
        haltInstall("unsupported device"); /* No tr here as not got lang yet */
        return;
    }
    /* Mount the BOOT filesystem */
    logger->addLine("Mounting boot filesystem");
    bool hasMount = false;
    hasMount = utils->mountPartition(device, MNT_BOOT);
    if (! hasMount && utils->getOSMCDev() == "atv")
    {
        /* Super hacky for Apple TV 1st gen. Sometimes no internal disk */
        hasMount = utils->mountPartition(device, "/dev/sda1");
        device->setRoot("/dev/sda2");
        device->setBootNeedsFormat(false);
    }
    if (! hasMount)
    {
        haltInstall("could not mount bootfs");
        return;
    }
    /* Sanity check: need filesystem.tar.xz */
    QFile fileSystem(QString(MNT_BOOT) + "/filesystem.tar.xz");
    if (! fileSystem.exists())
    {
        haltInstall("no filesystem found");
        return;
    }
    /* Load in preseeded values */
    preseed = new PreseedParser();
    if (preseed->isLoaded())
    {
        logger->addLine("Preseed file found, will attempt to parse");
        /* Locales */
        locale = preseed->getStringValue("globe/locale");
        if (! locale.isEmpty())
        {
            logger->addLine("Found a definition for globalisation: " + locale);
            QTranslator translator;
            if (translator.load(qApp->applicationDirPath() + "/osmc_" + locale + ".qm"))
            {
                logger->addLine("Translation loaded successfully!");
                qApp->installTranslator(&translator);
                ui->retranslateUi(this);
            }
            else
                logger->addLine("Could not load translation");
        }
        /* Install target */
        installTarget = preseed->getStringValue("target/storage");
        if (! installTarget.isEmpty())
        {
            logger->addLine("Found a definition for storage: " + installTarget);
            if (installTarget == "nfs")
            {
                QString nfsPath = preseed->getStringValue("target/storagePath");
                if (! nfsPath.isEmpty())
                {
                    device->setRoot(nfsPath);
                    useNFS = true;
                }
            }
            if (installTarget == "usb")
            {
                /* Behaviour for handling USB installs */
                if (utils->getOSMCDev() == "rbp1") { device->setRoot("/dev/sda1"); }
                if (utils->getOSMCDev() == "rbp2") { device->setRoot("/dev/sda1"); }
                if (utils->getOSMCDev() == "vero1") { device->setRoot("/dev/sda1"); }
                if (utils->getOSMCDev() == "atv") { device->setRoot("/dev/sda1"); } /* It's not USB, it's the internal disk.. but this is a hack */
                for (int i = 0; i <= 60; i++)
                {
                    ui->statusLabel->setText(tr("USB install:") + " " + QString::number(60 - i) + " " + ("seconds to remove device before data loss"));
                    qApp->processEvents();
                    system("/bin/sleep 1");
                }
            }
        }
        /* Bring up network if using NFS */
        if (useNFS)
        {
            logger->addLine("NFS installation chosen, must bring up network");
            nw = new Network();
            nw->setIP(preseed->getStringValue("network/ip"));
            nw->setMask(preseed->getStringValue("network/mask"));
            nw->setGW(preseed->getStringValue("network/gw"));
            nw->setDNS1(preseed->getStringValue("network/dns1"));
            nw->setDNS2(preseed->getStringValue("network/dns2"));
            if (! nw->isDefined())
            {
                logger->addLine("Either network preseed definition incomplete, or user wants DHCP");
                nw->setAuto();
            }
            logger->addLine("Attempting to bring up eth0");
            ui->statusLabel->setText(tr("Configuring Network"));
            nw->bringUp();
        }
    }
    else
    {
        logger->addLine("No preseed file was found");
    }
    /* If !nfs, create necessary partitions */
    if (! useNFS)
    {
        logger->addLine("Creating root partition");
        ui->statusLabel->setText(tr("Formatting device"));
        qApp->processEvents(); /* Force GUI update */
        QString rootBase = device->getRoot();
        if (rootBase.contains("mmcblk"))
            rootBase.chop(2);
        else
            rootBase.chop(1);
        logger->addLine("From a root partition of " + device->getRoot() + ", I have deduced a base device of " + rootBase);
        if (device->hasRootChanged() && utils->getOSMCDev() != "atv") // && utils.getOSMCDev() != "pc" eventually.. -- cause we want boot there too.
        {
            logger->addLine("Must mklabel as root fs is on another device");
            utils->mklabel(rootBase, false);
            utils->mkpart(rootBase, "ext4", "4096s", "100%");
            utils->fmtpart(device->getRoot(), "ext4");
        }
        else
        {
            if (! device->doesBootNeedsFormat())
            {
                int size = utils->getPartSize(rootBase, device->getBootFS());
                if (size == -1)
                {
                    logger->addLine("Issue getting size of device");
                    haltInstall(tr("cannot work out partition size"));
                    return;
                }
                if (device->deviceUsesGPT())
                {
                    /* GPT is too clever: has secondary header; so we need to trash it and recreate the partition layout */
                    /* NB: for some reason on 4.x this does not work all the time. So we have some parted patches to make sure it does */
                    logger->addLine("We are using GPT. I need to erase the first 512 bytes and reconstruct the partition table");
                    QString ddCmd = "/bin/dd if=/dev/zero of=" + rootBase + " bs=512 count=1 conv=fsync";
                    system(ddCmd.toLocal8Bit());
                    int fd;
                    QFile dev(rootBase);
                    dev.open(fd, QIODevice::ReadOnly);
                    ioctl(fd, BLKRRPART, NULL);
                    ioctl(fd, BLKFLSBUF, NULL);
                    dev.close();
                    utils->updateDevTable();
                    utils->updateDevTable();
                    if (utils->getOSMCDev() == "atv")
                    {
                        logger->addLine("Re-creating Apple TV partition structure");
                        utils->mklabel(rootBase, true);
                        utils->updateDevTable();
                        utils->mkpart(rootBase, "hfsplus", "40s", "256M");
                        /* We don't format /boot */
                        utils->setflag(rootBase, "1 atvrecv", true);
                        utils->updateDevTable();
                    }
                }
                logger->addLine("Determined " + QString::number(size) + " MB as end of first partition");
                utils->mkpart(rootBase, "ext4", QString::number(size + 2) + "M", "100%");
                utils->fmtpart(device->getRoot(), "ext4");
            }
            else
            {
                /* We have to create the partition structure for /boot too */
                logger->addLine("Must mklabel as rootfs is on another device");
                utils->mklabel(rootBase, true); /* GPT favoured on PC */
                logger->addLine("Making boot partition as this type of system needs one");
                if (utils->getOSMCDev() == "atv")
                {
                    utils->mkpart(rootBase, device->getBootFS(), "40s", "256M"); /* Hack to hard-code this for now */
                    utils->setflag(rootBase, "1 atvrecv", true);
                    utils->fmtpart(device->getBoot(), "hfsplus");
                }
                utils->updateDevTable();
                logger->addLine("Making root partition");
                int size = utils->getPartSize(rootBase, device->getBootFS());
                if (size == -1)
                {
                    logger->addLine("Issue getting size of device");
                    haltInstall(tr("cannot work out partition size"));
                    return;
                }
                logger->addLine("Determined " + QString::number(size) + " MB as end of first partition");
                utils->mkpart(rootBase, "ext4", QString::number(size + 2) + "M", "100%");
                utils->fmtpart(device->getRoot(), "ext4");
            }
        }
    }
    /* Mount root filesystem */
    if (useNFS)
        bc = new BootloaderConfig(device, nw, utils, logger, preseed);
    else
        bc = new BootloaderConfig(device, NULL, utils, logger, preseed);
    logger->addLine("Mounting root");
    if ( ! utils->mountPartition(device, MNT_ROOT))
    {
        logger->addLine("Error occured trying to mount root of " + device->getRoot());
        haltInstall(tr("can't mount root"));
        return;
    }
    if (useNFS)
        system("rm -rf /mnt/root/*"); /* BusyBox tar does not like overwrites. Clear nfsroot first */
   /* Extract root filesystem */
   ui->statusLabel->setText(tr("Installing files"));
   logger->addLine("Extracting files to root filesystem");
   ui->statusProgressBar->setMinimum(0);
   ui->statusProgressBar->setMaximum(100);

   QThread* thread = new QThread(this);
   ExtractWorker *worker = new ExtractWorker(fileSystem.fileName(), MNT_ROOT, logger);
   worker->moveToThread(thread);
   connect(thread, SIGNAL(started()), worker, SLOT(extract()));
   connect(worker, SIGNAL(progressUpdate(unsigned)), this, SLOT(setProgress(unsigned)));
   connect(worker, SIGNAL(error(QString)), this, SLOT(haltInstall(QString)));
   connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
   connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
   connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
   connect(thread, SIGNAL(finished()), this, SLOT(finished()));
   thread->start();
}
コード例 #12
0
ファイル: companion.cpp プロジェクト: CoyotteDundee/opentx
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(companion);
  QApplication app(argc, argv);
  app.setApplicationName("OpenTX Companion");
  app.setOrganizationName("OpenTX");
  app.setOrganizationDomain("open-tx.org");
  app.setAttribute(Qt::AA_DontShowIconsInMenus, false);

#ifdef __APPLE__
  app.setStyle(new MyProxyStyle);
#endif

  QTranslator companionTranslator;
  companionTranslator.load(":/companion_" + g.locale());
  QTranslator qtTranslator;
  qtTranslator.load((QString)"qt_" + g.locale().left(2), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  app.installTranslator(&companionTranslator);
  app.installTranslator(&qtTranslator);

  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

#if defined(JOYSTICKS) || defined(SIMU_AUDIO)
  uint32_t sdlFlags = 0;
  #ifdef JOYSTICKS
    sdlFlags |= SDL_INIT_JOYSTICK;
  #endif
  #ifdef SIMU_AUDIO
    sdlFlags |= SDL_INIT_AUDIO;
  #endif
  if (SDL_Init(sdlFlags) < 0) {
    fprintf(stderr, "ERROR: couldn't initialize SDL: %s\n", SDL_GetError());
  }
#endif

  RegisterEepromInterfaces();
  registerOpenTxFirmwares();

  if (g.profile[g.id()].fwType().isEmpty()){
    g.profile[g.id()].fwType(default_firmware_variant->getId());
    g.profile[g.id()].fwName("");
  }

  QString splashScreen;
  if ( g.profile[g.id()].fwType().contains("taranis"))     splashScreen = ":/images/splasht.png";
  else if ( g.profile[g.id()].fwType().contains("9xrpro")) splashScreen = ":/images/splashp.png";
  else if ( g.profile[g.id()].fwType().contains("9xr"))    splashScreen = ":/images/splashr.png";
  else  splashScreen = ":/images/splash.png";

  QPixmap pixmap = QPixmap(splashScreen);
  QSplashScreen *splash = new QSplashScreen(pixmap);

  current_firmware_variant = GetFirmware(g.profile[g.id()].fwType());

  MainWindow *mainWin = new MainWindow();
  if (g.showSplash()) {
    splash->show();
    QTimer::singleShot(1000*SPLASH_TIME, splash, SLOT(close()));
    QTimer::singleShot(1000*SPLASH_TIME, mainWin, SLOT(show()));
  }
  else {
    mainWin->show();
  }

  int result = app.exec();

  delete splash;
  delete mainWin;

  UnregisterFirmwares();
  UnregisterEepromInterfaces();

#if defined(JOYSTICKS) || defined(SIMU_AUDIO)
  SDL_Quit();
#endif

  return result;
}
コード例 #13
0
ファイル: main.cpp プロジェクト: kuailexs/symbiandump-mw3
int main(int argc, char *argv[])
{
    QString error;
    QString arg;
    QString collectionFile;
    QString configFile;
    QString basePath;
    bool showHelp = false;
    bool showVersion = false;

    QCoreApplication app(argc, argv);
    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);
    }

    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());

    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;
}
コード例 #14
0
ファイル: main.cpp プロジェクト: Boaz1/GrblHoming
int main(int argc, char *argv[])
{
    // setup logging
    Log4Qt::LogManager::rootLogger();
    //Log4Qt::TTCCLayout *p_layout = new Log4Qt::TTCCLayout(Log4Qt::TTCCLayout::ISO8601);
    //Log4Qt::PatternLayout *p_layout = new Log4Qt::PatternLayout(Log4Qt::PatternLayout::TTCC_CONVERSION_PATTERN);
    p_layout = new Log4Qt::PatternLayout("%d %p (%c) - %m%n");
    p_layout->setName(QLatin1String("GC Basic Layout"));
    p_layout->activateOptions();

    // Create a console appender
    Log4Qt::ConsoleAppender *p_appender = new Log4Qt::ConsoleAppender(p_layout, Log4Qt::ConsoleAppender::STDOUT_TARGET);
    p_appender->setName(QLatin1String("GC Basic Console Appender"));
#ifdef QT_DEBUG
    p_appender->setThreshold(Log4Qt::Level::TRACE_INT);
#else
    p_appender->setThreshold(Log4Qt::Level::WARN_INT);
#endif
    p_appender->activateOptions();
    Log4Qt::Logger::rootLogger()->addAppender(p_appender);

    // Create a file appender
    p_fappender = new Log4Qt::FileAppender();
    p_fappender->setLayout(p_layout);
    p_fappender->setThreshold(Log4Qt::Level::TRACE_INT);
    p_fappender->setFile(QDir::homePath() + "/GrblController.log");
    p_fappender->setName(QLatin1String("GC Basic File Appender"));
    // don't open until ready (later during startup)
    //p_fappender->activateOptions();
    //Log4Qt::Logger::rootLogger()->addAppender(p_fappender);

    QApplication a(argc, argv);

    QString locale = QLocale::system().name().section('_', 0, 0);
    QString dir = QDir::currentPath() + "/trlocale";
    QString file = QString("GrblController_") + locale;
	QTranslator translator;
    bool r = translator.load(file, dir);
    if (!r)
    {
        dir = QDir::currentPath() + "/../GrblHoming/trlocale";
        translator.load(file, dir);
    }
    a.installTranslator(&translator);

    QString xlatpath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    file = QString("qt_") + locale ;
    QTranslator qtTranslator;
    r = qtTranslator.load(file , xlatpath);
    if (!r)
    {
        xlatpath = QDir::currentPath() + "/trlocale";
        qtTranslator.load(file, xlatpath);
    }
    a.installTranslator(&qtTranslator);

    MainWindow w;
    w.show();

    int result = a.exec();

    if (pDebugLogFile != NULL)
    {
        fclose(pDebugLogFile);
        pDebugLogFile = NULL;
    }
    return result;
}
コード例 #15
0
ファイル: main.cpp プロジェクト: QShen3/QVideo
Q_DECL_EXPORT int main(int argc, char *argv[])
{
#ifdef Q_OS_SYMBIAN
    QApplication::setAttribute((Qt::ApplicationAttribute)11);   //Qt::AA_CaptureMultimediaKeys
#endif
    QApplication app(argc, argv);

    app.setApplicationName("QVideo");
    app.setOrganizationName("QShen");
    app.setApplicationVersion(VER);



    QString locale = QLocale::system().name();
    QTranslator translator;
    if(!translator.load(QString("QVideo_") + locale,":/i18n")){
        qDebug()<<"translator load erro";
    }
    app.installTranslator(&translator);

    Utility utility;
    Settings settings;

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    QmlApplicationViewer viewer;

    //viewer.setAttribute(Qt::WA_OpaquePaintEvent);
    //viewer.setAttribute(Qt::WA_NoSystemBackground);
    //viewer.viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
    //viewer.viewport()->setAttribute(Qt::WA_NoSystemBackground);
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait);

    viewer.rootContext()->setContextProperty("utility", &utility);
    viewer.rootContext()->setContextProperty("settings", &settings);

    viewer.rootContext()->setContextProperty("appVersion", app.applicationVersion());

#ifdef Q_OS_SYMBIAN
    QSplashScreen *splash = new QSplashScreen(QPixmap(":/qml/pic/splash_symbian.png"));
    splash->show();
    splash->raise();

    viewer.setSource(QUrl("qrc:/qml/Symbian/main.qml"));
#elif defined(Q_OS_HARMATTAN)
    //QApplication::setGraphicsSystem("native");
    viewer.setSource(QUrl("qrc:/qml/Meego/main.qml"));
#elif defined(Q_WS_SIMULATOR)
    viewer.setSource(QUrl("qrc:/qml/Symbian/main.qml"));
#endif
    viewer.showExpanded();
#else
    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty("utility",&utility);
#ifdef Q_OS_WIN32
    engine.load(QUrl(QStringLiteral("qrc:/qml/Win32/main.qml")));
#endif

#endif

#ifdef Q_OS_SYMBIAN
    splash->finish(&viewer);
    splash->deleteLater();
#endif
    return app.exec();
}
コード例 #16
0
ファイル: main.cpp プロジェクト: iamsergio/flow-pomodoro
int main(int argc, char *argv[])
{
    Utils::printTimeInfo(QStringLiteral("main"));

    // qputenv("QML_DISABLE_DISTANCEFIELD", "1");
#ifdef Q_OS_WIN
    // qputenv("QT_QPA_PLATFORM","windows:fontengine=freetype");
#endif
#ifndef Q_OS_ANDROID
    qInstallMessageHandler(flowMessageHandler);
#endif
#ifdef FLOW_STATIC_BUILD
    Q_INIT_RESOURCE(shellscriptplugin);
    Q_INIT_RESOURCE(hostsplugin);
#endif

    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    Application app(argc, argv);
    Utils::printTimeInfo(QStringLiteral("main: created QApplication"));
    app.setOrganizationName(QStringLiteral("KDAB"));
    app.setApplicationName(QStringLiteral("flow"));

    QTranslator translator;
    translator.load(QStringLiteral(":/translations/flow_%1").arg(QLocale::system().name())); // export LANG="pt_PT" to change
    app.installTranslator(&translator);
    Utils::printTimeInfo(QStringLiteral("main: installed QTranslator"));

    RuntimeConfiguration runtimeConfig;
    runtimeConfig.setDataFileName(defaultDataFileName());
    runtimeConfig.setMobileUI(Utils::platformRequiresMobileUI() || qApp->arguments().contains("--mobile"));
    runtimeConfig.setSaveEnabled(!qApp->arguments().contains("--read-only"));

    Kernel kernel(runtimeConfig);
    kernel.storage()->load();

    // app.connect(&app, &Application::focusObjectChanged, &onFocusObjectChanged);

    Utils::printTimeInfo(QStringLiteral("main: created Kernel::instance()"));
    QuickView window(&kernel);
    Utils::printTimeInfo(QStringLiteral("main: created QuickView"));
    initDBus(&kernel);
    Utils::printTimeInfo(QStringLiteral("main: initialized dbus"));

    if (runtimeConfig.isMobileUI()) {
        window.showMaximized(); // Don't use fullscreen on android
    } else {
        window.show();
    }

    if (logsDebugToFile()) { // Logging to file, so lets be a bit more verbose
        for (auto screen : QGuiApplication::screens()) {
            if (screen) {
                qDebug() << "Logical DPI=" << screen->logicalDotsPerInch()
                         << "; Physical DPI=" << screen->physicalDotsPerInch()
                         << "; Physical DPI X=" << screen->physicalDotsPerInchX()
                         << "; Resolution=" << screen->size()
                         << "; Name=" << screen->name();
            } else {
                qWarning() << "Null screen";
            }
        }
    }

    Utils::printTimeInfo(QStringLiteral("main: starting app.exec()"));
    return app.exec();
}
コード例 #17
0
ファイル: main.cpp プロジェクト: sicily/qt4.8.4
int main(int argc, char **argv)
{
#ifdef QT_BOOTSTRAPPED
    initBinaryDir(
#ifndef Q_OS_WIN
            argv[0]
#endif
            );
#else
    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
#endif // QT_BOOTSTRAPPED

    ConversionData cd;
    cd.m_verbose = true; // the default is true starting with Qt 4.2
    bool removeIdentical = false;
    Translator tor;
    QStringList inputFiles;
    QString outputFile;

    for (int i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-compress")) {
            cd.m_saveMode = SaveStripped;
            continue;
        } else if (!strcmp(argv[i], "-idbased")) {
            cd.m_idBased = true;
            continue;
        } else if (!strcmp(argv[i], "-nocompress")) {
            cd.m_saveMode = SaveEverything;
            continue;
        } else if (!strcmp(argv[i], "-removeidentical")) {
            removeIdentical = true;
            continue;
        } else if (!strcmp(argv[i], "-nounfinished")) {
            cd.m_ignoreUnfinished = true;
            continue;
        } else if (!strcmp(argv[i], "-markuntranslated")) {
            if (i == argc - 1) {
                printUsage();
                return 1;
            }
            cd.m_unTrPrefix = QString::fromLocal8Bit(argv[++i]);
        } else if (!strcmp(argv[i], "-silent")) {
            cd.m_verbose = false;
            continue;
        } else if (!strcmp(argv[i], "-verbose")) {
            cd.m_verbose = true;
            continue;
        } else if (!strcmp(argv[i], "-version")) {
            printOut(LR::tr("lrelease version %1\n").arg(QLatin1String(QT_VERSION_STR)));
            return 0;
        } else if (!strcmp(argv[i], "-qm")) {
            if (i == argc - 1) {
                printUsage();
                return 1;
            }
            outputFile = QString::fromLocal8Bit(argv[++i]);
        } else if (!strcmp(argv[i], "-help")) {
            printUsage();
            return 0;
        } else if (argv[i][0] == '-') {
            printUsage();
            return 1;
        } else {
            inputFiles << QString::fromLocal8Bit(argv[i]);
        }
    }

    if (inputFiles.isEmpty()) {
        printUsage();
        return 1;
    }

    foreach (const QString &inputFile, inputFiles) {
        if (inputFile.endsWith(QLatin1String(".pro"), Qt::CaseInsensitive)
            || inputFile.endsWith(QLatin1String(".pri"), Qt::CaseInsensitive)) {
            QFileInfo fi(inputFile);

            parseHandler.verbose = evalHandler.verbose = cd.isVerbose();
            ProFileOption option;
#ifdef QT_BOOTSTRAPPED
            option.initProperties(binDir + QLatin1String("/qmake"));
#else
            option.initProperties(app.applicationDirPath() + QLatin1String("/qmake"));
#endif
            ProFileParser parser(0, &parseHandler);
            ProFileEvaluator visitor(&option, &parser, &evalHandler);

            ProFile *pro;
            if (!(pro = parser.parsedProFile(QDir::cleanPath(fi.absoluteFilePath())))) {
                printErr(LR::tr(
                          "lrelease error: cannot read project file '%1'.\n")
                          .arg(inputFile));
                continue;
            }
            if (!visitor.accept(pro)) {
                printErr(LR::tr(
                          "lrelease error: cannot process project file '%1'.\n")
                          .arg(inputFile));
                pro->deref();
                continue;
            }
            pro->deref();

            QStringList translations = visitor.values(QLatin1String("TRANSLATIONS"));
            if (translations.isEmpty()) {
                printErr(LR::tr(
                          "lrelease warning: Met no 'TRANSLATIONS' entry in project file '%1'\n")
                          .arg(inputFile));
            } else {
                QDir proDir(fi.absolutePath());
                foreach (const QString &trans, translations)
                    if (!releaseTsFile(QFileInfo(proDir, trans).filePath(), cd, removeIdentical))
                        return 1;
            }
        } else {
            if (outputFile.isEmpty()) {
コード例 #18
0
ファイル: main.cpp プロジェクト: 151706061/QQStars
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    
    app.setApplicationName ("QQStars");
    app.setApplicationVersion ("1.0.0");
    app.setOrganizationName ("雨后星辰");
    app.setApplicationDisplayName ("星辰QQ");
    
    QTranslator *translator = new QTranslator;
    translator->load (":/qt_zh_CN.qm");
    QApplication::installTranslator (translator);
    
    QQmlApplicationEngine *engine = new QQmlApplicationEngine;
    engine->setNetworkAccessManagerFactory (new MyNetworkAccessManagerFactory());//给qml设置网络请求所用的类
    
    qmlRegisterType<TextEditPlayGif>("MyTextEditPlugin", 1, 0, "TextEditPlayGif");
    qmlRegisterType<MyWindow>("mywindow", 1,0, "MyQuickWindow");
    qmlRegisterType<SystemTrayIcon>("mywindow", 1,0, "MySystemTrayIcon");
    qmlRegisterType<MyMenu>("mywindow", 1,0, "MyMenu");
    qmlRegisterType<MenuSeparator>("mywindow", 1,0, "MenuSeparator");
    qmlRegisterType<MyMenuItem>("mywindow", 1,0, "MyMenuItem");
    qmlRegisterType<MyShortcut>("utility", 1,0, "MyShortcut");
    qmlRegisterType<DownloadImage>("utility", 1, 0, "DownloadImage");
    qmlRegisterType<QQCommand>("qqstars", 1,0, "QQ");
    qmlRegisterType<FriendInfo>("QQItemInfo", 1,0, "FriendInfo");
    qmlRegisterType<GroupInfo>("QQItemInfo", 1,0, "GroupInfo");
    qmlRegisterType<DiscuInfo>("QQItemInfo", 1,0, "DiscuInfo");
    qmlRegisterType<QQItemInfo>("QQItemInfo", 1,0, "QQItemInfo");
    qmlRegisterType<ChatMessageInfo>("QQItemInfo", 1, 0, "ChatMessageInfo");
    qmlRegisterType<ChatMessageInfoList>("QQItemInfo", 1, 0, "ChatMessageInfoList");
    qmlRegisterType<MyImage>("mywindow", 1,0, "MyImage");
    qmlRegisterType<MySvgView>("mywindow", 1, 0, "SvgView");
    qmlRegisterType<MyMessageBox>("mywindow", 1, 0, "MessageBox");
   
    Utility *utility=Utility::createUtilityClass ();
    QNetworkRequest* request = utility->getHttpRequest ()->getNetworkRequest ();
    request->setRawHeader ("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2");//和腾讯服务器打交道需要设置这个
    request->setHeader (QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    
    request = utility->getDownloadImage ()->getHttpRequest ()->getNetworkRequest ();
    request->setRawHeader ("Referer", "http://web2.qq.com/webqq.html");//需要设置这个,不然腾讯服务器不响应你的请求
    request->setRawHeader ("Accept", "image/webp,*/*;q=0.8");
    
    utility->initUtility (new QSettings, engine);
    
    QQmlComponent component0(engine, QUrl("qrc:/qml/Api/QQApi.qml"));
    QQCommand *qqapi = qobject_cast<QQCommand *>(component0.create ());

    engine->rootContext ()->setContextProperty ("myqq", qqapi);
    
    QQmlComponent component(engine, QUrl("qrc:/qml/Utility/SystemTray.qml"));
    SystemTrayIcon *systemTray = qobject_cast<SystemTrayIcon *>(component.create ());
#ifdef Q_OS_WIN
    systemTray->setParent (Utility::createUtilityClass ());//不设置父对象会导致程序退出后托盘还存在的问题
#endif
    engine->rootContext ()->setContextProperty ("systemTray", systemTray);//将程序托盘注册过去
    qqapi->loadLoginWindow ();//加载登录窗口
    
    return app.exec();
}
コード例 #19
0
ファイル: main.cpp プロジェクト: 0xB767B/LibrePCB
int main(int argc, char* argv[])
{
    Application app(argc, argv);

    // Set the organization / application names must be done very early because some other
    // classes will use these values (for example QSettings, Debug (for the file logging path))!
    Application::setOrganizationName("LibrePCB");
    Application::setOrganizationDomain("librepcb.org");
#ifdef GIT_BRANCH
    Application::setApplicationName(QString("LibrePCB_git-%1").arg(GIT_BRANCH));
#else
    Application::setApplicationName("LibrePCB");
#endif
    Application::setApplicationVersion(Version(QString("%1.%2.%3").arg(APP_VERSION_MAJOR).arg(APP_VERSION_MINOR).arg(APP_VERSION_PATCH)));


    Debug::instance(); // this creates the Debug object and installs the message handler.


    // Install Qt translations
    QTranslator qtTranslator;
    qtTranslator.load("qt_" % QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app.installTranslator(&qtTranslator);

    // Install system language translations (all system languages defined in the system settings, in the defined order)
    QTranslator systemTranslator;
    systemTranslator.load(QLocale::system(), "librepcb", "_", ":/i18n/");
    app.installTranslator(&systemTranslator);

    // Install language translations (like "de" for German)
    QTranslator appTranslator1;
    appTranslator1.load("librepcb_" % QLocale::system().name().split("_").at(0), ":/i18n");
    app.installTranslator(&appTranslator1);

    // Install language/country translations (like "de_ch" for German/Switzerland)
    QTranslator appTranslator2;
    appTranslator2.load("librepcb_" % QLocale::system().name(), ":/i18n");
    app.installTranslator(&appTranslator2);


    Application::setQuitOnLastWindowClosed(false);


    // this is to remove the ugly frames around widgets in all status bars...
    // (from http://www.qtcentre.org/threads/1904)
    app.setStyleSheet("QStatusBar::item { border: 0px solid black; }");



    // Initialization finished, open the workspace (or show the first run wizard)...
    FilePath wsPath(Workspace::getMostRecentlyUsedWorkspacePath());
    if (!Workspace::isValidWorkspacePath(wsPath))
    {
        FirstRunWizard wizard;
        if (wizard.exec() != QDialog::Accepted) return 0;
        wsPath = wizard.getWorkspaceFilePath();
        if (wizard.getCreateNewWorkspace())
        {
            if (!Workspace::createNewWorkspace(wsPath))
            {
                QMessageBox::critical(0, Application::translate("Workspace",
                    "Error"), Application::translate("Workspace", "Could not "
                    "create the workspace directory. Check file permissions."));
                return 0; // TODO: Show the wizard again instead of closing the application
            }
        }
        Workspace::setMostRecentlyUsedWorkspacePath(wsPath);
    }

    try
    {
        Workspace ws(wsPath);   // The Workspace constructor can throw an exception.
        ControlPanel p(ws);
        p.show();

        return appExec();
    }
    catch (UserCanceled& e)
    {
        return 0; // quit the application
    }
    catch (Exception& e)
    {
        QMessageBox::critical(0, Application::translate("Workspace",
            "Cannot open the workspace"), QString(Application::translate(
            "Workspace", "The workspace \"%1\" cannot be opened: %2"))
            .arg(wsPath.toNative(), e.getUserMsg()));
        return 0; // quit the application
    }

    return 0;
}
コード例 #20
0
int main(int argc, char *argv[])
{
#ifdef WIN32
    qInstallMsgHandler(myMessageOutput);
#endif
#if defined(Q_OS_MACX)
    // On Mac, switch working directory to resources folder
    CFURLRef pluginRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef macPath = CFURLCopyFileSystemPath(pluginRef, kCFURLPOSIXPathStyle);
    QString path( CFStringGetCStringPtr(macPath, CFStringGetSystemEncoding()) );
    path += "/Contents/Resources";
    QDir::setCurrent( path );
    CFRelease(pluginRef);
    CFRelease(macPath);
#elif defined(PO_DATA_REPO)
    QDir::setCurrent(PO_DATA_REPO);
#endif

    srand(time(NULL));
    try
    {
        //HotKeyClass HotKeyEvent;
        QApplication a(argc, argv);
        //a.installEventFilter(&HotKeyEvent);

        /* Names to use later for QSettings */
        QCoreApplication::setApplicationName("Pokeymon-Online");
        QCoreApplication::setOrganizationName("Dreambelievers");

        QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar);

        QSettings settings;
        if (settings.value("language").isNull()) {
            settings.setValue("language", QLocale::system().name().section('_', 0, 0));
        }

        QString locale = settings.value("language").toString();

        QTranslator translator;
        translator.load(QString("trans/translation_") + locale);
        a.installTranslator(&translator);

        /* icon ;) */
#if not defined(Q_OS_MACX)
        a.setWindowIcon(QIcon("db/icon.png"));
#endif

        MainEngine w;

        return a.exec();
    }  /*catch (const std::exception &e) {
        qDebug() << "Caught runtime " << e.what();
    } catch (const QString &s) {
        qDebug() << "Caught string " << s;
    } */catch (const char* s) {
        qDebug() << "Caught const char*  " << s;
    } /*catch (...) {
        qDebug() << "Caught Exception.";
    }*/
    return 0;
}
コード例 #21
0
ファイル: stopwatch.cpp プロジェクト: korha/_Other_
//-------------------------------------------------------------------------------------------------
StopWatch::StopWatch() : QWidget(),
    timer(new QTimer(this)),
    strFormat("m:ss.zzz"),
    iChop(1)
{
    const QString strAppName = qAppName(),
            strAppDir = qApp->applicationDirPath();
    QTranslator translator;
    if (translator.load(strAppName, strAppDir) || translator.load(strAppName + '_' + QLocale::system().name(), strAppDir))
        qApp->installTranslator(&translator);

    timer->setInterval(eIntervalMs);
    int iNumDigits = 8;

    //args
    const QStringList slistArgs = qApp->arguments();
    if (slistArgs.size() > 1)
        switch (slistArgs.at(1).toInt())
        {
        case 1:
        {
            strFormat = "hh:mm:ss";
            iChop = 0;
            //iNumDigits = 8;
            timer->setInterval(eIntervalSec);
            break;
        }
        case 2:
        {
            strFormat = "hh:mm:ss.zzz";
            iChop = 2;
            iNumDigits = 10;
            //timer->setInterval(eIntervalMs);
            break;
        }
        case 3:
        {
            strFormat = "hh:mm:ss.zzz";
            //iChop = 1;
            iNumDigits = 11;
            //timer->setInterval(eIntervalMs);
            break;
        }
        case 4:
        {
            strFormat = "hh:mm:ss.zzz";
            iChop = 0;
            iNumDigits = 12;
            //timer->setInterval(eIntervalMs);
            break;
        }
        case 5:
        {
            strFormat = "h:mm:ss";
            iChop = 0;
            //iNumDigits = 8;
            timer->setInterval(eIntervalSec);
            break;
        }
        case 6:
        {
            strFormat = "h:mm:ss.zzz";
            iChop = 2;
            iNumDigits = 10;
            //timer->setInterval(eIntervalMs);
            break;
        }
        case 7:
        {
            strFormat = "h:mm:ss.zzz";
            //iChop = 1;
            iNumDigits = 11;
            //timer->setInterval(eIntervalMs);
            break;
        }
        case 8:
        {
            strFormat = "h:mm:ss.zzz";
            iChop = 0;
            iNumDigits = 12;
            //timer->setInterval(eIntervalMs);
            break;
        }
        case 9:
        {
            strFormat = "mm:ss";
            iChop = 0;
            iNumDigits = 5;
            timer->setInterval(eIntervalSec);
            break;
        }
        case 10:
        {
            strFormat = "mm:ss.zzz";
            iChop = 2;
            iNumDigits = 7;
            //timer->setInterval(eIntervalMs);
            break;
        }
        case 11:
        {
            strFormat = "mm:ss.zzz";
            //iChop = 1;
            //iNumDigits = 8;
            //timer->setInterval(eIntervalMs);
            break;
        }
        case 12:
        {
            strFormat = "mm:ss.zzz";
            iChop = 0;
            iNumDigits = 9;
            //timer->setInterval(eIntervalMs);
            break;
        }
        case 13:
        {
            strFormat = "m:ss";
            iChop = 0;
            iNumDigits = 5;
            timer->setInterval(eIntervalSec);
            break;
        }
        case 14:
        {
            //strFormat = "m:ss.zzz";
            iChop = 2;
            iNumDigits = 7;
            //timer->setInterval(eIntervalMs);
            break;
        }
            //case 15:
            //{
            //strFormat = "m:ss.zzz";
            //iChop = 1;
            //iNumDigits = 8;
            //timer->setInterval(eIntervalMs);
            //break;
            //}
        case 16:
        {
            //strFormat = "m:ss.zzz";
            iChop = 0;
            iNumDigits = 9;
            //timer->setInterval(eIntervalMs);
            break;
        }
        }

    QString strTime = QTime(0, 0).toString(strFormat);
    strTime.chop(iChop);

    lcdNumb = new QLCDNumber(iNumDigits, this);
    lcdNumb->setFrameStyle(QFrame::NoFrame);
    lcdNumb->setFixedSize(eWidthDigitSegm*iNumDigits, eWidthDigitSegm*2);
    lcdNumb->display(strTime);
    pbStartStop = new QPushButton(style()->standardIcon(QStyle::SP_CommandLink), "Start", this);
    pbStartStop->setCheckable(true);
    pbCountdown = new QPushButton(style()->standardIcon(QStyle::SP_ArrowDown), "Countdown", this);
    pbCountdown->setEnabled(false);
    teList = new QPlainTextEdit(this);
    teList->setWordWrapMode(QTextOption::NoWrap);
    QPushButton *pbClean = new QPushButton(style()->standardIcon(QStyle::SP_DialogResetButton), "Clean", this);
    QVBoxLayout *vblMain = new QVBoxLayout(this);
    vblMain->addWidget(lcdNumb, 0, Qt::AlignHCenter);
    vblMain->addWidget(pbStartStop);
    vblMain->addWidget(pbCountdown);
    vblMain->addWidget(teList);
    vblMain->addWidget(pbClean);

    //connects
    connect(pbStartStop, SIGNAL(clicked()), this, SLOT(slotStartStop()));
    connect(pbCountdown, SIGNAL(clicked()), this, SLOT(slotCountdown()));
    connect(pbClean, SIGNAL(clicked()), teList, SLOT(clear()));
    connect(timer, SIGNAL(timeout()), this, SLOT(slotShowTime()));

    //settings
    this->restoreGeometry(QSettings("UserPrograms", strAppName).value("Geometry").toByteArray());
}
コード例 #22
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(guiclient);

  QString username;
  QString databaseURL;
  QString passwd;
  QString company;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;
  bool    haveEnhancedAuth= false;
  bool    _enhancedAuth   = false;
  bool    haveRequireSSL  = false;
  bool    _requireSSL     = false;
  bool    havePasswd      = false;
  bool    cloudOption     = false;
  bool    haveCloud       = false;

  qInstallMsgHandler(xTupleMessageOutput);
  QApplication app(argc, argv);

#if QT_VERSION >= 0x040400
  // This is the correct place for this call but on versions less
  // than 4.4 it causes a crash for an unknown reason so it is
  // called later on earlier versions.
  QCoreApplication::addLibraryPath(QString("."));
#endif

#ifndef Q_WS_MACX
  QApplication::setWindowIcon(QIcon(":/images/icon32x32.png"));
#endif

  // Try and load a default translation file and install it
  QTranslator defaultTranslator(&app);
  if (defaultTranslator.load("default.qm", app.applicationDirPath()))
    app.installTranslator(&defaultTranslator);

  app.processEvents();

  if (argc > 1)
  {
    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.contains("-databaseURL=", Qt::CaseInsensitive))
      {
        haveDatabaseURL = TRUE;
        databaseURL = argument.right(argument.length() - 13);
      }
      else if (argument.contains("-username="******"-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.contains("-noAuth", Qt::CaseInsensitive))
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      } 
      else if (argument.contains("-enhancedAuth", Qt::CaseInsensitive))
      {
        haveEnhancedAuth = true;
        _enhancedAuth = true;
        if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive))
          _enhancedAuth = false;
      }
      else if (argument.contains("-requireSSL", Qt::CaseInsensitive))
      {
        haveRequireSSL = true;
        _requireSSL = true;
        if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive))
          _requireSSL = false;
      }
      else if (argument.contains("-cloud", Qt::CaseInsensitive))
      {
        haveCloud = true;
        cloudOption = true;
        if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive))
          cloudOption = false;
      }
      else if (argument.contains("-company=", Qt::CaseInsensitive))
      {
        company = argument.right(argument.length() - 9);
      }
    }
  }

  _splash = new QSplashScreen();
  _splash->setPixmap(QPixmap(":/images/splashEmpty.png"));

  _evaluation = FALSE;

  if (!loggedIn)
  {
    ParameterList params;
    params.append("copyright", _Copyright);
    params.append("version", _Version);
    params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__));

    if (haveUsername)
      params.append("username", username);

    if (havePasswd)
      params.append("password", passwd);

    if (haveDatabaseURL)
      params.append("databaseURL", databaseURL);

    if (haveEnhancedAuth)
      params.append("enhancedAuth", _enhancedAuth);
    
    if (haveRequireSSL)
      params.append("requireSSL", _requireSSL);

    if (_evaluation)
      params.append("evaluation");

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
      params.append("login");

    if (haveCloud)
      params.append("cloud", cloudOption);

    if (!company.isEmpty())
      params.append("company", company);

    login2 newdlg(0, "", TRUE);
    newdlg.set(params, _splash);

    if(newdlg.result() != QDialog::Accepted)
    {
      if (newdlg.exec() == QDialog::Rejected)
        return -1;
      else
      {
        databaseURL = newdlg._databaseURL;
        username = newdlg.username();
        __password = newdlg.password();
        company = newdlg.company();
        cloudOption = newdlg.useCloud();
      }
    }
  }

  XSqlQuery metric;
  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'Application')" );
  if(!metric.first() || (metric.value("metric_value").toString() == "Standard"))
  {
    // check if the xtmfg package is installed
    metric.exec("SELECT pkghead_name FROM pkghead WHERE pkghead_name='xtmfg'");
    if(metric.first())
    {
      _splash->setPixmap(QPixmap(":/images/splashMfgEdition.png"));
      _Name = _Name.arg("Manufacturing");
    }
    else
    {
      _splash->setPixmap(QPixmap(":/images/splashStdEdition.png"));
      _Name = _Name.arg("Standard");
    }

    _splash->showMessage(QObject::tr("Checking License Key"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
    metric.exec("SELECT COUNT(*) as _count"
                "  FROM pg_stat_activity"
                " WHERE(datid IN (SELECT datid"
                "                   FROM pg_stat_activity"
                "                  WHERE(procpid=pg_backend_pid())));");
    int cnt = 50000;
    if(metric.first())
      cnt = metric.value("_count").toInt();
    metric.exec("SELECT metric_value"
                "  FROM metric"
                " WHERE(metric_name = 'RegistrationKey');");
    bool checkPass = true;
    QString checkPassReason;
    QString rkey = "";
    if(metric.first())
      rkey = metric.value("metric_value").toString();
    XTupleProductKey pkey(rkey);
    if(pkey.valid() && pkey.version() == 1)
    {
      if(pkey.expiration() < QDate::currentDate())
      {
        checkPass = false;
        checkPassReason = QObject::tr("Your license has expired.");
      }
      else if(pkey.users() != 0 && (pkey.users()+1) < cnt)
      {
        checkPass = false;
        checkPassReason = QObject::tr("You have exceeded the number of allowed concurrent users for your license.");
      }
    }
    else
    {
      checkPass = false;
      checkPassReason = QObject::tr("<p>The Registration key installed for this system does not appear to be valid.");
    }
    if(!checkPass)
    {
      _splash->hide();
      QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason);

      metric.exec("SELECT current_database() AS db,"
                  "       fetchMetricText('DatabaseName') AS dbname,"
                  "       fetchMetricText('remitto_name') AS name;");
      QString db = "";
      QString dbname = "";
      QString name = "";
      if(metric.first())
      {
        db = metric.value("db").toString();
        dbname = metric.value("dbname").toString();
        name = metric.value("name").toString();
      }

      QHttp *http = new QHttp();
      
      QUrl url;
      url.setPath("/api/regviolation.php");
      url.addQueryItem("key", QUrl::toPercentEncoding(rkey));
      url.addQueryItem("error", QUrl::toPercentEncoding(checkPassReason));
      url.addQueryItem("name", QUrl::toPercentEncoding(name));
      url.addQueryItem("dbname", QUrl::toPercentEncoding(dbname));
      url.addQueryItem("db", QUrl::toPercentEncoding(db));
      url.addQueryItem("cnt", QString::number(cnt));

      http->setHost("www.xtuple.org");
      http->get(url.toString());
      _splash->show();
    }
  }
  else
  {
    _splash->setPixmap(QPixmap(":/images/splashPostBooks.png"));
    _Name = _Name.arg("PostBooks");
  }

  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'ServerVersion')" );
  if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion))
  {
    bool disallowMismatch = false;
    metric.exec("SELECT metric_value FROM metric WHERE(metric_name='DisallowMismatchClientVersion')");
    if(metric.first() && (metric.value("metric_value").toString() == "t"))
      disallowMismatch = true;
    
    _splash->hide();
    int result;
    if(disallowMismatch)
      result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
        QObject::tr("<p>The version of the database you are connecting to is "
                    "not the version this client was designed to work against. "
                    "This client was designed to work against the database "
                    "version %1. The system has been configured to disallow "
                    "access in this case.<p>Please contact your systems "
                    "administrator.").arg(_dbVersion),
                 QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default );
    else
      result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
        QObject::tr("<p>The version of the database you are connecting to is "
                    "not the version this client was designed to work against. "
                    "This client was designed to work against the database "
                    "version %1. If you continue some or all functionality may "
                    "not work properly or at all. You may also cause other "
                    "problems on the database.<p>Do you want to continue "
                    "anyway?").arg(_dbVersion),
                 QMessageBox::Yes,
                 QMessageBox::No | QMessageBox::Escape | QMessageBox::Default );
    if(result != QMessageBox::Yes)
      return 0;
    _splash->show();
  }

  _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _metrics = new Metrics();

  _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _preferences = new Preferences(username);

  _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _privileges = new Privileges();

  // Load the translator and set the locale from the User's preferences
  _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  XSqlQuery langq("SELECT * "
                  "FROM usr, locale LEFT OUTER JOIN"
                  "     lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN"
                  "     country ON (locale_country_id=country_id) "
                  "WHERE ( (usr_username=CURRENT_USER)"
                  " AND (usr_locale_id=locale_id) );" );
  if (langq.first())
  {
    QStringList files;
    if (!langq.value("locale_lang_file").toString().isEmpty())
      files << langq.value("locale_lang_file").toString();

    QString langext;
    if (!langq.value("lang_abbr2").toString().isEmpty() && 
        !langq.value("country_abbr").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString() + "_" +
                langq.value("country_abbr").toString().toLower();
    }
    else if (!langq.value("lang_abbr2").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString();
    }

    if(!langext.isEmpty())
    {
      files << "xTuple";
      files << "openrpt";
      files << "reports";

      XSqlQuery pkglist("SELECT pkghead_name"
                        "  FROM pkghead"
                        " WHERE packageIsEnabled(pkghead_name);");
      while(pkglist.next())
        files << pkglist.value("pkghead_name").toString();
    }

    if (files.size() > 0)
    {
      QStringList notfound;
      QTranslator *translator = new QTranslator(&app);
      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        if (DEBUG)
          qDebug("looking for %s", (*fit).toAscii().data());
        if (translator->load(translationFile(langext, *fit)))
        {
          app.installTranslator(translator);
          qDebug("installed %s", (*fit).toAscii().data());
          translator = new QTranslator(&app);
        }
        else
          notfound << *fit;
      }

      if (! notfound.isEmpty() &&
          !_preferences->boolean("IngoreMissingTranslationFiles"))
        QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"),
                              QObject::tr("<p>The Translation Dictionaries %1 "
                                          "cannot be loaded. Reverting "
                                          "to the default dictionary." )
                                       .arg(notfound.join(QObject::tr(", "))));
    }

    /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or
       lang#, depending on what information is available
     */
    QString langAbbr = langq.value("lang_abbr2").toString();
    QString cntryAbbr = langq.value("country_abbr").toString().toUpper();
    if(cntryAbbr == "UK")
      cntryAbbr = "GB";
    if (! langAbbr.isEmpty() &&
        ! cntryAbbr.isEmpty())
      QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr));
    else if (! langAbbr.isEmpty())
      QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString()));
    else if (langq.value("lang_qt_number").toInt() &&
             langq.value("country_qt_number").toInt())
      QLocale::setDefault(
          QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()),
                  QLocale::Country(langq.value("country_qt_number").toInt())));
    else
      QLocale::setDefault(QLocale::system());

    qDebug("Locale set to language %s and country %s",
           QLocale().languageToString(QLocale().language()).toAscii().data(),
           QLocale().countryToString(QLocale().country()).toAscii().data());

  }
  else if (langq.lastError().type() != QSqlError::NoError)
  {
    systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__);
  }

  qApp->processEvents();
  QString key;

  // TODO: Add code to check a few locations - Hopefully done

  QString keypath;
  QString keyname;
  QString keytogether;
  
#ifdef Q_WS_WIN
  keypath = _metrics->value("CCWinEncKey");
#elif defined Q_WS_MACX
  keypath = _metrics->value("CCMacEncKey");
#elif defined Q_WS_X11
  keypath = _metrics->value("CCLinEncKey");
#endif
  
  if (keypath.isEmpty())
    keypath = app.applicationDirPath();

  if (! keypath.endsWith(QDir::separator()))
    keypath += QDir::separator();

  keyname = _metrics->value("CCEncKeyName");
  if (keyname.isEmpty())
  {
    keyname = "xTuple.key";
    keytogether = keypath + keyname;
    QFile kn(keytogether);
    if(!kn.exists())
      keyname = "OpenMFG.key";
  }
  
  keytogether = keypath + keyname;
  
  // qDebug("keytogether: %s", keytogether.toAscii().data());
  QFile keyFile(keytogether);

  if(keyFile.exists())
  {
    if(keyFile.open(QIODevice::ReadOnly))
    {
      key = keyFile.readLine(1024);
      // strip off any newline characters
      key = key.trimmed();
    }
  }

  omfgThis = 0;
  omfgThis = new GUIClient(databaseURL, username);
  omfgThis->_key = key;
  omfgThis->_company = company;
  omfgThis->_useCloud = cloudOption;

// qDebug("Encryption Key: %s", key.toAscii().data() );
  
  if (key.length() > 0) {
	_splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor);
	qApp->processEvents();
	_metricsenc = new Metricsenc(key);
  }
  
  initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace());

// START code for updating the locale settings if they haven't been already
  XSqlQuery lc;
  lc.exec("SELECT count(*) FROM metric WHERE metric_name='AutoUpdateLocaleHasRun';");
  lc.first();
  if(lc.value(0).toInt() == 0)
  {
    lc.exec("INSERT INTO metric (metric_name, metric_value) values('AutoUpdateLocaleHasRun', 't');");
    lc.exec("SELECT locale_id from locale;");
    while(lc.next())
    {
      ParameterList params;
      params.append("mode","edit");
      params.append("locale_id", lc.value(0));
      sysLocale lcdlg;
      lcdlg.set(params);
      lcdlg.sSave();
    }
  }
// END code for updating locale settings

  QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows()));
  if (omfgThis->_singleWindow.isEmpty())
  {
    omfgThis->setAttribute(Qt::WA_DeleteOnClose);
    omfgThis->show();
  }
  // keep this synchronized with GUIClient and user.ui.h
  else if (omfgThis->_singleWindow == "woTimeClock")
  {
    ScriptToolbox sb(0);
    QWidget* newdlg = sb.openWindow("woTimeClock");
    if(newdlg)
    {
      XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg);
      if(mw)
      {
        ParameterList params;
        params.append("captive");
        mw->set(params);
      }
      newdlg->setAttribute(Qt::WA_DeleteOnClose);
      QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit()));
      newdlg->show();
    }
    else
    {
コード例 #23
0
/*!
    Constructor.
*/
NmApplication::NmApplication(int &argc, char *argv[], Hb::ApplicationFlags flags)
: HbApplication(argc,argv,flags),
  mMainWindow(NULL),
  mViewStack(NULL),
  mActiveViewId(NmUiViewNone),
  mUiEngine(NULL),
  mBackAction(NULL),
  mExtensionManager(NULL),
  mMbListModel(NULL),
  mServiceViewId(NmUiViewNone),
  mForegroundService(false),
  mEffects(NULL),
  mAttaManager(NULL),
  mSettingsViewLauncher(NULL),
  mViewReady(false),
  mQueryDialog(NULL),
  mBackButtonPressed(false),
  mApplicationHidden(false),
  mErrorNoteTimer(NULL),
  mActivation(NULL),
  mActivityStorage(NULL)
{
    // Load the translation file.
    QTranslator *translator = new QTranslator(this);
    QString lang = QLocale::system().name();
    QString appName = "mail_";
    QString path = "Z:/resource/qt/translations/";
    translator->load(appName + lang, path);
    installTranslator(translator);
    setApplicationName(hbTrId("txt_mail_title_mail"));
    
    mActivation = new AfActivation(this);
    mActivityStorage = new AfActivityStorage(this);
    
    quint64 accountId = 0;
    QString activateId = this->activateId();
    if (mActivation->reason() == Af::ActivationReasonActivity &&
        activateId.startsWith(NmActivityName) ) {
        QString accountIdString = activateId.mid(NmActivityName.length());
        accountId = accountIdString.toULongLong();
    }
            
    TRAP_IGNORE(mUiEngine = NmUiEngine::instance());
        
    // Create network access manager and cache for application use.
    mNetManager = new NmViewerViewNetManager(*mUiEngine);
    QNetworkDiskCache *cache = new QNetworkDiskCache();
    cache->setCacheDirectory(
        QDesktopServices::storageLocation(QDesktopServices::CacheLocation));
    mNetManager->setCache(cache);
    
    createMainWindow();
    
    // Attachment manager can be shared between viewer and editor.
    // The application class has the ownership.
    mAttaManager = new NmAttachmentManager(*mUiEngine);
    
    mSendServiceInterface =
        new NmSendServiceInterface(NmSendServiceName, NULL, *mUiEngine, this);
    mSendServiceInterface2 =
        new NmSendServiceInterface(emailFullServiceNameSend, NULL, *mUiEngine, this);
    mUriServiceInterface =
        new NmUriServiceInterface(NULL, *mUiEngine, this);
    mMailboxServiceInterface =
        new NmMailboxServiceInterface(NULL, *mUiEngine, this);
    mViewerServiceInterface =
        new NmViewerServiceInterface(NULL, this, *mUiEngine);
    
    if(accountId != 0) {
        QVariant mailbox;
        mailbox.setValue(accountId);
        mMailboxServiceInterface->displayInboxByMailboxId(mailbox);
    }
    
    mEffects = new NmUiEffects(*mMainWindow);
    
    QObject::connect(
            mActivation, SIGNAL(activated(Af::ActivationReason, QString, QVariantHash)), 
            this, SLOT(activityActivated()));
}
コード例 #24
0
ファイル: main.cpp プロジェクト: tynn/H4KvT
int main(int argc, char **argv)
{
	Vals vals;

	/* the application */
	QApplication app(argc, argv);
	app.setApplicationName(APP_NAME);
	app.setWindowIcon(QIcon(":/icon"));
	Window window;

	/* translations */
	QTranslator qtr;
	if (qtr.load("qt_" + QLocale::system().name(), QTR_PATH))
		app.installTranslator(&qtr);

	QTranslator htr;
	if (htr.load("H4KvT_" + QLocale::system().name(), ":/"))
		app.installTranslator(&htr);

	/* display information */
	QTextEdit *text = new QTextEdit;
	text->setReadOnly(true);
	text->setLineWrapMode(QTextEdit::NoWrap);
	text->setToolTip(Window::tr("Drop any file for hashing"));
	QObject::connect(&window, &Window::idle, text, &QWidget::setEnabled);

	/* compare hash */
	QLineEdit *test = new QLineEdit;
	HexVal hexval;
	test->setValidator(&hexval);
	test->installEventFilter(&window);
	test->setToolTip(Window::tr("Compare hashes"));

	QObject::connect(test, &QLineEdit::textChanged,
		[&](const QString &newValue) { if (vals.name != "") {
			std::string hashVal = newValue.toStdString();
			std::transform(hashVal.begin(), hashVal.end(), hashVal.begin(), ::tolower);
			std::stringstream html;
			if (hashVal != "")
				html << "<style>.h" << hashVal << "{color:green}</style>";
			html << "<div style='margin-bottom:2; font-size:27px'><i><b>" << vals.name << "</b></i></div>";
			html << "<div style='margin-bottom:7; margin-left:23; font-size:13px'>" << vals.path << "</div>";
			if (!ALL(vals,"")) {
				html << "<div style='font-size:13px'><table>";
				if (vals.md5 != "")
					html << "<tr><td>md5: </td><td class='h" << vals.md5 << "'>" << vals.md5 << "</td</tr>";
				if (vals.sha1 != "")
					html << "<tr><td>sha1: </td><td class='h" << vals.sha1 << "'>" << vals.sha1 << "</td</tr>";
				if (vals.sha224 != "")
					html << "<tr><td>sha224: </td><td class='h" << vals.sha224 << "'>" << vals.sha224 << "</td</tr>";
				if (vals.sha256 != "")
					html << "<tr><td>sha256: </td><td class='h" << vals.sha256 << "'>" << vals.sha256 << "</td</tr>";
				if (vals.sha384 != "")
					html << "<tr><td>sha384: </td><td class='h" << vals.sha384 << "'>" << vals.sha384 << "</td</tr>";
				if (vals.sha512 != "")
					html << "<tr><td>sha512: </td><td class='h" << vals.sha512 << "'>" << vals.sha512 << "</td</tr>";
				html << "</table></div>";
			}
			int horizontal = text->horizontalScrollBar()->value();
			int vertical = text->verticalScrollBar()->value();
			text->setHtml(QString::fromStdString(html.str()));
			text->horizontalScrollBar()->setValue(horizontal);
			text->verticalScrollBar()->setValue(vertical);
			test->setStyleSheet(ANY(vals,hashVal) ? "color:green" : "");
		}});

	/* error messages */
	QLabel *error = new QLabel;
	error->setStyleSheet("color:red");

	/* test or error */
	QStackedWidget *stack = new QStackedWidget;
	delete stack->layout();
	stack->setLayout(new Stack);
	stack->addWidget(error);
	stack->addWidget(test);
	stack->setCurrentIndex(1);

	/* toggle test or error */
	QPushButton *hash = new QPushButton(QIcon(":/icon"), "");
	hash->setCheckable(true);
	hash->setChecked(true);
	hash->setToolTip(Window::tr("Compare hashes"));
	QObject::connect(hash, &QPushButton::toggled, stack, &QStackedWidget::setCurrentIndex);

	/* store method */
	QSettings settings("H4KvT", "H4KvT");

	/* more methods */
	bool more;
	try {
		settings.setValue("MoreHashingMethods", more = moreOrLess());
	} catch (...) {
		more = settings.value("MoreHashingMethods", false).toBool();
	}

	/* hashing method */
	QComboBox *meth = new QComboBox;
	meth->addItem("md5");
	meth->addItem("sha1");
	if (more) meth->addItem("sha224");
	meth->addItem("sha256");
	if (more) meth->addItem("sha384");
	meth->addItem("sha512");
	meth->setToolTip(Window::tr("Hashing method"));
	meth->setCurrentText(settings.value("HashingMethod", "md5").toString());
	QObject::connect(&window, &Window::idle, meth, &QWidget::setEnabled);

	QObject::connect(meth, &QComboBox::currentTextChanged,
		[&](const QString &text) { settings.setValue("HashingMethod", text); });

	/* toolbar */
	QHBoxLayout *pane = new QHBoxLayout;
	pane->addWidget(hash, 0, Qt::AlignLeft);
	pane->addWidget(stack);
	pane->addWidget(meth, 0, Qt::AlignRight);

	/* main layout */
	QVBoxLayout *layout = new QVBoxLayout;
	layout->addWidget(text);
	layout->addLayout(pane);

	/* the window */
	window.centralWidget()->setLayout(layout);
	window.show();

	/* future hashing */
	QFutureWatcher<Vals> zu;
	QObject::connect(&zu, &QFutureWatcher<Vals>::finished,
		[&]() {
			Vals valsi = zu.future().result();
			window.idle(true);
			if (valsi.path == "") {
				error->setText(QString::fromStdString(valsi.name));
				hash->setChecked(false);
			} else {
				error->clear();
				vals += valsi;
				test->textChanged(test->text());
			}
		});

	QObject::connect(meth, &QComboBox::currentTextChanged,
		[&](const QString &text) { if (vals.name != "") {
			window.idle(false);
			zu.setFuture(QtConcurrent::run(&update, text, vals));
		}});

	QObject::connect(&window, &Window::fileDroped,
		[&](const QString &name, const QString &path) {
			window.idle(false);
			zu.setFuture(QtConcurrent::run(&update, meth->currentText(), Vals(name, path)));
		});

	/* hashing info */
	QGraphicsBlurEffect blur;
	blur.setBlurHints(QGraphicsBlurEffect::AnimationHint);

	QPropertyAnimation anim(&blur, "blurRadius");
	anim.setDuration(2000);
	anim.setLoopCount(-1);
	anim.setKeyValueAt(0, 0);
	anim.setKeyValueAt(0.5, 3);
	anim.setKeyValueAt(1, 0);

	QLabel *hashing = new QLabel;
	hashing->setPixmap(QPixmap(":/icon"));
	hashing->setAttribute(Qt::WA_TransparentForMouseEvents);
	hashing->setGraphicsEffect(&blur);
	hashing->hide();
	(new QHBoxLayout(text))->addWidget(hashing, 0, Qt::AlignCenter);

	QObject::connect(&blur, &QGraphicsBlurEffect::blurRadiusChanged,
		hashing, static_cast<void(QWidget::*)()>(&QWidget::update));

	QObject::connect(&window, &Window::idle,
		[&](bool idle) {
			if (idle) {
				hashing->hide();
				anim.stop();
			} else {
				hashing->show();
				anim.start();
			}
		});

	/* about app */
	QMenu about;
	QAction *action = about.addAction(QIcon(":/icon"), Window::tr("About %1").arg(APP_NAME));
	action->setMenuRole(QAction::AboutRole);
	QObject::connect(action, &QAction::triggered, &window, &Window::about);

	error->setContextMenuPolicy(Qt::NoContextMenu);
	hash->setContextMenuPolicy(Qt::NoContextMenu);
	meth->setContextMenuPolicy(Qt::NoContextMenu);
	window.setContextMenuPolicy(Qt::CustomContextMenu);
	QObject::connect(&window, &QWidget::customContextMenuRequested,
		[&about, &window](const QPoint &pos) { about.popup(window.mapToGlobal(pos)); });

	text->setContextMenuPolicy(Qt::CustomContextMenu);
	QObject::connect(text, &QWidget::customContextMenuRequested,
		[action, text](const QPoint &pos) {
			if (QMenu *m = text->createStandardContextMenu()) {
				m->insertAction(m->insertSeparator(m->actions()[0]), action);
				m->popup(text->mapToGlobal(pos));
			}
		});

	test->setContextMenuPolicy(Qt::CustomContextMenu);
	QObject::connect(test, &QWidget::customContextMenuRequested,
		[action, test](const QPoint &pos) {
			if (QMenu *m = test->createStandardContextMenu()) {
				m->insertAction(m->insertSeparator(m->actions()[0]), action);
				m->popup(test->mapToGlobal(pos));
			}
		});

	return app.exec();
}
コード例 #25
0
ファイル: main.cpp プロジェクト: JosefMeixner/opentoonz
int main(int argc, char *argv[])
{
#ifdef Q_OS_WIN
	//  Enable standard input/output on Windows Platform for debug
	BOOL consoleAttached = ::AttachConsole(ATTACH_PARENT_PROCESS);
	if (consoleAttached) {
		freopen("CON", "r", stdin);
		freopen("CON", "w", stdout);
		freopen("CON", "w", stderr);
	}
#endif

	/*-- "-layout [レイアウト設定ファイル名]" で、必要なモジュールのPageだけのレイアウトで起動することを可能にする --*/
	QString argumentLayoutFileName = "";
	TFilePath loadScenePath;
	if (argc > 1) {
		for (int a = 1; a < argc; a++) {
			if (QString(argv[a]) == "-layout") {
				argumentLayoutFileName = QString(argv[a + 1]);
				a++;
			} else
				loadScenePath = TFilePath(argv[a]);
		}
	}

	QApplication a(argc, argv);

#ifdef Q_OS_WIN
	//	Since currently OpenToonz does not work with OpenGL of software or angle,
	//	force Qt to use desktop OpenGL
	a.setAttribute(Qt::AA_UseDesktopOpenGL, true);
#endif

	// Some Qt objects are destroyed badly withouth a living qApp. So, we must enforce a way to either
	// postpone the application destruction until the very end, OR ensure that sensible objects are
	// destroyed before.

	// Using a static QApplication only worked on Windows, and in any case C++ respects the statics destruction
	// order ONLY within the same library. On MAC, it made the app crash on exit o_o. So, nope.

	std::auto_ptr<QObject> mainScope(new QObject(&a)); // A QObject destroyed before the qApp is therefore explicitly
	mainScope->setObjectName("mainScope");			   // provided. It can be accessed by looking in the qApp's children.

#ifdef _WIN32
#ifndef x64
	//Store the floating point control word. It will be re-set before Toonz initialization
	//has ended.
	unsigned int fpWord = 0;
	_controlfp_s(&fpWord, 0, 0);
#endif
#endif

#ifdef _WIN32
	//At least on windows, Qt's 4.5.2 native windows feature tend to create
	//weird flickering effects when dragging panel separators.
	a.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
#endif

	//Set the app's locale for numeric stuff to standard C. This is important for atof() and similar
	//calls that are locale-dependant.
	setlocale(LC_NUMERIC, "C");

// Set current directory to the bundle/application path - this is needed to have correct relative paths
#ifdef MACOSX
	{
		QDir appDir(QApplication::applicationDirPath());
		appDir.cdUp(), appDir.cdUp(), appDir.cdUp();

		bool ret = QDir::setCurrent(appDir.absolutePath());
		assert(ret);
	}
#endif

	// splash screen
	QPixmap splashPixmap(":Resources/splash.png");
#ifdef _WIN32
	a.setFont(QFont("Arial", 10));
#else
	a.setFont(QFont("Helvetica", 10));
#endif

	QString offsetStr("\n\n\n\n\n\n\n\n");

	TSystem::hasMainLoop(true);

	TMessageRepository::instance();

	QSplashScreen splash(splashPixmap);
	splash.show();
	a.processEvents();

	splash.showMessage(offsetStr + "Initializing QGLFormat...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// OpenGL
	QGLFormat fmt;
	fmt.setAlpha(true);
	fmt.setStencil(true);
	QGLFormat::setDefaultFormat(fmt);

#ifdef LINUX
	glutInit(&argc, argv);
#endif

	splash.showMessage(offsetStr + "Initializing Toonz environment ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	//Install run out of contiguous memory callback
	TBigMemoryManager::instance()->setRunOutOfContiguousMemoryHandler(&toonzRunOutOfContMemHandler);

	// Toonz environment
	initToonzEnv();

	// Initialize thread components
	TThread::init();

	TProjectManager *projectManager = TProjectManager::instance();
	if (Preferences::instance()->isSVNEnabled()) {
		// Read Version Control repositories and add it to project manager as "special" svn project root
		VersionControl::instance()->init();
		QList<SVNRepository> repositories = VersionControl::instance()->getRepositories();
		int count = repositories.size();
		for (int i = 0; i < count; i++) {
			SVNRepository r = repositories.at(i);

			TFilePath localPath(r.m_localPath.toStdWString());
			if (!TFileStatus(localPath).doesExist()) {
				try {
					TSystem::mkDir(localPath);
				} catch (TException &e) {
					fatalError(QString::fromStdWString(e.getMessage()));
				}
			}
			projectManager->addSVNProjectsRoot(localPath);
		}
	}

#if defined(MACOSX) && defined(__LP64__)

	//Load the shared memory settings
	int shmmax = Preferences::instance()->getShmMax();
	int shmseg = Preferences::instance()->getShmSeg();
	int shmall = Preferences::instance()->getShmAll();
	int shmmni = Preferences::instance()->getShmMni();

	if (shmall < 0) //Make sure that at least 100 MB of shared memory are available
		shmall = (tipc::shm_maxSharedPages() < (100 << 8)) ? (100 << 8) : -1;

	tipc::shm_set(shmmax, shmseg, shmall, shmmni);

#endif

	// DVDirModel must be instantiated after Version Control initialization...
	FolderListenerManager::instance()->addListener(DvDirModel::instance());

	splash.showMessage(offsetStr + "Loading Translator ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// Carico la traduzione contenuta in toonz.qm (se � presente)
	QString languagePathString = QString::fromStdString(toString(TEnv::getConfigDir() + "loc"));
#ifndef WIN32
	//the merge of menu on osx can cause problems with different languages with the Preferences menu
	//qt_mac_set_menubar_merge(false);
	languagePathString += "/" + Preferences::instance()->getCurrentLanguage();
#else
	languagePathString += "\\" + Preferences::instance()->getCurrentLanguage();
#endif
	QTranslator translator;
#ifdef LINETEST
	translator.load("linetest", languagePathString);
#else
	translator.load("toonz", languagePathString);
#endif

	// La installo
	a.installTranslator(&translator);

	// Carico la traduzione contenuta in toonzqt.qm (se e' presente)
	QTranslator translator2;
	translator2.load("toonzqt", languagePathString);
	a.installTranslator(&translator2);

	// Carico la traduzione contenuta in tnzcore.qm (se e' presente)
	QTranslator tnzcoreTranslator;
	tnzcoreTranslator.load("tnzcore", languagePathString);
	qApp->installTranslator(&tnzcoreTranslator);

	// Carico la traduzione contenuta in toonzlib.qm (se e' presente)
	QTranslator toonzlibTranslator;
	toonzlibTranslator.load("toonzlib", languagePathString);
	qApp->installTranslator(&toonzlibTranslator);

	// Carico la traduzione contenuta in colorfx.qm (se e' presente)
	QTranslator colorfxTranslator;
	colorfxTranslator.load("colorfx", languagePathString);
	qApp->installTranslator(&colorfxTranslator);

	// Carico la traduzione contenuta in tools.qm
	QTranslator toolTranslator;
	toolTranslator.load("tnztools", languagePathString);
	qApp->installTranslator(&toolTranslator);

	// Aggiorno la traduzione delle properties di tutti i tools
	TTool::updateToolsPropertiesTranslation();

	splash.showMessage(offsetStr + "Loading styles ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// stile
	QApplication::setStyle("windows");

	IconGenerator::setFilmstripIconSize(Preferences::instance()->getIconSize());

	splash.showMessage(offsetStr + "Loading shaders ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	loadShaderInterfaces(ToonzFolder::getLibraryFolder() + TFilePath("shaders"));

	splash.showMessage(offsetStr + "Initializing Toonz application ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	TTool::setApplication(TApp::instance());
	TApp::instance()->init();

//iwsw commented out temporarily
#if 0 
  QStringList monitorNames;
  /*-- 接続モニタがPVM-2541の場合のみLUTを読み込む --*/
  if (Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
  {
	  /*-- 接続モニタがPVM-2541の場合のみLUTを読み込む --*/
	  monitorNames = Ghibli3DLutUtil::getMonitorName();
	  if (monitorNames.contains(QString::fromStdWString(L"PVM-2541")))
		  /*-- 3DLUTファイルを読み込む --*/
		  Ghibli3DLutUtil::loadLutFile(Preferences::instance()->get3DLutPath());
  }
  /*-- 接続モニタをスプラッシュ画面にも表示 --*/
  if (!monitorNames.isEmpty())
  {
	  lastUpdateStr += QString("Monitor Name : ");
	  for (int mn = 0; mn < monitorNames.size(); mn++)
	  {
		  if (mn != 0)
			  lastUpdateStr += QString(", ");
		  lastUpdateStr += monitorNames.at(mn);
	  }
	  lastUpdateStr += QString("\n");
  }
#endif

	splash.showMessage(offsetStr + "Loading Plugins...", Qt::AlignCenter, Qt::white);
	a.processEvents();
	/* poll the thread ends: 
	 絶対に必要なわけではないが PluginLoader は中で setup ハンドラが常に固有のスレッドで呼ばれるよう main thread queue の blocking をしているので
	 processEvents を行う必要がある
   */
	while (!PluginLoader::load_entries("")) {
		a.processEvents();
	}

	splash.showMessage(offsetStr + "Creating main window ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	/*-- Layoutファイル名をMainWindowのctorに渡す --*/
	MainWindow w(argumentLayoutFileName);

	splash.showMessage(offsetStr + "Loading style sheet ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// Carico lo styleSheet
	QString currentStyle = Preferences::instance()->getCurrentStyleSheet();
	a.setStyleSheet(currentStyle);

	TApp::instance()->setMainWindow(&w);
	w.setWindowTitle(applicationFullName);

	splash.showMessage(offsetStr + "Starting main window ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	TFilePath fp = ToonzFolder::getModuleFile("mainwindow.ini");
	QSettings settings(toQString(fp), QSettings::IniFormat);
	w.restoreGeometry(settings.value("MainWindowGeometry").toByteArray());

#ifndef MACOSX
	//Workaround for the maximized window case: Qt delivers two resize events, one in the normal geometry, before
	//maximizing (why!?), the second afterwards - all inside the following show() call. This makes troublesome for
	//the docking system to correctly restore the saved geometry. Fortunately, MainWindow::showEvent(..) gets called
	//just between the two, so we can disable the currentRoom layout right before showing and re-enable it after
	//the normal resize has happened.
	if (w.isMaximized())
		w.getCurrentRoom()->layout()->setEnabled(false);
#endif

	QRect splashGeometry = splash.geometry();
	splash.finish(&w);

	a.setQuitOnLastWindowClosed(false);
// a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
	w.checkForUpdates();

	w.show();

	//Show floating panels only after the main window has been shown
	w.startupFloatingPanels();

	CommandManager::instance()->execute(T_Hand);
	if (!loadScenePath.isEmpty()) {
		splash.showMessage(QString("Loading file '") + loadScenePath.getQString() + "'...", Qt::AlignCenter, Qt::white);

		loadScenePath = loadScenePath.withType("tnz");
		if (TFileStatus(loadScenePath).doesExist())
			IoCmd::loadScene(loadScenePath);
	}

	QFont *myFont;

	std::string family = EnvSoftwareCurrentFont;
	myFont = new QFont(QString(family.c_str()));

	myFont->setPixelSize(EnvSoftwareCurrentFontSize);
	/*-- フォントのBoldの指定 --*/
	std::string weight = EnvSoftwareCurrentFontWeight;
	if (strcmp(weight.c_str(), "Yes") == 0)
		myFont->setBold(true);
	else
		myFont->setBold(false);
	a.setFont(*myFont);

	QAction *action = CommandManager::instance()->getAction("MI_OpenTMessage");
	if (action)
		QObject::connect(TMessageRepository::instance(), SIGNAL(openMessageCenter()), action, SLOT(trigger()));

	QObject::connect(
		TUndoManager::manager(), SIGNAL(somethingChanged()),
		TApp::instance()->getCurrentScene(), SLOT(setDirtyFlag()));

#ifdef _WIN32
#ifndef x64
	//On 32-bit architecture, there could be cases in which initialization could alter the
	//FPU floating point control word. I've seen this happen when loading some AVI coded (VFAPI),
	//where 80-bit internal precision was used instead of the standard 64-bit (much faster and
	//sufficient - especially considering that x86 truncates to 64-bit representation anyway).
	//IN ANY CASE, revert to the original control word.
	//In the x64 case these precision changes simply should not take place up to _controlfp_s
	//documentation.
	_controlfp_s(0, fpWord, -1);
#endif
#endif

	a.installEventFilter(TApp::instance());

	int ret = a.exec();

	TUndoManager::manager()->reset();
	PreviewFxManager::instance()->reset();

#ifdef _WIN32
	if (consoleAttached) {
		::FreeConsole();
	}
#endif

	return ret;
}
コード例 #26
0
ファイル: main.cpp プロジェクト: coolshahabaz/trunk
int main(int argc, char **argv)
{
	//See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions
	/** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory
		on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to
		ensure that resource sharing between contexts stays functional as all internal contexts are created
		using the correct version and profile.
	**/
	{
		QSurfaceFormat format = QSurfaceFormat::defaultFormat();
		format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
		format.setOption(QSurfaceFormat::StereoBuffers, true);
		format.setStencilBufferSize(0);
#ifdef CC_GL_WINDOW_USE_QWINDOW
		format.setStereo(true);
#endif
#ifdef Q_OS_MAC
		format.setStereo(false);
		format.setVersion( 2, 1 );
		format.setProfile( QSurfaceFormat::CoreProfile );
#endif
#ifdef QT_DEBUG
		format.setOption(QSurfaceFormat::DebugContext, true);
#endif
		QSurfaceFormat::setDefaultFormat(format);
	}

	//The 'AA_ShareOpenGLContexts' attribute must be defined BEFORE the creation of the Q(Gui)Application
	//DGM: this is mandatory to enable exclusive full screen for ccGLWidget (at least on Windows)
	QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);

	//QT initialiation
	qccApplication app(argc, argv);

	//Locale management
	{
		//Force 'english' locale so as to get a consistent behavior everywhere
		QLocale locale = QLocale(QLocale::English);
		locale.setNumberOptions(QLocale::c().numberOptions());
		QLocale::setDefault(locale);

#ifdef Q_OS_UNIX
		//We reset the numeric locale for POSIX functions
		//See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings
		setlocale(LC_NUMERIC, "C");
#endif
	}

#ifdef USE_VLD
	VLDEnable();
#endif

#ifdef Q_OS_MAC	
	// This makes sure that our "working directory" is not within the application bundle
	QDir  appDir = QCoreApplication::applicationDirPath();
	
	if ( appDir.dirName() == "MacOS" )
	{
		appDir.cdUp();
		appDir.cdUp();
		appDir.cdUp();
		
		QDir::setCurrent( appDir.absolutePath() );
	}
#endif

	//store the log message until a valid logging instance is registered
	ccLog::EnableMessageBackup(true);
	
	//restore some global parameters
	{
		QSettings settings;
		settings.beginGroup(ccPS::GlobalShift());
		double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble();
		double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble();
		settings.endGroup();

		ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0));
		
		ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord);
		ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag);
	}

	//Command line mode?
	bool commandLine = (argc > 1 && argv[1][0] == '-');
	
	//specific commands
	int lastArgumentIndex = 1;
	QTranslator translator;
	if (commandLine)
	{
		//translation file selection
		if (QString(argv[lastArgumentIndex]).toUpper() == "-LANG")
		{
			QString langFilename = QString(argv[2]);

			//Load translation file
			if (translator.load(langFilename, QCoreApplication::applicationDirPath()))
			{
				qApp->installTranslator(&translator);
			}
			else
			{
				QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename));
			}
			commandLine = false;
			lastArgumentIndex += 2;
		}
	}

	//splash screen
	QSplashScreen* splash = 0;
	QTime splashStartTime;

	//standard mode
	if (!commandLine)
	{
		if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0)
		{
			QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!");
			return EXIT_FAILURE;
		}

		//splash screen
		splashStartTime.start();
		QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png"));
		splash = new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint);
		splash->show();
		QApplication::processEvents();
	}

	//global structures initialization
	FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!)
	ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization
	ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization

	//load the plugins
	tPluginInfoList plugins;
	QStringList dirFilters;
	QStringList pluginPaths;
	{
		QString appPath = QCoreApplication::applicationDirPath();

#if defined(Q_OS_MAC)
		dirFilters << "*.dylib";

		// plugins are in the bundle
		appPath.remove("MacOS");

		pluginPaths += (appPath + "Plugins/ccPlugins");
#if defined(CC_MAC_DEV_PATHS)
		// used for development only - this is the path where the plugins are built
		// this avoids having to install into the application bundle when developing
		pluginPaths += (appPath + "../../../ccPlugins");
#endif
#elif defined(Q_OS_WIN)
		dirFilters << "*.dll";

		//plugins are in bin/plugins
		pluginPaths << (appPath + "/plugins");
#elif defined(Q_OS_LINUX)
		dirFilters << "*.so";

		// Plugins are relative to the bin directory where the executable is found
		QDir  binDir(appPath);

		if (binDir.dirName() == "bin")
		{
			binDir.cdUp();

			pluginPaths << (binDir.absolutePath() + "/lib/cloudcompare/plugins");
		}
		else
		{
			// Choose a reasonable default to look in
			pluginPaths << "/usr/lib/cloudcompare/plugins";
		}
#else
		#warning Need to specify the plugin path for this OS.
#endif

#ifdef Q_OS_MAC
		// Add any app data paths
		// Plugins in these directories take precendence over the included ones
		QStringList appDataPaths = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);

		for (const QString &appDataPath : appDataPaths)
		{
			pluginPaths << (appDataPath + "/plugins");
		}
#endif
	}

	ccPlugins::LoadPlugins(plugins, pluginPaths, dirFilters);
	
	int result = 0;

	//command line mode
	if (commandLine)
	{
		//command line processing (no GUI)
		result = ccCommandLineParser::Parse(argc, argv);
	}
	else
	{
		//main window init.
		MainWindow* mainWindow = MainWindow::TheInstance();
		if (!mainWindow)
		{
			QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!");
			return EXIT_FAILURE;
		}
		mainWindow->dispatchPlugins(plugins, pluginPaths);
		mainWindow->show();
		QApplication::processEvents();

		//show current Global Shift parameters in Console
		{
			ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2")
				.arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0)
				.arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0));
		}

		if (argc > lastArgumentIndex)
		{
			if (splash)
				splash->close();

			//any additional argument is assumed to be a filename --> we try to load it/them
			QStringList filenames;
			for (int i = lastArgumentIndex; i < argc; ++i)
			{
				QString arg(argv[i]);
				//special command: auto start a plugin
				if (arg.startsWith(":start-plugin:"))
				{
					QString pluginName = arg.mid(14);
					QString pluginNameUpper = pluginName.toUpper();
					//look for this plugin
					bool found = false;
					for (const tPluginInfo &plugin : plugins)
					{
						if (plugin.object->getName().replace(' ', '_').toUpper() == pluginNameUpper)
						{
							found = true;
							bool success = plugin.object->start();
							if (!success)
							{
								ccLog::Error(QString("Failed to start the plugin '%1'").arg(plugin.object->getName()));
							}
							break;
						}
					}

					if (!found)
					{
						ccLog::Error(QString("Couldn't find the plugin '%1'").arg(pluginName.replace('_', ' ')));
					}
				}
				else
				{
					filenames << arg;
				}
			}

			mainWindow->addToDB(filenames);
		}
		
		if (splash)
		{
			//we want the splash screen to be visible a minimum amount of time (1000 ms.)
			while (splashStartTime.elapsed() < 1000)
			{
				splash->raise();
				QApplication::processEvents(); //to let the system breath!
			}

			splash->close();
			QApplication::processEvents();

			delete splash;
			splash = 0;
		}

		//let's rock!
		try
		{
			result = app.exec();
		}
		catch (...)
		{
			QMessageBox::warning(0, "CC crashed!", "Hum, it seems that CC has crashed... Sorry about that :)");
		}

		//release the plugins
		for (tPluginInfo &plugin : plugins)
		{
			plugin.object->stop(); //just in case
			if (!plugin.qObject->parent())
			{
				delete plugin.object;
				plugin.object = 0;
				plugin.qObject = 0;
			}
		}

	}

	//release global structures
	MainWindow::DestroyInstance();
	FileIOFilter::UnregisterAll();

#ifdef CC_TRACK_ALIVE_SHARED_OBJECTS
	//for debug purposes
	unsigned alive = CCShareable::GetAliveCount();
	if (alive > 1)
	{
		printf("Error: some shared objects (%u) have not been released on program end!",alive);
		system("PAUSE");
	}
#endif

	return result;
}
コード例 #27
0
ファイル: main.cpp プロジェクト: Jorgelig/routerkeygenPC
int main(int argc, char * argv[]) {
    QApplication app(argc, argv);
    QTranslator translator;
    QApplication::setOrganizationName("com.doublecheck");
    QApplication::setApplicationName(PROJECT_NAME);
    QApplication::setApplicationVersion(PROJECT_VERSION);
    QString qmFile = app.applicationName().toLower() + "_" + QLocale::system().name();
    if ( translator.load(qmFile,":/lang") )
        app.installTranslator(&translator);
    QCmdLineParser parser;
    parser.setApplicationName(QCoreApplication::applicationName());
    parser.addOption("-s", QCmdLineArgument::StoreValue, QObject::tr("SSID"), "--ssid", "network_name");
    parser.addOption("-m", QCmdLineArgument::StoreValue, QObject::tr("MAC address"), "--mac", "mac_address");
    parser.addOption("-v", QCmdLineArgument::StoreTrue, QObject::tr("Version"), "--version");
    parser.addOption("-q", QCmdLineArgument::StoreTrue, QObject::tr("Print only calculated keys"), "--quiet");
    parser.addOption("--no-gui", QCmdLineArgument::StoreTrue, QObject::tr("No UI launch"));
    QString error = "";
    QVariantMap options = parser.parse(QCoreApplication::arguments(), &error);
    if ( !error.isEmpty() ){
        std::cout << error.toUtf8().data() << std::endl <<  parser.help().toUtf8().data();
        return -1;
    }
    if ( options.value("v", false).toBool() ){
        std::cout << QObject::tr("Version: %1").arg(app.applicationVersion()).toUtf8().data() << std::endl;
        return 0;
    }
    if ( options.contains("s") || options.contains("m") ){
        WirelessMatcher m;
        QString mac = options.value("m", "").toString().toUpper();
        if ( mac.length()>0 && mac.count(QRegExp("^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$")) == 0 ){
            mac = "";
            if ( !options.value("q", false).toBool() )
                std::cout << QObject::tr("Invalid MAC. It will not be used.").toUtf8().data() << std::endl;
        }
        QString ssid = options.value("s", "").toString();
        QScanResult wifi(ssid,mac);
        wifi.checkSupport(m);
        QVector<Keygen *> * keygens = wifi.getKeygens();
        if (keygens == NULL ){
            if ( !options.value("q", false).toBool() )
                std::cout << QObject::tr("Out of memory.").toUtf8().data() << std::endl;
            return -100;
        }
        if ( keygens->size() == 0){
            if ( !options.value("q", false).toBool() )
                std::cout << QObject::tr("Unsupported network. Check the MAC address and the SSID.").toUtf8().data() << std::endl;
            return -2;
        }
        if ( !options.value("q", false).toBool() )
            std::cout << QObject::tr("Calculating keys. This can take a while.").toUtf8().data() << std::endl;
        QVector<QString> results;
        for ( int i = 0; i < keygens->size(); ++i ){
            try{
                QVector<QString> r = keygens->at(i)->getResults();
                foreach (QString s, r) {
                    results.append(s);
                }
            }catch (int e){
                if ( !options.value("q", false).toBool() )
                    std::cout << QObject::tr("Errors while calculating.").toUtf8().data() << std::endl;
                return -3;
            }
        }
        if (results.isEmpty()) {
            if ( !options.value("q", false).toBool() )
                std::cout << QObject::tr("No keys were calculated.").toUtf8().data() << std::endl;
            return -1;
        }else{
            if ( !options.value("q", false).toBool() )
                std::cout << QObject::tr("Calculated Passwords for %1").arg(wifi.getSsidName()).toUtf8().data() << std::endl;
            for (int i = 0; i < results.size(); ++i)
                std::cout <<  results.at(i).toLatin1().data() << std::endl;
            return 0;
        }
    }
コード例 #28
0
ファイル: main.cpp プロジェクト: jvillasante/linea10
int main(int argc, char *argv[])
{
    signal(SIGINT, signalHandler);
    signal(SIGABRT, signalHandler);
    signal(SIGTERM, signalHandler);

    QApplication app(argc, argv);
    app.setOrganizationName("Genera");
#ifdef TEMPO
    app.setApplicationName("Tempo10");
#endif
#ifdef SNACK
    app.setApplicationName("Snack10");
#endif
#ifdef PRESENCIA
    app.setApplicationName("Presencia10");
    Utils::disableLeds();
#endif

    QString appPath = QApplication::applicationDirPath();

    QString configPath = "/mnt/jffs2/app.ini";
    settings = new QSettings(configPath, QSettings::IniFormat);

    QString lang = settings->value("lang", "es").toString();
    DEBUG("Language is: %s.", lang.toStdString().c_str());

    QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
    QTranslator translator;
    if (lang == "es") {
        if (translator.load("app_es.qm", appPath + "/Resources/languages")) {
            app.installTranslator(&translator);
        } else {
            DEBUG("Unable to install app_es.qm translation.");
        }
    } else {
        if (translator.load("app_en.qm", appPath + "/Resources/languages")) {
            app.installTranslator(&translator);
        } else {
            DEBUG("Unable to install app_en.qm translation.");
        }
    }

    DEBUG("****************************************************************************");
    DEBUG("Equipo: %s", settings->value("tipoEquipo").toString().toStdString().c_str());
    DEBUG("NTP IP: %s", settings->value("ntpIP").toString().toStdString().c_str());
    DEBUG("Lang: %s", settings->value("lang").toString().toStdString().c_str());
    DEBUG("Empresa Holding: %s", settings->value("empresaHolding").toString().toStdString().c_str());
    DEBUG("serialEquipo: %s", settings->value("serialEquipo").toString().toStdString().c_str());
    DEBUG("identificadorEquipo: %s", settings->value("identificadorEquipo").toString().toStdString().c_str());
#ifdef PRESENCIA
    DEBUG("Tipo de Equipo: %s", (settings->value("presenciaType").toString() == "In") ? "Entrada" : "Salida");
#endif
    DEBUG("wsIp: %s", settings->value("wsIP").toString().toStdString().c_str());
    DEBUG("wsPort: %s", settings->value("wsPort").toString().toStdString().c_str());
    DEBUG("wsCargaMasivaURL: %s", settings->value("wsCargaMasivaURL").toString().toStdString().c_str());
    DEBUG("wsFirmwareUpdateURL: %s", settings->value("wsFirmwareUpdateURL").toString().toStdString().c_str());
    DEBUG("wsSincronizacionURL: %s", settings->value("wsSincronizacionURL").toString().toStdString().c_str());
    DEBUG("wsVerificaPersonaURL: %s", settings->value("wsVerificaPersonaURL").toString().toStdString().c_str());
    DEBUG("wsEnrollURL: %s", settings->value("wsEnrollURL").toString().toStdString().c_str());
    DEBUG("wsAlarmasURL: %s", settings->value("wsAlarmasURL").toString().toStdString().c_str());
    DEBUG("****************************************************************************");

    int WIDTH = 240;
    int HEIGHT = 320;
    int screenWidth, screenHeight;
    int x, y;

    window = new MainWindow(settings);
    QDesktopWidget *desktop = QApplication::desktop();

    screenWidth = desktop->width();
    screenHeight = desktop->height();

    x = (screenWidth - WIDTH) / 2;
    y = (screenHeight - HEIGHT) / 2;

    window->resize(WIDTH, HEIGHT);
    window->move(x, y);
    window->setWindowOpacity(1.0);
    window->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);

    window->showFullScreen();

    int rc = app.exec();

    if (window) {
        DEBUG("MainWindow Flag: %d", window->flag);
        if (window->flag == 500) {
            if (settings) {
                delete settings;
            }
            if (window)   {
                delete window;
            }

            DEBUG("Bye Bye...");
            fflush(stdout);
            fflush(stderr);
            execl("/sbin/reboot", "reboot", NULL);
            return 0;
        }
    }

    if (settings) {
        delete settings;
    }
    if (window)   {
        delete window;
    }

    DEBUG("Bye Bye...");
    fflush(stdout);
    fflush(stderr);
    return rc;
}
コード例 #29
0
ファイル: main.cpp プロジェクト: leonidborisenko/boomaga
int main(int argc, char *argv[])
{
    readEnvFile();

    QApplication application(argc, argv);

    QTranslator qtTranslator;
    qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    application.installTranslator(&qtTranslator);


    QTranslator translator;
    translator.load(QString("%1/boomaga_%2.qm").arg(TRANSLATIONS_DIR, QLocale::system().name()));
    application.installTranslator(&translator);


    QStringList files;
    QStringList titles;
    bool autoRemove = false;

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

        //*************************************************
        if (arg == "-h" || arg == "--help")
        {
            printHelp();
            return 0;
        }

        //*************************************************
        if (arg == "-V" || arg == "--version")
        {
            printVersion();
            return 0;
        }

        //*************************************************
        if (arg == "-t" || arg == "--title")
        {
            if (i+1 < args.count())
            {
                titles << args.at(i+1);
                i++;
                continue;
            }
            else
            {
                return printError("'title' is missing.");
            }
        }

        //*************************************************
        if (arg == "--autoremove")
        {
            autoRemove = true;
            continue;
        }

        //*************************************************
        files << args.at(i);
    }

    BoomagaDbus dbus("org.boomaga", "/boomaga");

    MainWindow mainWindow;
    mainWindow.show();
    application.processEvents();

    project->load(files, titles, "", autoRemove);

    return application.exec();
}
コード例 #30
0
ファイル: main.cpp プロジェクト: ronalde/quimup-packaging
int main(int argc, char **argv)
{
    QtSingleApplication app("quimup", argc, argv);
    bool b_multiple_instances = false;
    QString locale = "xx";
    QString message;
    int filecount = 0;
    // handle command line args
    for (int a = 1; a < argc; ++a)
    {
        QString msg = QString::fromUtf8(argv[a]);

        if ( msg == "-p" || msg == "-play")
        {
            message = "-play:" + message;
        }
        else
        if ( msg == "-i" || msg == "-instance")
        {
            b_multiple_instances = true;
        }
        else
        if ( msg == "-l"  || msg == "-locale" )
        {
            if (a < (argc-1) )
            {
                locale = argv[a+1];
                // possible stray '-l'
                if ( locale.startsWith("-") || locale.startsWith("file") )
                    locale = "xx";
                else
                    a++;
            }
        }
        else
        if (msg == "-h" || msg == "-help")
        {
            printf ("----\nQuimup version 1.4.0\n"); // VERSION //
            printf ("© 2008-2014 Johan Spee <*****@*****.**>\n");
            printf ("This program is licensed by the GPL and distributed in the hope that it will be useful, but without any warranty.\n");
            printf ("----\ncommand line parameters:\n");
            printf (" -h(elp)           show this information and exit\n");
            printf (" -i(nstance)       force a new instance of Quimup\n");
            printf (" -l(ocale) xx      use locale 'xx' (fr, po, en_GB, etc) or 'none' to force internal locale\n");
            printf (" -l(ocale) file    use locale from full path to quimup_xx.qm file\n");
            printf (" -p(lay) %%U        play files in %%U (or %%F) in new playlist\n");
            printf ("  %%U               append files in %%U (or %%F) to the playlist\n----\n");
            return 0;
        }
        else // if URL
        if ( msg.startsWith("file://"))
        {
            // we have a string in URL format, so convert special chars:
            msg = ( QUrl::fromEncoded ((const char*)msg.toUtf8()) ).toString();
            message.append(msg);
            filecount++;
        }
        else //  if plain path
        if (msg.startsWith("/") )
        {
            msg = "file://" + msg; // used as separator
            message.append(msg);
            filecount++;
        }
    }

    // send the args (and find out if a previous instance exists)
    if (!b_multiple_instances && app.sendMessage(message))
    {
        printf ("Quimup : already running (use '-i' to force a new instance)\n");
        return 0;
    }

    printf ("Quimup : starting new instance\n");

    //// Localization start >
    QTranslator trnsltr;
    //QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
    bool b_locale_loaded = false;
    bool b_locale_default = true;
    if (locale == "xx") // no -l parameter was passed
        locale = QLocale::system().name();
    else
        b_locale_default = false;

    if (locale != "none")
    {
        if (!b_locale_default)
        {
            printf ("Locale : '%s': ", (const char*)locale.toUtf8());
            if ( locale.startsWith("/") && locale.endsWith(".qm")) // full path to a file
            {
                if ( trnsltr.load(locale) )
                {
                   printf ("OK\n");
                   b_locale_loaded = true;
                }
                else
                   printf ("failed! (using none)\n");
            }
            else // first try installation path, next default path
            {
                QDir dir(QApplication::applicationDirPath());

                if ( trnsltr.load(QString("quimup_") + locale, dir.absolutePath()) )
                {
                    printf ("OK (from %s)\n", (const char*)dir.absolutePath().toUtf8());
                    b_locale_loaded = true;
                }
                else
                {
                    if ( trnsltr.load(QString("quimup_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) )
                    {
                        printf ("OK (from default location)\n");
                        b_locale_loaded = true;
                    }
                    else
                         printf ("failed! (using none)\n");
                }
            }

        }
        else // locale file in defaut system location
        {
            printf ("Locale : ");
            if ( trnsltr.load(QString("quimup_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) )
            {
                printf ("using default (%s)\n", (const char*)locale.toUtf8());
                b_locale_loaded = true;
            }
            else
                printf ("using none\n");
        }
    }
    else
       printf ("Locale : using none (requested)\n");

    if (b_locale_loaded)
        app.installTranslator(&trnsltr);

    //// < end Localization

    qm_core *core = new qm_core();

    // handle files
    if (filecount > 0)
    {
        core->player->browser_window->plist_view->on_open_with_request(message);
    }

    QObject::connect(&app, SIGNAL(messageReceived(const QString&)), core, SLOT(on_message_from_2nd_instance(const QString&)));
    QObject::connect(&app, SIGNAL(aboutToQuit()), core, SLOT(on_system_quit()));

    return app.exec();
}