示例#1
0
int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osvi);

    // check windows version
    if (!(osvi.dwMajorVersion > 6 || osvi.dwMajorVersion == 6 && osvi.dwMinorVersion >= 1))  {
        QMessageBox msgBox;
        msgBox.setText(QObject::tr("Unsupported windows version."));
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();

#ifdef QT_DEBUG
        std::cout<<"ERR: unsupported windows version"<<std::endl;
#endif

        exit(EXIT_UNSUPPORTED_WINDOWS_VERSION);
    }

    // attempt to load the wm dll
    if (!loadDwmDll(getDwmStatus, setDwmColors, getDwmColors)) {
        QMessageBox msgBox;
        msgBox.setText(QObject::tr("Could not load dwmapi.dll."));
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();

#ifdef QT_DEBUG
        std::cout<<"ERR: could not load dwmapi.dll"<<std::endl;
#endif

        exit(EXIT_DLL_LOAD_FAIL);
    }

    BOOL ok;
    getDwmStatus(&ok);
    if (!ok) {
        // TODO: replace with a warning inside the window
        exit(EXIT_COMPOSITION_DISABLED);
    }

    QSharedMemory shared("075fa67f-eefe-43de-91dd-9c2ec23def4b");

    if(!shared.create(512, QSharedMemory::ReadWrite)) {
        QMessageBox msgBox;
        msgBox.setText(QObject::tr("Can't start more than one instance of ColorShifter."));
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();

#ifdef QT_DEBUG
        std::cout<<"ERR: can't start multiple instances"<<std::endl;
#endif
        exit(EXIT_MULTIPLE_INSTANCES);
    }

    MainWindow w;
    QApplication::connect(&a, SIGNAL(aboutToQuit()), &w, SLOT(on_quitButton_clicked()));

    // check if starts minimized
    bool minimized = false;
    for (int i = 0; i < argc; i++) {
        if (!(strcmp(argv[i], "--minimized"))) {
            minimized = true;
        }
    }

    if (!minimized) {
        w.show();
    } else {
#ifdef QT_DEBUG
        std::cout<<"Starting minimized"<<std::endl;
#endif
    }

    return a.exec();

    /*
    Color color1, color2;
    DwmColor crt = { 0 };

    color1.SetMerged(0xFFFF0000);
    color2.SetMerged(0xFF0000FF);
    crt = exportColor(color1);
    setDwmColors(&crt, 0);

    for (int i = 0; i < 100; i++) {
        crt = exportColor(interpolate(color1, color2, i * 1.0 / 100));
        setDwmColors(&crt, 0);
        Sleep(60);
    }
    */

    exit(EXIT_A_EXEC_DID_NOT_RETURN);
}
           m_qmlPuppetPreviewProcess->start(applicationPath, QStringList() << socketToken << "previewmode" << "-graphicssystem raster");

           m_qmlPuppetRenderProcess = new QProcess;
           m_qmlPuppetRenderProcess->setProcessEnvironment(environment);
           m_qmlPuppetRenderProcess->setObjectName("RenderProcess");
           connect(m_qmlPuppetRenderProcess.data(), SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)));
           connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), m_qmlPuppetRenderProcess.data(), SLOT(kill()));
           if (fowardQmlpuppetOutput) {
               m_qmlPuppetRenderProcess->setProcessChannelMode(QProcess::MergedChannels);
               connect(m_qmlPuppetRenderProcess.data(), SIGNAL(readyRead()), this, SLOT(printRenderProcessOutput()));
           }
           m_qmlPuppetRenderProcess->start(applicationPath, QStringList() << socketToken << "rendermode" << "-graphicssystem raster");

       }

       connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(deleteLater()));

       if (m_qmlPuppetEditorProcess->waitForStarted(10000)) {
           connect(m_qmlPuppetEditorProcess.data(), SIGNAL(finished(int)), m_qmlPuppetEditorProcess.data(),SLOT(deleteLater()));

           if (runModus == NormalModus) {
               m_qmlPuppetPreviewProcess->waitForStarted();
               connect(m_qmlPuppetPreviewProcess.data(), SIGNAL(finished(int)), m_qmlPuppetPreviewProcess.data(),SLOT(deleteLater()));

               m_qmlPuppetRenderProcess->waitForStarted();
               connect(m_qmlPuppetRenderProcess.data(), SIGNAL(finished(int)), m_qmlPuppetRenderProcess.data(),SLOT(deleteLater()));
           }

           if (!m_localServer->hasPendingConnections())
               m_localServer->waitForNewConnection(10000);
示例#3
0
void Slave::startup()
{
    registerBuiltinBurners();
    loadEmbeddedPython();

    LOG_5( "Slave::startup()" );
    mHost = Host::currentHost();

    mSpooler = new Spooler( this );

    if( !mHost.isRecord() ) {
        if( mAutoRegister ) {
            LOG_3( "Slave::startup: no host record, auto-registering" );
            mHost = Host::autoRegister();
        } else {
            LOG_3( "Slave::startup: no host record, uh oh!" );
            exit(-1);
        }
    } else
        mHost.updateHardwareInfo();

    mHostStatus = mHost.hostStatus();

    if( !mHostStatus.isRecord() ) {
        if( mAutoRegister ) {
            LOG_3( "Slave::startup: No host status record(are all your triggers installed?), creating one" );
            mHostStatus.setHost( mHost );
            mHostStatus.setOnline( 1 );
        } else {
            LOG_3( "Slave::startup: no host status record, uh oh!" );
            exit(-1);
        }
    }
    mHostStatus.setAvailableMemory( mHost.memory() );
    mHostStatus.commit();

    connect( Database::current()->connection(), SIGNAL( connectionLost() ), SLOT( slotConnectionLost() ) );
    connect( Database::current()->connection(), SIGNAL( connected() ), SLOT( slotConnected() ) );

    // The rest of the initialization is only for normal mode where we moniter and manipulate
    // the hosts status.  In burn only mode we simply execute a job and exit
    if( mBurnOnlyJobAssignmentKey ) {
        burn( JobAssignment(mBurnOnlyJobAssignmentKey) );
        return;
    }

    mService = Service::ensureServiceExists("Assburner");

    // Start remote log server and set port in our Assburner HostService record
    RemoteLogServer * rls = new RemoteLogServer();
    HostService hs = HostService::recordByHostAndService( mHost, mService );
    if( hs.isRecord() && rls->tcpServer()->isListening() ) {
        hs.setRemoteLogPort( rls->tcpServer()->serverPort() );
        hs.commit();
    }

    // Set host version string.
    mHost.setAbVersion( "v" + QString(VERSION));
    mHost.commit();

    // Reset any frame assignments and set our host status
    // to ready.  Do we need this anymore?  The reaper
    // should now detect and re-assign frames if we are
    // offline, and this prevents a client-update from
    // happening when assburner starts.
    //
    // Nope, this doesn't f**k with the status, so it is
    // safe.  It just clears fkeyJob to slaveFrames.  And
    // returns any frames that have fkeyHost=this
    mHostStatus.returnSlaveFrames();

    loadForbiddenProcesses();

    mTimer = new QTimer( this );
    connect( mTimer, SIGNAL( timeout() ), SLOT( loop() ) );

    // Default 5000ms, min 200ms, max 600,000ms - 10 minutes
    mLoopTime = qMax( 200, qMin( 1000 * 60 * 10, Config::getInt( "assburnerLoopTime", 5000 ) ) );

    // Default mLoopTime / 2,  min 100ms, max mLoopTime
    mQuickLoopTime = qMax( 100, qMin( mLoopTime, Config::getInt( "assburnerQuickLoopTime", mLoopTime / 2 ) ) );

    // Default 60 seconds, min 10 seconds.
    mPulsePeriod = qMax( 10, Config::getInt( "arsenalPulsePeriod", 600 ) );

    // Default 60 seconds, min 10 seconds.
    mMemCheckPeriod = qMax( 10, Config::getInt( "abMemCheckPeriod", 60 ) );

    IniConfig & c = config();

    c.pushSection( "BackgroundMode" );
    mBackgroundModeEnabled = c.readBool( "Enabled", true );
    c.popSection();

    // Pulse right away.
    pulse();

    // We need to set our host status to offline when assburner quits
    connect( qApp, SIGNAL( aboutToQuit() ), SLOT( offlineFromAboutToQuit() ) );

    if( mUseGui ) {
        mIdle = new Idle();
        connect( mIdle, SIGNAL( secondsIdle( int ) ), SLOT( slotSecondsIdle( int ) ) );
        mIdle->start();
    }

    if( mHostStatus.slaveStatus() == "client-update-offline" )
        offline();
    else if( mHostStatus.slaveStatus() == "client-update" )
        clientUpdate();
    else {
        // Store the current status
        QString currentStatus = mHostStatus.slaveStatus();

        // We run the host through the online method first
        online();

        // Check if the old host status wasn't empty
        if( !currentStatus.isEmpty() ) {
            // Resume the state the host was in.
            LOG_3("Slave::startup() Resuming previous status of " + currentStatus);
            handleStatusChange(currentStatus, "");
        }
    }

    // Create a timer for logged in user checks
    mUserTimer = new QTimer( this );
    connect( mUserTimer, SIGNAL( timeout() ), SLOT( updateLoggedUsers() ) );

    // Set it to trigger every 5 mins
    mUserTimer->start(300000);

    LOG_5( "Slave::startup() done" );
}
示例#4
0
 void PluginFactoryAdaptor::quit (const QDBusMessage& p_msg) const {
     emit aboutToQuit ();
     Factory::Shutdown ();
 }
示例#5
0
 void CoreAdaptor::quit (const QDBusMessage& p_msg) const {
     emit aboutToQuit ();
     QDBusMessage l_msg = QDBusMessage::createMethodCall ("org.thesii.Wintermute","/Factory", "org.thesii.Wintermute.Factory","quit");
     QDBusConnection::sessionBus ().call (l_msg,QDBus::NoBlock);
     haltSystem ();
 }
示例#6
0
文件: mainapp.cpp 项目: Daylie/Totem
    QMetaObject::invokeMethod(receiver, "onStart", Qt::QueuedConnection);
    receiver->m_futureInterface->reportStarted();
    foreach(ExtensionSystem::PluginSpec *spec, queue)
    {
        pm->loadPlugin(spec,ExtensionSystem::PluginSpec::Loaded);
        receiver->m_futureInterface->setProgressValue(
                    receiver->m_futureInterface->progressValue() + 1);
    }
    receiver->m_futureInterface->reportFinished();
    pm->loadPluginsAuto();

    //初始化应用程序实例
    receiver->app.initialize();
    QObject::connect(&(receiver->app), SIGNAL(messageReceived(QString)),
                     pm, SLOT(remoteArguments(QString)));
    QObject::connect(&(receiver->app), SIGNAL(aboutToQuit()), pm, SLOT(shutdown()));

    QMetaObject::invokeMethod(receiver, "onFinish", Qt::QueuedConnection);


    return 0;
}
MainApp::MainApp(const QString &id, int &argc, char **argv) :
    app(id, argc, argv)
{

}

MainApp::~MainApp()
{
    if(m_pLoader)
示例#7
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(guiclient);

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

  QApplication app(argc, argv);

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

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

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

  app.processEvents();

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

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

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

  _evaluation = FALSE;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if (files.size() > 0)
    {
      bool langFound = false;

      QTranslator *translator = new QTranslator(&app);
      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit)
        {
          if (DEBUG)
            qDebug("looking for %s in %s",
                   (*fit).toAscii().data(), (*pit).toAscii().data());
          if (translator->load(*fit, *pit))
          {
            app.installTranslator(translator);
            langFound = true;
            qDebug("installed %s/%s",
                   (*pit).toAscii().data(), (*fit).toAscii().data());
            translator = new QTranslator(&app);
            break;
          }
        }
      }

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

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

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

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

  qApp->processEvents();
  QString key;

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

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

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

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

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

  omfgThis = 0;
  omfgThis = new GUIClient(databaseURL, username);
  omfgThis->_key = key;

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

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

  QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows()));
  if (omfgThis->_singleWindow.isEmpty())
  {
    omfgThis->setAttribute(Qt::WA_DeleteOnClose);
    omfgThis->show();
  }
  // keep this synchronized with GUIClient and user.ui.h
  else if (omfgThis->_singleWindow == "woTimeClock")
  {
    ScriptToolbox sb(0);
    QWidget* newdlg = sb.openWindow("woTimeClock");
    if(newdlg)
    {
      XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg);
      if(mw)
      {
        ParameterList params;
        params.append("captive");
        mw->set(params);
      }
      newdlg->setAttribute(Qt::WA_DeleteOnClose);
      QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit()));
      newdlg->show();
    }
    else
    {
示例#8
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	setWindowIcon(QIcon(":icon.ico"));

	MainWindow::appPath = qApp->applicationDirPath();

	loadStyle();

	// member initialization
	dockWidget	 = new DockWidget;
	calWidget	= new BrowserWidget;
	crmWidget   = new BrowserWidget;

	toolBar		= new QToolBar(tr("Aktionen"));
	accountList = new AccountList(this);
	contactList = new ContactList(this);
	mainLayout	= new QStackedLayout();
	settings	= SugarSettings::getInstance();
	settingsDialog = new SettingsDialog;

	addDockWidget(Qt::BottomDockWidgetArea, dockWidget);
	dockWidget->hide();
	accountList->hide();
	calWidget->setAddress(QUrl(settings->calendarUrl));
	crmWidget->setAddress(QUrl(settings->crmUrl));
	mainLayout->addWidget(accountList);
	mainLayout->addWidget(contactList);
	//mainLayout->addWidget(projectList);
	mainLayout->addWidget(calWidget);
	mainLayout->addWidget(crmWidget);
	mainLayout->addWidget(settingsDialog);

	toolBar->setIconSize(QSize(14, 14));
	toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
	toolBar->setMovable(false);

	QAction *accountsAct = new QAction(QIcon(":accounts.png"), tr("Firmen"), this);
	QAction *contactsAct = new QAction(QIcon(":contacts.png"), tr("Kontakte"), this);
	QAction *projectsAct = new QAction(QIcon(":projects.png"), tr("Projekte"), this);
	openCalAct			 = new QAction(QIcon(":calendar.png"), tr("Kalender"), this);
	openCrmAct			 = new QAction(QIcon(":calendar.png"), tr("SugarCrm"), this);

	addAccountAct			= new QAction(QIcon(":add-account.png"), tr("Neue Firma"), this);
	QAction *addContactAct	= new QAction(QIcon(":add-contact.png"), tr("Neuer Kontakt"), this);
	QAction *addProjectAct	= new QAction(QIcon(":add-project.png"), tr("Neues Projekt"), this);
	QAction *addTaskAct		= new QAction(QIcon(":add-task.png"),    tr("Neue Aufgabe"), this);
	pressViewAct			= new QAction(QIcon(":news.png"), tr("Pressekontakte"), this);

	connect(addAccountAct, SIGNAL(triggered()),
			this, SLOT(addAccount()));
	connect(openCalAct, SIGNAL(triggered()),
			this, SLOT(displayCalendar()));
	connect(openCrmAct, SIGNAL(triggered()),
			this, SLOT(displayCrm()));
	//connect(pressViewAct, SIGNAL(triggered()),
	//		this, SLOT(displayPressList()));
	connect(accountsAct, SIGNAL(triggered()),
			this, SLOT(displayAccounts()));
	connect(contactsAct, SIGNAL(triggered()),
			this, SLOT(displayContacts()));

	toolBar->addWidget(new QLabel(tr("Ansichten")));
	toolBar->addAction(accountsAct);
	toolBar->addAction(contactsAct);
	toolBar->addAction(projectsAct);
	toolBar->addAction(openCalAct);
	toolBar->addAction(openCrmAct);
	toolBar->addWidget(new QLabel(tr("Aktionen")));
	// TODO: fix this
	toolBar->addAction(addAccountAct);
	toolBar->addAction(addContactAct);
	toolBar->addAction(addProjectAct);
	toolBar->addAction(addTaskAct);
	//toolBar->addAction(pressViewAct);

	addToolBar(Qt::LeftToolBarArea, toolBar);
	toolBar->hide();

	QPushButton *loginBtn = new QPushButton(QIcon(":login.png"), tr("Login"), this);
	connect(loginBtn, SIGNAL(pressed()),
			this, SLOT(login()));
	QGridLayout *l = new QGridLayout(this);
	QWidget *c = new QWidget(this);
	QWidget *w = new QWidget(this);

	l->addWidget(loginBtn, 1, 1, Qt::AlignCenter);
	c->setLayout(l);
	mainLayout->addWidget(c);
	mainLayout->setCurrentWidget(c);
	w->setLayout(mainLayout);
	setCentralWidget(w);

	// initialize dialogs
	loadingDialog = new LoadingDialog(this);
	loginDialog   = new LoginDialog(this);
	loadingDialog->setVisible(false);
	loginDialog->setVisible(false);

	crm = SugarCrm::getInstance();
	accountModel = AccountModel::getInstance();
	contactModel = ContactModel::getInstance();

	accountsFilterModel = new AccountProxyModel(this);
	contactsFilterModel = new ContactProxyModel(this);

	//filterModel = new AccountProxyModel(this);
	//filterModel->setSourceModel(accountModel);

	accountsFilterModel->setSourceModel(accountModel);
	contactsFilterModel->setSourceModel(contactModel);

	restoreGeometry(settings->windowGeometry);

	// QML display
	//centerView = new QmlView(this);

	//centerView->setUrl(QUrl("SugarCrm.qml"));
	//centerView->setAttribute(Qt::WA_OpaquePaintEvent);
	//centerView->setAttribute(Qt::WA_NoSystemBackground);
	//centerView->setFocus();

	//contx = centerView->rootContext();
	//contx->addDefaultObject(this);
	//contx->setContextProperty("qmlViewer", this);
	//contx->setContextProperty("accountModel", proxyModel);

	// connecting ui actions
	connect(ui->actionLogin, SIGNAL(triggered()),
			this, SLOT(login()));
	connect(ui->actionEinstellungen, SIGNAL(triggered()),
			this, SLOT(displaySettings()));
	connect(ui->actionLogout, SIGNAL(triggered()),
			qApp, SLOT(quit()));
	connect(ui->actionServer_Zeit, SIGNAL(triggered()),
			crm, SLOT(getServerTime()));
	connect(ui->actionSugarFlavor, SIGNAL(triggered()),
			crm, SLOT(getSugarFlavor()));
	connect(ui->actionReloadStyle, SIGNAL(triggered()),
			this, SLOT(loadStyle()));
	connect(ui->actionAboutQt, SIGNAL(triggered()),
			qApp, SLOT(aboutQt()));
	connect(ui->actionWebsite, SIGNAL(triggered()),
			this, SLOT(openProjectHomepage()));
	connect(ui->actionSpenden, SIGNAL(triggered()),
			this, SLOT(openDonationWebsite()));
	connect(qApp, SIGNAL(aboutToQuit()),
			this, SLOT(cleanup()));

	// DEBUG XML COMMUNICATION
	//connect(crm, SIGNAL(sendingMessage(QString)),
	//		this, SLOT(debug(QString)));
	//connect(crm->trans, SIGNAL(newSoapMessage(QString)),
	//		this, SLOT(debug(QString)));

	connect(crm, SIGNAL(unknownAction(QString)),
			this, SLOT(unknownAction(QString)));

	// login response
	connect(crm, SIGNAL(loginFailed()),
			this, SLOT(loginResponse()));

	connect(crm, SIGNAL(loginSuccessful()),
			this, SLOT(loginResponse()));

	// soap error handling
	// TODO: improve!
	connect(crm, SIGNAL(returnedFaultyMessage(QString)),
			loadingDialog, SLOT(hide()));

	connect(crm, SIGNAL(returnedFaultyMessage(QString)),
			this, SLOT(setStatusMsg(QString)));

	connect(accountModel, SIGNAL(dataReady()),
			this, SLOT(displayAccounts()));

	//TODO: change this when it works
	//setCentralWidget(centerView);
	//centerView->execute();

	//rootComponent = centerView->root();
	//QVariant *tmp = new QVariant(contx->property("authView"));
	//QmlComponent authComponent((QObject *) tmp);  // centerView->engine(), QUrl("content/AuthView.qml"));
	//authView = authComponent.create(contx);
	//qDebug() << authView->dynamicPropertyN();

	//connect(rootComponent, SIGNAL(loggingIn()),
	//		this, SLOT(login()));
	//connect(rootComponent, SIGNAL(searching()),
	//		this, SLOT(doSearch()));
	/*connect(accountModel, SIGNAL(dataReady()),
			this, SLOT(assignData()));
	connect(this, SIGNAL(listReady()),
			rootComponent, SLOT(displayAccounts()));*/
	//connect(accountModel, SIGNAL(dataReady()),
	//		rootComponent, SLOT(displayAccounts()));

	setStatusMsg(tr("Bereit"), 2500);
}
示例#9
0
int main(int argc, char **argv)
{
  QCoreApplication qca(argc, argv);
  QStringList args = QCoreApplication::arguments();

  Settings settings = Settings::CommandLineParse(args);
  if(settings.Help || !settings.IsValid()) {
    QTextStream qtout(stdout, QIODevice::WriteOnly);
    qtout << "usage: " << args[0] << " [options] [settings.conf]\n\n";
    qtout << "options:\n";
    qtout << Settings::GetUsage() << "\n";
    if(!settings.Help) {
      qtout << "error: " << settings.GetError() << "\n\n";
    }
    return -1;
  }
  Settings::ApplicationSettings = settings;

  QList<QSharedPointer<Node> > nodes;

  QSharedPointer<ISink> default_sink(new DummySink());
  QSharedPointer<SinkMultiplexer> app_sink(new SinkMultiplexer());

  QSharedPointer<CommandLine> commandline;
  QSharedPointer<SignalSink> signal_sink(new SignalSink());
  app_sink->AddSink(signal_sink.data());

  QSharedPointer<KeyShare> keys(new KeyShare(settings.PublicKeys));
  Hash hashalgo;
  foreach(const Id &server, settings.ServerIds) {
    QString serv = server.ToString();
    if(!keys->Contains(serv)) {
      qFatal("Missing key for %s", serv.toLatin1().data());
    }
    Q_ASSERT(Id(hashalgo.ComputeHash(keys->GetKey(serv)->GetByteArray())) == server);
  }

  QList<Address> local_end_points = settings.LocalEndPoints;

  for(int idx = 0; idx < settings.LocalNodeCount; idx++) {
    Id local_id = idx < settings.LocalId.count() ? settings.LocalId[idx] : Id();
    QSharedPointer<AsymmetricKey> key;

    QString key_path = settings.PrivateKeys + "/" + local_id.ToString();
    QFile key_file(key_path);
    if(key_file.exists()) {
      key = QSharedPointer<AsymmetricKey>(new DsaPrivateKey(key_path));
    } else {
      QByteArray id = local_id.GetByteArray();
      key = QSharedPointer<AsymmetricKey>(new DsaPrivateKey(id, true));
    }

    QSharedPointer<ISink> nsink = (idx == 0) ? app_sink.dynamicCast<ISink>() : default_sink;
    QSharedPointer<Overlay> overlay(new Overlay(local_id, local_end_points,
          settings.RemoteEndPoints, settings.ServerIds));
    overlay->SetSharedPointer(overlay);

    CreateRound create_round = RoundFactory::GetCreateRound(settings.RoundType);
    QSharedPointer<Session> session;
    if(settings.ServerIds.contains(local_id)) {
      session = MakeSession<ServerSession>(overlay, key, keys, create_round);
    } else {
      session = MakeSession<ClientSession>(overlay, key, keys, create_round);
    }
    session->SetSink(nsink.data());
    QSharedPointer<Node> node(new Node(key, keys, overlay, nsink, session));
    nodes.append(node);

    for(int idx = 0; idx < local_end_points.count(); idx++) {
      local_end_points[idx] = AddressFactory::GetInstance().
        CreateAny(local_end_points[idx].GetType());
    }
  }

  QScopedPointer<WebServer> ws;
//  QScopedPointer<SessionEntryTunnel> tun_entry;
//  QScopedPointer<SessionExitTunnel> tun_exit;

  if(settings.Console) {
    commandline = QSharedPointer<CommandLine>(new CommandLine(nodes));
    QObject::connect(&qca, SIGNAL(aboutToQuit()), commandline.data(), SLOT(Stop()));
    commandline->Start();
    app_sink->AddSink(commandline.data());
  }

  if(settings.WebServer) {
    ws.reset(new WebServer(settings.WebServerUrl));

    /* Stop Web server when application is about to quit */
    QObject::connect(&qca, SIGNAL(aboutToQuit()), ws.data(), SLOT(Stop()));

    /* When the web server stops, quit the application */
    QObject::connect(ws.data(), SIGNAL(Stopped()), &qca, SLOT(quit()));

    QSharedPointer<GetMessagesService> get_messages(new GetMessagesService());
    QObject::connect(signal_sink.data(), SIGNAL(IncomingData(const QByteArray&)),
        get_messages.data(), SLOT(HandleIncomingMessage(const QByteArray&)));
    ws->AddRoute(QHttpRequest::HTTP_GET, "/session/messages", get_messages);

    QSharedPointer<GetFileService> get_webpage(new GetFileService("index.html"));
    ws->AddRoute(QHttpRequest::HTTP_GET, "/web", get_webpage);

    QSharedPointer<GetDirectoryService> get_dir(new GetDirectoryService("webpath"));
    ws->AddRoute(QHttpRequest::HTTP_GET, "/dir", get_dir);

    QSharedPointer<SessionService> session_serv(new SessionService(nodes[0]->GetSession()));
    ws->AddRoute(QHttpRequest::HTTP_GET, "/session", session_serv);

    QSharedPointer<SendMessageService> send_message(new SendMessageService(nodes[0]->GetSession()));
    ws->AddRoute(QHttpRequest::HTTP_POST, "/session/send", send_message);

//    QSharedPointer<BuddiesService> bs(new BuddiesService(nodes[0]->GetSessionManager()));
//    ws->AddRoute(QHttpRequest::HTTP_GET, "/session/buddies", bs);

    ws->Start();
  }
示例#10
0
MainWindow::MainWindow()
{
    //CREATION DU MENU
    setWindowTitle("CalcUTC");
    this->size_min();
    QMenu *menuOption = menuBar()->addMenu("&Option");
    QAction *actionQuitter = new QAction("&Quitter", this); //AJOUT DE QUITTER
    menuOption->addAction(actionQuitter);
    QAction *actionProgEdit = new QAction("Nouveau programme", this); // Ajout d'une action créer nouveau programme qui ouvre un QEDITTEXT
    menuOption->addAction(actionProgEdit);

    QMenu *menuAffichage = menuBar()->addMenu("&Affichage");
    QAction *actionClavier = new QAction("&Clavier", this);   //OPTION D'AFFICHAGE DU CLAVIER ET DES FONCTIONS SCIENTIFIQUES
    menuAffichage->addAction(actionClavier);
    QAction *actionScientifique = new QAction("&Mode scientifique", this);
    menuAffichage->addAction(actionScientifique);
    QAction *actionProg = new QAction("&Gestion Programme",this);
    menuAffichage->addAction(actionProg);


    QAction *actionRedo = new QAction("&Redo", this);  // AJOUT DU "Redo"
    menuOption->addAction(actionRedo);
    actionRedo->setIcon(QIcon("\\Users\\Adrien\\Documents\\Adrien\\UTC\\GI 02\\LO21\\Projet\\version finale\\projet_1_0\\images/arrow_redo.png"));
    actionRedo->setShortcut(QKeySequence(tr("Ctrl+y")));

    QAction *actionUndo = new QAction("&Undo", this);  // AJOUT DU "Undo"
    menuOption->addAction(actionUndo);
    actionUndo->setIcon(QIcon("\\Users\\Adrien\\Documents\\Adrien\\UTC\\GI 02\\LO21\\Projet\\version finale\\projet_1_0\\images/arrow_undo.png"));
    actionUndo->setShortcut(QKeySequence(tr("Ctrl+z")));

    QMenu *menuAide = menuBar()->addMenu("&Aide");
    QAction *actionAPropos = new QAction("&A propos", this);  // AJOUT DU "A PROPOS"
    menuAide->addAction(actionAPropos);

    // GESTION DES SIGNAUX ET SLOTS DU MENU
    connect(actionQuitter, SIGNAL(triggered()), qApp, SLOT(quit()));
    actionQuitter->setShortcut(QKeySequence("Escape"));
    connect(actionScientifique, SIGNAL(triggered()), this, SLOT(afficher_scientique()));
    connect(actionClavier, SIGNAL(triggered()), this, SLOT(afficher_clavier()));
    actionClavier->setCheckable(true);
    actionScientifique->setCheckable(true);
    // CONNECT DU PROGEDIT

    connect(actionProg,SIGNAL(triggered(bool)), this, SLOT(openProgWindow()));
    connect(actionProgEdit,SIGNAL(triggered()), this, SLOT(openEditProg())); // OUVRE LE QEDITTEXT
    connect(actionAPropos,SIGNAL(triggered(bool)), this, SLOT(afficher_APropos()));


    //INITIALISATION DES OBJETS DU .h
    mainArea = new QWidget;
    mainSet = new QHBoxLayout;
    scientificPad = new scientific_pad;
    scientificPad->hide();


    keyboard = new Keyboard();
    keyboard->hide();
    controlScreen = new QWidget();
    controlScreen->setFixedSize(QSize(280, 300));

    pile = new Pile ;
    qDebug()<<pile;
    controleur = Controleur::getInstance(LiteraleManager::getInstance() , *pile) ;
    message = new QLineEdit() ;
    commande = new QLineEdit() ;
    vuePile = new QTableWidget (pile->getNbItemsToAffiche(),1) ;
    pile_create();
    topLayout = new QHBoxLayout();

    middleLayout = new QHBoxLayout();
    boutons_droits = new QVBoxLayout();

    bottomLayout = new QHBoxLayout();
    pile_plus = new QPushButton();
    pile_moins = new QPushButton();
    enter = new QPushButton();

    leftLayout = new QVBoxLayout();
    leftLayout->addWidget(vuePile);
    vuePile->setStyleSheet("background : rgba(35,141,214,45)");

    commande->setStyleSheet("background : rgba(35,141,214,45)");
    //MIDDLELAYOUT SETTINGS

    middleLayout->addLayout(leftLayout);
    middleLayout->addLayout(boutons_droits);

    boutons_droits->addWidget(pile_plus);
    boutons_droits->addWidget(pile_moins);

    //BOTTOM LAYOUT SETTINGS

    bottomLayout->addWidget(commande);
    bottomLayout->addWidget(enter);
    enter->setIcon(QIcon("\\Users\\Adrien\\Documents\\Adrien\\UTC\\GI 02\\LO21\\Projet\\version finale\\projet_1_0\\images/enter-arrow.png"));
    enter->setFlat(true);
    enter->setFocusPolicy(Qt::NoFocus);

    connect(enter,SIGNAL(clicked(bool)),this,SLOT(slot_getNextCommande()));

    //BOUTON PILE SETTINGS + CONNECT
    pile_plus->setIcon(QIcon("\\Users\\Adrien\\Documents\\Adrien\\UTC\\GI 02\\LO21\\Projet\\version finale\\projet_1_0\\images/add.png"));
    pile_plus->setFlat(true);
    pile_plus->setFocusPolicy(Qt::NoFocus);
    pile_moins->setIcon(QIcon("\\Users\\Adrien\\Documents\\Adrien\\UTC\\GI 02\\LO21\\Projet\\version finale\\projet_1_0\\images/minus.png"));
    pile_moins->setFlat(true);
    pile_moins->setFocusPolicy(Qt::NoFocus);

    connect(pile_plus,SIGNAL(clicked(bool)),pile,SLOT(aug_pile()));
    connect(pile_plus,SIGNAL(clicked(bool)),this,SLOT(pile_create()));
    connect(pile_moins,SIGNAL(clicked(bool)),pile,SLOT(dim_pile()));
    connect(pile_moins,SIGNAL(clicked(bool)),this,SLOT(pile_create()));

    // MESSAGE SETTINGS

    message->setReadOnly(true);    //empèche d'écrire dans la lineEdit
    message->setStyleSheet("background: blue; color: yellow");
    message->setAlignment(Qt::AlignHCenter);
    message->setFixedHeight(45);

    //VUE PLIE SETTINGS

    vuePile->horizontalHeader()->setVisible(false);   //enlève l'indice de col
    vuePile->horizontalHeader()->setStretchLastSection(true);   //ajuste la largeur à la fenetre
    vuePile->setSelectionMode(QAbstractItemView::NoSelection);
    vuePile->setEditTriggers(QAbstractItemView::NoEditTriggers) ;  //empèche d'écrire dans les cellules

    //SOUND_LOCK SETTINGS
    sound_lock = new QPushButton();
    sound_lock->setIcon(QIcon("\\Users\\Adrien\\Documents\\Adrien\\UTC\\GI 02\\LO21\\Projet\\version finale\\projet_1_0\\images/speaker.png"));
    sound_lock->setFlat(true);
    sound_lock->setFocusPolicy(Qt::NoFocus);
    connect(sound_lock,SIGNAL(clicked(bool)),this,SLOT(sound_disable()));

    //GESTION DES CONNECTS DU SCIENTIFIC_PAD

    connect(scientificPad->cos, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->sin, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->tan, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->arccos, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->arcsin, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->arctan, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->sqrt, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->puis, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->exp, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->ln, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->div, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    connect(scientificPad->mod, SIGNAL(clicked(bool)), this, SLOT(keyboardButtonPressed()));
    

    //GESTION DES CONNECTS DU CONTROLSCREEN
    connect(commande, SIGNAL (returnPressed()) , this , SLOT(slot_getNextCommande())) ;
    connect(pile , SIGNAL (modificationEtat()) , this, SLOT(refresh())) ;

    //GESTION DES CONNECTS DU KEYBOARD

    connect(keyboard->b1,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->b2,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->b3,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->b4,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->b5,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->b6,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->b7,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->b8,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->b9,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->b0,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->bplus,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->bmoins,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->bdiv,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->bmult,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->clear,SIGNAL(clicked(bool)),commande, SLOT(clear()));
    connect(keyboard->space,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->bComp,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->bPo,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));
    connect(keyboard->bPf,SIGNAL(clicked(bool)),this, SLOT(keyboardButtonPressed()));


    //CREATION DES LIENS ENTRE LES LAYOUTS


    mainSet->addWidget(scientificPad);
    scientificPad->setStyleSheet("background : rgba(35,141,214,45)");
    mainSet->addWidget(controlScreen);
    message->setStyleSheet("background : rgba(35,186,117,45)");
    vuePile->setStyleSheet("background : rgba(35,141,214,25)");;
    mainSet->addWidget(keyboard);
    keyboard->setStyleSheet("background : rgba(35,141,214,45)");


    topLayout->addWidget(message);
    topLayout->addWidget(sound_lock);

    LcontrolScreen = new QVBoxLayout;
    controlScreen->setLayout(LcontrolScreen);
    LcontrolScreen->addLayout(topLayout);
    LcontrolScreen->addLayout(middleLayout);
    LcontrolScreen->addLayout(bottomLayout);


    mainArea->setLayout(mainSet);
    setCentralWidget(mainArea);

    //GESTION SAUVEGARDE CONTEXTE

    connect(qApp,SIGNAL(aboutToQuit()),this,SLOT(save_context()));
    open_context();
}
示例#11
0
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    //MainWindow w;
    //w.show();

    QStringList args;
    for (int i=1; i<argc; i++) {
        args << QString(argv[i]);
    }

    qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch());

    //args << "/tmp/tp903426a1_f13b_43a2_a1b8_5ff229f26018_run_java_script.js";

//	FTElectrodeArrayView *V=new FTElectrodeArrayView;
//	int M=100,T=30;
//	Mda L; L.allocate(M,2);
//	Mda W; W.allocate(M,T);
//	for (int i=0; i<M; i++) {
//		L.setValue(i/6 + ((i%6)%2)*0.5,i,0);
//		L.setValue(i%6,i,1);
//		for (int t=0; t<T; t++) {
//			W.setValue(i+t,i,t);
//		}
//	}
//	V->setElectrodeLocations(L);
//	V->setWaveform(W);
//	V->show();
//	return a.exec();

    QString script_path;
    QString waveforms_path;
    QString locations_path;
    for (int i=0; i<args.count(); i++) {
        QString str=args[i];
        if (str=="--waveforms") {
            waveforms_path=args.value(i+1);
        }
        if (str=="--locations") {
            locations_path=args.value(i+1);
        }
    }

    QScriptEngine *engine=new QScriptEngine;

    //qScriptRegisterMetaType(engine, myObjectToScriptValue, myObjectFromScriptValue);


    FTController FIRETRACK;
    QScriptValue FIRETRACK_value = engine->newQObject(&FIRETRACK);
    //QScriptValue FIRETRACK_value = engine->newQObject(new QObject());
    engine->globalObject().setProperty("FIRETRACK", FIRETRACK_value);

    QString script;
    if (!script_path.isEmpty()) {
        script=read_text_file(script_path);
    } else {
        if (waveforms_path.isEmpty()) {
            waveforms_path=a.applicationDirPath()+"/../testdata/waveforms_first_5e5_points.mda";
            if ((!QFile::exists(waveforms_path))||(QFileInfo(waveforms_path).size()<1e6)) {
                QMessageBox::StandardButton reply=
                    QMessageBox::question(0,"Start download?","Test data must be downloaded. Start download?",QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes);
                if (reply==QMessageBox::No) exit(0);
                QMessageBox::information(0,"Downloading","Please wait while file is downloaded. Click OK to start download.");
                QString url="http://97.107.129.125/waveforms_first_5e5_points.mda";
                if (!download_file(url,waveforms_path)) {
                    QMessageBox::information(0,"Error Downloading","There was a problem downloading the file "+url+". Is curl installed? Exiting.");
                    exit(0);
                }
                QMessageBox::information(0,"File downloaded","It appears that the file was downloaded properly. Press OK to continue.");
            }

            //waveforms_path="/home/magland/gazelle_backup/current/matlab/scda_ss/jfm/core/scratch/test_all_channels/first_1e3_points_filtered.mda";
        }
        if (locations_path.isEmpty()) {
            locations_path=a.applicationDirPath()+"/../testdata/locations.mda";
        }
        script="";
        script+=QString("var V%1=FIRETRACK.createFireTrackWidget();\n").arg(0);
        script+=QString("var X%1=FIRETRACK.readArray('%2');\n").arg(0).arg(waveforms_path);
        script+=QString("var L%1=FIRETRACK.readArray('%2');\n").arg(0).arg(locations_path);
        script+=QString("V%1.setWaveforms(X%1);\n").arg(0);
        script+=QString("V%1.setElectrodeLocations(L%1);\n").arg(0);
        //script+=QString("V%1.setTitle(\"This is a test %1.\");\n").arg(0);
        script+=QString("V%1.show();\n").arg(0);
        script+=QString("V%1.animate();\n").arg(0);
        script+="\n";
    }

    QScriptValue result = engine->evaluate(script);
    if (result.isError()) {
        qWarning() << "Error running script: "+result.toString();
    }

    CleanupObject cleanup_object;
    QObject::connect(&a, SIGNAL(aboutToQuit()), &cleanup_object, SLOT(closing()));

    int ret=a.exec();

    engine->collectGarbage();

    delete engine;
    printf("Number of files open: %d, number of unfreed mallocs: %d, number of unfreed megabytes: %g\n",jnumfilesopen(),jmalloccount(),(int)jbytesallocated()*1.0/1000000);

    return ret;
}
示例#12
0
    modes["04_1v3"] = tr("4 players (Hulao Pass)");
    modes["05p"] = tr("5 players");
    modes["06p"] = tr("6 players");
    modes["06pd"] = tr("6 players (2 renegades)");
    modes["06_3v3"] = tr("6 players (3v3)");
    modes["06_XMode"] = tr("6 players (XMode)");
    modes["07p"] = tr("7 players");
    modes["08p"] = tr("8 players");
    modes["08pd"] = tr("8 players (2 renegades)");
    modes["08pz"] = tr("8 players (0 renegade)");
    modes["09p"] = tr("9 players");
    modes["10pd"] = tr("10 players");
    modes["10p"] = tr("10 players (1 renegade)");
    modes["10pz"] = tr("10 players (0 renegade)");

    connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(deleteLater()));

    foreach (const Skill *skill, skills.values()) {
        Skill *mutable_skill = const_cast<Skill *>(skill);
        mutable_skill->initMediaSource();
    }
}

lua_State *Engine::getLuaState() const{
    return lua;
}

void Engine::addTranslationEntry(const char *key, const char *value) {
    translations.insert(key, QString::fromUtf8(value));
}
ListingTable::ListingTable(PartCategory* partCat, Filter* filter, QWidget* parent)
		: QTableView(parent), partCat(partCat), model(new PartTableModel(partCat, filter, this)), ignoreSectionResize(false)
{
	setModel(model);

	QHeaderView* hheader = horizontalHeader();

	verticalHeader()->hide();

	hheader->setStretchLastSection(true);
    hheader->setCascadingSectionResizes(false);
    hheader->setMovable(true);


    setSelectionBehavior(SelectRows);

    setDragEnabled(true);
    setDragDropMode(DragOnly);

    setAutoScroll(true);
    setSortingEnabled(true);

    sortByColumn(0, Qt::AscendingOrder);

    setContextMenuPolicy(Qt::CustomContextMenu);
    hheader->setContextMenuPolicy(Qt::CustomContextMenu);

	connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(partActivatedSlot(const QModelIndex&)));
	connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(contextMenuRequested(const QPoint&)));
	connect(hheader, SIGNAL(customContextMenuRequested(const QPoint&)),
			this, SLOT(headerContextMenuRequested(const QPoint&)));


	System* sys = System::getInstance();
	EditStack* editStack = sys->getEditStack();

	connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(aboutToQuit()));

	connect(partCat, SIGNAL(recordEdited(unsigned int, PartCategory::DataMap)), this, SLOT(updateData()));
	connect(partCat, SIGNAL(recordCreated(unsigned int, PartCategory::DataMap)), this, SLOT(updateData()));
	connect(partCat, SIGNAL(recordsRemoved(QList<unsigned int>)), this, SLOT(updateData()));

	connect(editStack, SIGNAL(undone(EditCommand*)), this, SLOT(updateData()));
	connect(editStack, SIGNAL(redone(EditCommand*)), this, SLOT(updateData()));

	connect(selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)),
			this, SLOT(currentChanged(const QModelIndex&, const QModelIndex&)));
	connect(selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
    		this, SLOT(selectionChangedSlot(const QItemSelection&, const QItemSelection&)));
	connect(model, SIGNAL(updateRequested()), this, SLOT(updateData()));


	QSettings s;

	s.beginGroup(QString("gui_geometry_%1").arg(partCat->getTableName()));

	if (!s.contains("lt_state")  ||  !restoreState(s.value("lt_state").toByteArray())) {
		unsigned initialTotalWidth = 1000;
		int nc = model->columnCount();

		for (unsigned int i = 0 ; i < nc-1 ; i++) {
			setColumnWidth(i, initialTotalWidth / nc);
		}
	}

	s.endGroup();
}
示例#14
0
文件: daemon.cpp 项目: idaohang/mole
Daemon::Daemon(int argc, char *argv[])
  : QCoreApplication(argc, argv)
{
  initSettings();

  char defaultLogFilename[] = DEFAULT_LOG_FILE;
  char* logFilename = defaultLogFilename;

  int port = DEFAULT_LOCAL_PORT;
  bool isDaemon = true;
  bool runWiFiScanner = true;
  bool runMovementDetector = true;
  bool recordScans = false;
  bool runAllAlgorithms = false;

  //////////////////////////////////////////////////////////
  // Make sure no other arguments have been given
  QStringList args = QCoreApplication::arguments();
  QStringListIterator argsIter(args);
  argsIter.next(); // moled

  while (argsIter.hasNext()) {
    QString arg = argsIter.next();
    if (arg == "-h") {
      usage();
    } else if (arg == "-v") {
      version();
    } else if (arg == "-d") {
        debug = true;
    } else if (arg == "-n") {
        isDaemon = false;
        logFilename = NULL;
    } else if (arg == "-l") {
	logFilename = argsIter.next().toAscii().data();
    } else if (arg == "-s") {
        mapServerURL = argsIter.next();
    } else if (arg == "-f") {
        staticServerURL = argsIter.next();
    } else if (arg == "-r") {
        rootPathname = argsIter.next();
    } else if (arg == "-p") {
        port = argsIter.next().toInt();
    } else if (arg == "--no-accelerometer") {
        runMovementDetector = false;
    } else if (arg == "--no-wifi") {
        runWiFiScanner = false;
    } else if (arg == "-S") {
        recordScans = true;
    } else if (arg == "-A") {
      runAllAlgorithms = true;
    } else if (arg == "-H") {
      SpeedSensor::HibernateWhenInactive = true;
    } else {
        usage();
    }
  }

  // Seed rng
  QTime time = QTime::currentTime();
  qsrand((uint)time.msec());

  settings = new QSettings(QSettings::SystemScope, MOLE_ORGANIZATION,
                                      MOLE_APPLICATION, this);

  //////////////////////////////////////////////////////////
  // Read default settings
  if (settings->contains("wifi_scanning")) {
    runWiFiScanner = settings->value("wifi_scanning").toBool();
  }
  if (settings->contains("movement_detector")) {
    runMovementDetector = settings->value("movement_detector").toBool();
  }
  if (settings->contains("map_server_url")) {
    mapServerURL = settings->value("map_server_url").toString();
  }
  if (settings->contains("fingerprint_server_url")) {
    staticServerURL = settings->value("fingerprint_server_url").toString();
  }
  if (settings->contains("port")) {
    port = settings->value("port").toInt();
  }
  if (settings->contains("root_path")) {
    rootPathname = settings->value("root_path").toString();
  }

  if (isDaemon) {
    daemonize();
  } else {
    qDebug() << "not daemonizing";
  }

  //////////////////////////////////////////////////////////
  // check a few things before daemonizing
  initCommon(this, logFilename);

  qWarning() << "Starting mole daemon "
             << "debug=" << debug
             << "port=" << port
             << "wifi_scanning=" << runWiFiScanner
             << "movement_detector=" << runMovementDetector
             << "logFilename=" << logFilename
             << "map_server_url=" << mapServerURL
             << "fingerprint_server_url=" << staticServerURL
             << "rootPath=" << rootPathname;

  // start create map directory
  if (!rootDir.exists("map")) {
    bool ret = rootDir.mkdir("map");
    if (!ret) {
      qFatal("Failed to create map directory. Exiting...");
      exit(-1);
    }
    qDebug() << "created map dir";
  }
  // end create map directory

  // reset session cookie on MOLEd restart
  resetSessionCookie();

  m_localizer = new Localizer(this, runAllAlgorithms);

  if (runMovementDetector && SpeedSensor::haveAccelerometer()) {
    m_scanQueue = new ScanQueue(this, m_localizer, 0, recordScans);
  } else {
    // since we are not detecting motion, only use this many scans
    // for localization
    const int maxActiveQueueLength = 12;
    m_scanQueue = new ScanQueue(this, m_localizer, maxActiveQueueLength, recordScans);
  }

  m_binder = new Binder(this, m_localizer, m_scanQueue);
  m_proximity = new Proximity(this, m_localizer);
  m_localServer = new LocalServer(this, m_localizer, m_binder, port);

  m_scanner = 0;
  if (runWiFiScanner) {
    m_scanner = new Scanner(this);
    connect(m_scanner, SIGNAL(setWiFiDesc(QString)), m_binder, SLOT(setWiFiDesc(QString)));
    connect(m_scanner, SIGNAL(addReading(QString,QString,qint16,qint8)),
            m_scanQueue, SLOT(addReading(QString,QString,qint16,qint8)));
    connect(m_scanner, SIGNAL(scanCompleted()), m_scanQueue, SLOT(scanCompleted()));
  }

  m_speedSensor = 0;
  if (runMovementDetector && SpeedSensor::haveAccelerometer()) {
    m_speedSensor = new SpeedSensor(this);
    connect(m_speedSensor, SIGNAL(hibernate(bool)), m_scanner, SLOT(handleHibernate(bool)));
    connect(m_speedSensor, SIGNAL(hibernate(bool)), m_localizer, SLOT(handleHibernate(bool)));

    connect(m_speedSensor, SIGNAL(motionChange(Motion)), m_localizer, SLOT(handleMotionChange(Motion)));
    connect(m_speedSensor, SIGNAL(motionChange(Motion)), m_scanQueue, SLOT(handleMotionChange(Motion)));


  }

  connect(this, SIGNAL(aboutToQuit()), SLOT(handle_quit()));

  if (runWiFiScanner) {
    m_scanner->start();
  }

}
    connect(&tap_update_timer_, SIGNAL(timeout()), this, SLOT(updateTaps()));

    // Application-wide style sheet
    QString app_style_sheet = qApp->styleSheet();
#if defined(Q_OS_MAC) && QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
    // Qt uses the HITheme API to draw splitters. In recent versions of OS X
    // this looks particularly bad: https://bugreports.qt.io/browse/QTBUG-43425
    // This doesn't look native but it looks better than Yosemite's bit-rotten
    // rendering of HIThemeSplitterDrawInfo.
    app_style_sheet +=
            "QSplitter::handle:vertical { height: 0px; }\n"
            "QSplitter::handle:horizontal { width: 0px; }\n";
#endif
    qApp->setStyleSheet(app_style_sheet);

    connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(cleanup()));
}

void WiresharkApplication::registerUpdate(register_action_e action, const char *message)
{
    emit splashUpdate(action, message);
}

void WiresharkApplication::emitAppSignal(AppSignal signal)
{
    switch (signal) {
    case ColumnsChanged:
        emit columnsChanged();
        break;
    case FilterExpressionsChanged:
        emit filterExpressionsChanged();
示例#16
0
int main (int argc, char *argv[])
{
    QApplication app(argc, argv);

    QCoreApplication::setOrganizationName("Neo Software");
    QCoreApplication::setOrganizationDomain("neo.de");
    QCoreApplication::setApplicationName("Qwired");

    QSettings settings;

#ifdef Q_WS_MAC
    if (!app.style()->objectName().startsWith("macintosh")) {
        app.setStyleSheet("* {font-size: 11px;} QWidget { background-color: #DDD; }");
    }
#endif

    // Basic first-time initialization
    if (settings.allKeys().isEmpty()) {
        // The main bookmark
        settings.beginWriteArray("bookmarks", 1);
        settings.setArrayIndex(0);
        settings.setValue("name", "Official Qwired Server");
        settings.setValue("address", "hl.neo.de");
        settings.endArray();
    }

    // Translation loader
    QTranslator translator;
    QString tmpLocaleShort = QLocale::system().name().section ( "_",0,0 );
    QStringList tmpLocaleList;
    if (settings.contains("general/language") && settings.value("general/language").toString()!="_auto_" ) {
        tmpLocaleList.append(QString(":lang_%1.qm").arg(settings.value("general/language").toString()));
    } else {
        tmpLocaleList.append(QLocale::system().name()); // long locale, from file
        tmpLocaleList.append(tmpLocaleShort); // short locale, from file
        tmpLocaleList.append(QString(":%1.qm").arg(QLocale::system().name())); // long locale, from res
        tmpLocaleList.append(QString(":lang_%1.qm").arg(tmpLocaleShort) );
    }
    QStringListIterator i(tmpLocaleList);
    while (i.hasNext()) {
        QString tmpName = i.next();
        if(translator.load(tmpName)) {
            app.installTranslator(&translator);
            break;
        } else {
            qDebug() << "Trying to load locale:"<<tmpName<<": Failed (trying next)";
        }
    }


    // Configure the proxying, if needed
    if (settings.value("proxy/type").toInt() != 0) {
        QNetworkProxy proxy((QNetworkProxy::ProxyType)settings.value("proxy/type").toInt());
        proxy.setHostName(settings.value("proxy/host").toString());
        proxy.setPort(settings.value("proxy/port").toInt());
        proxy.setUser(settings.value("proxy/username").toString());
        proxy.setPassword(settings.value("proxy/password").toString());
        QNetworkProxy::setApplicationProxy(proxy);
    }



    // Singleton
    QwcSingleton *singleton = &WSINGLETON::Instance();
    QObject::connect(&app, SIGNAL(aboutToQuit()),
                     singleton, SLOT(cleanUp()));
    singleton->createTrayIcon();

    // Create the settings directory
    QDir settingDir(QwcSingleton::systemSettingsDirectory());
    if (!settingDir.exists()) {
        settingDir.mkpath(".");
    }


    singleton->createInitialSessions();

    return app.exec();
}
QNativeWifiEngine::QNativeWifiEngine(QObject *parent)
:   QBearerEngineImpl(parent), handle(INVALID_HANDLE_VALUE)
{
    connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(closeHandle()));
}
示例#18
0
文件: main.cpp 项目: Margaral/QGIS
  {
    QStringList gdalShares;
    QString appResources( QDir::cleanPath( QgsApplication::pkgDataPath() ) );
    gdalShares << QCoreApplication::applicationDirPath().append( "/share/gdal" )
    << appResources.append( "/share/gdal" )
    << appResources.append( "/gdal" );
    Q_FOREACH ( const QString& gdalShare, gdalShares )
    {
      if ( QFile::exists( gdalShare ) )
      {
        setenv( "GDAL_DATA", gdalShare.toUtf8().constData(), 1 );
        break;
      }
    }
  }
#endif

  QgsBrowser w;

  a.connect( &a, SIGNAL( aboutToQuit() ), &w, SLOT( saveWindowState() ) );
  w.restoreWindowState();

  w.show();

  a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );

  QgsEditorWidgetRegistry::initEditors();

  return a.exec();
}
示例#19
0
文件: edbee.cpp 项目: edbee/edbee-lib
/// Call this method to automaticly shutdown the texteditor manager on shutdown
/// (This method listens to the qApp::aboutToQuit signal
void Edbee::autoShutDownOnAppExit()
{
    connect( qApp, SIGNAL(aboutToQuit()),this,SLOT(shutdown()) );
}
示例#20
0
int main(int argc, char *argv[])
{
     QApplication app(argc, argv);

#if QT_VERSION < 0x050000
     // Removed in Qt5
     QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
     QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
#endif

     app.setApplicationName(BINARY_NAME);
     app.setOrganizationName(BINARY_NAME);
     app.setApplicationVersion(PACKAGE_VERSION);

     QStringList args = qApp->arguments();
     if (args.contains("--version") ||
         args.contains("-version") ||
         args.contains("-v")) {
         std::cout << qPrintable(VERSION_MESSAGE);
         return 0;
     }

     if (args.contains("--help") ||
         args.contains("-help") ||
         args.contains("-h")) {
         std::cout << qPrintable(HELP_MESSAGE);
         return 0;
     }

     // Create plugins manager
     ExtensionSystem::PluginManager pluginManager;
     pluginManager.setFileExtension(QString("pluginspec"));

     // Getting & feeding libraries/plugins path
     QStringList libpath;
#ifdef LIBRARY_BASENAME
     libpath << Utils::applicationPluginsPath(QString(BINARY_NAME), QString(LIBRARY_BASENAME));
#else
     libpath << Utils::applicationPluginsPath(QString(BINARY_NAME), "");
#endif
     if (libpath.isEmpty())
         return 123;
     pluginManager.setPluginPaths(libpath);

     // Add some debugging information
     Utils::Log::logCompilationConfiguration();

     // Manage plugin manager options
     QStringList arguments = app.arguments(); // adapted arguments list is passed to plugin manager later
     QMap<QString, QString> foundAppOptions;
     if (arguments.size() > 1) {
         QMap<QString, bool> appOptions;
         QString errorMessage;
         if (!pluginManager.parseOptions(arguments, appOptions, &foundAppOptions, &errorMessage)) {
                // qWarning() << errorMessage;
                // qWarning() << HELP_MESSAGE;
                // return -1;
         }
     }

     const PluginSpecSet plugins = pluginManager.plugins();
     ExtensionSystem::PluginSpec *coreplugin = 0;

     if (WarnAllPluginSpecs) {
        foreach (ExtensionSystem::PluginSpec *spec, plugins) {
            qWarning() << "PluginSpecs :::"<< spec->filePath() << spec->name() << spec->version();
        }
    }

    foreach (ExtensionSystem::PluginSpec *spec, plugins) {
        if (spec->name() == QString(COREPLUGINSNAME)) {
            coreplugin = spec;
            break;
        }
    }

    ExtensionSystem::PluginSpec *userplugin = 0;
    foreach (ExtensionSystem::PluginSpec *spec, plugins) {
        if (spec->name() == QString(USERPLUGINSNAME)) {
            userplugin = spec;
            break;
        }
    }

    if (!coreplugin) {
        const QString reason = QCoreApplication::translate("Application", "Couldn't find 'Core.pluginspec' in %1").arg(qApp->libraryPaths().join("; "));
        qWarning() << reason;
//        displayError(msgCoreLoadFailure(reason));
        return 1;
    }
    if (!userplugin) {
        const QString reason = QCoreApplication::translate("Application", "Couldn't find 'UserManager.pluginspec' in %1").arg(qApp->libraryPaths().join("; "));
        qWarning() << reason;
//        displayError(msgCoreLoadFailure(reason));
        return 1;
    }


    if (coreplugin->hasError()) {
        qWarning() << coreplugin->errorString();
//        displayError(msgCoreLoadFailure(coreplugin->errorString()));
        return 1;
    }

    if (userplugin->hasError()) {
        qWarning() << userplugin->errorString();
//        displayError(msgCoreLoadFailure(coreplugin->errorString()));
        return 1;
    }

//    if (foundAppOptions.contains(QLatin1String(VERSION_OPTION))) {
//        printVersion(coreplugin, pluginManager);
//        return 0;
//    }
//    if (foundAppOptions.contains(QLatin1String(HELP_OPTION1))
//            || foundAppOptions.contains(QLatin1String(HELP_OPTION2))
//            || foundAppOptions.contains(QLatin1String(HELP_OPTION3))
//            || foundAppOptions.contains(QLatin1String(HELP_OPTION4))) {
//        printHelp(QFileInfo(app.applicationFilePath()).baseName(), pluginManager);
//        return 0;
//    }

//    const bool isFirstInstance = !app.isRunning();
//    if (!isFirstInstance && foundAppOptions.contains(QLatin1String(CLIENT_OPTION)))
//        return sendArguments(app, pluginManager.arguments()) ? 0 : -1;

//    foreach (ExtensionSystem::PluginSpec *spec, plugins) {
//        qWarning() << "PlugInSpec" << spec->name() << spec->errorString() << spec->state();
//    }

    pluginManager.loadPlugins();
    if (WarnAllPluginSpecs) {
        foreach (ExtensionSystem::PluginSpec *spec, plugins) {
            qWarning() << "PluginSpecs :::"<< spec->name() << "hasError:" << spec->hasError() << spec->errorString();
        }
    }

    if (coreplugin->hasError()) {
        qWarning() << coreplugin->errorString();
        return 1;
    }
    if (userplugin->hasError()) {
        qWarning() << userplugin->errorString();
//        displayError(msgCoreLoadFailure(coreplugin->errorString()));
        return 1;
    }


//    if (isFirstInstance) {
//        // Set up lock and remote arguments for the first instance only.
//        // Silently fallback to unconnected instances for any subsequent
//        // instances.
//        app.initialize();
//        QObject::connect(&app, SIGNAL(messageReceived(QString)), coreplugin->plugin(), SLOT(remoteArgument(QString)));
//    }
//    QObject::connect(&app, SIGNAL(fileOpenRequest(QString)), coreplugin->plugin(), SLOT(remoteArgument(QString)));

    // shutdown plugin manager on the exit
    QObject::connect(&app, SIGNAL(aboutToQuit()), &pluginManager, SLOT(shutdown()));

#ifdef WITH_TESTS
    // Do this after the event loop has started
    if (pluginManager.runningTests())
        QTimer::singleShot(100, &pluginManager, SLOT(startTests()));
#endif

    int r = app.exec();
//    Utils::Log::saveLog();
    return r;
}
TAbstractLogStream::TAbstractLogStream(const QList<TLogger *> &loggers, QObject *parent)
    : QObject(parent), loggerList(loggers), nonBuffering(false)
{
    connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(setNonBufferingMode()));
}
示例#22
0
文件: main.cpp 项目: phob/antimicro
int main(int argc, char *argv[])
{
    qRegisterMetaType<JoyButtonSlot*>();
    qRegisterMetaType<InputDevice*>();
    qRegisterMetaType<AutoProfileInfo*>();

    QTextStream outstream(stdout);
    QTextStream errorstream(stderr);

    // If running Win version, check if an explicit style
    // was defined on the command-line. If so, make a note
    // of it.
#ifdef Q_OS_WIN
    bool styleChangeFound = false;
    for (int i=0; i < argc && !styleChangeFound; i++)
    {
        char *tempchrstr = argv[i];
        QString temp = QString::fromUtf8(tempchrstr);
        if (temp == "-style")
        {
            styleChangeFound = true;
        }
    }
#endif

    CommandLineUtility cmdutility;
    QStringList cmdarguments = PadderCommon::arguments(argc, argv);
    cmdarguments.removeFirst();
    cmdutility.parseArguments(cmdarguments);

    Logger appLogger(&outstream, &errorstream);

    if (cmdutility.hasError())
    {
        appLogger.LogError(cmdutility.getErrorText());
        return 1;
    }
    else if (cmdutility.isHelpRequested())
    {
        appLogger.LogInfo(cmdutility.generateHelpString(), false);
        //cmdutility.printHelp();
        return 0;
    }
    else if (cmdutility.isVersionRequested())
    {
        appLogger.LogInfo(cmdutility.generateVersionString());
        //cmdutility.printVersionString();
        return 0;
    }

    if (cmdutility.getCurrentLogLevel() != appLogger.getCurrentLogLevel())
    {
        appLogger.setLogLevel(cmdutility.getCurrentLogLevel());
    }

    Q_INIT_RESOURCE(resources);

    QDir configDir(PadderCommon::configPath);
    if (!configDir.exists())
    {
        configDir.mkpath(PadderCommon::configPath);
    }

    QMap<SDL_JoystickID, InputDevice*> *joysticks = new QMap<SDL_JoystickID, InputDevice*>();

    // Cross-platform way of performing IPC. Currently,
    // only establish a connection and then disconnect.
    // In the future, there might be a reason to actually send
    // messages to the QLocalServer.
    QLocalSocket socket;
    socket.connectToServer(PadderCommon::localSocketKey);
    socket.waitForConnected(1000);
    if (socket.state() == QLocalSocket::ConnectedState)
    {
        // An instance of this program is already running.
        // Save app config and exit.
        QApplication a(argc, argv);
        AntiMicroSettings settings(PadderCommon::configFilePath, QSettings::IniFormat);
        InputDaemon *joypad_worker = new InputDaemon(joysticks, &settings, false);
        MainWindow w(joysticks, &cmdutility, &settings, false);

        if (!cmdutility.hasError() && cmdutility.hasProfile())
        {
            w.saveAppConfig();
        }

        joypad_worker->quit();
        w.removeJoyTabs();

        settings.sync();
        socket.disconnectFromServer();

        deleteInputDevices(joysticks);
        delete joysticks;
        joysticks = 0;

        delete joypad_worker;
        joypad_worker = 0;

        return 0;
    }

    LocalAntiMicroServer *localServer = 0;
    QApplication *a = 0;

#ifndef Q_OS_WIN
    if (cmdutility.launchAsDaemon())
    {
        pid_t pid, sid;

        //Fork the Parent Process
        pid = fork();

        if (pid == 0)
        {
            appLogger.LogInfo(QObject::tr("Daemon launched"));
            //outstream << QObject::tr("Daemon launched") << endl;

            a = new QApplication(argc, argv);
            localServer = new LocalAntiMicroServer();
            localServer->startLocalServer();
        }
        else if (pid < 0)
        {
            appLogger.LogError(QObject::tr("Failed to launch daemon"));
            //errorstream << QObject::tr("Failed to launch daemon") << endl;

            deleteInputDevices(joysticks);
            delete joysticks;
            joysticks = 0;

            exit(EXIT_FAILURE);
        }
        //We got a good pid, Close the Parent Process
        else if (pid > 0)
        {
            appLogger.LogInfo(QObject::tr("Launching daemon"));
            //outstream << QObject::tr("Launching daemon") << endl;

            deleteInputDevices(joysticks);
            delete joysticks;
            joysticks = 0;

            exit(EXIT_SUCCESS);
        }


    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
        #endif

        if (cmdutility.getDisplayString().isEmpty())
        {
            X11Extras::getInstance()->syncDisplay();
        }
        else
        {
            X11Extras::getInstance()->syncDisplay(cmdutility.getDisplayString());
            if (X11Extras::getInstance()->display() == NULL)
            {
                appLogger.LogError(QObject::tr("Display string \"%1\" is not valid.").arg(cmdutility.getDisplayString()));
                //errorstream << QObject::tr("Display string \"%1\" is not valid.").arg(cmdutility.getDisplayString()) << endl;

                deleteInputDevices(joysticks);
                delete joysticks;
                joysticks = 0;

                delete localServer;
                localServer = 0;

                X11Extras::deleteInstance();

                exit(EXIT_FAILURE);
            }
        }

        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
        #endif

    #endif

        //Change File Mask
        umask(0);

        //Create a new Signature Id for our child
        sid = setsid();
        if (sid < 0)
        {
            appLogger.LogError(QObject::tr("Failed to set a signature id for the daemon"));
            //errorstream << QObject::tr("Failed to set a signature id for the daemon") << endl;

            deleteInputDevices(joysticks);
            delete joysticks;
            joysticks = 0;

            delete localServer;
            localServer = 0;

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
            if (QApplication::platformName() == QStringLiteral("xcb"))
            {
        #endif
            X11Extras::deleteInstance();

        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
            }
        #endif
    #endif

            exit(EXIT_FAILURE);
        }

        if ((chdir("/")) < 0)
        {
            appLogger.LogError(QObject::tr("Failed to change working directory to /"));
            //errorstream << QObject::tr("Failed to change working directory to /")
            //            << endl;

            deleteInputDevices(joysticks);
            delete joysticks;
            joysticks = 0;

            delete localServer;
            localServer = 0;

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

            if (QApplication::platformName() == QStringLiteral("xcb"))
            {
        #endif
            X11Extras::deleteInstance();
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
            }
        #endif
    #endif

            exit(EXIT_FAILURE);
        }

        //Close Standard File Descriptors
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
    }
    else
    {
        a = new QApplication(argc, argv);
        localServer = new LocalAntiMicroServer();
        localServer->startLocalServer();

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
        #endif
        if (!cmdutility.getDisplayString().isEmpty())
        {
            X11Extras::getInstance()->syncDisplay(cmdutility.getDisplayString());
            if (X11Extras::getInstance()->display() == NULL)
            {
                appLogger.LogError(QObject::tr("Display string \"%1\" is not valid.").arg(cmdutility.getDisplayString()));
                //errorstream << QObject::tr("Display string \"%1\" is not valid.").arg(cmdutility.getDisplayString()) << endl;

                deleteInputDevices(joysticks);
                delete joysticks;
                joysticks = 0;

                delete localServer;
                localServer = 0;

                X11Extras::deleteInstance();

                exit(EXIT_FAILURE);
            }
        }

        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
        #endif
    #endif
    }

#else
    a = new QApplication (argc, argv);
    localServer = new LocalAntiMicroServer();
    localServer->startLocalServer();
#endif

    a->setQuitOnLastWindowClosed(false);

    //QString defaultStyleName = qApp->style()->objectName();

    // If running Win version and no explicit style was
    // defined, use the style Fusion by default. I find the
    // windowsvista style a tad ugly
#ifdef Q_OS_WIN
    if (!styleChangeFound)
    {
        qApp->setStyle(QStyleFactory::create("Fusion"));
    }

    QIcon::setThemeName("/");
#endif

    AntiMicroSettings settings(PadderCommon::configFilePath, QSettings::IniFormat);
    settings.importFromCommandLine(cmdutility);

    QString targetLang = QLocale::system().name();
    if (settings.contains("Language"))
    {
        targetLang = settings.value("Language").toString();
    }

    QTranslator qtTranslator;
    qtTranslator.load(QString("qt_").append(targetLang), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    a->installTranslator(&qtTranslator);

    QTranslator myappTranslator;
#if defined(Q_OS_UNIX)
    myappTranslator.load(QString("antimicro_").append(targetLang), QApplication::applicationDirPath().append("/../share/antimicro/translations"));
#elif defined(Q_OS_WIN)
    myappTranslator.load(QString("antimicro_").append(targetLang), QApplication::applicationDirPath().append("\\share\\antimicro\\translations"));
#endif
    a->installTranslator(&myappTranslator);

    InputDaemon *joypad_worker = new InputDaemon(joysticks, &settings);

#ifndef Q_OS_WIN
    // Have program handle SIGTERM
    struct sigaction termaction;
    termaction.sa_handler = &termSignalTermHandler;
    sigemptyset(&termaction.sa_mask);
    termaction.sa_flags = 0;

    sigaction(SIGTERM, &termaction, 0);

    // Have program handle SIGINT
    struct sigaction termint;
    termint.sa_handler = &termSignalIntHandler;
    sigemptyset(&termint.sa_mask);
    termint.sa_flags = 0;

    sigaction(SIGINT, &termint, 0);

#endif

    if (cmdutility.shouldListControllers())
    {
        AppLaunchHelper mainAppHelper(&settings, false);
        mainAppHelper.printControllerList(joysticks);

        joypad_worker->quit();

        deleteInputDevices(joysticks);
        delete joysticks;
        joysticks = 0;

        delete joypad_worker;
        joypad_worker = 0;

        delete localServer;
        localServer = 0;

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
        #endif
        X11Extras::deleteInstance();
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
        #endif
    #endif

        delete a;
        a = 0;

        return 0;
    }

#ifdef USE_SDL_2
    else if (cmdutility.shouldMapController())
    {
        MainWindow *w = new MainWindow(joysticks, &cmdutility, &settings);

        QObject::connect(a, SIGNAL(aboutToQuit()), w, SLOT(removeJoyTabs()));
        QObject::connect(a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(quit()));

        int app_result = a->exec();

        deleteInputDevices(joysticks);
        delete joysticks;
        joysticks = 0;

        delete joypad_worker;
        joypad_worker = 0;

        delete localServer;
        localServer = 0;

#ifdef WITH_X11
    #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
    #endif
        X11Extras::deleteInstance();
    #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
    #endif
#endif

        delete w;
        w = 0;

        delete a;
        a = 0;

        return app_result;
    }
#endif

#ifdef Q_OS_UNIX
    bool status = true;
    EventHandlerFactory *factory = EventHandlerFactory::getInstance(cmdutility.getEventGenerator());
    if (!factory)
    {
        status = false;
    }
    else
    {
        status = factory->handler()->init();
    }

#if defined(WITH_UINPUT) && defined(WITH_XTEST)
    // Use xtest as a fallback.
    if (!status && cmdutility.getEventGenerator() != EventHandlerFactory::fallBackIdentifier())
    {
        QString eventDisplayName = EventHandlerFactory::handlerDisplayName(
                    EventHandlerFactory::fallBackIdentifier());
        appLogger.LogInfo(QObject::tr("Attempting to use fallback option %1 for event generation.")
                                     .arg(eventDisplayName));
        //outstream << QObject::tr("Attempting to use fallback option %1 for event generation.")
        //             .arg(eventDisplayName) << endl;

        factory->deleteInstance();
        factory = EventHandlerFactory::getInstance(EventHandlerFactory::fallBackIdentifier());
        if (!factory)
        {
            status = false;
        }
        else
        {
            status = factory->handler()->init();
        }
    }
#endif

    if (!status)
    {
        appLogger.LogError(QObject::tr("Failed to open event generator. Exiting."));
        //errorstream << QObject::tr("Failed to open event generator. Exiting.") << endl;

        joypad_worker->quit();

        deleteInputDevices(joysticks);
        delete joysticks;
        joysticks = 0;

        delete joypad_worker;
        joypad_worker = 0;

        delete localServer;
        localServer = 0;

    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

        if (QApplication::platformName() == QStringLiteral("xcb"))
        {
        #endif
        X11Extras::deleteInstance();
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        }
        #endif
    #endif

        delete a;
        a = 0;

        return EXIT_FAILURE;
    }
    else
    {
        appLogger.LogInfo(QObject::tr("Using %1 as the event generator.").arg(factory->handler()->getName()));
        //outstream << QObject::tr("Using %1 as the event generator.").arg(factory->handler()->getName())
        //          << endl;
        factory->handler()->printPostMessages();
    }
#endif

    AntKeyMapper::getInstance(cmdutility.getEventGenerator());

    MainWindow *w = new MainWindow(joysticks, &cmdutility, &settings);

    FirstRunWizard *runWillard = 0;

    if (w->getGraphicalStatus() && FirstRunWizard::shouldDisplay(&settings))
    {
        runWillard = new FirstRunWizard(&settings, &qtTranslator, &myappTranslator);
        QObject::connect(runWillard, SIGNAL(finished(int)), w, SLOT(changeWindowStatus()));
        runWillard->show();
    }
    else
    {
        w->changeWindowStatus();
    }

    w->setAppTranslator(&qtTranslator);
    w->setTranslator(&myappTranslator);

    AppLaunchHelper mainAppHelper(&settings, w->getGraphicalStatus());
    mainAppHelper.initRunMethods();

    QObject::connect(joypad_worker,
                     SIGNAL(joysticksRefreshed(QMap<SDL_JoystickID, InputDevice*>*)),
                     w, SLOT(fillButtons(QMap<SDL_JoystickID, InputDevice*>*)));

    QObject::connect(w, SIGNAL(joystickRefreshRequested()), joypad_worker, SLOT(refresh()));
    QObject::connect(joypad_worker, SIGNAL(joystickRefreshed(InputDevice*)),
                     w, SLOT(fillButtons(InputDevice*)));

    QObject::connect(a, SIGNAL(aboutToQuit()), localServer, SLOT(close()));
    QObject::connect(a, SIGNAL(aboutToQuit()), w, SLOT(saveAppConfig()));
    QObject::connect(a, SIGNAL(aboutToQuit()), w, SLOT(removeJoyTabs()));
    QObject::connect(a, SIGNAL(aboutToQuit()), joypad_worker, SLOT(quit()));

#ifdef Q_OS_WIN
    QObject::connect(a, SIGNAL(aboutToQuit()), &mainAppHelper, SLOT(appQuitPointerPrecision()));
#endif
    QObject::connect(localServer, SIGNAL(clientdisconnect()), w, SLOT(handleInstanceDisconnect()));

#ifdef USE_SDL_2
    QObject::connect(w, SIGNAL(mappingUpdated(QString,InputDevice*)), joypad_worker, SLOT(refreshMapping(QString,InputDevice*)));
    QObject::connect(joypad_worker, SIGNAL(deviceUpdated(int,InputDevice*)), w, SLOT(testMappingUpdateNow(int,InputDevice*)));
    QObject::connect(joypad_worker, SIGNAL(deviceRemoved(SDL_JoystickID)), w, SLOT(removeJoyTab(SDL_JoystickID)));
    QObject::connect(joypad_worker, SIGNAL(deviceAdded(InputDevice*)), w, SLOT(addJoyTab(InputDevice*)));
#endif

#ifdef Q_OS_WIN
    // Raise process priority. Helps reduce timer delays caused by
    // the running of other processes.
    bool raisedPriority = WinExtras::raiseProcessPriority();
    if (!raisedPriority)
    {
        appLogger.LogInfo(QObject::tr("Could not raise process priority."));
        //outstream << QObject::tr("Could not raise process priority.") << endl;
    }
#else
    // Raise main thread prority. Helps reduce timer delays caused by
    // the running of other processes.
    QThread::currentThread()->setPriority(QThread::HighPriority);
#endif

    int app_result = a->exec();

    appLogger.LogInfo(QObject::tr("Quitting Program"));

    deleteInputDevices(joysticks);
    delete joysticks;
    joysticks = 0;

    delete joypad_worker;
    joypad_worker = 0;

    delete localServer;
    localServer = 0;

    AntKeyMapper::getInstance()->deleteInstance();

#ifdef Q_OS_UNIX
    #ifdef WITH_X11
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))

    if (QApplication::platformName() == QStringLiteral("xcb"))
    {
        #endif
    X11Extras::deleteInstance();
        #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    }
        #endif
    #endif

    EventHandlerFactory::getInstance()->handler()->cleanup();
    EventHandlerFactory::getInstance()->deleteInstance();
#endif

    delete w;
    w = 0;

    delete a;
    a = 0;

    return app_result;
}
示例#23
0
 void InstanceAdaptor::quit (const QDBusMessage& p_msg) const {
     const QString l_uuid = qobject_cast<AbstractPlugin*>(parent())->uuid();
     emit aboutToQuit ();
     qobject_cast<AbstractPlugin*>(parent())->doDeinitialize();
     emit pluginUnloaded (l_uuid);
 }
示例#24
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mainWindow = this;

    // Start device manager
    KbManager::init(CKB_VERSION_STR);
    connect(KbManager::kbManager(), SIGNAL(kbConnected(Kb*)), this, SLOT(addDevice(Kb*)));
    connect(KbManager::kbManager(), SIGNAL(kbDisconnected(Kb*)), this, SLOT(removeDevice(Kb*)));
    connect(KbManager::kbManager(), SIGNAL(versionUpdated()), this, SLOT(updateVersion()));
    connect(KbManager::scanTimer(), SIGNAL(timeout()), this, SLOT(timerTick()));

    // Set up tray icon
    restoreAction = new QAction(tr("Restore"), this);
    closeAction = new QAction(tr("Quit ckb"), this);
#ifdef USE_LIBAPPINDICATOR
    QString desktop = std::getenv("XDG_CURRENT_DESKTOP");
    unityDesktop = (desktop.toLower() == "unity");

    if(unityDesktop){
        trayIcon = 0;

        indicatorMenu = gtk_menu_new();
        indicatorMenuRestoreItem = gtk_menu_item_new_with_label("Restore");
        indicatorMenuQuitItem = gtk_menu_item_new_with_label("Quit ckb");

        gtk_menu_shell_append(GTK_MENU_SHELL(indicatorMenu), indicatorMenuRestoreItem);
        gtk_menu_shell_append(GTK_MENU_SHELL(indicatorMenu), indicatorMenuQuitItem);

        g_signal_connect(indicatorMenuQuitItem, "activate",
            G_CALLBACK(quitIndicator), this);
        g_signal_connect(indicatorMenuRestoreItem, "activate",
            G_CALLBACK(restoreIndicator), this);

        gtk_widget_show(indicatorMenuRestoreItem);
        gtk_widget_show(indicatorMenuQuitItem);

        indicator = app_indicator_new("ckb", "indicator-messages", APP_INDICATOR_CATEGORY_APPLICATION_STATUS);

        app_indicator_set_status(indicator, APP_INDICATOR_STATUS_ACTIVE);
        app_indicator_set_menu(indicator, GTK_MENU(indicatorMenu));
        app_indicator_set_icon(indicator, "ckb");
    } else
#endif // USE_LIBAPPINDICATOR
    {
        trayIconMenu = new QMenu(this);
        trayIconMenu->addAction(restoreAction);
        trayIconMenu->addAction(closeAction);
        trayIcon = new QSystemTrayIcon(QIcon(":/img/ckb-logo.png"), this);
        trayIcon->setContextMenu(trayIconMenu);
        connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconClicked(QSystemTrayIcon::ActivationReason)));
     }
     toggleTrayIcon(!CkbSettings::get("Program/SuppressTrayIcon").toBool());

#ifdef Q_OS_MACX
    // Make a custom "Close" menu action for OSX, as the default one brings up the "still running" popup unnecessarily
    QMenuBar* menuBar = new QMenuBar(this);
    setMenuBar(menuBar);
    this->menuBar()->addMenu("ckb")->addAction(closeAction);
#else
    // On linux, add a handler for Ctrl+Q
    new QShortcut(QKeySequence("Ctrl+Q"), this, SLOT(quitApp()));
#endif

    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(quitApp()));
    connect(closeAction, SIGNAL(triggered()), this, SLOT(quitApp()));
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(showWindow()));
    connect(qApp, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(stateChange(Qt::ApplicationState)));

    connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(cleanup()));

    ui->tabWidget->addTab(settingsWidget = new SettingsWidget(this), configLabel);
    settingsWidget->setVersion("ckb " CKB_VERSION_STR);
}
示例#25
0
MolconvWindow::MolconvWindow(QMainWindow *parent)
    : QMainWindow(parent)
    , d(new MolconvWindowPrivate)
    , ui(new Ui::MolconvWindow)
{
    ui->setupUi(this);

    d->m_ImportDialog = new ImportDialog(this);
    d->m_ExportDialog = new ExportDialog(this);
    d->m_NewGroupDialog = new NewGroupDialog(this);
    d->m_setBasisDialog = new setBasisDialog(this);
    d->m_ListOfMolecules = new ListOfMolecules(this);
    d->m_MoleculeSettings = new MoleculeSettings(this);

    addDockWidget(Qt::BottomDockWidgetArea, d->m_ListOfMolecules);
    addDockWidget(Qt::LeftDockWidgetArea, d->m_MoleculeSettings);

    ui->actionSet_internal_basis->setEnabled(false);
    ui->actionDuplicate->setEnabled(false);
    ui->actionRemove->setEnabled(false);
    ui->actionZero_Coordinates->setEnabled(false);
    ui->actionReset_Coordinates->setEnabled(false);
    ui->actionProperties->setEnabled(false);
    ui->actionAdd_To_Group->setEnabled(false);
    ui->actionAlign->setEnabled(false);

    connect(qApp, SIGNAL(aboutToQuit()), SLOT(quit()));

    connect(ui->actionImport_Molecule, SIGNAL(triggered()), SLOT(startImportDialog()));
    connect(ui->actionExport_Molecule, SIGNAL(triggered()), SLOT(startExportDialog()));
    connect(ui->actionQuit, SIGNAL(triggered()), SLOT(quit()));
    connect(ui->actionAbout, SIGNAL(triggered()), SLOT(about()));
    connect(ui->actionNew_Molecule_Group, SIGNAL(triggered()), SLOT(startNewGroupDialog()));
    connect(ui->actionSet_internal_basis, SIGNAL(triggered()), SLOT(startBasisDialog()));
    connect(ui->actionDuplicate, SIGNAL(triggered()), SLOT(DuplicateActiveMolecule()));
    connect(ui->actionRemove, SIGNAL(triggered()), SLOT(removeActiveMolecule()));
    connect(ui->actionReset, SIGNAL(triggered()), SLOT(ResetView()));
    connect(ui->actionZero_Coordinates, SIGNAL(triggered()), SLOT(zeroCoords()));
    connect(ui->actionReset_Coordinates, SIGNAL(triggered()), SLOT(resetCoords()));
    connect(ui->actionAlign, SIGNAL(triggered()), d->m_ListOfMolecules, SLOT(alignMolecules()));
    connect(ui->actionNavigate, SIGNAL(triggered()), SLOT(useNavigateTool()));
    connect(ui->actionSelect, SIGNAL(triggered()), SLOT(useSelectTool()));

    connect(d->m_ImportDialog, SIGNAL(accepted()), SLOT(openFile()));
    connect(d->m_NewGroupDialog, SIGNAL(accepted()), this, SLOT(newGroup()));
    connect(d->m_setBasisDialog, SIGNAL(ready()), SLOT(changeOriginBasis()));
    connect(d->m_ListOfMolecules, SIGNAL(newMoleculeSelected(molconv::moleculePtr&)), d->m_MoleculeSettings, SLOT(setMolecule(molconv::moleculePtr&)));
    connect(d->m_ListOfMolecules, SIGNAL(newMoleculeSelected(molconv::moleculePtr&)), SLOT(updateActiveMolecule(molconv::moleculePtr&)));
    connect(d->m_ListOfMolecules, SIGNAL(newGroupSelected(molconv::MoleculeGroup*)), d->m_MoleculeSettings, SLOT(setGroup(molconv::MoleculeGroup*)));
    connect(d->m_MoleculeSettings, SIGNAL(basisChanged()), SLOT(updateAxes()));
    connect(d->m_MoleculeSettings, SIGNAL(basisChanged()), SLOT(updateSelection()));

    GraphicsAxisItem *axes = new GraphicsAxisItem;
    ui->molconv_graphicsview->addItem(axes);

    d->m_Selection = new GraphicsSelectionItem;
    ui->molconv_graphicsview->addItem(d->m_Selection);

    d->m_navigatetool = boost::make_shared<NavigateTool>();
    d->m_selecttool = boost::make_shared<SelectTool>(this);
    useNavigateTool();

    ui->molconv_graphicsview->update();
}
示例#26
0
int main(int argc, char *argv[])
{
     QApplication app(argc, argv);

#if QT_VERSION < 0x050000
     // Removed in Qt5
     QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
     QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
#endif

     app.setApplicationName(BINARY_NAME);
     app.setOrganizationName(BINARY_NAME);
     app.setApplicationVersion(PACKAGE_VERSION);

     QStringList args = qApp->arguments();
     if (args.contains("--version") ||
         args.contains("-version") ||
         args.contains("-v")) {
         std::cout << qPrintable(VERSION_MESSAGE);
         return 0;
     }

     if (args.contains("--help") ||
         args.contains("-help") ||
         args.contains("-h")) {
         std::cout << qPrintable(HELP_MESSAGE);
         return 0;
     }

     // Create plugins manager
     ExtensionSystem::PluginManager pluginManager;
     pluginManager.setFileExtension(QString("pluginspec"));

     // Getting & feeding libraries/plugins path
     QStringList libpath;
#ifdef LIBRARY_BASENAME
     libpath << Utils::applicationPluginsPath(QString(BINARY_NAME), QString(LIBRARY_BASENAME));
#else
     libpath << Utils::applicationPluginsPath(QString(BINARY_NAME), "");
#endif
     if (libpath.isEmpty())
         return 123;
     pluginManager.setPluginPaths(libpath);

     // Add some debugging information
     Utils::Log::logCompilationConfiguration();

     const PluginSpecSet plugins = pluginManager.plugins();
     ExtensionSystem::PluginSpec *coreplugin = 0;

     if (WarnAllPluginSpecs) {
        foreach (ExtensionSystem::PluginSpec *spec, plugins) {
            qWarning() << "PluginSpecs :::"<< spec->filePath() << spec->name() << spec->version();
        }
    }

    foreach (ExtensionSystem::PluginSpec *spec, plugins) {
        if (spec->name() == QString(COREPLUGINSNAME)) {
            coreplugin = spec;
            break;
        }
    }

    if (!coreplugin) {
        const QString reason = QCoreApplication::translate("Application", "Couldn't find 'Core.pluginspec' in %1").arg(qApp->libraryPaths().join("; "));
        qWarning() << reason;
        return 1;
    }

    if (coreplugin->hasError()) {
        qWarning() << coreplugin->errorString();
        return 1;
    }

    pluginManager.loadPlugins();
    if (WarnAllPluginSpecs) {
        foreach (ExtensionSystem::PluginSpec *spec, plugins) {
            qWarning() << "PluginSpecs :::"<< spec->name() << "hasError:" << spec->hasError() << spec->errorString();
        }
    }

    if (coreplugin->hasError()) {
        qWarning() << coreplugin->errorString();
        return 1;
    }

    // shutdown plugin manager on the exit
    QObject::connect(&app, SIGNAL(aboutToQuit()), &pluginManager, SLOT(shutdown()));

    int r = app.exec();
//    Utils::Log::saveLog();
    return r;
}
NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceView, RunModus runModus, const QString &pathToQt)
    : NodeInstanceServerInterface(nodeInstanceView),
      m_localServer(new QLocalServer(this)),
      m_nodeInstanceView(nodeInstanceView),
      m_firstBlockSize(0),
      m_secondBlockSize(0),
      m_thirdBlockSize(0),
      m_writeCommandCounter(0),
      m_firstLastReadCommandCounter(0),
      m_secondLastReadCommandCounter(0),
      m_thirdLastReadCommandCounter(0),
      m_runModus(runModus),
      m_synchronizeId(-1)
{
   QString socketToken(QUuid::createUuid().toString());

   m_localServer->listen(socketToken);
   m_localServer->setMaxPendingConnections(3);

   QString applicationPath =  pathToQt + QLatin1String("/bin");
   if (runModus == TestModus) {
       applicationPath = QCoreApplication::applicationDirPath()
           + qmlPuppetApplicationDirectoryForTests()
           + qmlPuppetApplicationName();
   } else {
       applicationPath = macOSBundlePath(applicationPath);
       applicationPath += QLatin1Char('/') + qmlPuppetApplicationName();


#if defined(QT_NO_DEBUG) || defined(SEARCH_PUPPET_IN_CREATOR_BINPATH) // to prevent of choosing the wrong puppet in debug
       if (!QFileInfo(applicationPath).exists()) { //No qmlpuppet in Qt
           //We have to find out how to give not too intrusive feedback
           applicationPath = creatorQmlPuppetPath();
       }
#endif
   }


   QByteArray envImportPath = qgetenv("QTCREATOR_QMLPUPPET_PATH");
   if (!envImportPath.isEmpty())
       applicationPath = envImportPath;

   QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) && (defined(Q_OS_MAC) || defined(Q_OS_LINUX))
   environment.insert(QLatin1String("DESIGNER_DONT_USE_SHARED_MEMORY"), QLatin1String("1"));
#endif

   if (QFileInfo(applicationPath).exists()) {
       m_qmlPuppetEditorProcess = new QProcess;
       m_qmlPuppetEditorProcess->setProcessEnvironment(environment);
       m_qmlPuppetEditorProcess->setObjectName("EditorProcess");
       connect(m_qmlPuppetEditorProcess.data(), SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)));
       connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), m_qmlPuppetEditorProcess.data(), SLOT(kill()));
       bool fowardQmlpuppetOutput = !qgetenv("FORWARD_QMLPUPPET_OUTPUT").isEmpty();
       if (fowardQmlpuppetOutput) {
           m_qmlPuppetEditorProcess->setProcessChannelMode(QProcess::MergedChannels);
           connect(m_qmlPuppetEditorProcess.data(), SIGNAL(readyRead()), this, SLOT(printEditorProcessOutput()));
       }
       m_qmlPuppetEditorProcess->start(applicationPath, QStringList() << socketToken << "editormode" << "-graphicssystem raster");

       if (runModus == NormalModus) {
           m_qmlPuppetPreviewProcess = new QProcess;
           m_qmlPuppetPreviewProcess->setProcessEnvironment(environment);
           m_qmlPuppetPreviewProcess->setObjectName("PreviewProcess");
           connect(m_qmlPuppetPreviewProcess.data(), SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)));
           connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), m_qmlPuppetPreviewProcess.data(), SLOT(kill()));
           if (fowardQmlpuppetOutput) {
               m_qmlPuppetPreviewProcess->setProcessChannelMode(QProcess::MergedChannels);
               connect(m_qmlPuppetPreviewProcess.data(), SIGNAL(readyRead()), this, SLOT(printPreviewProcessOutput()));
           }
           m_qmlPuppetPreviewProcess->start(applicationPath, QStringList() << socketToken << "previewmode" << "-graphicssystem raster");

           m_qmlPuppetRenderProcess = new QProcess;
           m_qmlPuppetRenderProcess->setProcessEnvironment(environment);
           m_qmlPuppetRenderProcess->setObjectName("RenderProcess");
           connect(m_qmlPuppetRenderProcess.data(), SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)));
           connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), m_qmlPuppetRenderProcess.data(), SLOT(kill()));
           if (fowardQmlpuppetOutput) {
               m_qmlPuppetRenderProcess->setProcessChannelMode(QProcess::MergedChannels);
               connect(m_qmlPuppetRenderProcess.data(), SIGNAL(readyRead()), this, SLOT(printRenderProcessOutput()));
           }
           m_qmlPuppetRenderProcess->start(applicationPath, QStringList() << socketToken << "rendermode" << "-graphicssystem raster");

       }
示例#28
0
    HalalJapanAPI halalJapanAPI;
    halalJapanAPI.setDatabaseManager(&databaseManager);

    if(settings.getFirstRunning()) {
        QObject::connect(&halalJapanAPI, SIGNAL(firstSyncChanged(bool)), &settings, SLOT(setFirstRunning(bool)));
        halalJapanAPI.setBusyMessage("Preparing for first running...");
        halalJapanAPI.firstSync();
    }

    // inisialisai
    halalJapanAPI.setItemTotalPage(databaseManager.findTotalPage("items", settings.getItemPerPage()));
    halalJapanAPI.setCategoryTotalPage(databaseManager.findTotalPage("category", settings.getCategoryPerPage()));
    halalJapanAPI.setProducerTotalPage(databaseManager.findTotalPage("producer", settings.getCategoryPerPage()));
    halalJapanAPI.setPlaceTotalPage(databaseManager.findTotalPage("places", settings.getPlacePerPage()));

    QObject::connect(&app, SIGNAL(aboutToQuit()), &settings, SLOT(saveSettings()));
    QObject::connect(&halalJapanAPI, SIGNAL(lastUpdated(QDateTime)), &settings, SLOT(setLastUdpate(QDateTime)));

    QObject::connect(&settings, SIGNAL(itemPerPageChanged()), &databaseManager, SLOT(findItemTotalPage()));
    QObject::connect(&settings, SIGNAL(producerPerPageChanged()), &databaseManager, SLOT(findProducerTotalPage()));
    QObject::connect(&settings, SIGNAL(placePerPageChanged()), &databaseManager, SLOT(findPlaceTotalPage()));

    QObject::connect(&databaseManager, SIGNAL(itemTotalPageChanged(int)), &halalJapanAPI, SLOT(setItemTotalPage(int)));
    QObject::connect(&databaseManager, SIGNAL(categoryTotalPageChanged(int)), &halalJapanAPI, SLOT(setCategoryTotalPage(int)));
    QObject::connect(&databaseManager, SIGNAL(producerTotalPageChanged(int)), &halalJapanAPI, SLOT(setProducerTotalPage(int)));

    qRegisterMetaType<ItemListModel*>("ItemListModel");
    qmlRegisterType<ItemListModel>("Models",1,0,"ItemListModel");
    qRegisterMetaType<CategoryListModel*>("CategoryListModel");
    qmlRegisterType<CategoryListModel>("Models",1,0,"CategoryListModel");
    qRegisterMetaType<PaginationListModel*>("PaginationListModel");
示例#29
0
int main(int argc, char *argv[]) {
   Botan::LibraryInitializer Init;

#ifdef Q_WS_X11
   // QML is unusable with the xlib backend
   QApplication::setGraphicsSystem("raster");
#endif

   SharedTools::TSingleApplication app((QLatin1String(APP_NAME)), argc, argv);
   QCoreApplication::setApplicationName(QLatin1String(APP_NAME));
   QCoreApplication::setOrganizationName(QLatin1String("MIPT"));
   /*qDebug() << "main() app.IsRunning() =" << app.IsRunning();
      if(app.IsRunning()) {
            qDebug() << "We are not the first instance of the app, so sending message to the first..."
            << app.SendMessage("Activate");
            return 0;
         }*/

   // ------------------------------------------ Parse command line options ------------------------------------------
   QCommandLineParser CommandLineOptsParser;
   CommandLineOptsParser.setApplicationDescription(app.applicationName());
   CommandLineOptsParser.addHelpOption();
   CommandLineOptsParser.addVersionOption();
   QCommandLineOption HomeOption("config", "Path to config", "directory");
   CommandLineOptsParser.addOption(HomeOption);

   // Process the actual command line arguments given by the user
   CommandLineOptsParser.process(app);

   const QString HomeDir = CommandLineOptsParser.value(HomeOption);


   // --------------------------------------------------- Settings ---------------------------------------------------
   QSettings::setDefaultFormat(QSettings::IniFormat);
   QSettings *Settings;
   if(HomeDir.isEmpty())
      Settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, app.organizationName(), APP_NAME);
   else
      Settings = new QSettings(HomeDir + "/EventManager.ini", QSettings::IniFormat);




   // ----------------------------------------- PluginManager, load plugins  -----------------------------------------
   QScopedPointer<ExtSys::TPluginManager> PluginManager(ExtSys::TPluginManager::Instance());
   PluginManager->SetSettings(Settings);
   PluginManager->SetSpecFileExtension("pluginspec");
   const QStringList &PluginPaths = GetPluginPaths();
   PluginManager->SetPluginPaths(PluginPaths);

   const ExtSys::TPluginSpecList &Plugins = PluginManager->PluginSpecs();
   ExtSys::TPluginSpec *CorePlugin = nullptr;
   foreach (ExtSys::TPluginSpec *Spec, Plugins) {
      if(Spec->Name() == QLatin1String(CorePluginName)) {
         CorePlugin = Spec;
         break;
      }
   }
   if(!CorePlugin) {
      const QString &NativePaths = QDir::toNativeSeparators(PluginPaths.join(QLatin1String(",")));
      const QString &Reason = (QString("Application: Could not find '") + CorePluginName + "' in %1").arg(NativePaths);
      qCritical() << Reason;
      return 1;
   }
   if(CorePlugin->HasError()) {
      qCritical() << CorePlugin->ErrorString();
      return 1;
   }

   PluginManager->LoadPlugins();
   if(CorePlugin->HasError()) {
      qCritical() << CorePlugin->ErrorString();
      return 1;
   }
   {
      QStringList Errors;
      foreach(ExtSys::TPluginSpec *p, PluginManager->PluginSpecs())
         if(p->HasError())
            Errors << p->ErrorString();

      if(!Errors.isEmpty())
         QMessageBox::warning(nullptr, "Qt Creator - Plugin loader messages", Errors.join(QString::fromLatin1("\n\n")));
   }

   QObject::connect(&app, SIGNAL(aboutToQuit()), PluginManager.data(), SLOT(Shutdown()));

   return app.exec();
}
示例#30
0
Engine::Engine()
{
    Sanguosha = this;

    QStringList package_names;
    package_names << "StandardCard"
                  << "StandardExCard"
                  << "Maneuvering"
                  << "SPCard"
                  << "YitianCard"
                  << "Nostalgia"
                  << "Joy"
                  << "Disaster"
                  << "JoyEquip"
                  << "DishaCard"
                  << "QHSEquip"
                  << "Hide"

                  << "Standard"
                  << "Wind"
                  << "Fire"
                  << "Thicket"
                  << "Mountain"
                  << "God"
                  << "SP"
                  << "YJCM"
                  << "YJCM2012"
                  << "Special3v3"
                  << "BGM"
                  << "Yitian"
                  << "Wisdom"
                  << "Huangjin"
                  << "Ghost"
                  << "QHS"
                  << "YJ1st"
                  << "TBdiy"
                  << "Yan"
                  << "ChangbanSlope"
                  << "Test" ;

    foreach(QString name, package_names)
        addPackage(name);

    QStringList scene_names;
    scene_names << "Guandu"
                << "Fancheng"
                << "Couple"
                << "Zombie"
                << "Impasse"
                << "Custom";

    for(int i=1; i<=21; i++){
        scene_names << QString("MiniScene_%1").arg(i, 2, 10, QChar('0'));
    }

    foreach(QString name, scene_names)
        addScenario(name);

    foreach(const Skill *skill, skills.values()){
        Skill *mutable_skill = const_cast<Skill *>(skill);
        mutable_skill->initMediaSource();
    }

    // available game modes
    modes["02p"] = tr("2 players");
    //modes["02pbb"] = tr("2 players (using blance beam)");
    modes["02_1v1"] = tr("2 players (KOF style)");
    modes["03p"] = tr("3 players");
    modes["04p"] = tr("4 players");
    modes["04_1v3"] = tr("4 players (Hulao Pass)");
    modes["05p"] = tr("5 players");
    modes["05_2v3"] = tr("5 players (Changban Slope)");
    modes["06p"] = tr("6 players");
    modes["06pd"] = tr("6 players (2 renegades)");
    modes["06_3v3"] = tr("6 players (3v3)");
    modes["07p"] = tr("7 players");
    modes["08p"] = tr("8 players");
    modes["08pd"] = tr("8 players (2 renegades)");
    modes["08pz"] = tr("8 players (0 renegade)");
    modes["08same"] = tr("8 players (same mode)");
    modes["09p"] = tr("9 players");
    modes["10pd"] = tr("10 players");
    modes["10p"] = tr("10 players (1 renegade)");
    modes["10pz"] = tr("10 players (0 renegade)");

    connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(deleteLater()));

    QString error_msg;
    lua = createLuaState(false, error_msg);
    if(lua == NULL){
        QMessageBox::warning(NULL, tr("Lua script error"), error_msg);
        exit(1);
    }

    foreach(QString ban, getBanPackages()){
        addBanPackage(ban);
    }