示例#1
0
文件: main.cpp 项目: afibanez/eneboo
void aq_main(int argc, char **argv) 
{
  QPalette p(QColor(229, 229, 229), QColor(229, 229, 229));
  p.setColor(QPalette::Active, QColorGroup::Dark, QColor(246, 242, 246));
  p.setColor(QPalette::Inactive, QColorGroup::Dark, QColor(246, 242, 246));
  p.setColor(QPalette::Disabled, QColorGroup::Dark, QColor(246, 242, 246));
  p.setColor(QPalette::Active, QColorGroup::Base, QColor(255, 255, 248));
  p.setColor(QPalette::Inactive, QColorGroup::Base, QColor(255, 255, 248));
  p.setColor(QPalette::Disabled, QColorGroup::Base, QColor(255, 255, 248));
  p.setColor(QPalette::Active, QColorGroup::Highlight, QColor(95, 150, 205));
  p.setColor(QPalette::Active, QColorGroup::HighlightedText, Qt::white);
  p.setColor(QPalette::Active, QColorGroup::Highlight, QColor(95, 150, 205));
  p.setColor(QPalette::Inactive, QColorGroup::HighlightedText, Qt::white);
  p.setColor(QPalette::Active, QColorGroup::Highlight, QColor(95, 150, 205));
  p.setColor(QPalette::Disabled, QColorGroup::HighlightedText, Qt::white);
  p.setColor(QPalette::Inactive, QColorGroup::Text, Qt::black);
  p.setColor(QPalette::Disabled, QColorGroup::Text, QColor(100, 100, 100));
  p.setColor(QPalette::Active, QColorGroup::Foreground, QColor(30, 30, 30));
  p.setColor(QPalette::Inactive, QColorGroup::Foreground, QColor(30, 30, 30));
  p.setColor(QPalette::Disabled, QColorGroup::Foreground, QColor(100, 100, 100));
  p.setColor(QPalette::Active, QColorGroup::ButtonText, QColor(30, 30, 30));
  p.setColor(QPalette::Inactive, QColorGroup::ButtonText, QColor(30, 30, 30));
  p.setColor(QPalette::Disabled, QColorGroup::ButtonText, QColor(100, 100, 100));

  QString formAlone, callFunction, arguments, strConn, silentConn;
  bool quitAfterCall = false, autoLogin_ = false, noMax = false;

  for (int i = 1; i < argc; i++) {
    if (qstrcmp(argv[i], "-f") == 0) {
      if (i != argc - 1) {
        i++;
        formAlone = QString::fromLatin1(argv[i]);
      }
    } else if (qstrcmp(argv[i], "-c") == 0) {
      if (i != argc - 1) {
        i++;
        callFunction = QString::fromLatin1(argv[i]);
      }
    } else if (qstrcmp(argv[i], "-a") == 0) {
      if (i != argc - 1) {
        i++;
        arguments = QString::fromLatin1(argv[i]);
      }
    } else if (qstrcmp(argv[i], "-sc") == 0) {
      if (i != argc - 1) {
        i++;
        strConn = QString::fromLatin1(argv[i]);
      }
    } else if (qstrcmp(argv[i], "-silentconn") == 0) {
      if (i != argc - 1) {
        i++;
        silentConn = QString::fromLatin1(argv[i]);
      }
    } else if (qstrcmp(argv[i], "-q") == 0) {
      quitAfterCall = true;
    } else if (qstrcmp(argv[i], "-auto") == 0) {
      autoLogin_ = true;
    } else if (qstrcmp(argv[i], "-nomax") == 0) {
      noMax = true;
    }
  }

  FLApplication *AbanQ = aqApp;
  QFont appFont;

  QStringList paths(AbanQ->libraryPaths());
  QString pathApp(AQ_PREFIX + "/plugins");
  if (!paths.contains(pathApp))
    paths << pathApp;
  if (!paths.contains(AQ_LIB))
    paths << AQ_LIB;
  AbanQ->setLibraryPaths(paths);

  int pointSize = 8;

#if defined (Q_OS_LINUX)
  appFont.setFamily(FLSettings::readEntry("font/family", "Verdana"));
#endif

#if defined(Q_OS_WIN32)
  appFont.setFamily(FLSettings::readEntry("font/family", "Tahoma"));
#endif

#if defined(Q_OS_MACX)
  appFont.setFamily(FLSettings::readEntry("font/family", "Lucida Grande"));
  pointSize = 12;
  QString envPath(getenv("PATH"));
  envPath = "/sw/sbin:/sw/bin:" + envPath + ":/usr/X11R6/bin";
  setenv("PATH", envPath.local8Bit(), 1);
#endif

  appFont.setPointSize(FLSettings::readNumEntry("font/pointSize", pointSize));
  appFont.setBold(FLSettings::readBoolEntry("font/bold", false));
  appFont.setItalic(FLSettings::readBoolEntry("font/italic", false));
  appFont.setUnderline(FLSettings::readBoolEntry("font/underline", false));
  appFont.setStrikeOut(FLSettings::readBoolEntry("font/strikeOut", false));

  AbanQ->setFont(appFont);
  AbanQ->setStyle(FLSettings::readEntry("style", "QtCurve"));

  AbanQ->installTranslator(AbanQ->createSysTranslator(QString(QTextCodec::locale()).left(2), true));
  AbanQ->installTranslator(AbanQ->createSysTranslator("multilang"));
  AbanQ->setPalette(p, true);

  FLConnectDBDialog *s = 0;
  QSplashScreen *splash = 0;

  if (silentConn.isEmpty()) {
    bool autoLogin = FLSettings::readBoolEntry("application/autoLogin", autoLogin_);
    s = new FLConnectDBDialog(autoLogin, 0, "FLConnectDBDialog", 0, strConn);

    static_cast<QWidget *>(s->child("frMore"))->hide();
    s->adjustSize();
    s->setPalette(p);
    int ret = -1;
    bool connectAttempts = 0;

    do {
      if (!s->isShown()) {
        s->show();
        s->raise();
      }
      if (autoLogin && !connectAttempts) {
        QTimer::singleShot(1000, s, SLOT(tryConnect()));
        connectAttempts++;
      } else
        s->exec();
    } while (s->error());

    ret = s->result();
    QTimer::singleShot(0, s, SLOT(deleteLater()));

    if (ret != QDialog::Accepted) {
      QTimer::singleShot(0, AbanQ, SLOT(quit()));
      return;
    }

    splash = new QSplashScreen(QPixmap::fromMimeSource("splashabanq.png"));
    splash->show();
    splash->message(QT_TR_NOOP("Inicializando..."), Qt::AlignRight, QColor(0, 0, 0));
  } else if (!silentConnect(silentConn)) {
    QTimer::singleShot(0, AbanQ, SLOT(quit()));
    return;
  }
  AbanQ->setNotExit(FLSettings::readBoolEntry("application/notExit", false));
  AbanQ->setPrintProgram(FLSettings::readEntry("printing/printProgram", QString::null));
  AbanQ->flushX();
  AbanQ->syncX();
  AbanQ->processEvents();
  AbanQ->init(
    FLSettings::readEntry("application/formAlone", formAlone),
    FLSettings::readEntry("application/callFunction", callFunction),
    FLSettings::readEntry("application/arguments", arguments),
    FLSettings::readBoolEntry("application/quitAfterCall", quitAfterCall),
    FLSettings::readBoolEntry("application/noMax", noMax)
  );

  if (AbanQ->mainWidget()) {
    AbanQ->mainWidget()->show();
    AbanQ->mainWidget()->raise();
    if (splash) {
      splash->finish(AbanQ->mainWidget());
      delete splash;
    }
  } else {
    if (splash) {
      QTimer::singleShot(0, splash, SLOT(deleteLater()));
    }
  }
    
}
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(icons);

    QApplication a(argc, argv);

    // 系统图标
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        QMessageBox::critical(0, QObject::tr("Systray"),
                              QObject::tr("I couldn't detect any system tray "
                                          "on this system."));
        return 1;
    }

    QApplication::setQuitOnLastWindowClosed(false);

    QApplication::addLibraryPath("./plugins");

    QTextCodec::setCodecForTr(QTextCodec::codecForName("GB2312"));//让显示的文字不乱码
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));//让显示的文字不乱码
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));//让显示的文字不乱码

    bool isrunning = CheckIfRunning("lz_master_gui.exe", false);
    if (isrunning)
    {
        return 1;
    }
    isrunning = CheckIfRunning("lz_master_monitor.exe", true);
    if (isrunning)
    {
        return 1;
    }

    QSplashScreen *splash = new QSplashScreen();
    splash->setPixmap(QPixmap(":/image/start.png"));
    QTimer::singleShot(3000, splash, SLOT(close()));
    splash->show();
    Qt::Alignment topRight = Qt::AlignRight | Qt::AlignTop;
    splash->showMessage(QObject::tr("正在初始化..."),topRight,Qt::yellow);

    // 加载本地文件存储目录
    QFile file("master_datastore_path.txt");
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug() << QObject::tr("无文件master_datastore_path.txt,无法加载主控机数据存储目录位置");
        return 1;
    }
    else
    {
        QString parentpath = file.readLine().trimmed();
        MasterSetting::getSettingInstance()->setParentPath(parentpath);
        file.close();
    }

    // 【标记2】此处作废-因为MasterProgram类的run函数作废
    // 【注意】顺序:先有masterProgramInstance,才run,能连接信号槽
    //MasterProgram::getMasterProgramInstance()->run();
    /*******************************/
    MainWidget *w = new MainWidget(true, Collecting);
    w->show();

    // 【注意】顺序:先有masterProgramInstance,才能连接信号槽
    MasterProgram::getMasterProgramInstance();
    // connect函数必在MasterProgram::getMasterProgramInstance()之后
    MasterProgram::getMasterProgramInstance()->init();

    splash->showMessage(QObject::tr("正在启动程序..."),topRight,Qt::yellow);

    splash->finish(w);
    delete splash;

    return a.exec();
}
示例#3
0
Q_DECL_EXPORT int main(int argc, char *argv[])
{
    int currentExitCode = 0;

    QScopedPointer<QSymbianApplication> app(new QSymbianApplication(argc, argv));

    // Set App Info:
    app->setApplicationName("Battery Status");
    app->setOrganizationName("Motaz Alnuweiri");
    app->setApplicationVersion(APP_Version);

    // QT_DEBUG or QT_NO_DEBUG
//    #ifdef QT_DEBUG
//        // Install Debug Msgs Handler:
//        ClearDebugFile();
//        qInstallMsgHandler(DebugFileHandler);
//    #endif

    // Install EventFilter in QApplication:
    //app->installEventFilter(new myEventFilter);

    // Set App Splash Screen:
    QSplashScreen *splash = new QSplashScreen(QPixmap(":qml/Images/JPG/Splash_Screen.jpg"),
                                              Qt::WindowStaysOnTopHint);
    splash->show();

    // Check System Language & Load App Translator:
    QString systemLang = QLocale::system().name();
    QTranslator appTranslator;

    systemLang.truncate(2); //truncate(2) to ignore the country code

    if (QFile::exists("Languages/batterystatus_" + systemLang + ".qm")) {
        appTranslator.load("batterystatus_" + systemLang, "Languages");
    } else {
        appTranslator.load("batterystatus_en", "Languages");
    }

    // Install QTranslator to QApplication:
    app->installTranslator(&appTranslator);

    // Hide The App If Deactive:
    if (!app->foreground())
        QSymbianHelper::hideInBackground();

    // Register QSettings:
    QAppSettings appSettings;

    // Register QmlApplicationViewer:
    QmlApplicationViewer *viewer = new QmlApplicationViewer();
    //viewer.setResizeMode(QmlApplicationViewer::SizeRootObjectToView);
    //viewer.setAutoFillBackground(false);
    //viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait);

    // Register App HSWidget:
    QBatteryHSWidget *batteryHSWidget = new QBatteryHSWidget();
    batteryHSWidget->setBackgroundOpacity(appSettings.getWidgetOpacity());

    // Register QDeviceName:
    QDeviceName deviceName;

    // Register Class to QML:
    qmlRegisterType<QPSMode>("PSMode", 1, 0, "PSMode");
    qmlRegisterType<QGlobalNote>("GlobalNote", 1, 0, "GlobalNote");
    qmlRegisterType<QCBatteryInfo>("CBatteryInfo", 1, 0, "CBatteryInfo");
    qmlRegisterType<CommonType>("CommonType", 1, 0, "CommonType");

    // Set Propertys to QML:
    viewer->rootContext()->setContextProperty("APPName", QObject::tr("Battery Status"));
    viewer->rootContext()->setContextProperty("APPVersion", app->applicationVersion());
    viewer->rootContext()->setContextProperty("AppPath", app->applicationDirPath());
    viewer->rootContext()->setContextProperty("SymbianHelper", new QSymbianHelper);
    viewer->rootContext()->setContextProperty("AppSettings", &appSettings);
    viewer->rootContext()->setContextProperty("HSWidget", batteryHSWidget);
    viewer->rootContext()->setContextProperty("DeviceName", &deviceName);
    viewer->rootContext()->setContextProperty("QApp", app->instance());

    viewer->setSource(QUrl(QLatin1String("qrc:qml/main.qml")));
    //viewer.setSource(QUrl::fromLocalFile("qrc:qml/main.qml"));

    // Lock screen orientation in portrait only
    //viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait);

    //viewer.setGeometry(app->desktop()->screenGeometry());
    viewer->showFullScreen();

    // Stop Splash Screen & Delete It:
    splash->finish(viewer);
    splash->deleteLater();

    //viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);

    // Enter App Event Loop:
    currentExitCode = app->exec();

    // Cleun Pointers:
    delete viewer;
    delete batteryHSWidget;

    // Check If App Is Restarting:
    if(app->isRestarting()) {
        // Workround for my app to restart it self
        QProcess::startDetached(qApp->applicationFilePath());
    }

    return currentExitCode;
}
示例#4
0
文件: main.cpp 项目: husninazer/qt
QT_USE_NAMESPACE

int main(int argc, char **argv)
{
    Q_INIT_RESOURCE(linguist);

    QApplication app(argc, argv);
    QApplication::setOverrideCursor(Qt::WaitCursor);

    QStringList files;
    QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    QStringList args = app.arguments();

    for (int i = 1; i < args.count(); ++i) {
        QString argument = args.at(i);
        if (argument == QLatin1String("-resourcedir")) {
            if (i + 1 < args.count()) {
                resourceDir = QFile::decodeName(args.at(++i).toLocal8Bit());
            } else {
                // issue a warning
            }
        } else if (!files.contains(argument)) {
            files.append(argument);
        }
    }

    QTranslator translator;
    QTranslator qtTranslator;
    QString sysLocale = QLocale::system().name();
    if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir)) {
        app.installTranslator(&translator);
        if (qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir))
            app.installTranslator(&qtTranslator);
        else
            app.removeTranslator(&translator);
    }

    app.setOrganizationName(QLatin1String("Trolltech"));
    app.setApplicationName(QLatin1String("Linguist"));

    QSettings config;

    QWidget tmp;
    tmp.restoreGeometry(config.value(settingPath("Geometry/WindowGeometry")).toByteArray());

    QSplashScreen *splash = 0;
    int screenId = QApplication::desktop()->screenNumber(tmp.geometry().center());
    splash = new QSplashScreen(QApplication::desktop()->screen(screenId),
                               QPixmap(QLatin1String(":/images/splash.png")));
    if (QApplication::desktop()->isVirtualDesktop()) {
        QRect srect(0, 0, splash->width(), splash->height());
        splash->move(QApplication::desktop()->availableGeometry(screenId).center() - srect.center());
    }
    splash->setAttribute(Qt::WA_DeleteOnClose);
    splash->show();

    MainWindow mw;
    mw.show();
    splash->finish(&mw);
    QApplication::restoreOverrideCursor();

    mw.openFiles(files, true);

    return app.exec();
}
示例#5
0
int main(int argc, char *argv[])
{
	int dummy = errno;

	QApplication a(argc, argv);
	Debug::init(0);

#ifdef WIN32
	QFont font;
	font.setPointSize(10); 
	font.setFamily(("΢ÈíÑźÚ"));
	font.setBold(false);

	a.setFont(font);
#else
	QFont font;
	font.setPointSize(10); 
	font.setFamily(("WenQuanYi Zen Hei"));
	font.setBold(false);

	a.setFont(font);
#endif

	QPixmap pixmap(":/logo/resources/splash.png");
	QSplashScreen *splash = new QSplashScreen(pixmap);

    	splash->setStyleSheet(QStringLiteral("color : white;"));    
    	splash->show();

    	gFactory = new Factory;

	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(QObject::tr("Create Video Database ..."));
		gFactory->Init();
	}
	VSCLangType m_lang;
	gFactory->GetLang(m_lang);
	if (m_lang == VSC_LANG_AUTO)
	{
		if (QLocale::system().name() == "zh_CN")
		{
			LoadLangZH(a);
		}
	}
	else if (m_lang == VSC_LANG_ZH)
	{
		LoadLangZH(a);
	}//else if add more language to here
	
	splash->showMessage(QObject::tr("Starting ..."));
	VEvent::Init(*gFactory);
	VEMap::Init(*gFactory);
	VServiceMgr *pServiceMgr = VServiceMgr::CreateObject(*gFactory);
	
	VSCMainWindows w;

	//w.showMaximized();
	w.hide();
	//w.showFullScreen();
	splash->finish(&w);
	/* Auto  */
	if (gFactory->GetAutoLogin() == FALSE)
	{
		w.ShowLogin();
	}else
	{
		w.showMaximized();
	}

	delete splash;
	/* Every thread is ready, start the factory thread */
	
	gFactory->start();
	/* Init Mining framework */
	gMFramework = new MFramework(*gFactory);
	gMFramework->Init();

	gMFramework->start();

	/* Start the OpenCVR api server */
	gOAPIServer = new OAPIServer(*gFactory);
	gOAPIServer->start();
	
	return a.exec();
}
QSplashScreen* ngrt4n::infoScreen(const QString & msg) {
  QSplashScreen* screen = new QSplashScreen(QPixmap(":/images/built-in/loading-screen.png"));
  screen->showMessage(msg, Qt::AlignJustify|Qt::AlignVCenter);
  screen->show();
  return screen;
}
示例#7
0
文件: main.cpp 项目: mbravod/aeros
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QSplashScreen *splash;
    splash = new QSplashScreen;
    splash->setPixmap(QPixmap(":/Resources/cfesplash.png"));
    splash->show();
    Qt::Alignment bottomLeft = Qt::AlignLeft | Qt::AlignBottom;

    splash->showMessage(QObject::tr("Cargando Ajustes..."), bottomLeft, Qt::white);
    splash->showMessage(QObject::tr("Creando Interfaces..."), bottomLeft, Qt::white);

/*    SQLite sl;
    sl.IniciaBD();
    sl.VaciarTxtBD("C:/SiTTuGAs/Punteros.csv");//*/

    // Recuperamos la configuración
    Config *config = SQLite::getConfig();
    if(config == NULL)
    {
        qDebug()<<"Ha fallado la configuración...";
    }

    //Determinamos que modo es el adecuado
    if(config->getMode() == 0)
    {
        // Creamos la consola
        Console *w = new Console(config);
        w->show();
        splash->finish(w);
    }
    else
    {
        HTTPRequest *http = new HTTPRequest(config);
        //Proporciona acceso a informacion de la pantalla en los sistemas multi-cabeza
        QDesktopWidget *m = QApplication::desktop();
        //Lista de instancias a las interfaces
        QList <SiTTuGAs *> list;
        //variable auxiliar para la instancia de cada interfaz
        SiTTuGAs *w;

        //En base al numero de pantallas es como itera este lazo
        for(int i=0; i<m->screenCount(); i++)
        {
            //Creamos el gestor de las interfaces *(se cargan todas las interfaces)
            w = new SiTTuGAs(config, http);

            //lista que contiene referencias a todos los gestores creados
            list.push_front(w);
            //Devuelve la geometria disponible por la pantalla
            QRect r1=m->availableGeometry(i);
            //Movemos la interfaz de acuerdo con los valores recabados anteriormente
            w->move(r1.x(),r1.y());
        }
        //Terminamos splash
        splash->finish(w);
        //Iteramos hasta desplegar todas las GUI de SiTTuGAs
        foreach(SiTTuGAs *W, list)
        {
            //Las pantallas mantienen un tamaño de  1024 X 662 por lo que para presentar la interfaz adecuadamente la pantalla debe tener la misma resolución
            //W->showFullScreen();
            //temporalmete utilizaremos solo el desplegado normal de la pantalla para cada instancia generada
            W->show();
        }
    }

    return a.exec();
}
示例#8
0
int main(int argc, char * argv[])
{
    /*
     * Before starting main application, need to set 'QT_X11_NO_MITSHM=1'
     * to make the runtime work with IBM PPC machine.
     */
#if defined (Q_OS_LINUX)
    QByteArray val("1");
    qputenv("QT_X11_NO_MITSHM", val);
#endif

    // Create the QT application
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    // Setup the settings management
    QCoreApplication::setOrganizationName("pgadmin");
    QCoreApplication::setOrganizationDomain("pgadmin.org");
    QCoreApplication::setApplicationName(PGA_APP_NAME.toLower().replace(" ", ""));

#if QT_VERSION >= 0x050000
    // Set high DPI pixmap to display icons clear on Qt widget.
    QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

    // Create a hash of the executable path so we can run copies side-by-side
    QString homeDir = QDir::homePath();
    unsigned long exeHash = sdbm((unsigned char *)argv[0]);

    // Create the address file, that will be used to store the appserver URL for this instance
    addrFileName = homeDir + (QString("/.%1.%2.addr").arg(PGA_APP_NAME).arg(exeHash)).remove(" ");
    QFile addrFile(addrFileName);

    // Create a system-wide semaphore keyed by app name, exe hash and the username
    // to ensure instances are unique to the user and path
    QString userName = qgetenv("USER"); // *nix
    if (userName.isEmpty())
        userName = qgetenv("USERNAME"); // Windows

    QString semaName = QString("%1-%2-%3-sema").arg(PGA_APP_NAME).arg(userName).arg(exeHash);
    QString shmemName = QString("%1-%2-%3-shmem").arg(PGA_APP_NAME).arg(userName).arg(exeHash);

    QSystemSemaphore sema(semaName, 1);
    sema.acquire();

#ifndef Q_OS_WIN32
    // We may need to clean up stale shmem segments on *nix. Attaching and detaching
    // should remove the segment if it is orphaned.
    QSharedMemory stale_shmem(shmemName);
    if (stale_shmem.attach())
        stale_shmem.detach();
#endif

    QSharedMemory shmem(shmemName);
    bool is_running;
    if (shmem.attach())
    {
        is_running = true;
    }
    else
    {
        shmem.create(1);
        is_running = false;
    }
    sema.release();

    QSettings settings;

    if (is_running){
        addrFile.open(QIODevice::ReadOnly | QIODevice::Text);
        QTextStream in(&addrFile);
        QString addr = in.readLine();

        QString cmd = settings.value("BrowserCommand").toString();

        if (!cmd.isEmpty())
        {
            cmd.replace("%URL%", addr);
            QProcess::startDetached(cmd);
        }
        else
        {
            if (!QDesktopServices::openUrl(addr))
            {
                QString error(QWidget::tr("Failed to open the system default web browser. Is one installed?."));
                QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

                exit(1);
            }
        }

        return 0;
    }

    atexit(cleanup);

    // In windows and linux, it is required to set application level proxy
    // because socket bind logic to find free port gives socket creation error
    // when system proxy is configured. We are also setting
    // "setUseSystemConfiguration"=true to use the system proxy which will
    // override this application level proxy. As this bug is fixed in Qt 5.9 so
    // need to set application proxy for Qt version < 5.9.
    //
#if defined (Q_OS_WIN) && QT_VERSION <= 0x050800
    // Give dummy URL required to find proxy server configured in windows.
    QNetworkProxyQuery proxyQuery(QUrl("https://www.pgadmin.org"));
    QNetworkProxy l_proxy;
    QList<QNetworkProxy> listOfProxies = QNetworkProxyFactory::systemProxyForQuery(proxyQuery);

    if (listOfProxies.size())
    {
        l_proxy = listOfProxies[0];

        // If host name is not empty means proxy server is configured.
        if (!l_proxy.hostName().isEmpty()) {
            QNetworkProxy::setApplicationProxy(QNetworkProxy());
        }
    }
#endif

#if defined (Q_OS_LINUX) && QT_VERSION <= 0x050800
    QByteArray proxy_env;
    proxy_env = qgetenv("http_proxy");
    // If http_proxy environment is defined in linux then proxy server is configured.
    if (!proxy_env.isEmpty()) {
        QNetworkProxy::setApplicationProxy(QNetworkProxy());
    }
#endif

    // Display the spash screen
    QSplashScreen *splash = new QSplashScreen();
    splash->setPixmap(QPixmap(":/splash.png"));
    splash->show();
    app.processEvents(QEventLoop::AllEvents);

    quint16 port = 0L;

    // Find an unused port number. Essentially, we're just reserving one
    // here that Flask will use when we start up the server.
    // In order to use the socket, we need to free this socket ASAP.
    // Hence - putting this code in a code block so the scope of the socket
    // variable vanishes to make that socket available.
    {
#if QT_VERSION >= 0x050000
        QTcpSocket socket;

        #if QT_VERSION >= 0x050900
        socket.setProxy(QNetworkProxy::NoProxy);
        #endif

        socket.bind(0, QTcpSocket::ShareAddress);
#else
        QUdpSocket socket;
        socket.bind(0, QUdpSocket::ShareAddress);
#endif
        port = socket.localPort();
    }

    // Generate a random key to authenticate the client to the server
    QString key = QUuid::createUuid().toString();
    key = key.mid(1, key.length() - 2);

    // Generate the filename for the log
    logFileName = homeDir + (QString("/.%1.%2.log").arg(PGA_APP_NAME).arg(exeHash)).remove(" ");

    // Start the tray service
    TrayIcon *trayicon = new TrayIcon(logFileName);

    if (!trayicon->Init())
    {
        QString error = QString(QWidget::tr("An error occurred initialising the tray icon"));
        QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

        exit(1);
    }

    // Fire up the webserver
    Server *server;

    bool done = false;

    while (done != true)
    {
        server = new Server(port, key, logFileName);

        if (!server->Init())
        {
            splash->finish(NULL);

            qDebug() << server->getError();

            QString error = QString(QWidget::tr("An error occurred initialising the application server:\n\n%1")).arg(server->getError());
            QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

            exit(1);
        }

        server->start();

        // This is a hack to give the server a chance to start and potentially fail. As
        // the Python interpreter is a synchronous call, we can't check for proper startup
        // easily in a more robust way - we have to rely on a clean startup not returning.
        // It should always fail pretty quickly, and take longer to start if it succeeds, so
        // we don't really get a visible delay here.
        delay(1000);

        // Any errors?
        if (server->isFinished() || server->getError().length() > 0)
        {
            splash->finish(NULL);

            qDebug() << server->getError();

            QString error = QString(QWidget::tr("An error occurred initialising the application server:\n\n%1")).arg(server->getError());
            QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

            // Allow the user to tweak the Python Path if needed
            bool ok;

            ConfigWindow *dlg = new ConfigWindow();
            dlg->setWindowTitle(QWidget::tr("Configuration"));
            dlg->setBrowserCommand(settings.value("BrowserCommand").toString());
            dlg->setPythonPath(settings.value("PythonPath").toString());
            dlg->setApplicationPath(settings.value("ApplicationPath").toString());
            dlg->setModal(true);
            ok = dlg->exec();

            QString browsercommand = dlg->getBrowserCommand();
            QString pythonpath = dlg->getPythonPath();
            QString applicationpath = dlg->getApplicationPath();

            if (ok)
            {
                settings.setValue("BrowserCommand", browsercommand);
                settings.setValue("PythonPath", pythonpath);
                settings.setValue("ApplicationPath", applicationpath);
                settings.sync();
            }
            else
            {
                exit(1);
            }

            delete server;
        }
        else
            done = true;
    }

    // Ensure the server gets cleaned up later
    QObject::connect(server, SIGNAL(finished()), server, SLOT(deleteLater()));

    // Generate the app server URL
    QString appServerUrl = QString("http://127.0.0.1:%1/?key=%2").arg(port).arg(key);

    // Read the server connection timeout from the registry or set the default timeout.
    int timeout = settings.value("ConnectionTimeout", 30).toInt();

    // Now the server should be up, we'll attempt to connect and get a response.
    // We'll retry in a loop a few time before aborting if necessary.

    QTime endTime = QTime::currentTime().addSecs(timeout);
    bool alive = false;

    while(QTime::currentTime() <= endTime)
    {
        alive = PingServer(QUrl(appServerUrl));

        if (alive)
        {
            break;
        }

        delay(200);
    }

    // Attempt to connect one more time in case of a long network timeout while looping
    if (!alive && !PingServer(QUrl(appServerUrl)))
    {
        splash->finish(NULL);
        QString error(QWidget::tr("The application server could not be contacted."));
        QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

        exit(1);
    }

    // Stash the URL for any duplicate processes to open
    if (addrFile.open(QIODevice::WriteOnly))
    {
        addrFile.setPermissions(QFile::ReadOwner|QFile::WriteOwner);
        QTextStream out(&addrFile);
        out << appServerUrl << endl;
    }

    // Go!
    trayicon->setAppServerUrl(appServerUrl);
    // Enable the shutdown server menu as server started successfully.
    trayicon->enableShutdownMenu();

    QString cmd = settings.value("BrowserCommand").toString();

    if (!cmd.isEmpty())
    {
        cmd.replace("%URL%", appServerUrl);
        QProcess::startDetached(cmd);
    }
    else
    {
        if (!QDesktopServices::openUrl(appServerUrl))
        {
            QString error(QWidget::tr("Failed to open the system default web browser. Is one installed?."));
            QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

            exit(1);
        }
    }

    QObject::connect(trayicon, SIGNAL(shutdownSignal(QUrl)), server, SLOT(shutdown(QUrl)));

    splash->finish(NULL);

    return app.exec();
}
示例#9
0
int main(int argc, char **argv)
{
	//QT initialiation
	qccApplication app(argc, argv);

	//Force 'english' local so as to get a consistent behavior everywhere
	QLocale::setDefault(QLocale::English);

#ifdef Q_OS_LINUX
    // we reset the numeric locale. As suggested in documetation
    // see http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings
    // Basically - from doc: - "On Unix/Linux Qt is configured to use the system locale settings by default.
    // This can cause a conflict when using POSIX functions, for instance,
    // when converting between data types such as floats and strings"
    setlocale(LC_NUMERIC,"C");
#endif

#ifdef USE_VLD
	VLDEnable();
#endif

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

	//Command line mode?
	bool commandLine = (argc > 1 && argv[1][0] == '-');
	if (!commandLine)
	{
		//OpenGL?
		if (!QGLFormat::hasOpenGL())
		{
			QMessageBox::critical(0, "Error", "This application needs OpenGL 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
	ccTimer::Init();
	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

	int result = 0;

	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->show();
		QApplication::processEvents();

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

			//any additional argument is assumed to be a filename --> we try to load it/them
			QStringList filenames;
			for (int i=1; i<argc; ++i)
				filenames << QString(argv[i]);

			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 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;
}
示例#10
0
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QDir::setCurrent(a.applicationDirPath());

    // See if we are loading something from the commandline.
    QString fileArg("");
    QString suffix("");
    QString argument = a.arguments().last();
    QFileInfo info(a.arguments().last());
    if(info.exists() && info.isFile())
    {
        if(info.suffix() == "ogscene")
        {
            // Yes we've got an ogscene file to load.
            fileArg = info.absoluteFilePath();
            suffix = info.suffix();
        }
        else if(info.baseName() != "qtOgitor" && info.baseName() != "qtOgitor_d"  )
        {
            // We are trying to load something we can't load
            // Exit the application.
            QMessageBox msg(QMessageBox::Critical, "Ogitor Error", "We can only load Ogitor Scenes.\nExiting..");
            msg.exec();
            return 0;
        }
    }

    a.setOrganizationName("Ogitor");
    a.setApplicationName("qtOgitor");

#if(OGRE_PLATFORM == OGRE_PLATFORM_APPLE)
    QFile file(":/stylesheets/osx.qss");
#else
    QFile file(":/stylesheets/obsidian.qss");
#endif
    file.open(QFile::ReadOnly);
    QString styleSheet = QLatin1String(file.readAll());
    a.setStyleSheet(styleSheet);

    QSettings settings;
    QString languageFile = settings.value("preferences/customLanguage").toString();

    QTranslator qtTranslator;
    QTranslator ogitorTranslator;

    if(languageFile != "ogitor_en.qm")
    {
        QString lang = "../languages/qt_" + languageFile;
        lang.remove("ogitor_");

        QString lang2 = "../languages/" + languageFile;

        if(QFile::exists(lang) && QFile::exists(lang2))
        {
            if(qtTranslator.load(lang))
                a.installTranslator(&qtTranslator);

            if(ogitorTranslator.load(lang2))
                a.installTranslator(&ogitorTranslator);
        }
        else
        {    
            // If the system-wide Qt translation file is present, load it.
            if(qtTranslator.load("qt_" + QLocale::system().name(),
                QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
            {
                a.installTranslator(&qtTranslator);
            }
            // Otherwise: load our own Qt translation file.
            else if(qtTranslator.load("../languages/qt_" + QLocale::system().name()))
            {
                a.installTranslator(&qtTranslator);
            }

            // Install qtOgitor translator
            if(ogitorTranslator.load("../languages/ogitor_" + QLocale::system().name()))
            {
                a.installTranslator(&ogitorTranslator);
            }
        }
    }

    bool skipSplash = settings.value("preferences/skipSplash", false).toBool();

    QSplashScreen *splash;
    if(!skipSplash)
    {
        QPixmap pixmap(":/images/OgitorLogo.png");
        splash = new QSplashScreen(pixmap);
        splash->show();
    }

#ifdef _DEBUG
    setupOgre(resourcePath() + Ogre::String("plugins_debug.cfg"), Ogre::String("ogre.cfg"), Ogre::String("ogitor.log"));
#else
    setupOgre(resourcePath() + Ogre::String("plugins.cfg"), Ogre::String("ogre.cfg"), Ogre::String("ogitor.log"));
#endif

    readRecentFiles(settings);

    mOgitorMainWindow = new MainWindow();
    mOgitorMainWindow->show();
    
    mOgitorMainWindow->setApplicationObject(&a);

    QString sceneToLoad = "";
    QString lastLoadedScene = settings.value("preferences/lastLoadedScene", "").toString();
    if((settings.value("preferences/loadLastLoadedScene", false).toBool()) && (fileArg.isEmpty()))
    {
        if(!lastLoadedScene.isEmpty())
        {
            sceneToLoad = lastLoadedScene;
        }
    }
    else if(!fileArg.isEmpty())
    {
        sceneToLoad = fileArg;
    }

    if(!sceneToLoad.isEmpty())
    {
        if(suffix == "material")
        {
        }
        else
        {
            Ogitors::OgitorsRoot::getSingletonPtr()->LoadScene(sceneToLoad.toStdString());
        }
    }

    mOgitorMainWindow->repaint();

    if(!skipSplash)
    {
        splash->finish(mOgitorMainWindow);
        delete splash;
    }

    int retval = a.exec();

    writeRecentFiles();

    delete mOgitorMainWindow;
    delete shortCuts;
    OGRE_DELETE mOgitorsRoot;
    OGRE_DELETE mSystem;
    OGRE_DELETE mOgreRoot;

    return retval;
}
示例#11
0
文件: main.cpp 项目: seleznevae/JaG
int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    if (lockUniqueResource()) {

        //organization name must be before settings loading
        QCoreApplication::setOrganizationName("jag");
        QCoreApplication::setApplicationName("jag");
        global::setDefaultPreferences();
        PlotStyle::initializeDefaultPlotStyles();

        {
            QSettings settings;
            QVariant varSetting;
            if ((varSetting = settings.value("/Settings/gRussianLanguage")).isValid()) {
                global::gRussianLanguage = varSetting.toBool();
            }
        }

        QTranslator appTranslator;
        if (global::gRussianLanguage) {
            appTranslator.load(":/JaG_ru");
            app.installTranslator(&appTranslator);
        }


        QFont applFont = QApplication::font();
        applFont.setPointSize(9);
        QApplication::setFont(applFont);

        global::gApplicationStartTime = QDateTime::currentDateTime().toString("ddd d MMMM yyyy (hh_mm_ss)");

        QPixmap pixmap(":/wait");
        QSplashScreen *splashScreen = new QSplashScreen(pixmap,  Qt::WindowStaysOnTopHint);
        splashScreen->show();
        qApp->processEvents();
        JagMainWindow jagMainWindow;
        global::gJagMainWindowPointer = &jagMainWindow;
        QVector<DataSource*> dataSourceVector;
        if (argc > 1) {
            for (int i = 1; i < argc; ++i) {
                jagMainWindow.addDataSource(QString::fromLocal8Bit(argv[i]));
                qApp->processEvents();
            }
        }
        delete splashScreen;
        jagMainWindow.show();
        if (global::gIsBootTipShowingEnabled)
            jagMainWindow.showHelpInformation();
        auto ret = app.exec();
        unlockUniqueResource();
        return ret;
    } else {
        // if no arguments
        if (argc <= 1) {
            return EXIT_SUCCESS;
        }

        QVector<QString> fileNameVector;
        for (int i = 1; i < argc; ++i) {
            if (QDir::isAbsolutePath(QDir::fromNativeSeparators(QString::fromLocal8Bit(argv[i]))))
                fileNameVector.push_back(QString::fromLocal8Bit(argv[i]));
            else {
                fileNameVector.push_back(
                            QDir::toNativeSeparators(QDir().absoluteFilePath(QString::fromLocal8Bit(argv[i])))
                                        );
            }
        }
        DataSourceSender sender(fileNameVector);
        return app.exec();
    }
}
示例#12
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();
}
示例#13
0
int FIRST_LOGIN( USER_LOGIN_INFO_STRUCT * P_USER_LOGIN_INFO, bool p_ilk_kurulum )
{
    //! PROGRAM ILK CALISTIGINDA BURAYA DUSER VE GEREKLI
    //! BUTUN VERI TABANLARINI VE YETKI ATAMASINI YAPAR.

    //! NOTE : VERITABANI ILK YARATILDIGINDA DEFAULT OLARAK
    //! OLUSACAK KULLANICI VE BILGISAYAR BILGILERI

    P_USER_LOGIN_INFO->bilgisayar_kodu    = QObject::tr ("C01");
    P_USER_LOGIN_INFO->bilgisayar_adi     = QObject::tr ("C01 Computer");
    P_USER_LOGIN_INFO->kullanici_kodu     = QObject::tr ("U01");
    P_USER_LOGIN_INFO->kullanici_adi      = QObject::tr ("U01 User");
    P_USER_LOGIN_INFO->kullanici_sifre   = "";

    if( p_ilk_kurulum EQ true ) {
        P_USER_LOGIN_INFO->sql_motoru         = "NONE";
        P_USER_LOGIN_INFO->secili_sql_profili = QObject::tr ("Local Disk");
        P_USER_LOGIN_INFO->veritabani_kodu    = "000";
    }

    P_USER_LOGIN_INFO->veritabani_tanimi  = QString(QObject::tr ("%1 Database")).arg( P_USER_LOGIN_INFO->veritabani_kodu );

    if ( P_USER_LOGIN_INFO->is_first_login EQ true ) {
        QSplashScreen * splash = CREATE_SPLASH_SCREEN();
        splash->show();
        splash->showMessage((QString("Configuring program for first usage. Please wait ...")), Qt::AlignCenter, Qt::white );
        splash->finish(NULL);
    }

    //! SQL_LITE VERITABANINA BAGLANILMAYA CALISILDIGINDA OTOMATIK OLARAK
    //! BAGLANILAN ISIMDE BIR VERITABANI OLUSTURUR

    QString program_db_name = SQL_DBNAME_ONEK() + "adak_" + P_USER_LOGIN_INFO->veritabani_kodu;
    QString yonetim_db_name = SQL_DBNAME_ONEK() + "adak_yonetim";

    G_YONETIM_DB = CONNECT_TO_DATABASE( ADAK_YONETIM, yonetim_db_name, P_USER_LOGIN_INFO->sql_motoru );
    DB           = CONNECT_TO_DATABASE( ADAK_PROGRAM, program_db_name, P_USER_LOGIN_INFO->sql_motoru );

    G_YONETIM_DB->START_TRANSACTION();

    //! [1] YENI BIR VERI TABANI OLSTURULUYOR

    if( p_ilk_kurulum EQ false ) {
        QString uyari_string = QString (QObject::tr("Tables needed do not exist in database!"
            "\nWill create tables and a new user according to the information you gave.\n\n Will do;\n"
            "Create database : %1 - %2 .\n"
            "Create %3 : user and give it all the permissions."))
            .arg( P_USER_LOGIN_INFO->veritabani_kodu )
            .arg( P_USER_LOGIN_INFO->veritabani_tanimi  )
            .arg( P_USER_LOGIN_INFO->kullanici_kodu  );

        if ( P_USER_LOGIN_INFO->is_first_login EQ true ) {
            ADAK_MSG_ENUM answer = ADAK_YES_NO_CANCEL(uyari_string , NULL, NULL);

            if (answer NE ADAK_YES) {
                return ADAK_OK;
            }
        }
    }

    if ( P_USER_LOGIN_INFO->kullanici_id EQ 1 ) {
        return ADAK_OK;
    }

    if ( CREATE_TABLES_OF_YONETIM( yonetim_db_name ) EQ ADAK_FAIL ) {
        return ADAK_FAIL;
    }

    SQL_QUERY sql_query ( G_YONETIM_DB );

    sql_query.PREPARE_SELECT("ynt_kullanicilar", "kullanici_kodu","kullanici_kodu = :kullanici_kodu","");
    sql_query.SET_VALUE ( ":kullanici_kodu" , P_USER_LOGIN_INFO->kullanici_kodu );

    if ( sql_query.SELECT() EQ 0 ) {

        ADD_YONETICI_USER( P_USER_LOGIN_INFO->kullanici_sifre );

        sql_query.PREPARE_INSERT ( "ynt_kullanicilar","kullanici_id","kullanici_kodu, kullanici_adi,silinmis_mi, parola");

        sql_query.SET_VALUE ( ":kullanici_kodu" , P_USER_LOGIN_INFO->kullanici_kodu );
        sql_query.SET_VALUE ( ":kullanici_adi"  , P_USER_LOGIN_INFO->kullanici_adi  );
        sql_query.SET_VALUE ( ":silinmis_mi"    , 0 );

        QByteArray hash = QCryptographicHash::hash(QString(P_USER_LOGIN_INFO->kullanici_sifre).toUtf8(), QCryptographicHash::Md5);

        sql_query.SET_VALUE ( ":parola", QString( hash.toHex()));

        P_USER_LOGIN_INFO->kullanici_id = sql_query.INSERT();

        QStringList mac_adresleri = GET_MAC_ADDRESS();

        sql_query.PREPARE_INSERT ( "ynt_bilgisayarlar","bilgisayar_id","bilgisayar_kodu, bilgisayar_adi, "
                                   "mac_adresi_kablolu,mac_adresi_kablosuz,mac_adresi_3g, silinmis_mi ");

        sql_query.SET_VALUE( ":bilgisayar_kodu"     , P_USER_LOGIN_INFO->bilgisayar_kodu );
        sql_query.SET_VALUE( ":bilgisayar_adi"      , P_USER_LOGIN_INFO->bilgisayar_adi  );

        if ( mac_adresleri.size() >= 1 ) {
            sql_query.SET_VALUE( ":mac_adresi_kablolu", GET_MAC_ADDRESS().at(0)  );
        }
        else {
            sql_query.SET_VALUE( ":mac_adresi_kablolu", "" );
        }

        if ( mac_adresleri.size() >= 2 ) {
            sql_query.SET_VALUE( ":mac_adresi_kablosuz", GET_MAC_ADDRESS().at(1) );
        }
        else {
            sql_query.SET_VALUE( ":mac_adresi_kablosuz", "" );
        }

        if ( mac_adresleri.size() >= 3 ) {
            sql_query.SET_VALUE( ":mac_adresi_3g", GET_MAC_ADDRESS().at(2) );
        }
        else {
            sql_query.SET_VALUE( ":mac_adresi_3g", "" );
        }

        sql_query.SET_VALUE( ":silinmis_mi", 0 );

        P_USER_LOGIN_INFO->bilgisayar_id = sql_query.INSERT();

        //! VERITABANI ID OLUSUYOR.
        if ( CREATE_TABLES_OF_PROGRAM( P_USER_LOGIN_INFO, false ) EQ ADAK_FAIL ) {
            return ADAK_FAIL;
        }
        //! END

        sql_query.PREPARE_INSERT( "ynt_bilgisayar_kullanicilari","id","bilgisayar_id, kullanici_id");
        sql_query.SET_VALUE( ":bilgisayar_id", P_USER_LOGIN_INFO->bilgisayar_id );
        sql_query.SET_VALUE( ":kullanici_id" , P_USER_LOGIN_INFO->kullanici_id  );
        sql_query.INSERT();

        sql_query.PREPARE_INSERT( "ynt_veritabani_kullanicilari","id","veritabani_id, kullanici_id");
        sql_query.SET_VALUE( ":veritabani_id", P_USER_LOGIN_INFO->veritabani_id );
        sql_query.SET_VALUE( ":kullanici_id",  P_USER_LOGIN_INFO->kullanici_id  );
        sql_query.INSERT();
    }

    SET_STATIC_VALUES( P_USER_LOGIN_INFO );

    SET_KULLANICININ_CALISABILECEGI_VERITABANI_SAYISI ( 1 );
    SET_BILGISAYARDA_KAYITLI_KULLANICI_SAYISI         ( 1 );

    KULLANICI_TAM_YETKILENDIR( P_USER_LOGIN_INFO->kullanici_id );

    if (g_auto_login_flag EQ false) {
        SHOW_YARDIM_HATIRLATMA_DIALOG();
    }

    G_YONETIM_DB->COMMIT_TRANSACTION();

    //! [1] END

    return ADAK_OK;
}
示例#14
0
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;
}
示例#15
0
文件: main.cpp 项目: midzer/LibreCAD
/**
 * Main. Creates Application window.
 */
int main(int argc, char** argv)
{
    RS_DEBUG->setLevel(RS_Debug::D_WARNING);

    QApplication app(argc, argv);
    QCoreApplication::setOrganizationName("LibreCAD");
    QCoreApplication::setApplicationName("/LibreCAD");
    QCoreApplication::setApplicationVersion("master");

    QSplashScreen* splash = new QSplashScreen;

    RS_SETTINGS->beginGroup("Appearance");
    bool show_splash = RS_SETTINGS->readNumEntry("/ShowSplash", 1);
    RS_SETTINGS->endGroup();

    if (show_splash)
    {
        QPixmap pixmap(":/main/splash_librecad.png");
        splash->setPixmap(pixmap);
        splash->setAttribute(Qt::WA_DeleteOnClose);
        splash->show();
        splash->showMessage(QObject::tr("Loading.."),
                            Qt::AlignRight|Qt::AlignBottom, QC_SPLASH_TXTCOL);
        app.processEvents();
        RS_DEBUG->print("main: splashscreen: OK");
    }

    #if defined(Q_OS_MAC) && QT_VERSION > 0x050000
        //need stylesheet for Qt5 on mac
        app.setStyleSheet(
"QToolButton:checked"
"{"
"    background-color: rgb(160,160,160);"
"    border-style: inset;"
"}"
""
"QToolButton"
"{"
"    background-color: transparent;"
"}"
""
"QToolButton:hover"
"{"
"    background-color: rgb(255,255,255);"
"    border-style: outset;"
"}"
        );
    #endif

    const QString lpDebugSwitch0("-d"),lpDebugSwitch1("--debug") ;
    const QString help0("-h"), help1("--help");
    bool allowOptions=true;
    QList<int> argClean;
    for (int i=0; i<argc; i++)
    {
        QString argstr(argv[i]);
        if(allowOptions&&QString::compare("--", argstr)==0)
        {
            allowOptions=false;
            continue;
        }
        if (allowOptions && (help0.compare(argstr, Qt::CaseInsensitive)==0 ||
                             help1.compare(argstr, Qt::CaseInsensitive)==0 ))
        {
            qDebug()<<"librecad::usage: <options> <dxf file>";
            qDebug()<<"-h, --help\tdisplay this message";
            qDebug()<<"";
            qDebug()<<" --help\tdisplay this message";
            qDebug()<<"-d, --debug <level>";
            RS_DEBUG->print( RS_Debug::D_NOTHING, "possible debug levels:");
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Nothing", RS_Debug::D_NOTHING);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Critical", RS_Debug::D_CRITICAL);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Error", RS_Debug::D_ERROR);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Warning", RS_Debug::D_WARNING);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Notice", RS_Debug::D_NOTICE);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Informational", RS_Debug::D_INFORMATIONAL);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Debugging", RS_Debug::D_DEBUGGING);
            exit(0);
        }
        if ( allowOptions&& (argstr.startsWith(lpDebugSwitch0, Qt::CaseInsensitive) ||
                             argstr.startsWith(lpDebugSwitch1, Qt::CaseInsensitive) ))
        {
            argClean<<i;

            // to control the level of debugging output use --debug with level 0-6, e.g. --debug3
            // for a list of debug levels use --debug?
            // if no level follows, the debugging level is set
            argstr.remove(QRegExp("^"+lpDebugSwitch0));
            argstr.remove(QRegExp("^"+lpDebugSwitch1));
            char level;
            if(argstr.size()==0)
            {
                if(i+1<argc)
                {
                    if(QRegExp("\\d*").exactMatch(argv[i+1]))
                    {
                        ++i;
                        qDebug()<<"reading "<<argv[i]<<" as debugging level";
                        level=argv[i][0];
                        argClean<<i;
                    }
                    else
                        level='3';
                }
                else
                    level='3'; //default to D_WARNING
            }
            else
                level=argstr.toStdString()[0];

            switch(level)
            {
            case '?' :
                RS_DEBUG->print( RS_Debug::D_NOTHING, "possible debug levels:");
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Nothing", RS_Debug::D_NOTHING);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Critical", RS_Debug::D_CRITICAL);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Error", RS_Debug::D_ERROR);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Warning", RS_Debug::D_WARNING);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Notice", RS_Debug::D_NOTICE);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Informational", RS_Debug::D_INFORMATIONAL);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Debugging", RS_Debug::D_DEBUGGING);
                return 0;

            case '0' + RS_Debug::D_NOTHING :
                RS_DEBUG->setLevel( RS_Debug::D_NOTHING);
                ++i;
                break;

            case '0' + RS_Debug::D_CRITICAL :
                RS_DEBUG->setLevel( RS_Debug::D_CRITICAL);
                ++i;
                break;

            case '0' + RS_Debug::D_ERROR :
                RS_DEBUG->setLevel( RS_Debug::D_ERROR);
                ++i;
                break;

            case '0' + RS_Debug::D_WARNING :
                RS_DEBUG->setLevel( RS_Debug::D_WARNING);
                ++i;
                break;

            case '0' + RS_Debug::D_NOTICE :
                RS_DEBUG->setLevel( RS_Debug::D_NOTICE);
                ++i;
                break;

            case '0' + RS_Debug::D_INFORMATIONAL :
                RS_DEBUG->setLevel( RS_Debug::D_INFORMATIONAL);
                ++i;
                break;

            case '0' + RS_Debug::D_DEBUGGING :
                RS_DEBUG->setLevel( RS_Debug::D_DEBUGGING);
                ++i;
                break;

            default :
                RS_DEBUG->setLevel(RS_Debug::D_DEBUGGING);
                break;
            }
        }
    }
    RS_DEBUG->print("param 0: %s", argv[0]);

    QFileInfo prgInfo( QFile::decodeName(argv[0]) );
    QString prgDir(prgInfo.absolutePath());
    RS_SETTINGS->init(XSTR(QC_COMPANYKEY), XSTR(QC_APPKEY));
    RS_SYSTEM->init(XSTR(QC_APPNAME), XSTR(QC_VERSION), XSTR(QC_APPDIR), prgDir);

    // parse command line arguments that might not need a launched program:
    QStringList fileList = handleArgs(argc, argv, argClean);

    QString lang;
    QString langCmd;
    QString unit;

    RS_SETTINGS->beginGroup("/Defaults");
    #ifndef QC_PREDEFINED_UNIT
        unit = RS_SETTINGS->readEntry("/Unit", "Invalid");
    #else
        unit = RS_SETTINGS->readEntry("/Unit", QC_PREDEFINED_UNIT);
    #endif
    RS_SETTINGS->endGroup();

    // show initial config dialog:
    if (unit=="Invalid")
    {
        RS_DEBUG->print("main: show initial config dialog..");
        QG_DlgInitial di(nullptr);
        QPixmap pxm(":/main/intro_librecad.png");
        di.setPixmap(pxm);
        if (di.exec())
        {
            RS_SETTINGS->beginGroup("/Defaults");
            unit = RS_SETTINGS->readEntry("/Unit", "None");
            RS_SETTINGS->endGroup();
        }
        RS_DEBUG->print("main: show initial config dialog: OK");
    }

    RS_DEBUG->print("main: init fontlist..");
    RS_FONTLIST->init();
    RS_DEBUG->print("main: init fontlist: OK");

    RS_DEBUG->print("main: init patternlist..");
    RS_PATTERNLIST->init();
    RS_DEBUG->print("main: init patternlist: OK");

    RS_DEBUG->print("main: init scriptlist..");
    RS_SCRIPTLIST->init();
    RS_DEBUG->print("main: init scriptlist: OK");

    RS_DEBUG->print("main: loading translation..");
    RS_SETTINGS->beginGroup("/Appearance");
    #ifdef QC_PREDEFINED_LOCALE
        lang = RS_SETTINGS->readEntry("/Language", "");
        if (lang.isEmpty())
        {
            lang=QC_PREDEFINED_LOCALE;
            RS_SETTINGS->writeEntry("/Language", lang);
        }
        langCmd = RS_SETTINGS->readEntry("/LanguageCmd", "");
        if (langCmd.isEmpty())
        {
            langCmd=QC_PREDEFINED_LOCALE;
            RS_SETTINGS->writeEntry("/LanguageCmd", langCmd);
        }
    #else
        lang = RS_SETTINGS->readEntry("/Language", "en");
        langCmd = RS_SETTINGS->readEntry("/LanguageCmd", "en");
    #endif
    RS_SETTINGS->endGroup();

    RS_SYSTEM->loadTranslation(lang, langCmd);
    RS_DEBUG->print("main: loading translation: OK");

    RS_DEBUG->print("main: creating main window..");
    QC_ApplicationWindow appWin;
    RS_DEBUG->print("main: setting caption");
    appWin.setWindowTitle(XSTR(QC_APPNAME));

    RS_DEBUG->print("main: show main window");

    RS_SETTINGS->beginGroup("/Geometry");
    int windowWidth = RS_SETTINGS->readNumEntry("/WindowWidth", 0);
    int windowHeight = RS_SETTINGS->readNumEntry("/WindowHeight", 0);
    int windowX = RS_SETTINGS->readNumEntry("/WindowX", 30);
    int windowY = RS_SETTINGS->readNumEntry("/WindowY", 30);
    RS_SETTINGS->endGroup();

    if (windowWidth != 0)
        appWin.resize(windowWidth, windowHeight);

    appWin.move(windowX, windowY);

    RS_SETTINGS->beginGroup("Defaults");
    bool maximize = RS_SETTINGS->readNumEntry("/Maximize", 0);
    RS_SETTINGS->endGroup();
    if (maximize || windowWidth == 0)
        appWin.showMaximized();
    else
        appWin.show();

    RS_DEBUG->print("main: set focus");
    appWin.setFocus();
    RS_DEBUG->print("main: creating main window: OK");

    if (show_splash)
    {
        RS_DEBUG->print("main: updating splash");
        splash->raise();
        splash->showMessage(QObject::tr("Loading..."),
                Qt::AlignRight|Qt::AlignBottom, QC_SPLASH_TXTCOL);
        RS_DEBUG->print("main: processing events");
        qApp->processEvents();
        RS_DEBUG->print("main: updating splash: OK");
    }

    // Set LC_NUMERIC so that entering numeric values uses . as the decimal seperator
    setlocale(LC_NUMERIC, "C");

    RS_DEBUG->print("main: loading files..");
    bool files_loaded = false;
    for (QStringList::Iterator it = fileList.begin(); it != fileList.end(); ++it )
    {
        if (show_splash)
        {
            splash->showMessage(QObject::tr("Loading File %1..")
                    .arg(QDir::toNativeSeparators(*it)),
            Qt::AlignRight|Qt::AlignBottom, QC_SPLASH_TXTCOL);
            qApp->processEvents();
        }
        appWin.slotFileOpen(*it, RS2::FormatUnknown);
        files_loaded = true;
    }
    RS_DEBUG->print("main: loading files: OK");

    RS_DEBUG->print("main: app.exec()");

    if (!files_loaded)
    {
        appWin.slotFileNewNew();
    }

    if (show_splash)
        splash->finish(&appWin);
    else
        delete splash;

    int return_code = app.exec();

    RS_DEBUG->print("main: exited Qt event loop");

    return return_code;
}
示例#16
0
int main(int argc, char* argv[]) {
  QApplication app(argc, argv);
  app.setApplicationName("digitalnotewallet");
  app.setApplicationVersion(Settings::instance().getVersion());
  app.setQuitOnLastWindowClosed(false);

#ifndef Q_OS_MAC
  QApplication::setStyle(QStyleFactory::create("Fusion"));
#endif

  CommandLineParser cmdLineParser(nullptr);
  Settings::instance().setCommandLineParser(&cmdLineParser);
  bool cmdLineParseResult = cmdLineParser.process(app.arguments());
  Settings::instance().load();

#ifdef Q_OS_WIN
  if(!cmdLineParseResult) {
    QMessageBox::critical(nullptr, QObject::tr("Error"), cmdLineParser.getErrorText());
    return app.exec();
  } else if (cmdLineParser.hasHelpOption()) {
    QMessageBox::information(nullptr, QObject::tr("Help"), cmdLineParser.getHelpText());
    return app.exec();
  }
#endif

  LoggerAdapter::instance().init();

  QString dataDirPath = Settings::instance().getDataDir().absolutePath();
  if (!QDir().exists(dataDirPath)) {
    QDir().mkpath(dataDirPath);
  }

  QLockFile lockFile(Settings::instance().getDataDir().absoluteFilePath(QApplication::applicationName() + ".lock"));
  if (!lockFile.tryLock()) {
    QMessageBox::warning(nullptr, QObject::tr("Fail"), QString("%1 wallet already running").arg(CurrencyAdapter::instance().getCurrencyDisplayName()));
    return 0;
  }

  QLocale::setDefault(QLocale::c());

  SignalHandler::instance().init();
  QObject::connect(&SignalHandler::instance(), &SignalHandler::quitSignal, &app, &QApplication::quit);

  QSplashScreen* splash = new QSplashScreen(QPixmap(":images/splash"), Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
  if (!splash->isVisible()) {
    splash->show();
  }

  splash->showMessage(QObject::tr("Loading blockchain..."), Qt::AlignLeft | Qt::AlignBottom, Qt::black);
  app.processEvents();
  qRegisterMetaType<CryptoNote::TransactionId>("CryptoNote::TransactionId");
  qRegisterMetaType<quintptr>("quintptr");
  if (!NodeAdapter::instance().init()) {
    return 0;
  }

  splash->finish(&MainWindow::instance());
  MainWindow::instance().show();
  WalletAdapter::instance().open("");
  QObject::connect(QApplication::instance(), &QApplication::aboutToQuit, []() {
    MainWindow::instance().quit();
    if (WalletAdapter::instance().isOpen()) {
      WalletAdapter::instance().close();
    }

    NodeAdapter::instance().deinit();
  });

  return app.exec();
}
示例#17
0
文件: main.cpp 项目: dreamfrog/noobs
int main(int argc, char *argv[])
{
    // Wait for keyboard to appear before displaying anything
    KeyDetection::waitForKeyboard();

    QFile f("/sys/module/bcm2708/parameters/boardrev");
    f.open(f.ReadOnly);
    int rev = f.readAll().trimmed().toInt();
    f.close();

    qDebug() << "Board revision is " << rev;

    int gpioChannel;

    if (rev == 2 || rev == 3)
        gpioChannel = 0;
    else
        gpioChannel = 2;

    QApplication a(argc, argv);
    RightButtonFilter rbf;
    GpioInput gpio(gpioChannel);

    bool runinstaller = false;
    bool gpio_trigger = false;
    bool keyboard_trigger = true;
    bool force_trigger = false;

    QString defaultLang = "en";
    QString defaultKeyboard = "gb";
    QString defaultDisplay = "0";
    QString defaultPartition = "800";

    // Process command-line arguments
    for (int i=1; i<argc; i++)
    {
        // Flag to indicate first boot
        if (strcmp(argv[i], "-runinstaller") == 0)
            runinstaller = true;
        // Enables use of GPIO 3 to force NOOBS to launch by pulling low
        else if (strcmp(argv[i], "-gpiotriggerenable") == 0)
            gpio_trigger = true;
        // Disables use of keyboard to trigger recovery GUI
        else if (strcmp(argv[i], "-keyboardtriggerdisable") == 0)
            keyboard_trigger = false;
        // Forces display of recovery GUI every time
        else if (strcmp(argv[i], "-forcetrigger") == 0)
            force_trigger = true;
        // Allow default language to be specified in commandline
        else if (strcmp(argv[i], "-lang") == 0)
        {
            if (argc > i+1)
                defaultLang = argv[i+1];
        }
        // Allow default keyboard layout to be specified in commandline
        else if (strcmp(argv[i], "-kbdlayout") == 0)
        {
            if (argc > i+1)
                defaultKeyboard = argv[i+1];
        }
        // Allow default display mode to be specified in commandline
        else if (strcmp(argv[i], "-dispmode") == 0)
        {
            if (argc > i+1)
                defaultDisplay = --argv[i+1];
        }
        // Allow default boot partition to be specified in commandline
        else if (strcmp(argv[i], "-partition") == 0)
        {
            if (argc > i+1)
                defaultPartition = argv[i+1];
        }
    }

    // Intercept right mouse clicks sent to the title bar
    a.installEventFilter(&rbf);

#ifdef Q_WS_QWS
    QWSServer::setCursorVisible(false);
#endif

    // Set wallpaper and icon, if we have resource files for that
    if (QFile::exists(":/icons/raspberry_icon.png"))
        a.setWindowIcon(QIcon(":/icons/raspberry_icon.png"));

#ifdef Q_WS_QWS
        QWSServer::setBackground(BACKGROUND_COLOR);
#endif
        QSplashScreen *splash = new QSplashScreen(QPixmap(":/wallpaper.png"));
        splash->show();
        QApplication::processEvents();

    // If -runinstaller is not specified, only continue if SHIFT is pressed, GPIO is triggered,
    // or no OS is installed (/dev/mmcblk0p5 does not exist)
    bool bailout = !runinstaller
        && !force_trigger
        && !(gpio_trigger && (gpio.value() == 0 ))
        && !(keyboard_trigger && KeyDetection::isF10pressed())
        && QFile::exists(FAT_PARTITION_OF_IMAGE);

    // Keyboard detection done, load normal hid driver
    //QProcess::execute("/sbin/modprobe usbhid");

    // Default to booting first extended partition
    putFileContents("/sys/module/bcm2708/parameters/reboot_part", "5\n");

    if (bailout)
    {
        splash->hide();
        reboot_to_extended(defaultPartition, true);
    }

#ifdef Q_WS_QWS
    QWSServer::setCursorVisible(true);
#endif

    // Main window in the middle of screen
    MainWindow mw(defaultDisplay, splash);
    mw.setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, mw.size(), a.desktop()->availableGeometry()));
    mw.show();

#ifdef ENABLE_LANGUAGE_CHOOSER
     // Language chooser at the bottom center
    LanguageDialog* ld = new LanguageDialog(defaultLang, defaultKeyboard);
    ld->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignHCenter | Qt::AlignBottom, ld->size(), a.desktop()->availableGeometry()));
    ld->show();
#endif

    a.exec();
    reboot_to_extended(defaultPartition, false);

    return 0;
}
示例#18
0
int main( int argc, char ** argv )
{
	QApplication::setColorSpec( QApplication::CustomColor );

    QApplication a( argc, argv );
	a.setApplicationVersion( APP_VERSION );

    QSplashScreen* splash = new QSplashScreen;
    splash->setPixmap( QPixmap(":/icons/tonatiuhsplash.png") );
    splash->show();

    Qt::Alignment topRight = Qt::AlignRight | Qt::AlignTop;

    splash->showMessage(QObject::tr("Loading libraries..."), topRight, Qt::black);


    QApplication::addLibraryPath( QApplication::applicationDirPath()
	        + QDir::separator() + "marble" );

	SoQt::init( (QWidget *) NULL );

	//MFVec2::initClass();
	UserMField::initClass();
	UserSField::initClass();
	TSceneKit::initClass();
	TMaterial::initClass();
	TDefaultMaterial::initClass();
	TSeparatorKit::initClass();
	TShape::initClass();
	TCube::initClass();
	TLightShape::initClass();
	TShapeKit::initClass();
	TAnalyzerKit::initClass();
	TAnalyzerResultKit::initClass();
	TAnalyzerParameter::initClass();
	TAnalyzerResult::initClass();
	TAnalyzerLevel::initClass();
	TSquare::initClass();
	TLightKit::initClass();
	TSunShape::initClass();
	TDefaultSunShape::initClass();
	TTracker::initClass();
	TTrackerForAiming::initClass();
	TDefaultTracker::initClass();
	TSceneTracker::initClass();
	GraphicRootTracker::initClass();
	TTransmissivity::initClass();
	TDefaultTransmissivity::initClass();


	splash->showMessage( QObject::tr("Setting up the main window..."), topRight, Qt::black );


	QDir pluginsDirectory( qApp->applicationDirPath() );
	pluginsDirectory.cd( "plugins" );
	PluginManager pluginManager;
	pluginManager.LoadAvailablePlugins( pluginsDirectory );

    int exit;
   	if( argc > 1 )
   	{
   		QString tonatiuhFile = argv[1];

    	QFileInfo fileInfo( tonatiuhFile );
    	if( fileInfo.completeSuffix() == QLatin1String( "tnhs") )
    	{

    		QString fileName( argv[1] );
    		QFileInfo fileInfo( fileName );

    		QDir testDirectory( fileInfo.absolutePath() );
    		testDirectory.cd( "." );

    		QScriptEngine* interpreter = new QScriptEngine;
    		qScriptRegisterSequenceMetaType<QVector<QVariant> >(interpreter);


    		MainWindow* mw = new MainWindow( QLatin1String("") );
    		mw->SetPluginManager( &pluginManager );
    		QScriptValue tonatiuh = interpreter->newQObject( mw );
    		interpreter->globalObject().setProperty( "tonatiuh", tonatiuh );


    		QFile scriptFile( fileName );
    		if( !scriptFile.open( QIODevice::ReadOnly) )
    		{
    			QString errorMessage = QString( "Cannot open file %1." ).arg( fileName );
    			std::cerr<<errorMessage.toStdString()<<std::endl;
    		}


    		QTextStream in( &scriptFile );
    		QString program = in.readAll();
    		scriptFile.close();


    		QScriptSyntaxCheckResult checkResult = interpreter->checkSyntax( program );
    		if( checkResult.state() != QScriptSyntaxCheckResult::Valid )
    		{
    			QString errorMessage = QString( "Script Syntaxis Error.\n"
    					"Line: %1. %2" ).arg( QString::number( checkResult.errorLineNumber() ), checkResult.errorMessage () );
    			std::cerr<<errorMessage.toStdString()<<std::endl;
    			return -1;
    		}

    		QScriptValue result = interpreter->evaluate( program );
    		if( result.isError () )
    		{
    			QScriptValue lineNumber = result.property( "lineNumber");

    			QString errorMessage = QString( "Script Execution Error.\nLine %1. %2" ).arg( QString::number( lineNumber.toNumber() ), result.toString() );
    			std::cerr<<errorMessage.toStdString()<<std::endl;
    			return -1;

    		}

       		delete mw;
       		delete interpreter;
    		exit = 0;
    	}
    	else
    	{

    		MainWindow* mw = new MainWindow( tonatiuhFile );
    		mw->SetPluginManager( &pluginManager );


       		mw->show();
       	    splash->finish( mw );
       	    delete splash;
    	    exit = a.exec();
       		delete mw;
    	}
   	}
   	else
   	{
   		MainWindow* mw = new MainWindow("");
		mw->SetPluginManager( &pluginManager );
   		mw->show();
   	    splash->finish( mw );
   	    delete splash;
	    exit = a.exec();
   		delete mw;

   	}

	return exit;
}
示例#19
0
int gui_main(int argc, char **argv) {

	File_logger* initialization_log = new File_logger("sgems_status.log");
	initialization_log->subscribe(GsTLlog);

	QTscribe* qt_error_scribe = new QTscribe;
	qt_error_scribe->subscribe(GsTLcerr);

	GsTLlog << gstlIO::no_wait_end;
	//-----

	//---------------------
	// Initialize the libraries, manage the splash-screen, and set-up the
	// main application window

	QApplication app(argc, argv);
	QApplication::addLibraryPath(path_to_plugins());

	//QPixmap pixmap(path_to_splash_image());
  QPixmap pixmap(":/sgems-main/new_splash2-beta.bmp");

	QSplashScreen* splash = new QSplashScreen(pixmap);
  splash->show();

	splash->setFont(QFont("Times", 8, QFont::Bold));
	splash->showMessage("Initializing...");
	app.processEvents();

	Lib_initializer::init();

	splash->showMessage("Loading colormaps...");
	app.processEvents();
	Lib_initializer::load_colormaps();

	splash->showMessage("Loading geostat plugins...");
	app.processEvents();
	Lib_initializer::load_geostat_algos();
	Lib_initializer::load_filters_plugins();

	splash->showMessage("Loading action plugins...");
	app.processEvents();
	Lib_initializer::load_action_plugins();
	Lib_initializer::load_python_scripts();
	Lib_initializer::load_python_group_scripts();

	SoDB::init();
	//  QSP_application* appli = new QSP_application( 0 );
	//  SoQt::init( appli );
	//SoClipPlaneManip::initClass();
	//  GsTL_SoClipPlaneManip::initClass();
	GsTL_SoNode::initClass();
	SoVolumeRendering::init();

	QSP_application* appli = new QSP_application(0);
	SoQt::init(appli);

	//deprecated
	//app.setMainWidget( appli );

	Status_bar_scribe* statusbar_scribe = new Status_bar_scribe(appli->statusBar());
	statusbar_scribe->subscribe(GsTLcerr);
	statusbar_scribe->subscribe(GsTLcout);

	appli->init();  
	appli->setWindowTitle("SGeMS beta");

	// restore preferences
	QSettings settings;
	settings.setPath(QSettings::NativeFormat, QSettings::UserScope, "scrf.stanford.edu");
	int height = settings.value("/geometry/height", 480).toInt();
	int width = settings.value("/geometry/width", 640).toInt();
	appli->resize(QSize(width, height));

	bool show_algo_panel = settings.value("/panels/algo", true).toBool();
	bool show_cli_panel = settings.value("/panels/cli", false).toBool();

	appli->setWindowIcon(QIcon(":/sgems-main/new_icon6_32x32.bmp"));
  //QIcon windowIcon("d:/code-dev/GsTLAppli-qt4/GsTLAppli/main/new_icon6_32x32.bmp");
  //appli->setWindowIcon(windowIcon);
  
	appli->show();
  appli->show_algo_panel(show_algo_panel);
	appli->show_commands_panel(show_cli_panel);

	//------------------
	SmartPtr<Named_interface> ni = Root::instance()->interface(projects_manager + "/" + "project");
	GsTL_project* project = dynamic_cast<GsTL_project*> (ni.raw_ptr());
	appli_assert( project );
	Python_project_wrapper::set_project(project);
	//------------------


	splash->finish(appli);
	delete splash;

	//------------------------
	// Everything is now ready. We set up one more logging device, and it's done

	GsTLlog << gstlIO::wait_end;

	initialization_log->unsubscribe(GsTLlog);

	File_logger* main_log = new File_logger("sgems_history.log");
	main_log->subscribe(GsTLlog);
	main_log->append_newline(true);

	/*
	 //-------------
	 QSP_application appli( 0 );
	 SoQt::init( &appli );

	 app.setMainWidget( &appli );

	 Status_bar_scribe* statusbar_scribe = new Status_bar_scribe( appli.statusBar() );
	 statusbar_scribe->subscribe( GsTLcerr );

	 appli.init();
	 appli.show();
	 appli.setCaption( "SGeMS" );
	 //--------------
	 */
	SoQt::mainLoop();

	//delete appli;
	Lib_initializer::release();

	Root::instance()->list_all(std::cout);

	return 0;
}
示例#20
0
文件: main.cpp 项目: NLxjtu/McCad
// MAIN
//////////////////////
int main(int argc, char *argv[]) {
    // define messenger system
    McCadMessenger_Singleton *msgr = McCadMessenger_Singleton::Instance();
    McCadMessenger_ObserverInterface* stdCoutObserver = new McCadMessenger_StdOut;
    msgr->Register(stdCoutObserver);

    // define plugin path
    char* pLibPath = getenv("MCCAD_LIBDIR");
    OSD_Path pluginPath("empty");
    if (pLibPath == NULL) {
        cout << "MCCAD_LIBDIR is not defined!!! " << endl;
        return 1;
    }
    else
        pluginPath = OSD_Path(pLibPath);

    // load plugins
    McCadEXPlug_PluginManager* pluginManager = McCadEXPlug_PluginManager::Instance();
    pluginManager->LoadSharedLibrary(pluginPath);

    // handle input parameters
    TCollection_AsciiString Prog = argv[0];
    if(argc > 4 ) {
        string arg3(argv[3]), arg4(argv[4]);
        if(arg3 == ">" || arg3 == ">>") {
            argc = 3;
        }
        else if(arg4 == ">" || arg4 == ">>") {
            argc = 4;
        }
        else {
            printUsage(Prog);
            exit(0);
        }
    }
    bool openFile = false;

    // handle input
    TCollection_AsciiString inName;
 if(argc > 1)

//if (1)
   {
        TCollection_AsciiString inParameter;
        inParameter = argv[1];
        if(argc > 2)
            inName = argv[2];
        TCollection_AsciiString outputName;        
        TCollection_AsciiString strMatName = "";
        if (argc > 3)
            strMatName = argv[3];
        if(inParameter.IsEqual("-h") || inParameter.IsEqual("--help")) {
            printUsage();
            exit(0);
        }

        /* test code */
        //inParameter = "-m";
        TCollection_AsciiString config_file = "McCadConfig.txt";
        //inName = "convertedTest.stp";
        //strMatName = "material.xml";
        /* test code */

        // Expander
        if(inParameter.IsEqual("-e") || inParameter.IsEqual("--explode")) {
            cout << "\nMcCad_Exploder\n====================\n\n";
            Handle_TopTools_HSequenceOfShape inputShapes = readFile( inName );
            McCadIOHelper_Expander expander(inputShapes);
            Handle_TopTools_HSequenceOfShape expandedFiles = expander.GetExplodedShapes();
            if(expandedFiles->Length() < 2){
                TCollection_AsciiString message("Failed to expand file : ");
                message.AssignCat(inName);
                msgr->Message(message.ToCString());
                exit(0);
            }
            TCollection_AsciiString tmpName(inName);
            TCollection_AsciiString fileFilter = tmpName.Split( tmpName.SearchFromEnd(".") -1 );
            for(int i=1; i<=expandedFiles->Length(); i++){
                TCollection_AsciiString outName(tmpName);
                outName.Prepend("ExOut");
                outName.AssignCat("_");
                outName.AssignCat(i);
                outName.AssignCat(fileFilter);
                Handle_TopTools_HSequenceOfShape singleShape = new TopTools_HSequenceOfShape;
                singleShape->Append(expandedFiles->Value(i));
                writeFile(outName, singleShape);
            }
        }

        // Convertor
        else if(inParameter.IsEqual("-d") || inParameter.IsEqual("--decompose")) {
            cout << "\nMcCad_Decomposer\n====================\n\n";
            // read file
            Handle_TopTools_HSequenceOfShape inputShapes = readFile( inName );

            // decompose geometry
            McCadConvertTools_Convertor convertor(inputShapes);
            convertor.Convert();
            if (argc == 4 && !outputName.IsEmpty())
                convertor.SetFileName(outputName);

            if(!convertor.IsConverted()){
                cout << "Conversion failed!!!\n";
                return -1;
            }

            // export decomposed geometry to stp file
            TCollection_AsciiString exportName("converted");
            exportName += inName;
            inName = exportName.Split(exportName.SearchFromEnd("."));
            exportName += "stp";
            writeFile( exportName, convertor.GetConvertedModel());
            }

            // export decomposed geometry to stp file
        // Lei Lu 20150501
//            TCollection_AsciiString exportName("converted");
//            exportName += inName;
//            inName = exportName.Split(exportName.SearchFromEnd("."));
//            exportName += "stp";
//            writeFile( exportName, convertor.GetConvertedModel());
      //  }

        // Fuse
        else if(inParameter.IsEqual("-f") || inParameter.IsEqual("--fuse")) {
            cout << "\nMcCad_Fusioner\n====================\n\n";
            McCadIOHelper_Merger myMerger(inName);
            if(argc == 4 && !outputName.IsEmpty())
                myMerger.MergeToFile(outputName);
            else
                myMerger.Merge();
        }

        // Surface check
        else if(inParameter.IsEqual("-s") || inParameter.IsEqual("--surface-check")) {
            cout << "\n McCad_SurfaceChecker\n====================\n\n";
            if(argc < 3 || (argc == 4 && outputName.IsEmpty()) || argc > 4) {
                cout << "Output file name required\n\n";
                exit(-1);
            }
            McCadCSGTool_SurfaceChecker surfCheck;
            surfCheck.readDirectory(inName, outputName);
        }

        // Void Generator
        else if(inParameter.IsEqual("-m") || inParameter.IsEqual("--mcnp") ||
                inParameter.IsEqual("-t") || inParameter.IsEqual("--tripoli")||
                inParameter.IsEqual("-g") || inParameter.IsEqual("--gdml"))
        {
            // read parameter file
            if (!McCadConvertConfig::ReadPrmt(config_file))
            {
                return 0;
            }

            McCadInputModelData input_model;           
            if (!input_model.LoadSTEPModel(inName))
            {
                cout << "#Main Function: Read geometry data error! Please check the input file name!\n\n";
                return 0;
            }

            // New void generation algorithm
            // Modified by Lei Lu 12/08/2012 ~ 18/12/2013
            McCadVoidCellManager * pVoidCellManager = new McCadVoidCellManager();



            Handle(TopTools_HSequenceOfShape) hInputShape = input_model.GetModelData();
            pVoidCellManager->ReadGeomData( hInputShape );
            pVoidCellManager->ReadMatData(strMatName);
            TCollection_AsciiString outName = inName;       // Set the output file name
            outName.Split(outName.SearchFromEnd(".")-1);    // Remove the file extension.

            if(inParameter.IsEqual("-t") || inParameter.IsEqual("--tripoli"))
            {
                pVoidCellManager->SetConvetor("TRIPOLI");
                outName += "_TRIPOLI.txt";
            }
            else if(inParameter.IsEqual("-m") || inParameter.IsEqual("--mcnp"))
            {
                pVoidCellManager->SetConvetor("MCNP");
                outName += "_MCNP.txt";
            }
            //qiu add to generate GDML input
            else if (inParameter.IsEqual("-g") || inParameter.IsEqual("--gdml"))
            {
                pVoidCellManager->SetConvetor("GDML");
                outName += ".gdml";
            }


            pVoidCellManager->SetOutFileName(outName);
            pVoidCellManager->Process();                    // Process the conversion work

            delete pVoidCellManager;
            pVoidCellManager = NULL;
        }

        // open file for GUI
        else if(inParameter.Search(".stp")  > 0 || inParameter.Search(".mcn")  > 0 ||
                inParameter.Search(".d")    > 0 || inParameter.Search(".step") > 0 ||
                inParameter.Search(".mcnp") > 0 || inParameter.Search(".tri")  > 0 ||
                inParameter.IsEqual(".") )
        {
            openFile = true;
            inName = inParameter;
        }

        // print version
        else if(inParameter.IsEqual("-v") || inParameter.IsEqual("--version"))
            printVersion();
        else {
            cout << "\nUnknown Parameter ... " << argv[1] << endl;
            printUsage(Prog);
        }

        if(!openFile)
            return 0;
    }

    // GUI
    //////////////////////////////////////
    QApplication app(argc, argv);
    QSplashScreen* splash = new QSplashScreen(QPixmap(":images/splash.png"), Qt::WindowStaysOnTopHint);
    splash->show();
    splash->showMessage(app.tr("Loading libraries ....."), Qt::AlignRight | Qt::AlignBottom);
    QMcCad_Application QMcWin;

    // loading plugins
    QMcWin.SetPluginPath(pluginPath);
    QMcWin.LoadPlugins();
    Handle_TColStd_HSequenceOfAsciiString Formats = QMcWin.Formats();
    for (int j=1; j<= Formats->Length(); j++)
        splash->showMessage(app.tr(Formats->Value(j).ToCString()), Qt::AlignRight|Qt::AlignBottom);

    QMcWin.show();

    // delete splash
    if (splash) {
        splash->finish(&QMcWin);
        delete splash;
    }

    // open file imediately after window is loaded
    if(openFile)
        QMcWin.SetOpenFile(inName);

    // run Qt program
    return app.exec();
}
示例#21
0
文件: main.cpp 项目: KhuramAli/pcbsd
int main(int argc, char *argv[])
{
    QString changeLang;

    QApplication a(argc, argv);

    // Check what directory our app is in
    QString appDir;
    if ( QFile::exists("/usr/local/bin/pc-sysinstaller") )
      appDir = "/usr/local/share/pcbsd";
    else
      appDir = QCoreApplication::applicationDirPath();

    QTranslator translator;
    QLocale mylocale;
    QString langCode = mylocale.name();

    if ( ! changeLang.isEmpty() )       
       langCode = changeLang;

    if ( QFile::exists(appDir + "/i18n/SysInstaller_" + langCode + ".qm" ) ) {
      translator.load( QString("SysInstaller_") + langCode, appDir + "/i18n/" );
      a.installTranslator(&translator);
      qDebug() << "Loaded Translation:" << appDir + "/i18n/SysInstaller_" + langCode + ".qm";
    } else {
      qDebug() << "Could not find: " << appDir + "/i18n/SysInstaller_" + langCode + ".qm";
      langCode = "";
    }

    if ( argc == 2)
    {
      QString flag = argv[1];
      if ( flag == "-checkhardware" )
      {
        dialogCheckHardware d;
        QDesktopWidget *desk = a.desktop();
        QRect dimensions = desk->screenGeometry();
        int wid = dimensions.width();     // returns desktop width
        int hig = dimensions.height();    // returns desktop height
        d.setGeometry((wid/2) - (355/2), (hig/2) - (151/2), 355, 151);
        d.programInit();
        d.show();
        a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );
        return a.exec();
      }
    }


    // Show our splash screen, so the user doesn't freak that that it takes a few seconds to show up
    QPixmap pixmap(":/PCBSD/images/pcbsdheader.png");
    QSplashScreen *splash = new QSplashScreen(pixmap);
    splash->show();

    Installer w;


    // Center the installer
    QRect dimensions = QApplication::desktop()->screenGeometry();
    int wid = dimensions.width();     // returns desktop width
    int hig = dimensions.height();    // returns desktop height
    w.setGeometry((wid/2) - (650/2), (hig/2) - (435/2), 650, 435);

    // Start the init
    w.initInstall(splash);

    w.show();
    splash->finish(&w);
    
    return a.exec();
}
示例#22
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // Setup UI components
    ui->setupUi(this);
    ui->tableTabWidget->tabBar()->tabButton(0, QTabBar::RightSide)->resize(0, 0);
    QList<int> sizes;
    sizes << 100 << 1000;
    ui->splitter->setSizes(sizes);

    // Start splash screen
    QPixmap pixmap(":/images/resources/aperture_blue.png");
    QSplashScreen *splash = new QSplashScreen(pixmap);
    splash->show();

    // Open Database
    _dbManager = new DatabaseManager(this);
    QString messageResult = _dbManager->openDB();
    if(messageResult != NULL) {
        QMessageBox::critical(this, tr("Database Error"), "The database could not be opened: \n" + messageResult);
        ui->statusBar->showMessage("Open Database unsuccessful");

    } else {

        ui->statusBar->showMessage("Database Connected");

        messageResult = _dbManager->createCustomerAndInvoiceTables();
        if(messageResult != NULL){
            QMessageBox::critical(this, tr("Database Error"), "The tables could not be created: \n" + messageResult);
        }

        // Load the customer List
        _customerTableModel = new QSqlTableModel(this);
        _customerTableModel->setTable("customer");
        _customerTableModel->select();
        ui->listView->setModel(_customerTableModel);
        ui->listView->setModelColumn(1);
//        _customerModel = _dbManager->loadCustomerList();
//        if(_customerModel != NULL) {
//            ui->listView->setModel(_customerModel);
//            ui->statusBar->showMessage("Successfully loaded customer list");
//        } else {
//            QMessageBox::critical(this, tr("Database Error"), "The database could not load the customer list");
//            ui->statusBar->showMessage("Database: Load customer list unsuccessful");
//        }

        // Load all Invoice table
        _invoiceTableModel = new QSqlTableModel(this);
        _invoiceTableModel->setTable("invoice");
        _invoiceTableModel->select();
        ui->tableView->setModel(_invoiceTableModel);
//        _invoiceModel = _dbManager.loadInvoiceTable();

//        if(_invoiceModel != NULL) {
//            ui->tableView->setModel(_invoiceModel);
//            ui->statusBar->showMessage("Successfully loaded invoice table");
//        } else {
//            QMessageBox::critical(this, tr("Database Error"), "The database could not load the invoice table");
//            ui->statusBar->showMessage("Database: Load invoice table unsuccessful");
//        }

    }

    //QThread::sleep(3);
    splash->hide();
}
示例#23
0
文件: CApp.cpp 项目: Stroff/Amonsoft
//----------------------------------------------------------------------------
// Run app
//----------------------------------------------------------------------------
void CApp::runApp()
{

    // We must always have an application
    QApplication application( argc_, argv_ );
    AmonSoft *main = new AmonSoft; // We create our dialog

    dlgAmonSoft *gui = const_cast< dlgAmonSoft* >( g_gui );
    gui = main;

    // Shareware version !
    QDate currentDate = QDate::currentDate();
    QDate expireDate;
    expireDate.setYMD( 2007, 12, 30 );

    if( currentDate > expireDate )
    {
        QMessageBox::critical( main,
            "Votre version a expiré",
            "Veuillez contacter votre revendeur pour continuer à utiliser ce programme",
            QMessageBox::Ok,
            QMessageBox::NoButton );
        exit( 0 );
    }

    // Splash screen
    QImage imgSplash( "Forms/Img/Splash.PNG" );
    QSplashScreen *splash =
	    new QSplashScreen( imgSplash );

    splash->show();  

    Datas::usLastId = 0;
    Datas::usLastIdEntses = 0;

    splash->message(QObject::tr("Initialisation de Xerces..."),
	    Qt::AlignLeft | Qt::AlignTop, Qt::blue);

    XMLPlatformUtils::Initialize();

    //<-- Insert here modules to load during splash screen
    splash->message(QObject::tr("Chargement de l'interface..."),
        Qt::AlignLeft | Qt::AlignTop, Qt::blue);
    //-->

    application.setMainWidget( main );        // It is our main widget

    CUpdater  up( *main );
    up.updateAvailable();

    // Interface init
    splash->message(QObject::tr("Chargement des données..."),
        Qt::AlignLeft | Qt::AlignTop, Qt::blue);

    makeBackup();

    // Load searchs
    Datas::g_Search = new Datas::CSearch();
    Datas::g_Search->loadFileSearch( sSearchFile );
    Datas::g_Search->loadInComboBox( main->comboBoxSearchFunction, true );

    // Add empty enterprise and person to reset form
    Datas::CPersonnes    *pEmptyPerson = new Datas::CPersonnes( true );
    Datas::CEntreprise   *pEmptyEnterprise = new Datas::CEntreprise( true );

    Datas::g_listPersonnes.push_back( pEmptyPerson );
    Datas::g_listEntreprises.push_back( pEmptyEnterprise );
        
    // Initialize & load preference system
    g_Preferences = new Preferences::CPreferences();

    // Initialize parser
    g_Parser              = new CParser( sPersonnesFile );
    g_ParserEntses        = new CParser( sEntreprisesFile );
    g_ParserFamille       = new CParser( sFamilleFile );

    // Be carrefull, order is really important !
    loadXercesData( *main );
    loadXercesDataEntses( *main );
    loadXercesDataFamille( *main ); // Always after Personnes load !!

    // TODO: Put progress bar

    // Show version information
    QString   strVersion = "Amonsoft (c) Sesam micro 2005-2006 Version ";
    qDebug( strVersion + STR_APP_VERSION );

    main->lister();
    main->show(); // Show it...
        
    delete splash;

    application.exec();              // And run!

    saveXercesData();
    delete g_Preferences;

    XMLPlatformUtils::Terminate();    
}
示例#24
0
MainWindow::MainWindow()
	: mUi(new Ui::MainWindowUi())
	, mListenerManager(NULL)
	, mPropertyModel(NULL)
{
	QSettings settings("SPbSU", "QReal");
	//bool showSplash = settings.value("Splashscreen", true).toBool();
	bool showSplash = false;
	QSplashScreen* splash =
			new QSplashScreen(QPixmap(":/icons/kroki3.PNG"), Qt::SplashScreen | Qt::WindowStaysOnTopHint);

	QProgressBar *progress = new QProgressBar((QWidget*) splash);
	progress->move(20,270);
	progress->setFixedWidth(600);
	progress->setFixedHeight(15);
	progress->setRange(0, 100);

	// Step 1: splash screen loaded, progress bar initialized.
	progress->setValue(5);
	if (showSplash)
	{
		splash->show();
		QApplication::processEvents();
	}
	mUi->setupUi(this);

#if defined(Q_WS_WIN)
	mUi->menuSvn->setEnabled(false);  // Doesn't work under Windows anyway.
#endif

	mUi->tabs->setTabsClosable(true);
	mUi->tabs->setMovable(true);

	if (!showSplash)
		mUi->actionShowSplash->setChecked(false);

	mUi->minimapView->setRenderHint(QPainter::Antialiasing, true);

	// Step 2: Ui is ready, splash screen shown.
	progress->setValue(20);
	mUi->actionShow_grid->setChecked(settings.value("ShowGrid", true).toBool());
	mUi->actionShow_alignment->setChecked(settings.value("ShowAlignment", true).toBool());
	mUi->actionSwitch_on_grid->setChecked(settings.value("ActivateGrid", false).toBool());
	mUi->actionSwitch_on_alignment->setChecked(settings.value("ActivateAlignment", true).toBool());

	connect(mUi->actionQuit, SIGNAL(triggered()), this, SLOT(close()));

	connect(mUi->actionShowSplash, SIGNAL(toggled(bool)), this, SLOT (toggleShowSplash(bool)));

	connect(mUi->actionOpen, SIGNAL(triggered()), this, SLOT(open()));
	connect(mUi->actionSave, SIGNAL(triggered()), this, SLOT(saveAll()));
	connect(mUi->actionSave_as, SIGNAL(triggered()), this, SLOT(saveAs()));
	connect(mUi->actionPrint, SIGNAL(triggered()), this, SLOT(print()));
	connect(mUi->actionMakeSvg, SIGNAL(triggered()), this, SLOT(makeSvg()));

	connect(mUi->actionDeleteFromDiagram, SIGNAL(triggered()), this, SLOT(deleteFromDiagram()));

	connect(mUi->tabs, SIGNAL(currentChanged(int)), this, SLOT(changeMiniMapSource(int)));
	connect(mUi->tabs, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));

	connect(mUi->actionCheckout, SIGNAL(triggered()), this, SLOT(doCheckout()));
	connect(mUi->actionCommit, SIGNAL(triggered()), this, SLOT(doCommit()));
	connect(mUi->actionExport_to_XMI, SIGNAL(triggered()), this, SLOT(exportToXmi()));
	connect(mUi->actionGenerate_to_Java, SIGNAL(triggered()), this, SLOT(generateToJava()));
	connect(mUi->actionGenerate_to_Hascol, SIGNAL(triggered()), this, SLOT(generateToHascol()));
	connect(mUi->actionShape_Edit, SIGNAL(triggered()), this, SLOT(openShapeEditor()));
	connect(mUi->actionGenerate_Editor, SIGNAL(triggered()), this, SLOT(generateEditor()));
	connect(mUi->actionGenerate_Editor_qrmc, SIGNAL(triggered()), this, SLOT(generateEditorWithQRMC()));
	connect(mUi->actionParse_Editor_xml, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
	connect(mUi->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferencesDialog()));

	connect(mUi->actionParse_Hascol_sources, SIGNAL(triggered()), this, SLOT(parseHascol()));
	connect(mUi->actionParse_Java_Libraries, SIGNAL(triggered()), this, SLOT(parseJavaLibraries()));

	connect(mUi->actionPlugins, SIGNAL(triggered()), this, SLOT(settingsPlugins()));
	connect(mUi->actionShow_grid, SIGNAL(toggled(bool)), this, SLOT(showGrid(bool)));
	connect(mUi->actionShow_alignment, SIGNAL(toggled(bool)), this, SLOT(showAlignment(bool)));
	connect(mUi->actionSwitch_on_grid, SIGNAL(toggled(bool)), this, SLOT(switchGrid(bool)));
	connect(mUi->actionSwitch_on_alignment, SIGNAL(toggled(bool)), this, SLOT(switchAlignment(bool)));

	connect(mUi->actionHelp, SIGNAL(triggered()), this, SLOT(showHelp()));
	connect(mUi->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
	connect(mUi->actionAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

	connect(mUi->actionShow, SIGNAL(triggered()), this, SLOT(showGestures()));

	connect(mUi->minimapZoomSlider, SIGNAL(valueChanged(int)), this, SLOT(adjustMinimapZoom(int)));

	connect(mUi->actionDebug, SIGNAL(triggered()), this, SLOT(debug()));
	connect(mUi->actionDebug_Single_step, SIGNAL(triggered()), this, SLOT(debugSingleStep()));

	connect(mUi->actionClear, SIGNAL(triggered()), this, SLOT(exterminate()));
	connect(mUi->save_metamodel, SIGNAL(triggered()), this, SLOT(saveMetaModel()));

	adjustMinimapZoom(mUi->minimapZoomSlider->value());
	initGridProperties();

	// Step 3: Ui connects are done.
	progress->setValue(40);

	QString workingDir = settings.value("workingDir", ".").toString();

	mRootIndex = QModelIndex();
	mModels = new models::Models(workingDir, mEditorManager);

	mPropertyModel = new PropertyEditorModel(mEditorManager, mModels->logicalModelAssistApi());

	mUi->paletteDock->setWidget(mUi->paletteToolbox);
	mUi->errorDock->setWidget(mUi->errorListWidget);
	mUi->errorListWidget->init(this);
	mUi->errorDock->setVisible(false);
	mUi->propertyEditor->setModel(mPropertyModel);
	mUi->propertyEditor->verticalHeader()->hide();
	mUi->propertyEditor->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents);
	mUi->propertyEditor->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
	mUi->propertyEditor->setItemDelegate(&mDelegate);

	connect(mUi->graphicalModelExplorer, SIGNAL(clicked(QModelIndex const &)), this, SLOT(graphicalModelExplorerClicked(QModelIndex)));
	connect(mUi->logicalModelExplorer, SIGNAL(clicked(QModelIndex const &)), this, SLOT(logicalModelExplorerClicked(QModelIndex)));

	mUi->graphicalModelExplorer->addAction(mUi->actionDeleteFromDiagram);
	mUi->logicalModelExplorer->addAction(mUi->actionDeleteFromDiagram);

	// Step 4: Property editor and model explorers are initialized.
	progress->setValue(60);
	loadPlugins();
	showMaximized();

	// Step 5: Plugins are loaded.
	progress->setValue(70);

	settings.beginGroup("MainWindow");
	if (!settings.value("maximized", true).toBool()) {
		showNormal();
		resize(settings.value("size", QSize(1024, 800)).toSize());
		move(settings.value("pos", QPoint(0, 0)).toPoint());
	}
	settings.endGroup();

	// Step 6: Save loaded, models initialized.
	progress->setValue(80);

	mListenerManager = new ListenerManager(mEditorManager.listeners()
										   , mModels->logicalModelAssistApi(), mModels->graphicalModelAssistApi());

	TypeList missingPlugins = mEditorManager.checkNeededPlugins(mModels->logicalRepoApi(), mModels->graphicalRepoApi());
	if (!missingPlugins.isEmpty()) {
		QString text = "These plugins are not present, but needed to load the save:\n";
		foreach (NewType const type, missingPlugins) {
			text += type.editor() + "\n";
			QMessageBox::warning(this, tr("Some plugins are missing"), text);
			close();
			return;
		}
示例#25
0
void LiteApp::load(bool bUseSession)
{
    QSplashScreen *splash = 0;
    bool bSplash = m_settings->value(LITEAPP_SPLASHVISIBLE,true).toBool();
    if (bSplash) {
        splash = new QSplashScreen(QPixmap::fromImage(makeSplashImage(this)),Qt::WindowStaysOnTopHint);
    }
    if (bSplash) {
        splash->show();
    }

    if (bSplash) {
        splash->showMessage("liteide scan plugins ...",Qt::AlignLeft|Qt::AlignBottom);
    }

    qApp->processEvents();

    loadMimeType();
    loadPlugins();

    if (bSplash) {
        splash->showMessage("liteide load plugins ...",Qt::AlignLeft|Qt::AlignBottom);
    }

    qApp->processEvents();
    initPlugins();

    if (bSplash) {
        splash->showMessage("liteide load state ...",Qt::AlignLeft|Qt::AlignBottom);
    }

    qApp->processEvents();

    loadState();
    m_mainwindow->show();

    emit loaded();
    m_projectManager->setCurrentProject(0);

    if (bSplash) {
        splash->showMessage("liteide load session ...",Qt::AlignLeft|Qt::AlignBottom);
    }

    qApp->processEvents();

    appendLog("LiteApp","loaded");
    bool b = m_settings->value(LITEAPP_AUTOLOADLASTSESSION,true).toBool();
    if (b && bUseSession) {
        loadSession("default");
    }

    if (bSplash) {
        m_mainwindow->raise();
        splash->finish(m_mainwindow);
        splash->deleteLater();
    }

    this->appendLog("HtmlWidgetFactory",m_htmlWidgetManager->classNameList().join(" "));
    this->appendLog("DefaultHtmlWidgetFactory",m_htmlWidgetManager->defaultClassName());

    m_goProxy->call("version");
    m_goProxy->call("cmdlist");    
}
示例#26
0
文件: main.cpp 项目: K1161411/opencvr
int main(int argc, char *argv[])
{
	int dummy = errno;
	ClientFactory *pFactory = NULL;

	QApplication a(argc, argv);

	a.setStyle(new VStyle); 
	astring strVSCDefaultPath = VSC_DEFAULT_SYSPATH;
#ifdef WIN32
#ifndef _WIN64
	astring strLoggerPath = strVSCDefaultPath + "\\vidstor\\logs\\";
#else
	astring strLoggerPath = strVSCDefaultPath + "\\vidstor64\\logs\\";
#endif
#else
	astring strLoggerPath = strVSCDefaultPath + "/vidstor/logs/";
#endif
	Poco::File file1(strLoggerPath);
	file1.createDirectories();
	astring strLoggerFile = strLoggerPath + "opencvrclient";
	Debug::init(9200, strLoggerFile);

	Debug::logger().info("opencvrclient started");
	//Debug::logger().info("opencvrclient started {} {}", __LINE__, __FUNCTION__);
	//Debug::logger().info("opencvrclient started {} {}", __LINE__, __FUNCTION__);

#ifdef WIN32
	QFont font;
	font.setPointSize(10); 
	font.setFamily(("΢ÈíÑźÚ"));
	font.setBold(false);

	a.setFont(font);
#else
	QFont font;
	font.setPointSize(10); 
	font.setFamily(("WenQuanYi Zen Hei"));
	font.setBold(false);

	a.setFont(font);
#endif

	QPixmap pixmap(":/logo/resources/splash.png");
	QSplashScreen *splash = new QSplashScreen(pixmap);

	splash->setStyleSheet(QStringLiteral("color : white;"));    
	splash->show();
	
    pFactory = new ClientFactory;

	if (pFactory->Init() == FALSE)
	{
		astring strPath = VSC_DEFAULT_SYSPATH;
		pFactory->SetSystemPath(strPath);
		pFactory->Init();
	}

	VidLanguage m_lang;
	pFactory->GetLang(m_lang);
	if (m_lang == VID_LANG_AUTO)
	{
		if (QLocale::system().name() == "zh_CN")
		{
			LoadLangZH(a);
		}
	}
	else if (m_lang == VID_ZH_CN)
	{
		LoadLangZH(a);
	}//else if add more language to here

	
	splash->showMessage(QObject::tr("Starting ..."));

	VTaskMgr *pVTaskMgr = new VTaskMgr();

	VSCMainWindows w(*pFactory);

	//w.showMaximized();
	w.hide();
	//w.showFullScreen();
	splash->finish(&w);
	/* Auto  */
	if (pFactory->GetAutoLogin() == false)
	{
		w.ShowLogin();
	}else
	{
		w.showMaximized();
	}

	delete splash;
	return a.exec();
}
示例#27
0
void LiteApp::load(bool bUseSession, IApplication *baseApp)
{
    QSplashScreen *splash = 0;
    bool bSplash = m_settings->value(LITEAPP_SPLASHVISIBLE,true).toBool();
    if (baseApp) {
        bSplash = false;
    }
    if (bSplash) {
        splash = new QSplashScreen(QPixmap::fromImage(makeSplashImage(this)),Qt::WindowStaysOnTopHint);
    }
    if (bSplash) {
        splash->show();
    }

    if (bSplash) {
        splash->showMessage("Scanning plugins...",Qt::AlignLeft|Qt::AlignBottom);
    }

    qApp->processEvents();

    loadMimeType();
    loadPlugins();

    if (bSplash) {
        splash->showMessage("Loading plugins...",Qt::AlignLeft|Qt::AlignBottom);
    }

    qApp->processEvents();
    initPlugins();

    if (bSplash) {
        splash->showMessage("Loading state...",Qt::AlignLeft|Qt::AlignBottom);
    }

    qApp->processEvents();
    loadState();
    if (baseApp) {
        if (baseApp->mainWindow()->isMaximized()) {
            m_mainwindow->resize(800,600);
            m_mainwindow->show();
        } else {
            QRect rc = baseApp->mainWindow()->geometry();
            rc.adjust(20,20,20,20);
            m_mainwindow->setGeometry(rc);
            m_mainwindow->show();
        }
    } else {
        m_mainwindow->show();
    }

    emit loaded();
    m_projectManager->setCurrentProject(0);

    if (bSplash) {
        splash->showMessage("Loading session...",Qt::AlignLeft|Qt::AlignBottom);
    }

    qApp->processEvents();

    bool b = m_settings->value(LITEAPP_AUTOLOADLASTSESSION,true).toBool();
    if (b && bUseSession) {
        loadSession("default");
    }

    if (bSplash) {
        m_mainwindow->raise();
        splash->finish(m_mainwindow);
        splash->deleteLater();
    }

    this->appendLog("HtmlWidgetFactory",m_htmlWidgetManager->classNameList().join(" "));
    this->appendLog("DefaultHtmlWidgetFactory",m_htmlWidgetManager->defaultClassName());

    m_goProxy->call("version");
    m_goProxy->call("cmdlist");    
	
    appendLog("LiteApp","Finished loading");
}
示例#28
0
int SasiApp::exec()
{		
	QSplashScreen* splash = 0;
	QPixmap splash_pixmap;
	QWidget* show_screen = desktop()->screen( 0 );
	if ( splash_pixmap.load( SLcustomizations().GraphicsDir() + "/splash.png" ) )
	{
		splash = new QSplashScreen(show_screen,splash_pixmap);
		splash->show();
	}
	wxLogChain* logchain = 0;
	wxLog::SetActiveTarget( new wxLogChain( new wxLogStream( &std::cout ) ) );

	//this needs to called _before_ mainwindow instance is created
	wxInitAllImageHandlers();
	wxFileSystem::AddHandler(new wxZipFSHandler);
	wxSocketBase::Initialize();

	usync().FastLoadUnitSyncLibInit( );

	QDeclarativeView view(show_screen);
	QString qmldir;
	try {
		qmldir = SLcustomizations().QmlDir();
	}
	catch ( Customizations::DataException& e )
	{
		//for some f****d up reason the strings get internally f****d up w/o the hardcopy
		QList<QString> copy = e.errors_;
		QErrorWindow error_win ( copy );
		return error_win.exec();
	}

	AudioManager audio_manager (this);
	audio_manager.start();

	view.engine()->addImportPath( qmldir );
#ifdef __WXMSW__
	//for webkit declarative plugin
	view.engine()->addImportPath( QDir( QCoreApplication::applicationDirPath() + "/imports").absolutePath() );
#endif

	// Visual initialization
	view.engine()->addImageProvider("minimaps", new MinimapImageProvider);
	view.engine()->addImageProvider("graphics", new GraphicsProvider);
	view.engine()->addImageProvider("sides", new SideImageProvider);
#if USE_OPENGL
	QGLFormat format = QGLFormat::defaultFormat();
	#ifdef Q_WS_MAC
		format.setSampleBuffers(true);
	#else
		format.setSampleBuffers(false);
	#endif
	QGLWidget *glWidget = new QGLWidget(format, &view);
	view.setViewport(glWidget);
	view.setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
#endif
	view.setAttribute(Qt::WA_OpaquePaintEvent);
	view.setAttribute(Qt::WA_NoSystemBackground);
	view.setResizeMode(QDeclarativeView::SizeRootObjectToView);

	MaplistModel maplist_model( usync().GetMapList() );
	SkirmishModel skirmish_model;
	SideModel side_model( SLcustomizations().GetModname() );
	PresetModel preset_model(this);
	ScreenResolutionModel screenres_model(this);

	spring().connect( &spring(), SIGNAL(springStarted()), &audio_manager, SLOT(pause()));
	spring().connect( &spring(), SIGNAL(springStopped()), &audio_manager, SLOT(resume()));

	QObject::connect((QObject*)view.engine(), SIGNAL(quit()), this, SLOT(quit()));
	QObject::connect((QObject*)view.engine(), SIGNAL(quit()), &audio_manager, SLOT(doQuit()));
	QDeclarativeContext* ctxt = view.rootContext();
	ctxt->setContextProperty("maplistModel", &maplist_model );
	ctxt->setContextProperty("skirmishModel", &skirmish_model );
	ctxt->setContextProperty("sideModel", &side_model );
	ctxt->setContextProperty("audioManager", &audio_manager );
	ctxt->setContextProperty("presetModel", &preset_model );
	ctxt->setContextProperty("screenresModel", &screenres_model );

	const int sleep_seconds = -1;
	for ( int i = sleep_seconds; splash && i > 0; i-- ) {
		splash->showMessage( QString("sleeping for %1 seconds, just to show you this").arg( i ), Qt::AlignHCenter | Qt::AlignBottom );
		processEvents();
		sleep( 1 );
	}

	//	view.showFullScreen();
	if ( splash )
		splash->finish(&view);
	view.setSource(QUrl(qmldir + "/main.qml"));
	QObject::connect(this, SIGNAL(appLoaded()), (QObject*)view.rootObject(), SLOT(onAppLoaded()));

	QList<QDeclarativeError> errors = view.errors();
	if ( errors.size() )
	{
		QErrorWindow error_window ( errors );
		return error_window.exec();
	}
	view.show();
	view.setFocus();
	emit appLoaded();
	int ret = QApplication::exec();
	audio_manager.wait( 5 /*seconds*/ );
	return ret;
}
示例#29
0
int main(int argc, char *argv[])
{
    QtilitiesApplication a(argc, argv);
    QtilitiesApplication::setOrganizationName("Jaco Naude");
    QtilitiesApplication::setOrganizationDomain("Qtilities");
    QtilitiesApplication::setApplicationName("Main Window Example");
    QtilitiesApplication::setApplicationVersion(QtilitiesApplication::qtilitiesVersionString());

    // Create a QtilitiesMainWindow to show our different modes:
    QtilitiesMainWindow exampleMainWindow(QtilitiesMainWindow::ModesBottom);
    QtilitiesApplication::setMainWindow(&exampleMainWindow);

    // Create the configuration widget:
    ConfigurationWidget config_widget;
    config_widget.setCategorizedTabDisplay(true);
    QtilitiesApplication::setConfigWidget(&config_widget);

    // Initialize the logger:
    Log->setLoggerSessionConfigPath(QtilitiesApplication::applicationSessionPath());
    LOG_INITIALIZE();
    Log->setIsQtMessageHandler(false);

    // Add a formatting hint to the RichText formatting engine.
    AbstractFormattingEngine* rich_text_engine = Log->formattingEngineReference(qti_def_FORMATTING_ENGINE_RICH_TEXT);
    if (rich_text_engine) {
        QRegExp reg_exp_success_color = QRegExp(QObject::tr("Successfully") + "*",Qt::CaseInsensitive,QRegExp::Wildcard);
        CustomFormattingHint success_message_hint(reg_exp_success_color,"green",Logger::Info);
        rich_text_engine->addColorFormattingHint(success_message_hint);
    }

    // Speed up application launching a bit...
    ACTION_MANAGER->commandObserver()->startProcessingCycle();
    ACTION_MANAGER->actionContainerObserver()->startProcessingCycle();
    OBJECT_MANAGER->objectPool()->startProcessingCycle();

    // We show a splash screen in this example:
    #ifdef QT_NO_DEBUG
    QPixmap pixmap(QTILITIES_LOGO_BT_300x300);
    QSplashScreen *splash = new QSplashScreen(pixmap);
    splash->setWindowFlags(Qt::SplashScreen | Qt::WindowStaysOnTopHint);
    splash->show();
    QObject::connect(EXTENSION_SYSTEM,SIGNAL(newProgressMessage(QString)),splash,SLOT(showMessage(QString)));
    a.processEvents();
    #endif

    // Initialize the clipboard manager:
    CLIPBOARD_MANAGER->initialize();

    // Create menu related things.
    bool existed;
    ActionContainer* menu_bar = ACTION_MANAGER->createMenuBar(qti_action_MENUBAR_STANDARD,existed);
    exampleMainWindow.setMenuBar(menu_bar->menuBar());
    ActionContainer* file_menu = ACTION_MANAGER->createMenu(qti_action_FILE,existed);
    ActionContainer* edit_menu = ACTION_MANAGER->createMenu(qti_action_EDIT,existed);
    ActionContainer* view_menu = ACTION_MANAGER->createMenu(qti_action_VIEW,existed);
    ActionContainer* about_menu = ACTION_MANAGER->createMenu(qti_action_ABOUT,existed);
    menu_bar->addMenu(file_menu);
    menu_bar->addMenu(edit_menu);
    menu_bar->addMenu(view_menu);
    menu_bar->addMenu(about_menu);

    // Get the standard context.
    QList<int> std_context;
    std_context.push_front(CONTEXT_MANAGER->contextID(qti_def_CONTEXT_STANDARD));

    // Register action place holders for this application. This allows control of your menu structure.
    // File Menu
    Command* command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_FILE_SETTINGS,QObject::tr("Settings"),QKeySequence(),std_context);
    QObject::connect(command->action(),SIGNAL(triggered()),&config_widget,SLOT(show()));
    file_menu->addAction(command);

    // Edit Menu
    command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_EDIT_UNDO,QObject::tr("Undo"),QKeySequence(QKeySequence::Undo));
    command->setCategory(QtilitiesCategory("Editing"));
    edit_menu->addAction(command);
    command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_EDIT_REDO,QObject::tr("Redo"),QKeySequence(QKeySequence::Redo));
    command->setCategory(QtilitiesCategory("Editing"));
    edit_menu->addAction(command);
    edit_menu->addSeperator();
    command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_EDIT_COPY,QObject::tr("Copy"),QKeySequence(QKeySequence::Copy));
    command->setCategory(QtilitiesCategory("Editing"));
    edit_menu->addAction(command);
    command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_EDIT_CUT,QObject::tr("Cut"),QKeySequence(QKeySequence::Cut));
    command->setCategory(QtilitiesCategory("Editing"));
    edit_menu->addAction(command);
    command = ACTION_MANAGER->command(qti_action_EDIT_PASTE);
    command->setCategory(QtilitiesCategory("Editing"));
    edit_menu->addAction(command);
    edit_menu->addSeperator();
    command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_EDIT_SELECT_ALL,QObject::tr("Select All"),QKeySequence(QKeySequence::SelectAll));
    command->setCategory(QtilitiesCategory("Editing"));
    edit_menu->addAction(command);
    command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_EDIT_CLEAR,QObject::tr("Clear"));
    command->setCategory(QtilitiesCategory("Editing"));
    edit_menu->addAction(command);
    edit_menu->addSeperator();
    command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_EDIT_FIND,QObject::tr("Find"),QKeySequence(QKeySequence::Find));
    edit_menu->addAction(command);

    // Add the code editor config widget:
    CodeEditorWidgetConfig code_editor_config;
    OBJECT_MANAGER->registerObject(&code_editor_config,QtilitiesCategory("GUI::Configuration Pages (IConfigPage)","::"));

    // Create the Example before plugin loading since it registers a project items:
    ExampleMode* example_mode = new ExampleMode;
    file_menu->addSeperator();
    command = ACTION_MANAGER->registerActionPlaceHolder("File.ToggleModeIcon",QObject::tr("Toggle Mode Icon"),QKeySequence(),std_context);
    QObject::connect(command->action(),SIGNAL(triggered()),example_mode,SLOT(toggleModeIcon()));
    file_menu->addAction(command);
    OBJECT_MANAGER->registerObject(example_mode);

    file_menu->addSeperator();
    command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_FILE_EXIT,QObject::tr("Exit"),QKeySequence(QKeySequence::Close),std_context);
    QObject::connect(command->action(),SIGNAL(triggered()),QCoreApplication::instance(),SLOT(quit()));
    file_menu->addAction(command);
    // About Menu
    command = ACTION_MANAGER->registerActionPlaceHolder(qti_action_ABOUT_QTILITIES,QObject::tr("About Qtilities"),QKeySequence(),std_context);
    QObject::connect(command->action(),SIGNAL(triggered()),QtilitiesApplication::instance(),SLOT(aboutQtilities()));
    about_menu->addAction(command);
    command = ACTION_MANAGER->registerActionPlaceHolder("General.AboutQt","About Qt",QKeySequence(),std_context);
    about_menu->addAction(command);
    QObject::connect(command->action(),SIGNAL(triggered()),QApplication::instance(),SLOT(aboutQt()));


    // Load plugins using the extension system:
    Log->toggleQtMsgEngine(true);
    EXTENSION_SYSTEM->enablePluginActivityControl();
    EXTENSION_SYSTEM->addPluginPath("../../plugins/");
    EXTENSION_SYSTEM->initialize();
    Log->toggleQtMsgEngine(false);
    #ifdef QT_NO_DEBUG
    splash->clearMessage();
    #endif

    // Create the example file system side widget and add it to the global object pool
    QList<int> modes;
    modes << MODE_EXAMPLE_ID;
    SideViewerWidgetFactory* file_system_side_widget_helper = new SideViewerWidgetFactory(&SideWidgetFileSystem::factory,"File System",modes,modes);
    OBJECT_MANAGER->registerObject(file_system_side_widget_helper,QtilitiesCategory("GUI::Side Viewer Widgets (ISideViewerWidget)","::"));
    QObject::connect(file_system_side_widget_helper,SIGNAL(newWidgetCreated(QWidget*,QString)),example_mode,SLOT(handleNewFileSystemWidget(QWidget*)));
    SideViewerWidgetFactory* object_scope_side_widget_helper = new SideViewerWidgetFactory(&ObjectScopeWidget::factory,"Object Scope",modes,modes);
    OBJECT_MANAGER->registerObject(object_scope_side_widget_helper,QtilitiesCategory("GUI::Side Viewer Widgets (ISideViewerWidget)","::"));
    #ifdef QTILITIES_PROPERTY_BROWSER
    SideViewerWidgetFactory* property_editor_side_widget_helper = new SideViewerWidgetFactory(&ObjectPropertyBrowser::factory,"Property Browser",modes,modes);
    OBJECT_MANAGER->registerObject(property_editor_side_widget_helper,QtilitiesCategory("GUI::Side Viewer Widgets (ISideViewerWidget)","::"));
    #endif

    exampleMainWindow.modeManager()->initialize();

    // Register command editor config page.
    OBJECT_MANAGER->registerObject(ACTION_MANAGER->commandEditor(),QtilitiesCategory("GUI::Configuration Pages (IConfigPage)","::"));
    // Register extension system config page.
    OBJECT_MANAGER->registerObject(EXTENSION_SYSTEM->configWidget(),QtilitiesCategory("GUI::Configuration Pages (IConfigPage)","::"));

    // Report on the number of config pages found.
    QList<QObject*> registered_config_pages = OBJECT_MANAGER->registeredInterfaces("IConfigPage");
    LOG_INFO(QString("%1 configuration page(s) found in set of loaded plugins.").arg(registered_config_pages.count()));
    config_widget.initialize(registered_config_pages);

    // Report on the number of side widgets found.
    QList<QObject*> registered_side_widgets = OBJECT_MANAGER->registeredInterfaces("ISideViewerWidget");
    LOG_INFO(QString("%1 side viewer widget(s) found in set of loaded plugins.").arg(registered_side_widgets.count()));

    // Load the previous session's keyboard mapping file.
    QString shortcut_mapping_file = QString("%1/%2").arg(QtilitiesApplication::applicationSessionPath()).arg(qti_def_PATH_SHORTCUTS_FILE);
    ACTION_MANAGER->loadShortcutMapping(shortcut_mapping_file);

    // Show the main window:
    exampleMainWindow.readSettings();
    exampleMainWindow.show();
    #ifdef QT_NO_DEBUG
    splash->close();
    #endif

    LOG_INFO("< > < >");

    // Initialize the project manager:
    // PROJECT_MANAGER->setAllowedProjectTypes(IExportable::XML);
    PROJECT_MANAGER_INITIALIZE();

    ACTION_MANAGER->commandObserver()->endProcessingCycle(false);
    ACTION_MANAGER->actionContainerObserver()->endProcessingCycle(false);
    OBJECT_MANAGER->objectPool()->endProcessingCycle(false);

    #ifndef QTILITIES_NO_HELP
    HELP_MANAGER->initialize();
    #endif

    int result = a.exec();
    exampleMainWindow.writeSettings();

    // Finalize the project manager:
    PROJECT_MANAGER_FINALIZE();

    // Save the current keyboard mapping for the next session.
    ACTION_MANAGER->saveShortcutMapping(shortcut_mapping_file);

    LOG_FINALIZE();
    EXTENSION_SYSTEM->finalize();
    return result;
}
示例#30
0
文件: main.cpp 项目: VivekVetri/noobs
int main(int argc, char *argv[])
{
    GpioInput gpio(3);
    QApplication a(argc, argv);
    RightButtonFilter rbf;
    QString currentLangCode;
    bool runinstaller = false;

    // Process command-line arguments
    for (int i=1; i<argc; i++)
    {
        if (strcmp(argv[i], "-runinstaller") == 0)
            runinstaller = true;
        else if (strcmp(argv[i], "-lang") == 0)
            if (argc > i+1)
                currentLangCode = argv[++i];
    }

    // Intercept right mouse clicks sent to the title bar
    a.installEventFilter(&rbf);

#ifdef Q_WS_QWS
    QWSServer::setCursorVisible(false);

    // Set wallpaper and icon, if we have resource files for that
    if (QFile::exists(":/icons/raspberry_icon.png"))
        a.setWindowIcon(QIcon(":/icons/raspberry_icon.png"));

    //if (QFile::exists(":/wallpaper.png"))
    // {
//#ifdef CENTER_BACKGROUND_IMAGE
        // Using QSplashScreen to get a centered background image
        QWSServer::setBackground(BACKGROUND_COLOR);
        QSplashScreen *splash = new QSplashScreen(QPixmap(":/wallpaper.png"));
        splash->show();
        QApplication::processEvents();
//#else
        // Scale background image to fit screen
//        QRect dim = a.desktop()->availableGeometry();
        //       QWSServer::setBackground(QImage(":/wallpaper.png").scaled(dim.width(), dim.height()));
//#endif
//    }
//    else
//    {
//        QWSServer::setBackground(BACKGROUND_COLOR);
        //   }
//#endif
#endif

    // If -runinstaller is not specified, only continue if SHIFT is pressed, GPIO is triggered or no OS is installed (/dev/mmcblk0p6 does not exist)
    bool bailout = !runinstaller
         && gpio.value() != 0
         && !KeyDetection::isF10pressed()
         && QFile::exists(FAT_PARTITION_OF_IMAGE);

    if (bailout)
    {
        reboot_to_extended();
        //return 1;
    }

    // Keyboard detection done, load normal hid driver
    QProcess::execute("/sbin/modprobe usbhid");

#ifdef Q_WS_QWS
    QWSServer::setCursorVisible(true);
#endif

#ifdef ENABLE_LANGUAGE_CHOOSER
    // Language chooser at the bottom center
    LanguageDialog* ld = new LanguageDialog(&currentLangCode);
    ld->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignHCenter | Qt::AlignBottom, ld->size(), a.desktop()->availableGeometry()));
    ld->show();
#endif

    // Main window in the middle of screen
    MainWindow mw(&currentLangCode, splash, ld);
    mw.setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, mw.size(), a.desktop()->availableGeometry()));
    mw.show();

    a.exec();
    reboot_to_extended();

    return 0;
}