Example #1
0
bool PromiseTimer::start(unsigned dwMillisecond)
{
  timer.setSingleShot(true);
  timer.start(dwMillisecond);
  return true;
}
Example #2
0
BitcoinGUI::BitcoinGUI(QWidget *parent):
    QMainWindow(parent),
    clientModel(0),
    walletModel(0),
    encryptWalletAction(0),
    changePassphraseAction(0),
    unlockWalletAction(0),
    lockWalletAction(0),
    aboutQtAction(0),
    trayIcon(0),
    notificator(0),
    rpcConsole(0),
    nWeight(0)
{
    setFixedSize(970, 550);
	QFontDatabase::addApplicationFont(":/fonts/Bebas");
    setWindowTitle(tr("Pentacoin") + " - " + tr("Wallet"));
	qApp->setStyleSheet("QMainWindow { background-image:url(:images/bkg);border:none; } #frame { } QToolBar QLabel { padding-top: 0px;padding-bottom: 0px;spacing: 10px;} QToolBar QLabel:item { padding-top: 0px;padding-bottom: 0px;spacing: 10px;} #spacer { background: transparent;border:none; } #toolbar2 { border:none;width:0px;hight:0px;padding-top:40px;padding-bottom:0px; background-color: transparent; } #labelMiningIcon { padding-left:5px;font-family:Century Gothic;width:100%;font-size:10px;text-align:center;color:black; } QMenu { background-color: qlineargradient(spread:pad, x1:0.511, y1:1, x2:0.482909, y2:0, stop:0 rgba(232,232,232), stop:1 rgba(232,232,232)); color: black; padding-bottom:10px; } QMenu::item { color: black; background: transparent; } QMenu::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgba(99,99,99,45), stop: 1 rgba(99,99,99,45)); } QMenuBar { background-color: white; color: white; } QMenuBar::item { font-size:12px;padding-bottom:3px;padding-top:3px;padding-left:15px;padding-right:15px;color: black; background-color: white; } QMenuBar::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgba(99,99,99,45), stop: 1 rgba(99,99,99,45)); }");
#ifndef Q_OS_MAC
    qApp->setWindowIcon(QIcon(":icons/bitcoin"));
    setWindowIcon(QIcon(":icons/bitcoin"));
#else
    setUnifiedTitleAndToolBarOnMac(true);
    QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
    // Accept D&D of URIs
    setAcceptDrops(true);

    // Create actions for the toolbar, menu bar and tray/dock icon
    createActions();

    // Create application menu bar
    createMenuBar();

    // Create the toolbars
    createToolBars();

    // Create the tray icon (or setup the dock icon)
    createTrayIcon();

    // Create tabs
    overviewPage = new OverviewPage();

    transactionsPage = new QWidget(this);
    QVBoxLayout *vbox = new QVBoxLayout();
    transactionView = new TransactionView(this);
    vbox->addWidget(transactionView);
    transactionsPage->setLayout(vbox);

    addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);

    receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);

    sendCoinsPage = new SendCoinsDialog(this);

    signVerifyMessageDialog = new SignVerifyMessageDialog(this);
    masternodeManagerPage = new MasternodeManager(this);

    centralWidget = new QStackedWidget(this);
    centralWidget->addWidget(overviewPage);
    centralWidget->addWidget(transactionsPage);
    centralWidget->addWidget(addressBookPage);
    centralWidget->addWidget(receiveCoinsPage);
    centralWidget->addWidget(sendCoinsPage);
    centralWidget->addWidget(masternodeManagerPage);
    setCentralWidget(centralWidget);

    // Create status bar
    statusBar();

    // Status bar notification icons
    QFrame *frameBlocks = new QFrame();
    frameBlocks->setContentsMargins(0,0,0,0);
    frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
    QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
    frameBlocksLayout->setContentsMargins(3,0,3,0);
    frameBlocksLayout->setSpacing(3);
    labelEncryptionIcon = new QLabel();
    labelStakingIcon = new QLabel();
    labelConnectionsIcon = new QLabel();
    labelBlocksIcon = new QLabel();
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelEncryptionIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelStakingIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelConnectionsIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelBlocksIcon);
    frameBlocksLayout->addStretch();

    if (GetBoolArg("-staking", true))
    {
        QTimer *timerStakingIcon = new QTimer(labelStakingIcon);
        connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingIcon()));
        timerStakingIcon->start(30 * 1000);
        updateStakingIcon();
    }

    // Progress bar and label for blocks download
    progressBarLabel = new QLabel();
    progressBarLabel->setVisible(false);
    progressBar = new QProgressBar();
    addToolBarBreak(Qt::LeftToolBarArea);
    QToolBar *toolbar2 = addToolBar(tr("Tabs toolbar"));
    addToolBar(Qt::LeftToolBarArea,toolbar2);
    toolbar2->setOrientation(Qt::Vertical);
    toolbar2->setMovable( false );
    toolbar2->setObjectName("toolbar2");
    toolbar2->setFixedWidth(28);
    toolbar2->setIconSize(QSize(28,54));
	toolbar2->addWidget(labelEncryptionIcon);
	toolbar2->addWidget(labelStakingIcon);
    toolbar2->addWidget(labelConnectionsIcon);
    toolbar2->addWidget(labelBlocksIcon);
	toolbar2->setStyleSheet("#toolbar2 QToolButton { background: transparent;border:none;padding:0px;margin:0px;height:54px;width:28px; }");
	
    syncIconMovie = new QMovie(":/movies/update_spinner", "gif", this);

    // Clicking on a transaction on the overview page simply sends you to transaction history page
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));

    // Double-clicking on a transaction on the transaction history page shows details
    connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));

    rpcConsole = new RPCConsole(this);
    connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));

    // Clicking on "Verify Message" in the address book sends you to the verify message tab
    connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
    // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
    connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));

    gotoOverviewPage();
}
Example #3
0
 void startTimer(int msec) { auRepTimer.start(msec, true); }
Example #4
0
void QgsComposerLabel::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget )
{
  Q_UNUSED( itemStyle );
  Q_UNUSED( pWidget );
  if ( !painter )
  {
    return;
  }

  drawBackground( painter );
  painter->save();

  double penWidth = pen().widthF();
  QRectF painterRect( penWidth + mMargin, penWidth + mMargin, mTextBoxWidth - 2 * penWidth - 2 * mMargin, mTextBoxHeight - 2 * penWidth - 2 * mMargin );
  painter->translate( rect().width() / 2.0, rect().height() / 2.0 );
  painter->rotate( mRotation );
  painter->translate( -mTextBoxWidth / 2.0, -mTextBoxHeight / 2.0 );

  if ( mHtmlState )
  {
    painter->scale( 1.0 / mHtmlUnitsToMM / 10.0, 1.0 / mHtmlUnitsToMM / 10.0 );

    QWebPage* webPage = new QWebPage();

    //Setup event loop and timeout for rendering html
    QEventLoop loop;
    QTimer timeoutTimer;
    timeoutTimer.setSingleShot( true );

    //This makes the background transparent. Found on http://blog.qt.digia.com/blog/2009/06/30/transparent-qwebview-or-qwebpage/
    QPalette palette = webPage->palette();
    palette.setBrush( QPalette::Base, Qt::transparent );
    webPage->setPalette( palette );
    //webPage->setAttribute(Qt::WA_OpaquePaintEvent, false); //this does not compile, why ?

    webPage->setViewportSize( QSize( painterRect.width() * mHtmlUnitsToMM * 10.0, painterRect.height() * mHtmlUnitsToMM * 10.0 ) );
    webPage->mainFrame()->setZoomFactor( 10.0 );
    webPage->mainFrame()->setScrollBarPolicy( Qt::Horizontal, Qt::ScrollBarAlwaysOff );
    webPage->mainFrame()->setScrollBarPolicy( Qt::Vertical, Qt::ScrollBarAlwaysOff );

    // QGIS segfaults when rendering web page while in composer if html
    // contains images. So if we are not printing the composition, then
    // disable image loading
    if ( mComposition->plotStyle() != QgsComposition::Print &&
         mComposition->plotStyle() != QgsComposition::Postscript )
    {
      webPage->settings()->setAttribute( QWebSettings::AutoLoadImages, false );
    }

    //Connect timeout and webpage loadFinished signals to loop
    connect( &timeoutTimer, SIGNAL( timeout() ), &loop, SLOT( quit() ) );
    connect( webPage, SIGNAL( loadFinished( bool ) ), &loop, SLOT( quit() ) );

    //mHtmlLoaded tracks whether the QWebPage has completed loading
    //its html contents, set it initially to false. The loadingHtmlFinished slot will
    //set this to true after html is loaded.
    mHtmlLoaded = false;
    connect( webPage, SIGNAL( loadFinished( bool ) ), SLOT( loadingHtmlFinished( bool ) ) );

    webPage->mainFrame()->setHtml( displayText() );

    //For very basic html labels with no external assets, the html load will already be
    //complete before we even get a chance to start the QEventLoop. Make sure we check
    //this before starting the loop
    if ( !mHtmlLoaded )
    {
      // Start a 20 second timeout in case html loading will never complete
      timeoutTimer.start( 20000 );
      // Pause until html is loaded
      loop.exec();
    }

    webPage->mainFrame()->render( painter );//DELETE WEBPAGE ?
  }
  else
  {
Example #5
0
    void UrlFactory::TryCorrectGoogleVersions()
    {
        QMutexLocker locker(&mutex);
        if(CorrectGoogleVersions && !IsCorrectGoogleVersions())
        {
            QNetworkReply *reply;
            QNetworkRequest qheader;
            QNetworkAccessManager network;
            QEventLoop q;
            QTimer tT;
            tT.setSingleShot(true);
            connect(&network, SIGNAL(finished(QNetworkReply*)),
                    &q, SLOT(quit()));
            connect(&tT, SIGNAL(timeout()), &q, SLOT(quit()));
            network.setProxy(Proxy);
#ifdef DEBUG_URLFACTORY
            qDebug()<<"Correct GoogleVersion";
#endif //DEBUG_URLFACTORY
            setIsCorrectGoogleVersions(true);
            QString url = "http://maps.google.com";

            qheader.setUrl(QUrl(url));
            qheader.setRawHeader("User-Agent",UserAgent);
            reply=network.get(qheader);
            tT.start(Timeout);
            q.exec();
            if(!tT.isActive())
                return;
            tT.stop();
            if( (reply->error()!=QNetworkReply::NoError))
            {
#ifdef DEBUG_URLFACTORY
                qDebug()<<"Try corrected version withou abort or error:"<<reply->errorString();
#endif //DEBUG_URLFACTORY
                return;
            }
            QString html=QString(reply->readAll());
            QRegExp reg("\"*http://mt0.google.com/vt/lyrs=m@(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleMap = QString("m@%1").arg(gc[1]);
                VersionGoogleMapChina = VersionGoogleMap;
#ifdef DEBUG_URLFACTORY
                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleMap: "<<VersionGoogleMap;
#endif //DEBUG_URLFACTORY
            }

            reg=QRegExp("\"*http://mt0.google.com/vt/lyrs=h@(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleLabels = QString("h@%1").arg(gc[1]);
                VersionGoogleLabelsChina = VersionGoogleLabels;
#ifdef DEBUG_URLFACTORY
                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleLabels: "<<VersionGoogleLabels;
#endif //DEBUG_URLFACTORY
            }
            reg=QRegExp("\"*http://khm0.google.com/kh/v=(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleSatellite = gc[1];
                VersionGoogleSatelliteKorea = VersionGoogleSatellite;
                VersionGoogleSatelliteChina = "s@" + VersionGoogleSatellite;

                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleSatellite: "<<VersionGoogleSatellite;

            }
            reg=QRegExp("\"*http://mt0.google.com/vt/lyrs=t@(\\d*),r@(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleTerrain = QString("t@%1,r@%2").arg(gc[1]).arg(gc[2]);
                VersionGoogleTerrainChina = VersionGoogleTerrain;
#ifdef DEBUG_URLFACTORY
                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleTerrain: "<<VersionGoogleTerrain;
#endif //DEBUG_URLFACTORY
            }
            reply->deleteLater();

        }
Example #6
0
Scene::Scene( QUndoStack* undoStack ) : QGraphicsScene()
{
  // create timer
  for (double k=0; k<=359; k=k+1)
  {
       // These two lines throw a casting error.
      //
      //
      //
      //sine[k]=qSin(k*PI/180);
      //cosine[k]=qCos(k*PI/180);
      //
      //
      //
      //
      //

  }


  QTimer *timer = new QTimer(this);
  connect(timer, SIGNAL(timeout()), this, SLOT(manageObjects()));
  //connect(timer, SIGNAL(timeout()), this, SLOT(collisionDetection()));
  timer->start(1000/25); // fire the timer 25 times per second

  // initialise variables
  m_undoStack     = undoStack;
  this->setSceneRect(0,0,WINDOW_WIDTH-20, WINDOW_HEIGHT-40);


  // create invisible item to provide default top-left anchor to scene
  addLine( 0, 0, 0, 1, QPen(Qt::transparent, 1) );

  // connect selectionChanged signal to selectStations slot
  connect( this, SIGNAL(selectionChanged()), this, SLOT(selectStations()) );

  // set local variables and check if existing station clicked
  qreal           stationX = .5*WINDOW_WIDTH;
  qreal           stationY = .45*WINDOW_HEIGHT;
  qreal           asteroidX[4] = {0.75*WINDOW_WIDTH,0.65*WINDOW_WIDTH , 0.55*WINDOW_WIDTH, 0.45*WINDOW_WIDTH};
  qreal           asteroidY[4] = {0.75*WINDOW_WIDTH,0.65*WINDOW_WIDTH , 0.55*WINDOW_WIDTH, 0.45*WINDOW_WIDTH};
  qreal           bulletX = 0.25*WINDOW_WIDTH;
  qreal           bulletY = 0.25*WINDOW_HEIGHT;
  qreal           asteroidMoveX = -1;
  qreal           asteroidMoveY = -1;
  qreal           xDest, yDest;






  Station*  station = dynamic_cast<Station*>( itemAt( stationX, stationY ) );
  m_undoStack->push( new CommandStationAdd( this, stationX, stationY ) );
  emit message( QString("Ship add at %1,%2").arg(stationX).arg(stationY) );

  for(int i=0; i<=4; i++){
      Asteroid*  asteroid = dynamic_cast<Asteroid*>( itemAt( asteroidX[i], asteroidY[i]) );
      listOfAsteroids->append(asteroid);
      m_undoStack->push( new CommandAsteroidAdd( this, asteroidX[i], asteroidY[i] ) );
      emit message( QString("Asteroid add at %1,%2").arg(asteroidX[i]).arg(asteroidY[i]) );
  }

  Bullet*  bullet = dynamic_cast<Bullet*>( itemAt( bulletX, bulletY ) );
  m_undoStack->push( new CommandBulletAdd( this, bulletX, bulletY ) );
  emit message( QString("Bullet add at %1,%2").arg(bulletX).arg(bulletY) );







  /*
  asteroid = dynamic_cast<Asteroid*>( itemAt( asteroidX, asteroidY ));
  m_undoStack->push( new CommandAsteroidDelete( this, asteroid ) );

  dynamic_cast<Asteroid*>(itemAt(50,300));
  m_undoStack->push( new CommandAsteroidAdd( this, 50, 300 ) );
  */
}
Example #7
0
BitcoinGUI::BitcoinGUI(QWidget *parent):
    QMainWindow(parent),
    clientModel(0),
    walletModel(0),
    encryptWalletAction(0),
    changePassphraseAction(0),
    unlockWalletAction(0),
    lockWalletAction(0),
    aboutQtAction(0),
    trayIcon(0),
    notificator(0),
    rpcConsole(0),
    nWeight(0)
{
    // resize(850, 550);
	setFixedSize(920, 560);
    setWindowTitle(tr("ParkByte") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
    qApp->setWindowIcon(QIcon(":icons/bitcoin"));
    setWindowIcon(QIcon(":icons/bitcoin"));
#else
    setUnifiedTitleAndToolBarOnMac(true);
    QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
    // Accept D&D of URIs
    setAcceptDrops(true);

    // Create actions for the toolbar, menu bar and tray/dock icon
    createActions();

    // Create application menu bar
    createMenuBar();

    // Create the toolbars
    createToolBars();

    // Create the tray icon (or setup the dock icon)
    createTrayIcon();

    // Create tabs
    overviewPage = new OverviewPage();
	blockBrowser = new BlockBrowser(this);  //block

    transactionsPage = new QWidget(this);
    QVBoxLayout *vbox = new QVBoxLayout();
    transactionView = new TransactionView(this);
    vbox->addWidget(transactionView);
    transactionsPage->setLayout(vbox);

    addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);

    receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);

    sendCoinsPage = new SendCoinsDialog(this);

    signVerifyMessageDialog = new SignVerifyMessageDialog(this);

    centralWidget = new QStackedWidget(this);
    centralWidget->addWidget(overviewPage);
	centralWidget->addWidget(blockBrowser);   // block
    centralWidget->addWidget(transactionsPage);
    centralWidget->addWidget(addressBookPage);
    centralWidget->addWidget(receiveCoinsPage);
    centralWidget->addWidget(sendCoinsPage);
    setCentralWidget(centralWidget);

    // Create status bar
    statusBar();

    // Status bar notification icons
    QFrame *frameBlocks = new QFrame();
    frameBlocks->setContentsMargins(0,0,0,0);
    frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
    QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
    frameBlocksLayout->setContentsMargins(3,0,3,0);
    frameBlocksLayout->setSpacing(3);
    labelEncryptionIcon = new QLabel();
    labelStakingIcon = new QLabel();
    labelConnectionsIcon = new QLabel();
    labelBlocksIcon = new QLabel();
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelEncryptionIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelStakingIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelConnectionsIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelBlocksIcon);
    frameBlocksLayout->addStretch();

    if (GetBoolArg("-staking", true))
    {
        QTimer *timerStakingIcon = new QTimer(labelStakingIcon);
        connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingIcon()));
        timerStakingIcon->start(30 * 1000);
        updateStakingIcon();
    }

    // Progress bar and label for blocks download
    progressBarLabel = new QLabel();
    progressBarLabel->setVisible(false);
    progressBar = new QProgressBar();
    progressBar->setAlignment(Qt::AlignCenter);
    progressBar->setVisible(false);

    // Override style sheet for progress bar for styles that have a segmented progress bar,
    // as they make the text unreadable (workaround for issue #1071)
    // See https://qt-project.org/doc/qt-4.8/gallery.html
    QString curStyle = qApp->style()->metaObject()->className();
    if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
    {
        progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
    }

    statusBar()->addWidget(progressBarLabel);
    statusBar()->addWidget(progressBar);
    statusBar()->addPermanentWidget(frameBlocks);

    syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);

    // Clicking on a transaction on the overview page simply sends you to transaction history page
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));

    // Double-clicking on a transaction on the transaction history page shows details
    connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));

    rpcConsole = new RPCConsole(this);
    connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));

    // Clicking on "Verify Message" in the address book sends you to the verify message tab
    connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
    // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
    connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));

    gotoOverviewPage();
}
Example #8
0
void people::makeStatus(const QString text){
    ui.label_status->setText(text);
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), ui.label_status, SLOT(clear()));
    timer->start(10000);
}
Example #9
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString serialPortName;
    QString serialPortFriendlyName;
    QString sisFile;
    QString exeFile;
    QStringList cmdLine;
    QStringList args = QCoreApplication::arguments();
    QTextStream outstream(stdout);
    QTextStream errstream(stderr);
    QString downloadRemoteFile;
    QString downloadLocalFile;
    int loglevel=1;
    int timeout=0;
    bool crashlog = true;
    QString crashlogpath;
    QListIterator<QString> it(args);
    it.next(); //skip name of program
    while (it.hasNext()) {
        QString arg = it.next();

        if (arg.startsWith("-")) {
            if (arg == "--portname" || arg == "-p") {
                CHECK_PARAMETER_EXISTS
                serialPortName = it.next();
            }
            else if (arg == "--portfriendlyname" || arg == "-f") {
                CHECK_PARAMETER_EXISTS
                serialPortFriendlyName = it.next();
            }
            else if (arg == "--sis" || arg == "-s") {
                CHECK_PARAMETER_EXISTS
                sisFile = it.next();
                if (!QFileInfo(sisFile).exists()) {
                    errstream << "Sis file (" << sisFile << ") doesn't exist" << endl;
                    return 1;
                }
            }
            else if (arg == "--download" || arg == "-d") {
                CHECK_PARAMETER_EXISTS
                downloadRemoteFile = it.next();
                CHECK_PARAMETER_EXISTS
                downloadLocalFile = it.next();
            }
            else if (arg == "--timeout" || arg == "-t") {
                CHECK_PARAMETER_EXISTS
                bool ok;
                timeout = it.next().toInt(&ok);
                if (!ok) {
                    errstream << "Timeout must be specified in milliseconds" << endl;
                    return 1;
                }
            }
            else if (arg == "--verbose" || arg == "-v")
                loglevel=2;
            else if (arg == "--quiet" || arg == "-q")
                loglevel=0;
            else if (arg == "--nocrashlog")
                crashlog = false;
            else if (arg == "--crashlogpath") {
                CHECK_PARAMETER_EXISTS
                crashlogpath = it.next();
            }
            else
                errstream << "unknown command line option " << arg << endl;
        } else {
            exeFile = arg;
            while(it.hasNext()) {
                cmdLine.append(it.next());
            }
        }
    }

    if (exeFile.isEmpty() && sisFile.isEmpty() && 
        (downloadLocalFile.isEmpty() || downloadRemoteFile.isEmpty())) {
        printUsage(outstream, args[0]);
        return 1;
    }

    if (serialPortName.isEmpty()) {
        if (loglevel > 0)
            outstream << "Detecting serial ports" << endl;
        foreach (const SerialPortId &id, enumerateSerialPorts(loglevel)) {
            if (loglevel > 0)
                outstream << "Port Name: " << id.portName << ", "
                     << "Friendly Name:" << id.friendlyName << endl;
            if (!id.friendlyName.isEmpty()
                    && serialPortFriendlyName.isEmpty()
                    && (id.friendlyName.contains("symbian", Qt::CaseInsensitive)
                        || id.friendlyName.contains("s60", Qt::CaseInsensitive)
                        || id.friendlyName.contains("nokia", Qt::CaseInsensitive))) {
                serialPortName = id.portName;
                break;
            } else if (!id.friendlyName.isEmpty()
                    && !serialPortFriendlyName.isEmpty()
                    && id.friendlyName.contains(serialPortFriendlyName)) {
                serialPortName = id.portName;
                break;
            }
        }
        if (serialPortName.isEmpty()) {
            errstream << "No phone found, ensure USB cable is connected or specify manually with -p" << endl;
            return 1;
        }
    }

    QScopedPointer<trk::Launcher> launcher;
    launcher.reset(new trk::Launcher(trk::Launcher::ActionPingOnly));
    QFileInfo info(exeFile);
    if (!sisFile.isEmpty()) {
        launcher->addStartupActions(trk::Launcher::ActionCopyInstall);
        launcher->setCopyFileName(sisFile, "c:\\data\\testtemp.sis");
        launcher->setInstallFileName("c:\\data\\testtemp.sis");
    }
    else if (info.exists()) {
        launcher->addStartupActions(trk::Launcher::ActionCopy);
        launcher->setCopyFileName(exeFile, QString("c:\\sys\\bin\\") + info.fileName());
    }
    if (!exeFile.isEmpty()) {
        launcher->addStartupActions(trk::Launcher::ActionRun);
        launcher->setFileName(QString("c:\\sys\\bin\\") + info.fileName());
        launcher->setCommandLineArgs(cmdLine);
    }
    if (!downloadRemoteFile.isEmpty() && !downloadLocalFile.isEmpty()) {
        launcher->addStartupActions(trk::Launcher::ActionDownload);
        launcher->setDownloadFileName(downloadRemoteFile, downloadLocalFile);
    }
    if (loglevel > 0)
        outstream << "Connecting to target via " << serialPortName << endl;
    launcher->setTrkServerName(serialPortName);

    if (loglevel > 1)
        launcher->setVerbose(1);

    TrkSignalHandler handler;
    handler.setLogLevel(loglevel);
    handler.setCrashLogging(crashlog);
    handler.setCrashLogPath(crashlogpath);

    QObject::connect(launcher.data(), SIGNAL(copyingStarted()), &handler, SLOT(copyingStarted()));
    QObject::connect(launcher.data(), SIGNAL(canNotConnect(const QString &)), &handler, SLOT(canNotConnect(const QString &)));
    QObject::connect(launcher.data(), SIGNAL(canNotCreateFile(const QString &, const QString &)), &handler, SLOT(canNotCreateFile(const QString &, const QString &)));
    QObject::connect(launcher.data(), SIGNAL(canNotWriteFile(const QString &, const QString &)), &handler, SLOT(canNotWriteFile(const QString &, const QString &)));
    QObject::connect(launcher.data(), SIGNAL(canNotCloseFile(const QString &, const QString &)), &handler, SLOT(canNotCloseFile(const QString &, const QString &)));
    QObject::connect(launcher.data(), SIGNAL(installingStarted()), &handler, SLOT(installingStarted()));
    QObject::connect(launcher.data(), SIGNAL(canNotInstall(const QString &, const QString &)), &handler, SLOT(canNotInstall(const QString &, const QString &)));
    QObject::connect(launcher.data(), SIGNAL(installingFinished()), &handler, SLOT(installingFinished()));
    QObject::connect(launcher.data(), SIGNAL(startingApplication()), &handler, SLOT(startingApplication()));
    QObject::connect(launcher.data(), SIGNAL(applicationRunning(uint)), &handler, SLOT(applicationRunning(uint)));
    QObject::connect(launcher.data(), SIGNAL(canNotRun(const QString &)), &handler, SLOT(canNotRun(const QString &)));
    QObject::connect(launcher.data(), SIGNAL(applicationOutputReceived(const QString &)), &handler, SLOT(applicationOutputReceived(const QString &)));
    QObject::connect(launcher.data(), SIGNAL(copyProgress(int)), &handler, SLOT(copyProgress(int)));
    QObject::connect(launcher.data(), SIGNAL(stateChanged(int)), &handler, SLOT(stateChanged(int)));
    QObject::connect(launcher.data(), SIGNAL(processStopped(uint,uint,uint,QString)), &handler, SLOT(stopped(uint,uint,uint,QString)));
    QObject::connect(launcher.data(), SIGNAL(libraryLoaded(trk::Library)), &handler, SLOT(libraryLoaded(trk::Library)));
    QObject::connect(launcher.data(), SIGNAL(libraryUnloaded(trk::Library)), &handler, SLOT(libraryUnloaded(trk::Library)));
    QObject::connect(launcher.data(), SIGNAL(registersAndCallStackReadComplete(const QList<uint> &,const QByteArray &)), &handler, SLOT(registersAndCallStackReadComplete(const QList<uint> &,const QByteArray &)));
    QObject::connect(&handler, SIGNAL(resume(uint,uint)), launcher.data(), SLOT(resumeProcess(uint,uint)));
    QObject::connect(&handler, SIGNAL(terminate()), launcher.data(), SLOT(terminate()));
    QObject::connect(&handler, SIGNAL(getRegistersAndCallStack(uint,uint)), launcher.data(), SLOT(getRegistersAndCallStack(uint,uint)));
    QObject::connect(launcher.data(), SIGNAL(finished()), &handler, SLOT(finished()));

    QObject::connect(OsSignalConverter::instance(), SIGNAL(terminate()), launcher.data(), SLOT(terminate()), Qt::QueuedConnection);

    QTimer timer;
    timer.setSingleShot(true);
    QObject::connect(&timer, SIGNAL(timeout()), &handler, SLOT(timeout()));
    if (timeout > 0) {
        timer.start(timeout);
    }

    QString errorMessage;
    if (!launcher->startServer(&errorMessage)) {
        errstream << errorMessage << endl;
        return 1;
    }

    return a.exec();
}
Example #10
0
int main (int argc, char * argv[])
{
	QApplication app( argc, argv );
	
	//  Create QGraphicsScene
	QGraphicsScene scene;
	scene.setSceneRect( -600, -250, 1200, 500 );
	scene.setItemIndexMethod( QGraphicsScene::NoIndex );
	
	//  Draw road
	scene.addLine( -350, -150, -350, -100 );
	scene.addLine( -500, -100, -350, -100 );
	scene.addLine( -500, -50, -350, -50 );
	scene.addLine( -350, 150, -350, -50 );
	scene.addLine( -300, 150, -300, -50 );
	scene.addLine( -300, -150, -300, -100 );

	scene.addLine( -300, -100, 300, -100 );
	scene.addLine( -300, -50, 300, -50 );

	scene.addLine( 350, -150, 350, -100 );
	scene.addLine( 500, -100, 350, -100 );
	scene.addLine( 500, -50, 350, -50 );
	scene.addLine( 350, 150, 350, -50 );
	scene.addLine( 300, 150, 300, -50 );
	scene.addLine( 300, -150, 300, -100 );
	
	scene.addLine( -325, -100, -325, -150 );
	scene.addLine( -325, -50, -325, 150 );
	scene.addLine( 325, -100, 325, -150 );
	scene.addLine( 325, -50, 325, 150 );
	scene.addLine( -475, -75, -350, -75 );
	scene.addLine( -300, -75, 300, -75 );
	scene.addLine( 475, -75, 350, -75 );
	
	//  Road notation
	QGraphicsItem* ptext = scene.addText( "BSN" );
	ptext->setPos( -340, -180 );

	ptext = scene.addText( "BSS" );
	ptext->setPos( -340, 150 );

	ptext = scene.addText( "TBN" );
	ptext->setPos( 310, -180 );
	
	ptext = scene.addText( "TBS" );
	ptext->setPos( 310, 150 );
	
	ptext = scene.addText( "RHW" );
	ptext->setPos( -550, -85 );

	ptext = scene.addText( "RHE" );
	ptext->setPos( 510, -85 );

	//  Draw traffic lights

	//  Add cars to scene
	//Car *car = new Car;
	CarGenerator *pcargen = new CarGenerator( eBSN, -337.5, -150, Qt::blue );
	scene.addItem( pcargen );
	//car->setStartPos();


	//  Create QGraphicsView
	QGraphicsView view( &scene );
	view.setViewportUpdateMode( QGraphicsView::BoundingRectViewportUpdate );
	view.setWindowTitle( QT_TRANSLATE_NOOP(QGraphicsVIew, "Traffic simulation") );

	view.show();


	//  Set Timer
	QTimer timer;
	QObject::connect( &timer, SIGNAL(timeout()), &scene, SLOT(advance()) );
	timer.start( 1000/20 );
	
	return app.exec();
}
int main(int argc, char* argv[])
{
  try
  {
    terrama2::core::initializeTerraMA();
    terrama2::core::registerFactories();


    {
      QCoreApplication app(argc, argv);
      auto& serviceManager = terrama2::core::ServiceManager::getInstance();
      std::map<std::string, std::string> connInfo { {"PG_HOST", TERRAMA2_DATABASE_HOST},
                                                    {"PG_PORT", TERRAMA2_DATABASE_PORT},
                                                    {"PG_USER", TERRAMA2_DATABASE_USERNAME},
                                                    {"PG_PASSWORD", TERRAMA2_DATABASE_PASSWORD},
                                                    {"PG_DB_NAME", TERRAMA2_DATABASE_DBNAME},
                                                    {"PG_CONNECT_TIMEOUT", "4"},
                                                    {"PG_CLIENT_ENCODING", "UTF-8"}
                                                  };
      serviceManager.setLogConnectionInfo(connInfo);
      serviceManager.setInstanceId(1);

      auto dataManager = std::make_shared<terrama2::services::collector::core::DataManager>();

      addInput(dataManager);
      addOutput(dataManager);
      addStaticDataSeries(dataManager);

      terrama2::services::collector::core::Service service(dataManager);
      service.start();

      terrama2::services::collector::core::Collector* collector(new terrama2::services::collector::core::Collector());
      terrama2::services::collector::core::CollectorPtr collectorPtr(collector);
      collector->id = 1;
      collector->projectId = 1;
      collector->serviceInstanceId = 1;

      collector->inputDataSeries = 1;
      collector->outputDataSeries = 2;
      collector->inputOutputMap.emplace(1, 2);

      terrama2::services::collector::core::Intersection* intersection(new terrama2::services::collector::core::Intersection());
      terrama2::services::collector::core::IntersectionPtr intersectionPtr(intersection);

      // Adds the attribute "SIGLA" to the collected occurrences.
      intersection->collectorId = collector->id;
      std::vector<std::string> attrVec;
      attrVec.push_back("sigla");
      intersection->attributeMap[3] = attrVec;
      collector->intersection = intersectionPtr;


      dataManager->add(collectorPtr);

      QTimer timer;
      QObject::connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit()));
      timer.start(300000);
      app.exec();

      service.stopService();
    }

    terrama2::core::finalizeTerraMA();
  }
  catch(...)
  {
    // TODO: o que fazer com uncaught exception
    std::cout << "\n\nException...\n" << std::endl;
  }

  return 0;
}
	void initializeGL() {
		gl::createVertexArrays(1, &vao);
		gl::createBuffers(1, &positionBuffer);
		gl::createBuffers(1, &colorBuffer);
		gl::createBuffers(1, &indexBuffer);
		vao.bindElementBuffer(indexBuffer);
		constexpr static gl::Float colors[] = {
			1,0,0,1,
			0,1,0,1,
			0,0,1,1,
			1,1,0,1,
			1,0,0,1,
			0,1,0,1,
			0,0,1,1,
			1,1,0,1,
			1,0,0,1,
			0,1,0,1,
			0,0,1,1,
			1,1,0,1,
			1,0,0,1,
			0,1,0,1,
			0,0,1,1,
			1,1,0,1,
		};
#define POS0 -0.5f, 0.5f,0,1,
#define POS1 -0.5f,-0.5f,0,1,
#define POS2  0.5f,-0.5f,0,1,
#define POS3  0.5f, 0.5f,0,1,
		constexpr static gl::Float positions[] = {
			POS0
			POS1
			POS2
			POS3
			POS1
			POS2
			POS3
			POS0
			POS2
			POS3
			POS0
			POS1
			POS3
			POS0
			POS1
			POS2
		};
		gl::bufferData(positionBuffer, sizeof(positions), positions);
		gl::bufferData(colorBuffer, sizeof(colors), colors);
		constexpr static gl::UnsignedInteger index[] = { 0 };
		gl::bufferData(indexBuffer, sizeof(index), index);
		vao.bindBuffer(0, positionBuffer);
		vao.bindBuffer(1, colorBuffer);
		vao.bindDivisor(0, 1);
		vao.bindDivisor(1, 1);
		constexpr static char vs[] = R"(#version 450
layout(location=0) in vec4 iposition;
layout(location=1) in vec4 icolor;
out vec4 color;
void main(){
gl_Position = iposition;
gl_PointSize = 36+15*gl_InstanceID;
color = icolor;
}
)";
		constexpr static char fs[] = R"(#version 450
in vec4 color;
out vec4 fcolor;
void main(){
fcolor = vec4( gl_PointCoord.xy  ,color.x, 1);
}
)";
		program = gl::VFProgramLoadSources(vs, fs);
		{
			typedef void(QTimer::*TT)();
			timer.connect(&timer,TT(&QTimer::timeout),
				[this]() {
				++baseIndex;
				if (baseIndex > 3) { baseIndex = 0; }
				super->updateGL();
			}
				);
			timer.start(666);
		}
	}
Example #13
0
/** Constructor */
MainWindow::MainWindow(QWidget* parent, Qt::WFlags flags)
    : RWindow("MainWindow", parent, flags), ui(new Ui::MainWindow)
{
    /* Invoke the Qt Designer generated QObject setup routine */
    ui->setupUi(this);

    _instance = this;

    m_bStatusLoadDone = false;
    isIdle = false;
    onlineCount = 0;

    notifyMenu = NULL;

    /* Calculate only once */
    RsPeerDetails pd;
    if (rsPeers->getPeerDetails(rsPeers->getOwnId(), pd)) {
        nameAndLocation = QString("%1 (%2)").arg(QString::fromUtf8(pd.name.c_str())).arg(QString::fromUtf8(pd.location.c_str()));
    }

    setWindowTitle(tr("RetroShare %1 a secure decentralized communication platform").arg(retroshareVersion()) + " - " + nameAndLocation);

    /* WORK OUT IF WE"RE IN ADVANCED MODE OR NOT */
    bool advancedMode = false;
    std::string advsetting;
    if (rsConfig->getConfigurationOption(RS_CONFIG_ADVANCED, advsetting) && (advsetting == "YES")) {
        advancedMode = true;
    }

    /* add url handler for RetroShare links */
    QDesktopServices::setUrlHandler(RSLINK_SCHEME, this, "retroshareLinkActivated");
    QDesktopServices::setUrlHandler("http", this, "externalLinkActivated");
    QDesktopServices::setUrlHandler("https", this, "externalLinkActivated");

    // Setting icons
    this->setWindowIcon(QIcon(QString::fromUtf8(":/images/rstray3.png")));

    /* Create all the dialogs of which we only want one instance */
    _bandwidthGraph = new BandwidthGraph();

    #ifdef UNFINISHED
    applicationWindow = new ApplicationWindow();
    applicationWindow->hide();
    #endif    

    /** Left Side ToolBar**/
    connect(ui->actionAdd_Friend, SIGNAL(triggered() ), this , SLOT( addFriend() ) );
    connect(ui->actionAdd_Share, SIGNAL(triggered() ), this , SLOT( openShareManager() ) );
    connect(ui->actionOptions, SIGNAL(triggered()), this, SLOT( showSettings()) );
    connect(ui->actionMessenger, SIGNAL(triggered()), this, SLOT( showMessengerWindow()) );

    ui->actionMessenger->setVisible(true);

    connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT( showabout()) );
    //connect(ui->actionColor, SIGNAL(triggered()), this, SLOT( setStyle()) );

    /** adjusted quit behaviour: trigger a warning that can be switched off in the saved
        config file RetroShare.conf */
    connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(doQuit()));

    QList<QPair<MainPage*, QAction*> > notify;

    /* Create the Main pages and actions */
    QActionGroup *grp = new QActionGroup(this);
    QAction *action;

    ui->stackPages->add(newsFeed = new NewsFeed(ui->stackPages),
                       createPageAction(QIcon(IMAGE_NEWSFEED), tr("News feed"), grp));

//    ui->stackPages->add(networkDialog = new NetworkDialog(ui->stackPages),
//                       createPageAction(QIcon(IMAGE_NETWORK2), tr("Network"), grp));

    ui->stackPages->add(friendsDialog = new FriendsDialog(ui->stackPages),
                       action = createPageAction(QIcon(IMAGE_PEERS), tr("Friends"), grp));
    notify.push_back(QPair<MainPage*, QAction*>(friendsDialog, action));

//    ui->stackPages->add(searchDialog = new SearchDialog(ui->stackPages),
//                       createPageAction(QIcon(IMAGE_SEARCH), tr("Search"), grp));

    ui->stackPages->add(transfersDialog = new TransfersDialog(ui->stackPages),
                      action = createPageAction(QIcon(IMAGE_TRANSFERS), tr("File sharing"), grp));
    notify.push_back(QPair<MainPage*, QAction*>(transfersDialog, action));

    ui->stackPages->add(chatLobbyDialog = new ChatLobbyWidget(ui->stackPages),
                      action = createPageAction(QIcon(IMAGE_CHATLOBBY), tr("Chat Lobbies"), grp));
    notify.push_back(QPair<MainPage*, QAction*>(chatLobbyDialog, action));

    ui->stackPages->add(messagesDialog = new MessagesDialog(ui->stackPages),
                      action = createPageAction(QIcon(IMAGE_MESSAGES), tr("Messages"), grp));
    notify.push_back(QPair<MainPage*, QAction*>(messagesDialog, action));

    ui->stackPages->add(channelFeed = new ChannelFeed(ui->stackPages),
                      action = createPageAction(QIcon(IMAGE_CHANNELS), tr("Channels"), grp));
    notify.push_back(QPair<MainPage*, QAction*>(channelFeed, action));

#ifdef BLOGS
     ui->stackPages->add(blogsFeed = new BlogsDialog(ui->stackPages), createPageAction(QIcon(IMAGE_BLOGS), tr("Blogs"), grp));
#endif
                      
    ui->stackPages->add(forumsDialog = new ForumsDialog(ui->stackPages),
                       action = createPageAction(QIcon(IMAGE_FORUMS), tr("Forums"), grp));
    notify.push_back(QPair<MainPage*, QAction*>(forumsDialog, action));

	 std::cerr << "Looking for interfaces in existing plugins:" << std::endl;
	 for(int i = 0;i<rsPlugins->nbPlugins();++i)
	 {
		 QIcon icon ;

		 if(rsPlugins->plugin(i) != NULL && rsPlugins->plugin(i)->qt_page() != NULL)
		 {
			 if(rsPlugins->plugin(i)->qt_icon() != NULL)
				 icon = *rsPlugins->plugin(i)->qt_icon() ;
			 else
				 icon = QIcon(":images/extension_48.png") ;

			 std::cerr << "  Addign widget page for plugin " << rsPlugins->plugin(i)->getPluginName() << std::endl;
			 MainPage *pluginPage = rsPlugins->plugin(i)->qt_page();
			 QAction *pluginAction = createPageAction(icon, QString::fromUtf8(rsPlugins->plugin(i)->getPluginName().c_str()), grp);
			 ui->stackPages->add(pluginPage, pluginAction);
			 notify.push_back(QPair<MainPage*, QAction*>(pluginPage, pluginAction));
		 }
		 else if(rsPlugins->plugin(i) == NULL)
			 std::cerr << "  No plugin object !" << std::endl;
		 else
			 std::cerr << "  No plugin page !" << std::endl;

	 }

#ifndef RS_RELEASE_VERSION
#ifdef PLUGINMGR
    ui->stackPages->add(pluginsPage = new PluginsPage(ui->stackPages),
                       createPageAction(QIcon(IMAGE_PLUGINS), tr("Plugins"), grp));
#endif
#endif

#ifdef GETSTARTED_GUI
    MainPage *getStartedPage = NULL;

    if (!advancedMode)
    {
        ui->stackPages->add(getStartedPage = new GetStartedDialog(ui->stackPages),
                       createPageAction(QIcon(IMG_HELP), tr("Getting Started"), grp));
    }
#endif

    /* Create the toolbar */
    ui->toolBar->addActions(grp->actions());

    connect(grp, SIGNAL(triggered(QAction *)), ui->stackPages, SLOT(showPage(QAction *)));

#ifdef UNFINISHED
    ui->toolBar->addSeparator();
    addAction(new QAction(QIcon(IMAGE_UNFINISHED), tr("Unfinished"), ui->toolBar), SLOT(showApplWindow()));
#endif

    ui->stackPages->setCurrentIndex(Settings->getLastPageInMainWindow());

    /** StatusBar section ********/
    /* initialize combobox in status bar */
    statusComboBox = new QComboBox(statusBar());
    statusComboBox->setFocusPolicy(Qt::ClickFocus);
    initializeStatusObject(statusComboBox, true);

    QWidget *widget = new QWidget();
    QHBoxLayout *hbox = new QHBoxLayout();
    hbox->setMargin(0);
    hbox->setSpacing(6);
    hbox->addWidget(statusComboBox);
    widget->setLayout(hbox);
    statusBar()->addWidget(widget);

    peerstatus = new PeerStatus();
    statusBar()->addWidget(peerstatus);

    natstatus = new NATStatus();
    statusBar()->addWidget(natstatus);
    
    dhtstatus = new DHTStatus();
    statusBar()->addWidget(dhtstatus);

    hashingstatus = new HashingStatus();
    statusBar()->addPermanentWidget(hashingstatus);

    discstatus = new DiscStatus();
    statusBar()->addPermanentWidget(discstatus);

    ratesstatus = new RatesStatus();
    statusBar()->addPermanentWidget(ratesstatus);

    statusBar()->addPermanentWidget(new OpModeStatus());

    statusBar()->addPermanentWidget(new SoundStatus());
    /** Status Bar end ******/

    /* Creates a tray icon with a context menu and adds it to the system's * notification area. */
    createTrayIcon();

    QList<QPair<MainPage*, QAction*> >::iterator notifyIt;
    for (notifyIt = notify.begin(); notifyIt != notify.end(); ++notifyIt) {
        UserNotify *userNotify = notifyIt->first->getUserNotify(this);
        if (userNotify) {
            userNotify->initialize(ui->toolBar, notifyIt->second);
            connect(userNotify, SIGNAL(countChanged()), this, SLOT(updateTrayCombine()));
            userNotifyList.push_back(userNotify);
        }
    }

    createNotifyIcons();

    /* caclulate friend count */
    updateFriends();
    connect(NotifyQt::getInstance(), SIGNAL(peerStatusChanged(QString,int)), this, SLOT(updateFriends()));
    connect(NotifyQt::getInstance(), SIGNAL(friendsChanged()), this, SLOT(updateFriends()));

    loadOwnStatus();

    /* Set focus to the current page */
    ui->stackPages->currentWidget()->setFocus();

    idle = new Idle();
    idle->start();
    connect(idle, SIGNAL(secondsIdle(int)), this, SLOT(checkAndSetIdle(int)));

    QTimer *timer = new QTimer(this);
    timer->connect(timer, SIGNAL(timeout()), this, SLOT(updateStatus()));
    timer->start(1000);
}
Example #14
0
Window::Window() : plot( QString("Velocity") ), gain(5), count(0) // <-- 'c++ initialisation list' - google it!
{
      //taken purely from online, not our code! 
      //http://qwt.sourceforge.net/class_qwt_analog_clock.html
	//
	QwtAnalogClock *clock = new QwtAnalogClock();
	clock->scaleDraw()->setPenWidth(3);
	clock->setLineWidth(6);
	clock->setFrameShadow(QwtDial::Sunken);
	clock->setTime(); 
      // update the clock every second
      QTimer *timer = new QTimer(clock);
            timer->connect(timer, SIGNAL(timeout()), clock, SLOT(setCurrentTime()));
            timer->start(1000);





	// set up the gain knob
	knob.setValue(gain);

	// use the Qt signals/slots framework to update the gain -
	// every time the knob is moved, the setGain function will be called
	connect( &knob, SIGNAL(valueChanged(double)), SLOT(setGain(double)) );

	// set up the thermometer
	thermo.setFillBrush( QBrush(Qt::red) );
	thermo.setRange(0, 20);
	//thermo.show();


	// set up the initial plot data
	for( int index=0; index<plotDataSize; ++index )
	{
		xData[index] = index;
		yData[index] = gain * sin( M_PI * index/50 );
	}

	// make a plot curve from the data and attach it to the plot
	curve.setSamples(xData, yData, plotDataSize);
	curve.attach(&plot);

	plot.replot();
	plot.show();


	// set up the layout - knob above thermometer
	//vLayout.addWidget(&knob);
	  vLayout.addWidget(clock);
	//vLayout.addWidget(&thermo);


	// plot to the left of knob and thermometer
	hLayout.addLayout(&vLayout);
	hLayout.addWidget(&plot);

	setLayout(&hLayout);

        std::cout << "It is working\n";
        //Below is NOT THE RIGHT WAY TO DO IT, the preferred way is to use 
        // moveToThread() on QObject and then using the Signals and Slots sys-
        //tem. Essentially use the connect function on the QObject instantia-
        //tion to hook up the start() method of the QThread object and the 
        // desired method that does the processing 
        DaThread *ls =new DaThread();

         uint64_t  ls_time=1900;
          int ls_boolean = 1;
          uint64_t  rs_time=1100;
          int rs_boolean = 1;


        ls-> initiate(xData, yData,&ls_time, &ls_boolean, &rs_time,&rs_boolean);
        ls->start();
        std::cout << "It is working\n";

        //start the servos around the time the data starts to be read  

        // ServoThread *leftServo =new ServoThread();
        // leftServo-> initiate(PIN, &ls_time, &ls_boolean);
        // leftServo->start();
 std::cout << "It is working1\n";

         
        // ServoThread *rightServo =new ServoThread();
        // rightServo-> initiate(PIN2, &rs_time, &rs_boolean);
        // rightServo->start();
         
        // ls_boolean =0;
        // rs_boolean =0;
}
void RegularBattleScene::setupGui()
{
    int nslots = data()->numberOfSlots();

    gui.nick.resize(nslots);
    gui.level.resize(nslots);
    gui.gender.resize(nslots);
    gui.bars.resize(nslots);
    gui.status.resize(nslots);

    QVBoxLayout *l=  new QVBoxLayout(this);
    l->setMargin(0);

    /* As anyway the GraphicsZone is a fixed size, it's useless to
       resize that part, might as well let  the chat be resized */
    l->setSizeConstraint(QLayout::SetFixedSize);

    QHBoxLayout *firstLine = new QHBoxLayout();
    l->addLayout(firstLine);

    QHBoxLayout *midzone = new QHBoxLayout();
    l->addLayout(midzone);

    QHBoxLayout *lastLine = new QHBoxLayout();
    l->addLayout(lastLine);

    QVBoxLayout *teamAndName[2];

    for (int i = 0; i < 2; i++) {
        teamAndName[i] = new QVBoxLayout();
        teamAndName[i]->addLayout(createTeamLayout(gui.pokeballs[i]));
        teamAndName[i]->addWidget(gui.trainers[i] = new QLabel(data()->name(i)),0, Qt::AlignRight);
        gui.trainers[i]->setObjectName("TrainerNick");
    }

    firstLine->addWidget(createFullBarLayout(nslots, opponent()));
    firstLine->addLayout(teamAndName[opponent()]);

    gui.zone = new GraphicsZone(data(), gui.theme);

    /* Make the code below more generic? */
    QVBoxLayout *midme = new QVBoxLayout();
    midzone->addLayout(midme);
    midme->addStretch(100);
    gui.timers[myself()] = new QProgressBar();
    gui.timers[myself()]->setObjectName("TimeOut"); //for style sheets
    gui.timers[myself()]->setRange(0,300);
    QLabel *mybox = new QLabel();
    mybox->setObjectName("MyTrainerBox");
    mybox->setFixedSize(82,82);
    mybox->setPixmap(gui.theme->trainerSprite(data()->avatar(myself())));
    midme->addWidget(gui.timers[myself()]);
    midme->addWidget(mybox);

    midzone->addWidget(gui.zone);

    QVBoxLayout *midopp = new QVBoxLayout();
    midzone->addLayout(midopp);
    midopp->addStretch(100);
    gui.timers[opponent()] = new QProgressBar();
    gui.timers[opponent()]->setObjectName("TimeOut"); //for style sheets
    gui.timers[opponent()]->setRange(0,300);
    QLabel *oppbox = new QLabel();
    oppbox->setPixmap(gui.theme->trainerSprite(data()->avatar(opponent())));
    oppbox->setObjectName("OppTrainerBox");
    oppbox->setFixedSize(82,82);
    midopp->addWidget(oppbox);
    midopp->addWidget(gui.timers[opponent()]);

    lastLine->addLayout(teamAndName[myself()]);
    lastLine->addWidget(createFullBarLayout(nslots, myself()));

    QTimer *t = new QTimer (this);
    t->start(200);
    connect(t, SIGNAL(timeout()), SLOT(updateTimers()));
}
Example #16
0
/** ctor.
 * @param controller this can be either the Controller or, if the IP interface
 * is used, an IPClient.
 * @param scene reference to the MasterScene or to a client-side copy of the
 * Scene.
 * @param parent parent Qt widget. If left as \a NULL (default) then the window
 * is startet as an independent main window.
 **/
ssr::QUserInterface::QUserInterface(Publisher& controller, const Scene& scene
        , const std::string& path_to_gui_images
        , const std::string& path_to_scene_menu
        , unsigned int update_frequency
        , QWidget *parent)
  : QOpenGLPlotter(controller, scene, path_to_gui_images, parent),
    _active_scene(0),
    _ignore_mouse_events(false),
    _controlsParent(this)
{
  // set window title
  std::string type = _controller.get_renderer_name();
  if      (type == "wfs")        setWindowTitle("SSR - WFS");
  else if (type == "binaural")   setWindowTitle("SSR - Binaural");
  else if (type == "brs")        setWindowTitle("SSR - BRS");
  else if (type == "vbap")       setWindowTitle("SSR - VBAP");
  else if (type == "aap")        setWindowTitle("SSR - AAP");
  else if (type == "generic")    setWindowTitle("SSR - Generic Renderer");
  else if (type == "ambisonics") setWindowTitle("SSR - Ambisonics");
  else if (type == "") setWindowTitle("SSR");
  else setWindowTitle(type.c_str());

  setWindowIcon(QIcon("images/ssr_logo.png"));

  // make sure that buttons look good
  setMinimumSize(580, 215);

  // setWindowState( Qt::WindowFullScreen );
  // setWindowState( Qt::WindowMaximized );

  // set default size
  setGeometry(200, 100, 900, 800);
  
#ifdef ENABLE_FLOATING_CONTROL_PANEL
  // TODO: use screen size for initial window positions
  //QRect screenSize = QApplication::desktop()->screenGeometry();
  setGeometry(200, 70, 900, 700);
  _controlsParent = new QLabel(this, Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
  _controlsParent->setFixedSize(900, 75);
  _controlsParent->move(200, 780);
  _controlsParent->setWindowTitle("Controls");
  _controlsParent->installEventFilter(this);
  _controlsParent->show();
#else
  // build up frame around OpenGL window
  _frame = new QGUIFrame(this);
#endif

  _source_properties = new QSourceProperties(this);
  connect(_source_properties, SIGNAL(signal_set_source_mute(bool)), this, SLOT(_set_source_mute(bool)));
  connect(_source_properties, SIGNAL(signal_set_source_position_fixed(bool)), this, SLOT(_set_source_position_fixed(bool)));
  connect(_source_properties, SIGNAL(signal_set_source_model(int)), this, SLOT(_set_source_model(int)));
  _source_properties->hide();
  
  // set window icon
  QString path_to_image( _path_to_gui_images.c_str() ) ;
  setWindowIcon(QIcon(QPixmap(path_to_image.append("/ssr_logo_large.png"))));

  // build up buttons etc.
  _file_menu_label = new QFileMenuLabel(_controlsParent);
  //  _file_menu_label->setStyleSheet("border-width: 1px; border-color: black; border-style: solid");
  _file_menu_label->setIndent(5);
  _file_menu_label->setText("File");
  _file_menu_label->show();

  connect(_file_menu_label, SIGNAL(clicked()), this, SLOT(_show_file_menu()));

  _processing_button = new QPushButton(_controlsParent);
  _processing_button->setObjectName("_processing_button");
  _processing_button->setText("on/off");
  _processing_button->setCheckable(true);
  _processing_button->setFocusPolicy(Qt::NoFocus);
  _processing_button->show();

  connect(_processing_button, SIGNAL(clicked()), this, SLOT(_processing_button_pressed()));

  _skip_back_button = new QPushButton(_controlsParent);
  _skip_back_button->setObjectName("_skip_back_button");
  _skip_back_button->setFocusPolicy(Qt::NoFocus);
  _skip_back_button->show();

  connect(_skip_back_button, SIGNAL(clicked()), this, SLOT(_skip_back()));

  _pause_button = new QPushButton(_controlsParent);
  _pause_button->setObjectName("_pause_button");
  _pause_button->setCheckable(true);
  _pause_button->setFocusPolicy(Qt::NoFocus);
  _pause_button->show();

  connect(_pause_button, SIGNAL(clicked()), this, SLOT(_pause_button_pressed()));

  _play_button = new QPushButton(_controlsParent);
  _play_button->setObjectName("_play_button");
  _play_button->setCheckable(true);
  _play_button->setFocusPolicy(Qt::NoFocus);
  _play_button->show();

  connect(_play_button, SIGNAL(clicked()), this, SLOT(_play_button_pressed()));

  _time_line = new QSSRTimeLine(_controlsParent, UPDATEINTERVALFORQTWIDGETS);
  _time_line->show();
  connect(_time_line, SIGNAL(signal_transport_locate(float)), this, SLOT(_transport_locate(float)));

  _cpu_label = new QCPULabel(_controlsParent, UPDATEINTERVALFORQTWIDGETS);
  _cpu_label->show();

  _cpu_label_text_tag = new QLabel(_controlsParent);
  _cpu_label_text_tag->setAlignment(Qt::AlignCenter);
  _cpu_label_text_tag->setText("cpu");

  _zoom_label = new QZoomLabel(_controlsParent);
  _zoom_label->show();

  connect(_zoom_label, SIGNAL(signal_zoom_changed(int)), this, SLOT(_set_zoom(int)));
  connect(this, SIGNAL(signal_zoom_set(int)), _zoom_label, SLOT(update_display(int)));

  _zoom_label_text_tag = new QLabel(_controlsParent);
  _zoom_label_text_tag->setAlignment(Qt::AlignCenter);
  _zoom_label_text_tag->setText("zoom");
  _zoom_label_text_tag->show();

  _volume_slider = new QVolumeSlider(_controlsParent);
  _volume_slider->show();

  connect(_volume_slider, SIGNAL(signal_volume_changed(float)), this, SLOT(_set_master_volume(float)));

  _volume_slider_text_tag = new QLabel(_controlsParent);
  _volume_slider_text_tag->setAlignment(Qt::AlignCenter);
  _volume_slider_text_tag->setText("level");
  _volume_slider_text_tag->show();

  //  open_file_label = new QClickTextLabel( this );
  //  open_file_label->setGeometry( QRect( XREF, YREF, 270, 39 ) );
  //  open_file_label->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)1, 0, 0, open_file_label->sizePolicy().hasHeightForWidth() ) );

  // put labels into correct position
  _file_menu_label->setGeometry(DEFAULTFRAMELEFT, 24, FILEMENUWIDTH, 24);
  _processing_button->setGeometry(DEFAULTFRAMELEFT+FILEMENUWIDTH+
                                 BETWEENBUTTONSPACE, 20,
                                 BUTTONWIDTH, BUTTONHEIGHT);
  _skip_back_button->setGeometry(DEFAULTFRAMELEFT+FILEMENUWIDTH+
                                BETWEENBUTTONSPACE+BUTTONWIDTH+
                                BETWEENBUTTONSPACE, 20,
                                BUTTONWIDTH, BUTTONHEIGHT);
  _pause_button->setGeometry(DEFAULTFRAMELEFT+FILEMENUWIDTH+
                            2*(BETWEENBUTTONSPACE+BUTTONWIDTH)+
                            BETWEENBUTTONSPACE, 20,
                            BUTTONWIDTH, BUTTONHEIGHT);
  _play_button->setGeometry(DEFAULTFRAMELEFT+FILEMENUWIDTH+
                           3*(BETWEENBUTTONSPACE+BUTTONWIDTH)+
                           BETWEENBUTTONSPACE, 20,
                           BUTTONWIDTH, BUTTONHEIGHT);

  // functional inits
  _deselect_all_sources(); // no source selected

#ifdef ENABLE_FLOATING_CONTROL_PANEL
  // scene menu is not shown if floating control panel is used
  VERBOSE("Floating control panel is used, scene menu will not be shown.");
  (void)path_to_scene_menu;
#else
  // create the scene menu if an according config file is present
  _create_scene_menu(path_to_scene_menu);
#endif

  // update screen with update_frequency
  QTimer *timer = new QTimer(this);
  connect(timer, SIGNAL(timeout()), this, SLOT(_update_screen()));
  timer->start(static_cast<unsigned int>(1.0f/static_cast<float>(update_frequency) * 1000.0f));

#ifdef ENABLE_FLOATING_CONTROL_PANEL
  _resizeControls(_controlsParent->width());
#endif
}
Example #17
0
BitcoinGUI::BitcoinGUI(QWidget *parent):
    QMainWindow(parent),
    clientModel(0),
    walletModel(0),
    toolbar(0),
    encryptWalletAction(0),
    changePassphraseAction(0),
    unlockWalletAction(0),
    lockWalletAction(0),
    aboutQtAction(0),
    trayIcon(0),
    notificator(0),
    rpcConsole(0),
    prevBlocks(0),
    nWeight(0)
{
    resize(970, 550); 
    setWindowTitle(tr("SatoshiChain") + " - " + tr("Wallet"));
    qApp->setStyleSheet("QMainWindow { background-image: url(:images/bkg);border:none;font-family:'Open Sans,sans-serif'; } #frame { } QToolBar QLabel { padding-top: 0px;padding-bottom: 0px;spacing: 10px;} QToolBar QLabel:item { padding-top: 0px;padding-bottom: 0px;spacing: 10px;} #spacer { background:rgb(200,200,200);border:none; } #toolbar2 { border:none;width:0px;hight:0px;padding-top:0px;padding-bottom:0px; background: rgb(104,104,104); } #toolbar { border:1px;height:100%;padding-top:20px; background: rgb(200,200,200); text-align: left; color: black;min-width:150px;max-width:150px;} QToolBar QToolButton:hover {background-color:qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,stop: 0 rgb(200,200,200), stop: 1 rgb(104,104,104),stop: 2 rgb(104,104,104));}"
#ifdef Q_OS_MAC
"QToolBar QToolButton { font-family:sans-serif;font-size:12px;padding-left:20px;padding-right:45px;padding-top:5px;padding-bottom:5px; width:100%; color: rgb(104,104,104); text-align: left; background-color: rgb(200,200,200);  }"
#else
"QToolBar QToolButton { font-family:sans-serif;font-size:12px;padding-left:20px;padding-right:150px;padding-top:5px;padding-bottom:5px; width:100%; color: rgb(104,104,104); text-align: left; background-color: rgb(200,200,200);  }"
#endif
"#labelMiningIcon { padding-left:5px;font-family:sans-serif;width:100%;font-size:10px;text-align:center;color:black; } QMenu { background: rgb(200,200,200); color:black; padding-bottom:10px; } QMenu::item { color:black; background-color: transparent; } QMenu::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgb(200,200,200), stop: 1 rgb(200,200,200)); } QMenuBar { background: rgb(200,200,200); color:black; } QMenuBar::item { font-size:12px;padding-bottom:6px;padding-top:6px;padding-left:15px;padding-right:15px;color:black; background-color: transparent; } QMenuBar::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgb(200,200,200), stop: 1 rgb(200,200,200)); }");
#ifndef Q_OS_MAC
    qApp->setWindowIcon(QIcon(":icons/bitcoin"));
    setWindowIcon(QIcon(":icons/bitcoin"));
#else
    setUnifiedTitleAndToolBarOnMac(true);
    QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
    // Accept D&D of URIs
    setAcceptDrops(true);

    // Create actions for the toolbar, menu bar and tray/dock icon
    createActions();

    // Create application menu bar
    createMenuBar();

    // Create the toolbars
    createToolBars();

    // Create the tray icon (or setup the dock icon)
    createTrayIcon();

    // Create tabs
    overviewPage = new OverviewPage();

    //transactionsPage = new QWidget(this);
    //QVBoxLayout *vbox = new QVBoxLayout();
    //transactionView = new TransactionView(this);
    //vbox->addWidget(transactionView);
    //transactionsPage->setLayout(vbox);

    //addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);

    //receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);

    //sendCoinsPage = new SendCoinsDialog(this);

    signVerifyMessageDialog = new SignVerifyMessageDialog(this);

    centralStackedWidget = new QStackedWidget(this);
    centralStackedWidget->addWidget(overviewPage);
    //centralStackedWidget->addWidget(transactionsPage);
    //centralStackedWidget->addWidget(addressBookPage);
    //centralStackedWidget->addWidget(receiveCoinsPage);
    //centralStackedWidget->addWidget(sendCoinsPage);

    QWidget *centralWidget = new QWidget();
    QVBoxLayout *centralLayout = new QVBoxLayout(centralWidget);
#ifndef Q_OS_MAC
    centralLayout->addWidget(appMenuBar);
#endif
    centralLayout->addWidget(centralStackedWidget);

    setCentralWidget(centralWidget);

    // Status bar notification icons

    labelEncryptionIcon = new QLabel();
    labelStakingIcon = new QLabel();
    labelConnectionsIcon = new QLabel();
    labelBlocksIcon = new QLabel();
    //actionConvertIcon = new QAction(QIcon(":/icons/statistics"), tr(""), this);

    if (GetBoolArg("-staking", true))
    {
        QTimer *timerStakingIcon = new QTimer(labelStakingIcon);
        connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingIcon()));
        timerStakingIcon->start(30 * 1000);
        updateStakingIcon();
    }

	// Progress bar and label for blocks download
    progressBarLabel = new QLabel();
    progressBarLabel->setVisible(false);
    progressBar = new QProgressBar();
    addToolBarBreak(Qt::LeftToolBarArea);
    QToolBar *toolbar2 = addToolBar(tr("Tabs toolbar"));
    addToolBar(Qt::LeftToolBarArea,toolbar2);
    toolbar2->setOrientation(Qt::Vertical);
    toolbar2->setMovable( false );
    toolbar2->setObjectName("toolbar2");
    toolbar2->setFixedWidth(28);
    toolbar2->setIconSize(QSize(28,28));
	//toolbar2->addAction(actionConvertIcon);
    toolbar2->addWidget(labelEncryptionIcon);
    toolbar2->addWidget(labelStakingIcon);
    toolbar2->addWidget(labelConnectionsIcon);
    toolbar2->addWidget(labelBlocksIcon);
    	
	syncIconMovie = new QMovie(":/movies/update_spinner", "gif", this);

    // Clicking on a transaction on the overview page simply sends you to transaction history page
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
    //connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));

    // Double-clicking on a transaction on the transaction history page shows details
    //connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));

    rpcConsole = new RPCConsole(this);
    connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
    // prevents an oben debug window from becoming stuck/unusable on client shutdown
    connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));

    // Clicking on "Verify Message" in the address book sends you to the verify message tab
    //connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
    // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
    //connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));

    gotoOverviewPage();
}
Example #18
0
Window::Window()
{
    glWidgets[0][0] = new GLWidget(this, 0, 0);
    glWidgets[0][1] = new GLWidget(this, 1, 0);
    glWidgets[0][2] = new GLWidget(this, 2, 0);
    glWidgets[0][3] = new GLWidget(this, 3, 0);

    glWidgets[1][0] = new GLWidget(this, 4, 0);
    glWidgets[1][1] = new GLWidget(this, 5, 0);
    glWidgets[1][2] = new GLWidget(this, 6, 0);
    glWidgets[1][3] = new GLWidget(this, 7, 0);

    glWidgets[2][0] = new GLWidget(this, 8, 0);
    glWidgets[2][1] = new GLWidget(this, 9, 0);
    glWidgets[2][2] = new GLWidget(this, 10, 0);
    glWidgets[2][3] = new GLWidget(this, 11, 0);

    glWidgets[3][0] = new GLWidget(this, 12, 0);
    glWidgets[3][1] = new GLWidget(this, 13, 0);
    glWidgets[3][2] = new GLWidget(this, 14, 0);
    glWidgets[3][3] = new GLWidget(this, 15, 0);

    mainLayout = new QGridLayout;
    mouseOn = mouse[0] = mouse[1] = false;

    for (int i = 0; i < NumRows; ++i) {
        for (int j = 0; j < NumColumns; ++j) {
            mainLayout->addWidget(glWidgets[i][j], i, j);

            connect(glWidgets[i][j], SIGNAL(clicked()),
                    this, SLOT(setCurrentGlWidget()));
        }
    }
    setLayout(mainLayout);

    currentGlWidget = glWidgets[0][0];

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(rotateOneStep()));
    timer->start(20);

    setWindowTitle(tr("Sleep Dream Games"));

    shortcut(QKeySequence(Qt::Key_Escape), SLOT(keyHandleWM()));
    shortcut(QKeySequence(Qt::Key_Tab), SLOT(keyHandleWP()));

    shortcut(QKeySequence(Qt::Key_Space), SLOT(keyHandleXM()));
    shortcut(QKeySequence(Qt::Key_Enter), SLOT(keyHandleXP()));

    shortcut(QKeySequence(Qt::Key_Up), SLOT(keyHandleYM()));
    shortcut(QKeySequence(Qt::Key_Down), SLOT(keyHandleYP()));

    shortcut(QKeySequence(Qt::Key_Left), SLOT(keyHandleZM()));
    shortcut(QKeySequence(Qt::Key_Right), SLOT(keyHandleZP()));

    shortcut(QKeySequence(Qt::Key_Delete), SLOT(mouseFlip()));

    j = new Joystick();

    connect(j,SIGNAL(keyHandleWM()), this , SLOT(keyHandleWM()));
    connect(j,SIGNAL(keyHandleWP()), this , SLOT(keyHandleWP()));
    connect(j,SIGNAL(keyHandleXM()), this , SLOT(keyHandleXM()));
    connect(j,SIGNAL(keyHandleXP()), this , SLOT(keyHandleXP()));

    connect(j,SIGNAL(keyHandleYM()), this , SLOT(keyHandleYM()));
    connect(j,SIGNAL(keyHandleYP()), this , SLOT(keyHandleYP()));
    connect(j,SIGNAL(keyHandleZM()), this , SLOT(keyHandleZM()));
    connect(j,SIGNAL(keyHandleZP()), this , SLOT(keyHandleZP()));

    QTimer *hot = new QTimer(this);
    connect(hot, SIGNAL(timeout()), this, SLOT(hotPlug()));
    hot->start(1000);
}
Example #19
0
FacebookWidget::FacebookWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FacebookWidget)
{
    systemTrayIcon = new QSystemTrayIcon(QIcon(":/res/logo/Facebook-icon.png"));
    systemTrayMenu = new QMenu();
    notificationAction = new QAction(tr("Notifications"),this);
    friendRequestAction = new QAction(tr("Friend requests"),this);
    messagesAction = new QAction(tr("Messages"),this);
    quitAction = new QAction(tr("Quit"),this);
    windowVisibilityToggleAction = new QAction(tr("Hide"),this);
    aboutWindow = new AboutWindow();
    windowVisible = true;
    systemTrayMenu->addAction(windowVisibilityToggleAction);
    systemTrayMenu->addSeparator();
    systemTrayMenu->addAction(friendRequestAction);
    systemTrayMenu->addAction(messagesAction);
    systemTrayMenu->addAction(notificationAction);
    systemTrayMenu->addSeparator();
    systemTrayMenu->addAction(quitAction);
    systemTrayIcon->setContextMenu(systemTrayMenu);
    systemTrayIcon->show();
    themeSelectorWidget = new ThemeSelectorWidget();
    pressed = false;
    ui->setupUi(this);
    webView = new QWebView();
    ui->mainLayout->addWidget(webView);
    webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    this->setLayout(ui->mainLayout);
    connect(webView->page()->networkAccessManager(),SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),this,SLOT(sslErrorHandler(QNetworkReply*,QList<QSslError>)));
    connect(webView,SIGNAL(loadProgress(int)),ui->progressBar,SLOT(setValue(int)));
    connect(webView,SIGNAL(loadFinished(bool)),ui->progressBar,SLOT(reset()));
    connect(ui->backButton,SIGNAL(clicked()),webView,SLOT(back()));
    connect(ui->forwardButton,SIGNAL(clicked()),webView,SLOT(forward()));
    connect(ui->closeButton,SIGNAL(clicked()),this,SLOT(toggleWindowVisibility()));
    connect(quitAction,SIGNAL(triggered()),this,SLOT(quitActionTriggered()));
#ifndef Q_OS_MAC
    connect(systemTrayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(onSystemTrayClicked(QSystemTrayIcon::ActivationReason)));
#endif
    connect(friendRequestAction,SIGNAL(triggered()),this,SLOT(friendRequestActionTriggered()));
    connect(messagesAction,SIGNAL(triggered()),this,SLOT(messagesActionTriggered()));
    connect(notificationAction,SIGNAL(triggered()),this,SLOT(notificationActionTriggered()));
    connect(windowVisibilityToggleAction,SIGNAL(triggered()),this,SLOT(toggleWindowVisibility()));
    connect(webView->page(),SIGNAL(linkClicked(QUrl)),this,SLOT(delegateLink(QUrl)));
    connect(ui->aboutButton,SIGNAL(clicked()),aboutWindow,SLOT(show()));
    connect(ui->maximizeButton,SIGNAL(clicked()),this,SLOT(fullscreenToggle()));
    connect(ui->themeButton,SIGNAL(clicked()),themeSelectorWidget,SLOT(show()));
    connect(themeSelectorWidget,SIGNAL(applyTheme(QStringList)),this,SLOT(setTheme(QStringList)));
    connect(themeSelectorWidget,SIGNAL(useDefaultTheme()),this,SLOT(useDefaultTheme()));
    windowSizes << QRect(10,10,640,480);
    windowSizes << QRect(10,10,800,480);
    windowSizes << QRect(10,10,1030,600);
    windowSizes << desktopDetails.availableGeometry();
    windowSizeIndex = 2;
    setGeometry(windowSizes.at(2));
    setWindowFlags(Qt::FramelessWindowHint);
    themeRefreshTimer = new QTimer();
    QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled,true);
    QDir configDir = QDir::home();
    configDir.mkpath(".config/Socializer");
    configDir.mkpath(".config/Socializer/LocalStorage/");
    configDir.mkpath(".config/Socializer/OfflineStorage/");
    configDir.mkpath(".config/Socializer/IconDatabase/");
    configDir.mkpath(".config/Socializer/OfflineWebApplicationCache/");
    configDir.cd(".config/Socializer");
    configDir.cd("OfflineStorage");
    QWebSettings::setOfflineStoragePath(configDir.absolutePath());
    configDir.cdUp();
    configDir.cd("IconDatabase");
    QWebSettings::setIconDatabasePath(configDir.absolutePath());
    configDir.cdUp();
    configDir.cd("OfflineWebApplicationCache");
    QWebSettings::setOfflineWebApplicationCachePath(configDir.absolutePath());
    configDir.cdUp();
    QWebSettings::setMaximumPagesInCache(100);
    QWebSettings::globalSettings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled,true);
    QWebSettings::globalSettings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled,true);
    QWebSettings::globalSettings()->setAttribute(QWebSettings::LocalStorageEnabled,true);
    cookieJar = new CookieJar;
    webView->page()->networkAccessManager()->setCookieJar(cookieJar);
    cookieJar->load();
    configDir.cd("LocalStorage");
    webView->page()->settings()->setLocalStoragePath(configDir.absolutePath());
    webView->page()->settings()->setAttribute(QWebSettings::LocalStorageEnabled,true);
    configDir.cdUp();

    QTimer *refreshTimer = new QTimer();
    refreshTimer->setInterval(5000);
    connect(refreshTimer,SIGNAL(timeout()),this,SLOT(getNewStatus()));
    refreshTimer->start();
    fullscreen = false;
    loadApplicationState();
}
Example #20
0
GreenTower::GreenTower(QGraphicsItem *parent){
    // connect a timer to aquire_target
    QTimer * timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(aquire_target()));
    timer->start(1000);
}
Example #21
0
AssignmentClient::AssignmentClient(int &argc, char **argv) :
    QCoreApplication(argc, argv),
    _currentAssignment(NULL)
{
    setOrganizationName("High Fidelity");
    setOrganizationDomain("highfidelity.io");
    setApplicationName("assignment-client");
    QSettings::setDefaultFormat(QSettings::IniFormat);
    
    // register meta type is required for queued invoke method on Assignment subclasses
    
    // set the logging target to the the CHILD_TARGET_NAME
    Logging::setTargetName(ASSIGNMENT_CLIENT_TARGET_NAME);
    
    const char ASSIGNMENT_TYPE_OVVERIDE_OPTION[] = "-t";
    const char* assignmentTypeString = getCmdOption(argc, (const char**)argv, ASSIGNMENT_TYPE_OVVERIDE_OPTION);
    
    Assignment::Type requestAssignmentType = Assignment::AllTypes;
    
    if (assignmentTypeString) {
        // the user is asking to only be assigned to a particular type of assignment
        // so set that as the ::overridenAssignmentType to be used in requests
        requestAssignmentType = (Assignment::Type) atoi(assignmentTypeString);
    }
    
    const char ASSIGNMENT_POOL_OPTION[] = "--pool";
    const char* requestAssignmentPool = getCmdOption(argc, (const char**) argv, ASSIGNMENT_POOL_OPTION);
    
    
    // setup our _requestAssignment member variable from the passed arguments
    _requestAssignment = Assignment(Assignment::RequestCommand, requestAssignmentType, requestAssignmentPool);
    
    // create a NodeList as an unassigned client
    NodeList* nodeList = NodeList::createInstance(NodeType::Unassigned);
    
    const char CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION[] = "-a";
    const char CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION[] = "-p";
    
    // grab the overriden assignment-server hostname from argv, if it exists
    const char* customAssignmentServerHostname = getCmdOption(argc, (const char**)argv, CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION);
    const char* customAssignmentServerPortString = getCmdOption(argc,(const char**)argv, CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION);
    
    HifiSockAddr customAssignmentSocket;
    
    if (customAssignmentServerHostname || customAssignmentServerPortString) {
        
        // set the custom port or default if it wasn't passed
        unsigned short assignmentServerPort = customAssignmentServerPortString
        ? atoi(customAssignmentServerPortString) : DEFAULT_DOMAIN_SERVER_PORT;
        
        // set the custom hostname or default if it wasn't passed
        if (!customAssignmentServerHostname) {
            customAssignmentServerHostname = DEFAULT_ASSIGNMENT_SERVER_HOSTNAME;
        }
        
        customAssignmentSocket = HifiSockAddr(customAssignmentServerHostname, assignmentServerPort);
    }
    
    // set the custom assignment socket if we have it
    if (!customAssignmentSocket.isNull()) {
        nodeList->setAssignmentServerSocket(customAssignmentSocket);
    }
    
    // call a timer function every ASSIGNMENT_REQUEST_INTERVAL_MSECS to ask for assignment, if required
    qDebug() << "Waiting for assignment -" << _requestAssignment;
    
    QTimer* timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), SLOT(sendAssignmentRequest()));
    timer->start(ASSIGNMENT_REQUEST_INTERVAL_MSECS);
    
    // connect our readPendingDatagrams method to the readyRead() signal of the socket
    connect(&nodeList->getNodeSocket(), &QUdpSocket::readyRead, this, &AssignmentClient::readPendingDatagrams);
    
    // connections to AccountManager for authentication
    connect(&AccountManager::getInstance(), &AccountManager::authRequired,
            this, &AssignmentClient::handleAuthenticationRequest);
}
Example #22
0
int main(int argc, char *argv[])
{ 
#ifdef WINDOWS_SYS
	// The current directory of the application is changed when using the native dialog on Windows
	// This is a quick fix until libretroshare is using a absolute path in the portable Version
	extern bool Q_GUI_EXPORT qt_use_native_dialogs;
	qt_use_native_dialogs = false;

	{
		/* Set the current directory to the application dir,
		   because the start dir with autostart from the registry run key is not the exe dir */
		QApplication app(argc, argv);
		QDir::setCurrent(QCoreApplication::applicationDirPath());
	}
#endif

	QStringList args = char_array_to_stringlist(argv+1, argc-1);

	Q_INIT_RESOURCE(images);

	rsiface = NULL;

	NotifyQt *notify = NotifyQt::Create();
	createRsIface(*notify);
	createRsControl(*rsiface, *notify);

	/* RetroShare Core Objects */
	RsInit::InitRsConfig();
	int initResult = RsInit::InitRetroShare(argc, argv);

	if(initResult == RS_INIT_NO_KEYRING)	// happens when we already have accounts, but no pgp key. This is when switching to the openpgp-sdk version.
	{
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		/* Translate into the desired language */
		LanguageSupport::translate(LanguageSupport::defaultLanguageCode());

		QMessageBox msgBox;
		msgBox.setText(QObject::tr("This version of RetroShare is using OpenPGP-SDK. As a side effect, it's not using the system shared PGP keyring, but has it's own keyring shared by all RetroShare instances. <br><br>You do not appear to have such a keyring, although PGP keys are mentioned by existing RetroShare accounts, probably because you just changed to this new version of the software."));
		msgBox.setInformativeText(QObject::tr("Choose between:<br><ul><li><b>Ok</b> to copy the existing keyring from gnupg (safest bet), or </li><li><b>Close without saving</b> to start fresh with an empty keyring (you will be asked to create a new PGP key to work with RetroShare, or import a previously saved pgp keypair). </li><li><b>Cancel</b> to quit and forge a keyring by yourself (needs some PGP skills)</li></ul>"));
		msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Discard | QMessageBox::Cancel);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.setWindowIcon(QIcon(":/images/rstray3.png"));

		int ret = msgBox.exec();

		if(ret == QMessageBox::Cancel)
			return 0 ;
		if(ret == QMessageBox::Ok)
		{
			if(!RsInit::copyGnuPGKeyrings())
				return 0 ; 

			initResult = RsInit::InitRetroShare(argc, argv);

			displayWarningAboutDSAKeys() ;

		}
		else
			initResult = RS_INIT_OK ;
	}

	if (initResult < 0) {
		/* Error occured */
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		/* Translate into the desired language */
		LanguageSupport::translate(LanguageSupport::defaultLanguageCode());

		displayWarningAboutDSAKeys();

		QMessageBox mb(QMessageBox::Critical, QObject::tr("RetroShare"), "", QMessageBox::Ok);
		mb.setWindowIcon(QIcon(":/images/rstray3.png"));

		switch (initResult) 
		{
			case RS_INIT_AUTH_FAILED:
				std::cerr << "RsInit::InitRetroShare AuthGPG::InitAuth failed" << std::endl;
				mb.setText(QObject::tr("Initialization failed. Wrong or missing installation of PGP."));
				break;
			default:
				/* Unexpected return code */
				std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
				mb.setText(QObject::tr("An unexpected error occurred. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
				break;
		}
		mb.exec();
		return 1;
	}

	/* create global settings object
	   path maybe wrong, when no profile exist
	   in this case it can be use only for default values */
	RshareSettings::Create ();

	/* Setup The GUI Stuff */
	Rshare rshare(args, argc, argv, 
		QString::fromUtf8(RsInit::RsConfigDirectory().c_str()));

	std::string url = RsInit::getRetroShareLink();
	if (!url.empty()) {
		/* start with RetroShare link */
		EventReceiver eventReceiver;
		if (eventReceiver.sendRetroShareLink(QString::fromStdString(url))) {
			return 0;
		}

		/* Start RetroShare */
	}

	QSplashScreen splashScreen(QPixmap(":/images/splash.png")/* , Qt::WindowStaysOnTopHint*/);

	switch (initResult) {
	case RS_INIT_OK:
		{
			/* Login Dialog */
			/* check for existing Certificate */
			bool genCert = false;
			std::list<std::string> accountIds;
			if (RsInit::getAccountIds(accountIds) && (accountIds.size() > 0))
			{
				StartDialog sd;
				if (sd.exec() == QDialog::Rejected) {
					return 1;
				}

				/* if we're logged in */
				genCert = sd.requestedNewCert();
			}
			else
			{
				genCert = true;
			}

			if (genCert)
			{
				GenCertDialog gd(false);
				if (gd.exec () == QDialog::Rejected) {
					return 1;
				}
			}

			splashScreen.show();
		}
		break;
	case RS_INIT_HAVE_ACCOUNT:
		{
			splashScreen.show();
			splashScreen.showMessage(rshare.translate("SplashScreen", "Load profile"), Qt::AlignHCenter | Qt::AlignBottom);

			std::string preferredId;
			RsInit::getPreferedAccountId(preferredId);

			// true: note auto-login is active
			Rshare::loadCertificate(preferredId, true);
		}
		break;
	default:
		/* Unexpected return code */
		std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
		QMessageBox::warning(0, QObject::tr("RetroShare"), QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
		return 1;
	}

	/* recreate global settings object, now with correct path */
	RshareSettings::Create(true);
	Rshare::resetLanguageAndStyle();

	SoundManager::create();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Load configuration"), Qt::AlignHCenter | Qt::AlignBottom);

	/* stop Retroshare if startup fails */
	if (!rsicontrol->StartupRetroShare())
	{
		std::cerr << "libretroshare failed to startup!" << std::endl;
		return 1;
	}


	Rshare::initPlugins();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Create interface"), Qt::AlignHCenter | Qt::AlignBottom);

	RsharePeerSettings::Create();

	Emoticons::load();

	if (Settings->value(QString::fromUtf8("FirstRun"), true).toBool()) {
		splashScreen.hide();

		Settings->setValue(QString::fromUtf8("FirstRun"), false);

#ifdef __APPLE__
		/* For OSX, we set the default to "cleanlooks", as the AQUA style hides some input boxes 
		 * only on the first run - as the user might want to change it ;)
		 */
		QString osx_style("cleanlooks");
		Rshare::setStyle(osx_style);
		Settings->setInterfaceStyle(osx_style);
#endif

// This is now disabled - as it doesn't add very much.
// Need to make sure that defaults are sensible!
#ifdef ENABLE_QUICKSTART_WIZARD
		QuickStartWizard qstartWizard;
		qstartWizard.exec();
#endif

	}

	MainWindow *w = MainWindow::Create ();
	splashScreen.finish(w);

	EventReceiver *eventReceiver = NULL;
	if (Settings->getRetroShareProtocol()) {
		/* Create event receiver */
		eventReceiver = new EventReceiver;
		if (eventReceiver->start()) {
			QObject::connect(eventReceiver, SIGNAL(linkReceived(const QUrl&)), w, SLOT(retroshareLinkActivated(const QUrl&)));
		}
	}

	if (!url.empty()) {
		/* Now use link from the command line, because no RetroShare was running */
		RetroShareLink link(QString::fromStdString(url));
		if (link.valid()) {
			w->retroshareLinkActivated(link.toUrl());
		}
	}

	// I'm using a signal to transfer the hashing info to the mainwindow, because Qt schedules signals properly to
	// avoid clashes between infos from threads.
	//

	qRegisterMetaType<FileDetail>("FileDetail") ;

	std::cerr << "connecting signals and slots" << std::endl ;
	QObject::connect(notify,SIGNAL(gotTurtleSearchResult(qulonglong,FileDetail)),w->transfersDialog->searchDialog	,SLOT(updateFiles(qulonglong,FileDetail))) ;
	QObject::connect(notify,SIGNAL(deferredSignatureHandlingRequested()),notify,SLOT(handleSignatureEvent()),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(chatLobbyTimeShift(int)),notify,SLOT(handleChatLobbyTimeShift(int)),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(diskFull(int,int))						,w                   		,SLOT(displayDiskSpaceWarning(int,int))) ;
	QObject::connect(notify,SIGNAL(filesPreModChanged(bool))          ,w->transfersDialog->localSharedFiles			,SLOT(preModDirectories(bool)          )) ;
	QObject::connect(notify,SIGNAL(filesPreModChanged(bool))          ,w->transfersDialog->remoteSharedFiles		,SLOT(preModDirectories(bool)          )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w->transfersDialog->localSharedFiles			,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w->transfersDialog->remoteSharedFiles		,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w                         ,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(transfersChanged())                ,w->transfersDialog  		,SLOT(insertTransfers()                )) ;
	QObject::connect(notify,SIGNAL(publicChatChanged(int))            ,w->friendsDialog      		,SLOT(publicChatChanged(int)           ));
	QObject::connect(notify,SIGNAL(neighboursChanged())               ,w->friendsDialog->networkDialog    		,SLOT(securedUpdateDisplay())) ;
	QObject::connect(notify,SIGNAL(messagesChanged())                 ,w->messagesDialog   		,SLOT(insertMessages()                 )) ;
	QObject::connect(notify,SIGNAL(messagesTagsChanged())             ,w->messagesDialog   		,SLOT(messagesTagsChanged()            )) ;

	QObject::connect(notify,SIGNAL(chatStatusChanged(const QString&,const QString&,bool)),w->friendsDialog,SLOT(updatePeerStatusString(const QString&,const QString&,bool)));
	QObject::connect(notify,SIGNAL(ownStatusMessageChanged()),w->friendsDialog,SLOT(loadmypersonalstatus()));

	QObject::connect(notify,SIGNAL(logInfoChanged(const QString&))		,w->friendsDialog->networkDialog,SLOT(setLogInfo(QString))) ;
	QObject::connect(notify,SIGNAL(discInfoChanged())						,w->friendsDialog->networkView,SLOT(update()),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(errorOccurred(int,int,const QString&)),w,SLOT(displayErrorMessage(int,int,const QString&))) ;

	w->installGroupChatNotifier();

	/* only show window, if not startMinimized */
	if (RsInit::getStartMinimised() || Settings->getStartMinimized())
	{
		splashScreen.close();
	} else {
		w->show();
	}

	/* Startup a Timer to keep the gui's updated */
	QTimer *timer = new QTimer(w);
	timer -> connect(timer, SIGNAL(timeout()), notify, SLOT(UpdateGUI()));
	timer->start(1000);

	notify->enable() ;	// enable notification system after GUI creation, to avoid data races in Qt.

	/* dive into the endless loop */
	int ti = rshare.exec();
	delete w ;

	if (eventReceiver) {
		/* Destroy event receiver */
		delete eventReceiver;
		eventReceiver = NULL;
	}

	/* cleanup */
	ChatDialog::cleanupChat();

	rsicontrol->rsGlobalShutDown();

	delete(soundManager);
	soundManager = NULL;

	Settings->sync();
	delete(Settings);

	return ti ;
}
Example #23
0
DockPlugin::DockPlugin(unsigned base, const char *config)
        : Plugin(base)
{
    load_data(dockData, &data, config);
    dock = NULL;
    inactiveTime = 0;
    m_popup = NULL;

    Event ePlugin(EventGetPluginInfo, (void*)"_core");
    pluginInfo *info = (pluginInfo*)(ePlugin.process());
    core = static_cast<CorePlugin*>(info->plugin);

    DockMenu     = registerType();
    CmdTitle	 = registerType();
    CmdToggle    = registerType();
    CmdCustomize = registerType();

    Event eMenu(EventMenuCreate, (void*)DockMenu);
    eMenu.process();

    Command cmd;
    cmd->id          = CmdTitle;
    cmd->text        = I18N_NOOP("SIM");
    cmd->icon        = "ICQ";
    cmd->menu_id     = DockMenu;
    cmd->menu_grp    = 0x1000;
    cmd->flags       = COMMAND_TITLE;

    Event eCmd(EventCommandCreate, cmd);
    eCmd.process();

    cmd->id          = CmdCustomize;
    cmd->text        = I18N_NOOP("Customize menu");
    cmd->icon        = "configure";
    cmd->menu_id     = DockMenu;
    cmd->menu_grp    = 0x10000;
    cmd->accel       = 0;
    cmd->flags       = COMMAND_DEFAULT;

    eCmd.process();

    Event eDef(EventGetMenuDef, (void*)MenuMain);
    CommandsDef *def = (CommandsDef*)(eDef.process());
    if (def){
        CommandsList list(*def, true);
        CommandDef *s;
        while ((s = ++list) != NULL){
            if (s->id == 0)
                continue;
            cmd = *s;
            if (!(cmd->flags & COMMAND_IMPORTANT))
                cmd->menu_grp = 0;
            cmd->bar_id  = 0;
            cmd->menu_id = DockMenu;
            eCmd.process();
        }
    }

    cmd->id          = CmdToggle;
    cmd->text        = I18N_NOOP("Toggle main window");
    cmd->icon        = NULL;
    cmd->menu_id     = MenuMain;
    cmd->menu_grp    = 0;
    cmd->accel		 = "Ctrl+Shift+A";
    cmd->flags		 = COMMAND_CHECK_STATE | COMMAND_GLOBAL_ACCEL | COMMAND_IMPORTANT;
    eCmd.process();

    init();

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(timer()));
    timer->start(2000);
}
Example #24
0
/**This is a public slot that adds all of the necessary components for game play to the scene.
 * @brief Game::game_begin() adds objects of classes Ash, Pikachu, Snorlax, Muk,
 *        Beedrill, Tile, Score, and Health to the scene and then begins the game.
 */
void Game::game_begin() {
    // play game music
    game_music->play();

    // stop menu music
    menu_music->stop();

    // close the main manu
    main_widget->close();

    //if retrying game again, clear away the game over window
    scene->clearFocus();
    scene->clear();

    // set the level
    if (hard->isChecked()) isHard = true;

    // Create an Ash object player
    player_ash = new Ash;
    // make the player focusable and set it to be the current focus
    player_ash->setFlag(QGraphicsItem::ItemIsFocusable);
    player_ash->setFocus();
    // add the player to the scene
    scene->addItem(player_ash);

    // Create five Pikachu objects
    pikachu1 = new Pikachu;
    if (!isHard) pikachu1->setPos(50,240);
    else pikachu1->setPos(100,70);
    pikachu1->setSound(QUrl("qrc:/sounds/sound/pikachuuu.wav"));
    scene->addItem(pikachu1);

    pikachu2 = new Pikachu;
    if (!isHard) pikachu2->setPos(250,412);
    else pikachu2->setPos(180,412);
    pikachu2->setSound(QUrl("qrc:/sounds/sound/pika.wav"));
    scene->addItem(pikachu2);

    pikachu3 = new Pikachu;
    pikachu3->setPos(543,45);
    pikachu3->setSound(QUrl("qrc:/sounds/sound/pikachu.wav"));
    scene->addItem(pikachu3);

    pikachu4 = new Pikachu;
    if (!isHard) pikachu4->setPos(610,323);
    else pikachu4->setPos(500,350);
    pikachu4->setSound(QUrl("qrc:/sounds/sound/pikapi.wav"));
    scene->addItem(pikachu4);

    pikachu5 = new Pikachu;
    if (!isHard) pikachu5->setPos(1150,410);
    else pikachu5->setPos(1100,410);
    pikachu5->setSound(QUrl("qrc:/sounds/sound/pika.wav"));
    scene->addItem(pikachu5);

    // Create a snorlax
    snorlax = new Snorlax;
    scene->addItem(snorlax);

    // Create a button in hard mode
    if (isHard) {
        Button* button = new Button;
        scene->addItem(button);
    }

    // Create two muk objects
    muk1 = new Muk;
    muk1->setAsh(player_ash);
    muk1->setPos(100,412);
    if(isHard) muk1->start_movement();
    scene->addItem(muk1);

    muk2 = new Muk;
    muk2->setAsh(player_ash);
    muk2->setPos(740,130);
    if (isHard) muk2->start_movement();
    scene->addItem(muk2);

    if (isHard) {
        Muk* muk3 = new Muk;
        muk3->setAsh(player_ash);
        muk3->setPos(480,412);
        muk3->start_movement();
        scene->addItem(muk3);
    }

    // Create two beedril objects
    beedril1 = new Beedril;
    beedril1->setAsh(player_ash);
    beedril1->setPos(480,250);
    beedril1->set_vertical();
    beedril1->start_movement();
    scene->addItem(beedril1);

    beedril2 = new Beedril;
    beedril2->setAsh(player_ash);
    beedril2->setPos(1000,400);
    beedril2->start_movement();
    scene->addItem(beedril2);

    if (isHard) {
        Beedril* beedril3 = new Beedril;
        beedril3->setAsh(player_ash);
        beedril3->setPos(100,115);
        beedril3->start_movement();
        scene->addItem(beedril3);
    }

    // set up a score box
    score1 = new Score;
    score1->setGeometry(1000,0,40,40);
    scene->addWidget(score1);

    score2 = new Score;
    score2->setGeometry(1040,0,40,40);
    scene->addWidget(score2);

    score3 = new Score;
    score3->setGeometry(1080,0,40,40);
    scene->addWidget(score3);

    score4 = new Score;
    score4->setGeometry(1120,0,40,40);
    scene->addWidget(score4);

    score5 = new Score;
    score5->setGeometry(1160,0,40,40);
    scene->addWidget(score5);

    // set up health points
    health1 = new Health;
    health1->setGeometry(0,0,40,40);
    scene->addWidget(health1);

    health2 = new Health;
    health2->setGeometry(40,0,40,40);
    scene->addWidget(health2);

    health3 = new Health;
    health3->setGeometry(80,0,40,40);
    scene->addWidget(health3);

    // set up tiles
    tile1 = new Tile;
    tile1->setPos(0,465);
    scene->addItem(tile1);

    tile2 = new Tile;
    tile2->setPos(tile1->boundingRect().width()*0.2,465);
    scene->addItem(tile2);

    tile3 = new Tile;
    tile3->setPos(tile1->boundingRect().width()*0.4,465);
    scene->addItem(tile3);

    tile4 = new Tile;
    tile4->setPos(tile1->boundingRect().width()*0.6,465);
    scene->addItem(tile4);

    tile5 = new Tile;
    tile5->setPos(tile1->boundingRect().width()*0.8,465);
    scene->addItem(tile5);

    tile6 = new Tile;
    tile6->setPos(tile1->boundingRect().width(),465);
    scene->addItem(tile6);

    tile7 = new Tile;
    tile7->setPos(tile1->boundingRect().width()*1.2,465);
    scene->addItem(tile7);

    tile8 = new Tile;
    tile8->setPos(tile1->boundingRect().width()*1.4,465);
    scene->addItem(tile8);

    tile9 = new Tile;
    tile9->setPos(tile1->boundingRect().width()*1.6,465);
    scene->addItem(tile9);

    tile10 = new Tile;
    tile10->setPos(tile1->boundingRect().width()*1.8,465);
    scene->addItem(tile10);

    tile11 = new Tile;
    tile11->setPos(300,372);
    scene->addItem(tile11);

    tile12 = new Tile;
    tile12->setPos(50,290);
    scene->addItem(tile12);

    tile13 = new Tile;
    tile13->setPos(600,372);
    scene->addItem(tile13);

    tile14 = new Tile;
    tile14->setPos(600+tile1->boundingRect().width()*0.2,372);
    scene->addItem(tile14);

    tile15 = new Tile;
    tile15->setPos(1000,250);
    scene->addItem(tile15);

    tile16 = new Tile;
    tile16->setPos(700,180);
    scene->addItem(tile16);

    tile17 = new Tile;
    tile17->setPos(500,100);
    scene->addItem(tile17);

    //show the scene
    show();

    QTimer* statustimer = new QTimer(this);
    connect(statustimer, SIGNAL(timeout()), this, SLOT(update_score()));
    connect(statustimer,SIGNAL(timeout()),this,SLOT(update_health()));
    statustimer->start(100);
}
Example #25
0
bool FlowWidget::eventFilter(QObject *Object, QEvent *event)
{   
	QMouseEvent* e = static_cast<QMouseEvent*>(event);//鼠标事件
	static QPoint clickInipos;////记录鼠标点击的初始坐标,用来移动
	static bool leftMove = false;//判断是否左键移动
	QTimer mouseTimer;//鼠标按压时间计时器
	bool isSingleClick = true;//判断是否是单击
	int selNum = -1;//选择的模块号
	int numEnd = -1;//释放鼠标后找到的箭头结束模块号
	static int startNum = -1;//箭头开始的模块号,为保持记忆性,用静态变量
	//鼠标双击
	if (event->type() == QEvent::MouseButtonDblClick)
	{
		if (mouseTimer.isActive())
			mouseTimer.stop();//双击则停止鼠标计时器,判定为双击,不执行单击函数
		isSingleClick = false;

		//判断那个模块被鼠标双击
		selNum = findNum(e, flowIcon);
		num = selNum + 1;//num暂时先留着,传一下参,+1是去掉main模块
		if (selNum == -1)
		{
			qDebug() << "没有找到双击的模块" << endl;
		}
		else
		{
			if (flowIcon[selNum]->rect().contains(e->pos()) &&
				(e->button() == Qt::LeftButton)) //左键双击模块
			{
				Dialog *dialog = new Dialog(this);
				connect(dialog, SIGNAL(triggerSignal()), this->parent(), SLOT(changeCode()));//传信号给FFCP修正编辑框代码
				dialog->show();
			}
			if (flowIcon[selNum]->rect().contains(e->pos()) &&
				(e->button() == Qt::RightButton)) //右键双击模块
			{
				//销掉模块图
				flowIcon[selNum]->close();
				flowIcon.remove(selNum);

				//清除模块对应的线
				int selLineNum = selNum-1;//第1个模块对应第0个箭头
				if (selLineNum >= 0)
				{
					for (int i = 0; i < 4; i++){
						lines[selLineNum][i].setLine(0, 0, 0, 0);
					}
				}

				//清除相应模块代码
				QStringList globalCodeList = globalCode.split("\n");
				globalCodeList[selNum + 2] = "";//加上头文件两行头文件两行
				globalCode = globalCodeList.join("\n");
				emit triggerSignal();
			}
		}
		
	}

	//鼠标单击
	if (event->type() == QEvent::MouseButtonPress)
	{ 
		mouseTimer.start(300);//300毫秒后双击事件还不产生就判定是单击
		clickInipos = e->pos();//获得单击时鼠标位置
		if (isSingleClick){
			//找到被单击的模块
			selNum = findNum(e, flowIcon);
			startNum = selNum;
			if (selNum == -1){
				qDebug() << "没有找到单击的模块" << endl;
			}
			else{
				//左键单击模块
				if (flowIcon[selNum]->rect().contains(e->pos()) &&
					(e->button() == Qt::LeftButton))
				{					
				}
				//右键单击模块	
				else if (e->button() == Qt::RightButton)
				{
					qDebug() << "右键单击numstart:" << selNum<<endl;
					
				}
			}
			
		}
	}

	//鼠标移动
	if (event->type() == QEvent::MouseMove)
	{

		if (startNum == -1){
			qDebug() << "没有找到要移动的模块" << endl;
		}
		else{
			//移动的相对位移
			int dx = e->pos().x() - clickInipos.x();
			int dy = e->pos().y() - clickInipos.y();

			//左键移动
			if (e->buttons() & Qt::LeftButton)
			{
				//移动控件
				flowIcon[startNum]->move(flowIcon[startNum]->x() + dx, flowIcon[startNum]->y() + dy);
				leftMove = true;//控件移动,通知释放时箭头改变
			}
			//右键移动
			else if (e->buttons() & Qt::RightButton)
			{
				moveArrowShow(startNum, dx, dy);
				update();
			}

		}
	}

	//释放鼠标
	if ((event->type() == QEvent::MouseButtonRelease))
	{
		//找到释放后鼠标所在的模块
		numEnd = findNum(e, flowIcon);
		//右键释放
		if (e->button() == Qt::RightButton)
		{
			if (numEnd == -1 || startNum == -1){
				qDebug() << "没有找到两个模块" << endl;
			}
			else{
				drawArrow(flowIcon[startNum]->pos(), flowIcon[numEnd]->pos());
				update();

				//把箭头指向的所含的代码写入代码查看器
				globalCode = globalCode + flowText[num] + "\n";
				emit triggerSignal();
			}
			for (int i = 0; i < 4; i++){
				lineShow[i].setLine(0, 0, 0, 0);
			}
			update();//释放后清除实时显示的线
			
		}

		//左键释放
		if (e->button() == Qt::LeftButton)
		{
			qDebug() << "左键释放" << endl;
			if (leftMove){//左键移动后释放
				leftMove = false;
				moveArrowLast(numEnd);//移动模块上一个箭头
				moveArrowNext(numEnd);//移动模块下一个箭头
				update();
			}
		}

		startNum = -1;//释放鼠标后,开始位置归位
	}
	return false;
}
Example #26
0
ImageArea::ImageArea(const bool &isOpen, const QString &filePath, QWidget *parent) :
    QWidget(parent), mIsEdited(false), mIsPaint(false), mIsResize(false)
{
    setMouseTracking(true);

    mRightButtonPressed = false;
    mFilePath.clear();
    makeFormatsFilters();
    initializeImage();
    mZoomFactor = 1;

    mAdditionalTools = new AdditionalTools(this);

    mUndoStack = new QUndoStack(this);
    mUndoStack->setUndoLimit(DataSingleton::Instance()->getHistoryDepth());

    if(isOpen && filePath.isEmpty())
    {
        open();
    }
    else if(isOpen && !filePath.isEmpty())
    {
        open(filePath);
    }
    else
    {
        QPainter *painter = new QPainter(mImage);
        painter->fillRect(0, 0,
                          DataSingleton::Instance()->getBaseSize().width(),
                          DataSingleton::Instance()->getBaseSize().height(),
                          Qt::white);
        painter->end();

        resize(mImage->rect().right() + 6,
               mImage->rect().bottom() + 6);
    }

    QTimer *autoSaveTimer = new QTimer(this);
    autoSaveTimer->setInterval(DataSingleton::Instance()->getAutoSaveInterval() * 1000);
    connect(autoSaveTimer, SIGNAL(timeout()), this, SLOT(autoSave()));
    connect(mAdditionalTools, SIGNAL(sendNewImageSize(QSize)), this, SIGNAL(sendNewImageSize(QSize)));

    autoSaveTimer->start();

    SelectionInstrument *selectionInstrument = new SelectionInstrument(this);
    connect(selectionInstrument, SIGNAL(sendEnableCopyCutActions(bool)), this, SIGNAL(sendEnableCopyCutActions(bool)));
    connect(selectionInstrument, SIGNAL(sendEnableSelectionInstrument(bool)), this, SIGNAL(sendEnableSelectionInstrument(bool)));

    // Instruments handlers
    mInstrumentsHandlers.fill(0, (int)INSTRUMENTS_COUNT);
    mInstrumentsHandlers[CURSOR] = selectionInstrument;
    mInstrumentsHandlers[PEN] = new PencilInstrument(this);
    mInstrumentsHandlers[LINE] = new LineInstrument(this);
    mInstrumentsHandlers[ERASER] = new EraserInstrument(this);
    mInstrumentsHandlers[RECTANGLE] = new RectangleInstrument(this);
    mInstrumentsHandlers[ELLIPSE] = new EllipseInstrument(this);
    mInstrumentsHandlers[FILL] = new FillInstrument(this);
    mInstrumentsHandlers[SPRAY] = new SprayInstrument(this);
    mInstrumentsHandlers[MAGNIFIER] = new MagnifierInstrument(this);
    mInstrumentsHandlers[COLORPICKER] = new ColorpickerInstrument(this);
    mInstrumentsHandlers[CURVELINE] = new CurveLineInstrument(this);
    mInstrumentsHandlers[TEXT] = new TextInstrument(this);

    // Effects handlers
    mEffectsHandlers.fill(0, (int)EFFECTS_COUNT);
    mEffectsHandlers[NEGATIVE] = new NegativeEffect(this);
    mEffectsHandlers[GRAY] = new GrayEffect(this);
    mEffectsHandlers[BINARIZATION] = new BinarizationEffect(this);
    mEffectsHandlers[GAUSSIANBLUR] = new GaussianBlurEffect(this);
    mEffectsHandlers[GAMMA] = new GammaEffect(this);
    mEffectsHandlers[SHARPEN] = new SharpenEffect(this);
    mEffectsHandlers[CUSTOM] = new CustomEffect(this);
}
Example #27
0
BitcoinGUI::BitcoinGUI(QWidget *parent):
    QMainWindow(parent),
    clientModel(0),
    walletModel(0),
    encryptWalletAction(0),
    changePassphraseAction(0),
    unlockWalletAction(0),
    lockWalletAction(0),
    aboutQtAction(0),
    trayIcon(0),
    notificator(0),
    rpcConsole(0)
{
    resize(840, 550);
    setWindowTitle(tr("Global ") + tr("Wallet"));


#ifndef Q_OS_MAC
    qApp->setWindowIcon(QIcon(":icons/bitcoin"));
    setWindowIcon(QIcon(":icons/bitcoin"));
#else
    setUnifiedTitleAndToolBarOnMac(true);
    QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
	QApplication::setStyle(QStyleFactory::create("Fusion"));

    // Accept D&D of URIs
    setAcceptDrops(true);

    // Create actions for the toolbar, menu bar and tray/dock icon
    createActions();

    // Create application menu bar
    createMenuBar();

    // Create the toolbars
    createToolBars();

    // Create the tray icon (or setup the dock icon)
    createTrayIcon();
//    QFile style(":/styles/styles");
//    style.open(QFile::ReadOnly);
//    qApp->setStyleSheet(QString::fromUtf8(style.readAll()));
//    setStyleSheet("QMainWindow { background-image:url(:images/bkg);border:none;font-family:'Open Sans,sans-serif'; } #frame { } QToolBar QLabel { padding-top:15px;padding-bottom:10px;margin:0px; } #spacer { background:rgb(210,192,123);border:none; } #toolbar3 { border:none;width:1px; background-color: rgb(63,109,186); } #toolbar2 { border:none;width:28px; background-color:qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,stop: 0 rgb(210,192,123), stop: 1 rgb(227,213,195),stop: 2 rgb(59,62,65)); } #toolbar { border:none;height:100%;padding-top:20px; background: rgb(210,192,123); text-align: left; color: white;min-width:150px;max-width:150px;} QToolBar QToolButton:hover {background-color:qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,stop: 0 rgb(210,192,123), stop: 1 rgb(227,213,195),stop: 2 rgb(59,62,65));} QToolBar QToolButton { font-family:Century Gothic;padding-left:20px;padding-right:150px;padding-top:10px;padding-bottom:10px; width:100%; color: white; text-align: left; background-color: rgb(210,192,123) } #labelMiningIcon { padding-left:5px;font-family:Century Gothic;width:100%;font-size:10px;text-align:center;color:white; } QMenu { background: rgb(210,192,123); color:white; padding-bottom:10px; } QMenu::item { color:white; background-color: transparent; } QMenu::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgb(210,192,123), stop: 1 rgb(227,213,195)); } QMenuBar { background: rgb(210,192,123); color:white; } QMenuBar::item { font-size:12px;padding-bottom:8px;padding-top:8px;padding-left:15px;padding-right:15px;color:white; background-color: transparent; } QMenuBar::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgb(210,192,123), stop: 1 rgb(227,213,195)); }");
    qApp->setStyleSheet("QMainWindow { background-image:url(:images/bkg);border:none;font-family:'Open Sans,sans-serif'; } #frame { } QToolBar QLabel { padding-top:15px;padding-bottom:10px;margin:0px; } #spacer { background:rgb(63,109,186);border:none; } #toolbar3 { border:none;width:1px; background-color: rgb(63,109,186); } #toolbar2 { border:none;width:28px; background-color:rgb(63,109,186); } #toolbar { border:none;height:100%;padding-top:20px; background: rgb(63,109,186); text-align: left; color: white;min-width:150px;max-width:150px;} QToolBar QToolButton:hover {background-color:qlineargradient(x1: 0, y1: 0, x2: 2, y2: 2,stop: 0 rgb(63,109,186), stop: 1 rgb(216,252,251),stop: 2 rgb(59,62,65));} QToolBar QToolButton { font-family:Century Gothic;padding-left:20px;padding-right:150px;padding-top:10px;padding-bottom:10px; width:100%; color: white; text-align: left; background-color: rgb(63,109,186) } #labelMiningIcon { padding-left:5px;font-family:Century Gothic;width:100%;font-size:10px;text-align:center;color:white; } QMenu { background: rgb(63,109,186); color:white; padding-bottom:10px; } QMenu::item { color:white; background-color: transparent; } QMenu::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgb(63,109,186), stop: 1 rgb(149,204,244)); } QMenuBar { background: rgb(63,109,186); color:white; } QMenuBar::item { font-size:12px;padding-bottom:8px;padding-top:8px;padding-left:15px;padding-right:15px;color:white; background-color: transparent; } QMenuBar::item:selected { background-color:qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5,stop: 0 rgb(63,109,186), stop: 1 rgb(149,204,244)); }");


//#ifdef Q_OS_MAC
//    toolbar->setStyleSheet("QToolBar { background-color: transparent; border: 0px solid black; padding: 3px; }");
//#endif
    // Create tabs
    overviewPage = new OverviewPage();

    transactionsPage = new QWidget(this);
    QVBoxLayout *vbox = new QVBoxLayout();
    transactionView = new TransactionView(this);
    vbox->addWidget(transactionView);
    transactionsPage->setLayout(vbox);

    addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);

    receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);

    sendCoinsPage = new SendCoinsDialog(this);

    signVerifyMessageDialog = new SignVerifyMessageDialog(this);

    centralWidget = new QStackedWidget(this);
    centralWidget->addWidget(overviewPage);
    centralWidget->addWidget(transactionsPage);
    centralWidget->addWidget(addressBookPage);
    centralWidget->addWidget(receiveCoinsPage);
    centralWidget->addWidget(sendCoinsPage);
    setCentralWidget(centralWidget);

    // Create status bar
    statusBar();

    // Status bar notification icons

    labelEncryptionIcon = new QLabel();
    labelStakingIcon = new QLabel();
    labelConnectionsIcon = new QLabel();
    labelBlocksIcon = new QLabel();

    if (GetBoolArg("-staking", true))
    {
        QTimer *timerStakingIcon = new QTimer(labelStakingIcon);
        connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingIcon()));
        timerStakingIcon->start(30 * 1000);
        updateStakingIcon();
    }

    // Progress bar and label for blocks download
    progressBarLabel = new QLabel();
    progressBarLabel->setVisible(false);
    progressBar = new QProgressBar();


    progressBar->setAlignment(Qt::AlignCenter);
    progressBar->setVisible(false);

    // Override style sheet for progress bar for styles that have a segmented progress bar,
    // as they make the text unreadable (workaround for issue #1071)
    // See https://qt-project.org/doc/qt-4.8/gallery.html
    QString curStyle = qApp->style()->metaObject()->className();
    if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
    {
        progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #007FFF, stop: 1 #3B5998); border-radius: 7px; margin: 0px; }");
    }

    statusBar()->addWidget(progressBarLabel);
    statusBar()->addWidget(progressBar);
	
	
	
    addToolBarBreak(Qt::LeftToolBarArea);
    QToolBar *toolbar2 = addToolBar(tr("Tabs toolbar"));
    addToolBar(Qt::LeftToolBarArea,toolbar2);
    toolbar2->setOrientation(Qt::Vertical);
    toolbar2->setMovable( false );
    toolbar2->setObjectName("toolbar2");
    toolbar2->setFixedWidth(28);
    toolbar2->setIconSize(QSize(28,28));
    toolbar2->addWidget(labelEncryptionIcon);
    toolbar2->addWidget(labelStakingIcon);
    toolbar2->addWidget(labelConnectionsIcon);
    toolbar2->addWidget(labelBlocksIcon);
    toolbar2->setStyleSheet("#toolbar2 QToolButton { border:none;padding:0px;margin:0px;height:20px;width:28px;margin-top:36px; }");
//    toolbar2->setStyleSheet(QString::fromUtf8(style.readAll()));
	
	addToolBarBreak(Qt::TopToolBarArea);
    QToolBar *toolbar3 = addToolBar(tr("Green bar"));
    addToolBar(Qt::TopToolBarArea,toolbar3);
    toolbar3->setOrientation(Qt::Horizontal);
    toolbar3->setMovable( false );
    toolbar3->setObjectName("toolbar3");
    toolbar3->setFixedHeight(2);

    syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);

    // Clicking on a transaction on the overview page simply sends you to transaction history page
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));

    // Double-clicking on a transaction on the transaction history page shows details
    connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));

    rpcConsole = new RPCConsole(this);
    connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));

    // Clicking on "Verify Message" in the address book sends you to the verify message tab
    connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
    // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
    connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));

    gotoOverviewPage();
}
ComposeWidget::ComposeWidget(MainWindow *mainWindow, MSA::MSAFactory *msaFactory) :
    QWidget(0, Qt::Window),
    ui(new Ui::ComposeWidget),
    m_sentMail(false),
    m_messageUpdated(false),
    m_messageEverEdited(false),
    m_explicitDraft(false),
    m_appendUidReceived(false), m_appendUidValidity(0), m_appendUid(0), m_genUrlAuthReceived(false),
    m_mainWindow(mainWindow)
{
    setAttribute(Qt::WA_DeleteOnClose, true);

    Q_ASSERT(m_mainWindow);
    m_submission = new Composer::Submission(this, m_mainWindow->imapModel(), msaFactory);
    connect(m_submission, SIGNAL(succeeded()), this, SLOT(sent()));
    connect(m_submission, SIGNAL(failed(QString)), this, SLOT(gotError(QString)));

    ui->setupUi(this);
    sendButton = ui->buttonBox->addButton(tr("Send"), QDialogButtonBox::AcceptRole);
    connect(sendButton, SIGNAL(clicked()), this, SLOT(send()));
    cancelButton = ui->buttonBox->addButton(QDialogButtonBox::Cancel);
    connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
    ui->attachmentsView->setModel(m_submission->composer());
    connect(ui->attachButton, SIGNAL(clicked()), this, SLOT(slotAskForFileAttachment()));
    ui->attachmentsView->setContextMenuPolicy(Qt::ActionsContextMenu);

    m_actionRemoveAttachment = new QAction(tr("Remove"), this);
    connect(m_actionRemoveAttachment, SIGNAL(triggered()), this, SLOT(slotRemoveAttachment()));
    ui->attachmentsView->addAction(m_actionRemoveAttachment);

    connect(ui->attachmentsView, SIGNAL(itemDroppedOut()), SLOT(slotRemoveAttachment()));

    m_completionPopup = new QMenu(this);
    m_completionPopup->installEventFilter(this);
    connect (m_completionPopup, SIGNAL(triggered(QAction*)), SLOT(completeRecipient(QAction*)));

    // TODO: make this configurable?
    m_completionCount = 8;

    m_recipientListUpdateTimer = new QTimer(this);
    m_recipientListUpdateTimer->setSingleShot(true);
    m_recipientListUpdateTimer->setInterval(250);
    connect(m_recipientListUpdateTimer, SIGNAL(timeout()), SLOT(updateRecipientList()));

    ui->mailText->setFont(Gui::Util::systemMonospaceFont());

    connect(ui->mailText, SIGNAL(urlsAdded(QList<QUrl>)), SLOT(slotAttachFiles(QList<QUrl>)));
    connect(ui->mailText, SIGNAL(sendRequest()), SLOT(send()));
    connect(ui->mailText, SIGNAL(textChanged()), SLOT(setMessageUpdated()));

    FromAddressProxyModel *proxy = new FromAddressProxyModel(this);
    proxy->setSourceModel(m_mainWindow->senderIdentitiesModel());
    ui->sender->setModel(proxy);

    connect(ui->sender, SIGNAL(currentIndexChanged(int)), SLOT(slotUpdateSignature()));

    QTimer *autoSaveTimer = new QTimer(this);
    connect(autoSaveTimer, SIGNAL(timeout()), SLOT(autoSaveDraft()));
    autoSaveTimer->start(30*1000);

    m_autoSavePath = QString(
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
                QDesktopServices::storageLocation(QDesktopServices::CacheLocation)
#else
                QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
#endif
                + QLatin1Char('/') + QLatin1String("Drafts/"));
    QDir().mkpath(m_autoSavePath);

#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
    m_autoSavePath += QString::number(QDateTime(QDate(1970, 1, 1), QTime(0, 0, 0)).secsTo(QDateTime::currentDateTime())) + QLatin1String(".draft");
#else
    m_autoSavePath += QString::number(QDateTime::currentMSecsSinceEpoch()) + QLatin1String(".draft");
#endif
}
Example #29
0
DockWnd::DockWnd(QWidget *main)
        : QWidget(NULL)
{
#ifndef WIN32
    wharfIcon = NULL;
#endif
    connect(this, SIGNAL(toggleWin()), main, SLOT(toggleShow()));
    connect(this, SIGNAL(showPopup(QPoint)), main, SLOT(showPopup(QPoint)));
    connect(pClient, SIGNAL(event(ICQEvent*)), this, SLOT(processEvent(ICQEvent*)));
    connect(pClient, SIGNAL(messageRead(ICQMessage*)), this, SLOT(messageRead(ICQMessage*)));
    connect(pClient, SIGNAL(messageReceived(ICQMessage*)), this, SLOT(messageReceived(ICQMessage*)));
    connect(pMain, SIGNAL(iconChanged()), this, SLOT(reset()));
    m_state = 0;
    showIcon = State;
    QTimer *t = new QTimer(this);
    connect(t, SIGNAL(timeout()), this, SLOT(timer()));
    t->start(800);
    bool bWMDock = false;
#ifndef WIN32
    Atom r_type;
    int r_format;
    unsigned long count, bytes_remain;
    unsigned char *prop = NULL, *prop2 = NULL;
    Atom _XA_WIN_SUPPORTING_WM_CHECK = XInternAtom(qt_xdisplay(), XA_WIN_SUPPORTING_WM_CHECK, False);
    int p = XGetWindowProperty(qt_xdisplay(), qt_xrootwin(), _XA_WIN_SUPPORTING_WM_CHECK,
                               0, 1, False, XA_CARDINAL, &r_type, &r_format,
                               &count, &bytes_remain, &prop);

    if (p == Success && prop && r_type == XA_CARDINAL &&
            r_format == 32 && count == 1)
    {
        Window n = *(long *) prop;

        p = XGetWindowProperty(qt_xdisplay(), n, _XA_WIN_SUPPORTING_WM_CHECK, 0, 1,
                               False, XA_CARDINAL, &r_type, &r_format,
                               &count, &bytes_remain, &prop2);

        if (p == Success && prop2 && r_type == XA_CARDINAL &&
                r_format == 32 && count == 1)
            bWMDock = true;
    }

    if (prop)
        XFree(prop);
    if (prop2)
        XFree(prop2);

#endif
#ifdef USE_KDE
    log(L_DEBUG, "WM props? %u", bWMDock);
    if (!bWMDock)
        KWin::setSystemTrayWindowFor( winId(), main->topLevelWidget()->winId());
#endif
    needToggle = false;
#ifdef WIN32
    QWidget::hide();
    QWidget::setIcon(Pict(pClient->getStatusIcon()));
    gDock = this;
    oldDockProc = (WNDPROC)SetWindowLongW(winId(), GWL_WNDPROC, (LONG)DockWindowProc);
    if (oldDockProc == 0)
        oldDockProc = (WNDPROC)SetWindowLongA(winId(), GWL_WNDPROC, (LONG)DockWindowProc);
    NOTIFYICONDATAA notifyIconData;
    notifyIconData.cbSize = sizeof(notifyIconData);
    notifyIconData.hIcon = topData()->winIcon;
    notifyIconData.hWnd = winId();
    notifyIconData.szTip[0] = 0;
    notifyIconData.uCallbackMessage = WM_DOCK;
    notifyIconData.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
    notifyIconData.uID = 0;
    Shell_NotifyIconA(NIM_ADD, &notifyIconData);
#else
    if (!bWMDock){
        setBackgroundMode(X11ParentRelative);
        setIcon(Pict(pClient->getStatusIcon()));
#ifdef USE_KDE
        show();
#else
    hide();
#endif
    }else{
        wharfIcon = new WharfIcon(this);
        Display *dsp = x11Display();
        WId win = winId();
        XWMHints *hints;
        XClassHint classhint;
        classhint.res_name  = (char*)"sim";
        classhint.res_class = (char*)"sim";
        XSetClassHint(dsp, win, &classhint);
        hints = XGetWMHints(dsp, win);
        hints->initial_state = WithdrawnState;
        hints->icon_x = 0;
        hints->icon_y = 0;
        hints->icon_window = wharfIcon->winId();
        hints->window_group = win;
        hints->flags = WindowGroupHint | IconWindowHint | IconPositionHint | StateHint;
        XSetWMHints(dsp, win, hints);
        XFree( hints );
        XSetCommand(dsp, winId(), _argv, _argc);
        resize(64, 64);
        show();
    }
#endif
    loadUnread();
    reset();
}
Example #30
0
int main(int argc, char **argv)
{
	//See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions
	/** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory
		on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to
		ensure that resource sharing between contexts stays functional as all internal contexts are created
		using the correct version and profile.
	**/
	{
		QSurfaceFormat format = QSurfaceFormat::defaultFormat();
		format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
		format.setStencilBufferSize(0);
#ifdef CC_GL_WINDOW_USE_QWINDOW
		format.setStereo(true);
#endif
#ifdef Q_OS_MAC
		format.setStereo(false);
		format.setVersion( 2, 1 );
		format.setProfile( QSurfaceFormat::CoreProfile );
#endif
#ifdef QT_DEBUG
		format.setOption(QSurfaceFormat::DebugContext, true);
#endif
		QSurfaceFormat::setDefaultFormat(format);
	}

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

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

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

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

#ifdef USE_VLD
	VLDEnable();
#endif

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

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

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

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

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

	//splash screen
	QScopedPointer<QSplashScreen> splash(0);
	QTimer splashTimer;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			mainWindow->addToDB(filenames);
		}
		else if (splash)
		{
			//count-down to hide the timer (only effective once the application will have actually started!)
			QObject::connect(&splashTimer, &QTimer::timeout, [&]() { if (splash) splash->close(); QCoreApplication::processEvents(); splash.reset(); });
			splashTimer.setInterval(1000);
			splashTimer.start();
		}

		//change the default path to the application one (do this AFTER processing the command line)
		QDir::setCurrent(workingDir.absolutePath());

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

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

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

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

	return result;
}