SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
    QSplashScreen(pixmap, f)
{
    // set reference point, paddings
    int paddingLeftCol2         = 145;
    int paddingTopCol2          = 376;
    int line1 = 0;
    int line2 = 13;
    int line3 = 26;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
    QString versionText     = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText1   = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers"));
    QString copyrightText2   = QChar(0xA9)+QString(" %1 ").arg(COPYRIGHT_YEAR) + QString(tr("The TreasureHuntCoin developers"));

    QString font            = "Arial";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(GetBoolArg("-testnet")) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(70,70,70));

    pixPaint.setFont(QFont(font, 9*fontFactor));
    pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 9*fontFactor));
    pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1);
    pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2);

    pixPaint.end();

    this->setPixmap(newPixmap);
}
Example #2
0
    void Balancer::_doBalanceRound( DBClientBase& conn, vector<CandidateChunkPtr>* candidateChunks ) {
        verify( candidateChunks );

        //
        // 1. Check whether there is any sharded collection to be balanced by querying
        // the ShardsNS::collections collection
        //

        auto_ptr<DBClientCursor> cursor = conn.query(CollectionType::ConfigNS, BSONObj());

        if ( NULL == cursor.get() ) {
            warning() << "could not query " << CollectionType::ConfigNS
                      << " while trying to balance" << endl;
            return;
        }

        vector< string > collections;
        while ( cursor->more() ) {
            BSONObj col = cursor->nextSafe();

            // sharded collections will have a shard "key".
            if ( ! col[CollectionType::keyPattern()].eoo() &&
                 ! col[CollectionType::noBalance()].trueValue() ){
                collections.push_back( col[CollectionType::ns()].String() );
            }
            else if( col[CollectionType::noBalance()].trueValue() ){
                LOG(1) << "not balancing collection " << col[CollectionType::ns()].String()
                       << ", explicitly disabled" << endl;
            }

        }
        cursor.reset();

        if ( collections.empty() ) {
            LOG(1) << "no collections to balance" << endl;
            return;
        }

        //
        // 2. Get a list of all the shards that are participating in this balance round
        // along with any maximum allowed quotas and current utilization. We get the
        // latter by issuing db.serverStatus() (mem.mapped) to all shards.
        //
        // TODO: skip unresponsive shards and mark information as stale.
        //

        vector<Shard> allShards;
        Shard::getAllShards( allShards );
        if ( allShards.size() < 2) {
            LOG(1) << "can't balance without more active shards" << endl;
            return;
        }
        
        ShardInfoMap shardInfo;
        for ( vector<Shard>::const_iterator it = allShards.begin(); it != allShards.end(); ++it ) {
            const Shard& s = *it;
            ShardStatus status = s.getStatus();
            shardInfo[ s.getName() ] = ShardInfo( s.getMaxSize(),
                                                  status.mapped(),
                                                  s.isDraining(),
                                                  status.hasOpsQueued(),
                                                  s.tags(),
                                                  status.mongoVersion()
                                                  );
        }

        OCCASIONALLY warnOnMultiVersion( shardInfo );

        //
        // 3. For each collection, check if the balancing policy recommends moving anything around.
        //

        for (vector<string>::const_iterator it = collections.begin(); it != collections.end(); ++it ) {
            const string& ns = *it;

            map< string,vector<BSONObj> > shardToChunksMap;
            cursor = conn.query(ChunkType::ConfigNS,
                                QUERY(ChunkType::ns(ns)).sort(ChunkType::min()));

            set<BSONObj> allChunkMinimums;

            while ( cursor->more() ) {
                BSONObj chunk = cursor->nextSafe().getOwned();
                vector<BSONObj>& chunks = shardToChunksMap[chunk[ChunkType::shard()].String()];
                allChunkMinimums.insert( chunk[ChunkType::min()].Obj() );
                chunks.push_back( chunk );
            }
            cursor.reset();

            if (shardToChunksMap.empty()) {
                LOG(1) << "skipping empty collection (" << ns << ")";
                continue;
            }

            for ( vector<Shard>::iterator i=allShards.begin(); i!=allShards.end(); ++i ) {
                // this just makes sure there is an entry in shardToChunksMap for every shard
                Shard s = *i;
                shardToChunksMap[s.getName()].size();
            }

            DistributionStatus status( shardInfo, shardToChunksMap );

            // load tags
            Status result = clusterCreateIndex(TagsType::ConfigNS,
                                               BSON(TagsType::ns() << 1 << TagsType::min() << 1),
                                               true, // unique
                                               WriteConcernOptions::AllConfigs,
                                               NULL);

            if ( !result.isOK() ) {
                warning() << "could not create index tags_1_min_1: " << result.reason() << endl;
                continue;
            }

            cursor = conn.query(TagsType::ConfigNS,
                                QUERY(TagsType::ns(ns)).sort(TagsType::min()));

            vector<TagRange> ranges;

            while ( cursor->more() ) {
                BSONObj tag = cursor->nextSafe();
                TagRange tr(tag[TagsType::min()].Obj().getOwned(),
                            tag[TagsType::max()].Obj().getOwned(),
                            tag[TagsType::tag()].String());
                ranges.push_back(tr);
                uassert(16356,
                        str::stream() << "tag ranges not valid for: " << ns,
                        status.addTagRange(tr) );

            }
            cursor.reset();

            DBConfigPtr cfg = grid.getDBConfig( ns );
            if ( !cfg ) {
                warning() << "could not load db config to balance " << ns << " collection" << endl;
                continue;
            }

            // This line reloads the chunk manager once if this process doesn't know the collection
            // is sharded yet.
            ChunkManagerPtr cm = cfg->getChunkManagerIfExists( ns, true );
            if ( !cm ) {
                warning() << "could not load chunks to balance " << ns << " collection" << endl;
                continue;
            }

            // loop through tags to make sure no chunk spans tags; splits on tag min. for all chunks
            bool didAnySplits = false;
            for ( unsigned i = 0; i < ranges.size(); i++ ) {
                BSONObj min = ranges[i].min;

                min = cm->getShardKey().extendRangeBound( min, false );

                if ( allChunkMinimums.count( min ) > 0 )
                    continue;

                didAnySplits = true;

                log() << "ns: " << ns << " need to split on "
                      << min << " because there is a range there" << endl;

                ChunkPtr c = cm->findIntersectingChunk( min );

                vector<BSONObj> splitPoints;
                splitPoints.push_back( min );

                BSONObj res;
                if ( !c->multiSplit( splitPoints, res ) ) {
                    error() << "split failed: " << res << endl;
                }
                else {
                    LOG(1) << "split worked: " << res << endl;
                }
                break;
            }

            if ( didAnySplits ) {
                // state change, just wait till next round
                continue;
            }

            CandidateChunk* p = _policy->balance( ns, status, _balancedLastTime );
            if ( p ) candidateChunks->push_back( CandidateChunkPtr( p ) );
        }
    }
Example #3
0
dspInventoryAvailabilityBySourceVendor::dspInventoryAvailabilityBySourceVendor(QWidget* parent, const char* name, Qt::WFlags fl)
    : XWidget(parent, name, fl)
{
  setupUi(this);

  _showByGroupInt = new QButtonGroup(this);
  _showByGroupInt->addButton(_leadTime);
  _showByGroupInt->addButton(_byDays);
  _showByGroupInt->addButton(_byDate);
  _showByGroupInt->addButton(_byDates);

  connect(_availability, SIGNAL(populateMenu(QMenu*,QTreeWidgetItem*,int)), this, SLOT(sPopulateMenu(QMenu*,QTreeWidgetItem*)));
  connect(_print, SIGNAL(clicked()), this, SLOT(sPrint()));
  connect(_query, SIGNAL(clicked()), this, SLOT(sFillList()));
  connect(_showReorder, SIGNAL(toggled(bool)), this, SLOT(sHandleShowReorder(bool)));

  _availability->addColumn(tr("Vendor #"),     _itemColumn, Qt::AlignLeft,  true, "vend_number");
  _availability->addColumn(tr("Site"),         _whsColumn,  Qt::AlignCenter,true, "warehous_code");
  _availability->addColumn(tr("Item"),         _itemColumn, Qt::AlignLeft,  true, "item_number");
  _availability->addColumn(tr("Description"),  -1,          Qt::AlignLeft,  true, "itemdescrip");
  _availability->addColumn(tr("UOM"),          _uomColumn,  Qt::AlignCenter,true, "uom_name");
  _availability->addColumn(tr("LT"),           _whsColumn,  Qt::AlignCenter,true, "itemsite_leadtime");
  _availability->addColumn(tr("QOH"),          _qtyColumn,  Qt::AlignRight, true, "qoh");
  _availability->addColumn(tr("Allocated"),    _qtyColumn,  Qt::AlignRight, true, "allocated");
  _availability->addColumn(tr("Unallocated"),  _qtyColumn,  Qt::AlignRight, true, "unallocated");
  _availability->addColumn(tr("On Order"),     _qtyColumn,  Qt::AlignRight, true, "ordered");
  _availability->addColumn(tr("Reorder Lvl."), _qtyColumn,  Qt::AlignRight, true, "reorderlevel");
  _availability->addColumn(tr("OUT Level"),    _qtyColumn,  Qt::AlignRight, false, "outlevel");
  _availability->addColumn(tr("Available"),    _qtyColumn,  Qt::AlignRight, true, "available");
  
  if (_preferences->boolean("XCheckBox/forgetful"))
    _ignoreReorderAtZero->setChecked(true);

  sHandleShowReorder(_showReorder->isChecked());
}
Example #4
0
void Print::setPrintButtonText(bool inFileRadioButtonState)
{
    if(inFileRadioButtonState)
        ui->print->setText(tr("Save"));
    else ui->print->setText(tr("Print"));
}
void AskPassphraseDialog::accept()
{
    SecureString oldpass, newpass1, newpass2;
    if(!model)
        return;
    oldpass.reserve(MAX_PASSPHRASE_SIZE);
    newpass1.reserve(MAX_PASSPHRASE_SIZE);
    newpass2.reserve(MAX_PASSPHRASE_SIZE);
    // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    // Alternately, find a way to make this input mlock()'d to begin with.
    oldpass.assign(ui->passEdit1->text().toStdString().c_str());
    newpass1.assign(ui->passEdit2->text().toStdString().c_str());
    newpass2.assign(ui->passEdit3->text().toStdString().c_str());

    switch(mode)
    {
    case Encrypt: {
        if(newpass1.empty() || newpass2.empty())
        {
            // Cannot encrypt with empty passphrase
            break;
        }
        QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
                 tr("WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BOSCHICOINS</b>!\nAre you sure you wish to encrypt your wallet?"),
                 QMessageBox::Yes|QMessageBox::Cancel,
                 QMessageBox::Cancel);
        if(retval == QMessageBox::Yes)
        {
            if(newpass1 == newpass2)
            {
                if(model->setWalletEncrypted(true, newpass1))
                {
                    QMessageBox::warning(this, tr("Wallet encrypted"),
                                         tr("BoschiCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your boschicoin from being stolen by malware infecting your computer."));
                    QApplication::quit();
                }
                else
                {
                    QMessageBox::critical(this, tr("Wallet encryption failed"),
                                         tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
                }
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The supplied passphrases do not match."));
            }
        }
        else
        {
            QDialog::reject(); // Cancelled
        }
        } break;
    case Unlock:
        if(!model->setWalletLocked(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet unlock failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            QDialog::accept(); // Success
        }
        break;
    case Decrypt:
        if(!model->setWalletEncrypted(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet decryption failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            QDialog::accept(); // Success
        }
        break;
    case ChangePass:
        if(newpass1 == newpass2)
        {
            if(model->changePassphrase(oldpass, newpass1))
            {
                QMessageBox::information(this, tr("Wallet encrypted"),
                                     tr("Wallet passphrase was successfully changed."));
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The passphrase entered for the wallet decryption was incorrect."));
            }
        }
        else
        {
            QMessageBox::critical(this, tr("Wallet encryption failed"),
                                 tr("The supplied passphrases do not match."));
        }
        break;
    }
}
void TcpClient::slotDisconnected()
{
    sendBtn->setEnabled(false);
    enterBtn->setText(tr("进入聊天室"));
}
Example #7
0
void frmMain::UpdateData9(int value)
{
    ui->labValue->setText(tr("当前值:%1").arg(value));
}
Example #8
0
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
    // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
    statusBar()->clearMessage();

    // Acquire current block source
    enum BlockSource blockSource = clientModel->getBlockSource();
    switch (blockSource) {
        case BLOCK_SOURCE_NETWORK:
            progressBarLabel->setText(tr("Synchronizing with network..."));
            break;
        case BLOCK_SOURCE_DISK:
            progressBarLabel->setText(tr("Importing blocks from disk..."));
            break;
        case BLOCK_SOURCE_REINDEX:
            progressBarLabel->setText(tr("Reindexing blocks on disk..."));
            break;
        case BLOCK_SOURCE_NONE:
            // Case: not Importing, not Reindexing and no network connection
            progressBarLabel->setText(tr("No block source available..."));
            break;
    }

    QString tooltip;

    QDateTime lastBlockDate = clientModel->getLastBlockDate();
    QDateTime currentDate = QDateTime::currentDateTime();
    int secs = lastBlockDate.secsTo(currentDate);

    if(count < nTotalBlocks)
    {
        tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks);
    }
    else
    {
        tooltip = tr("Processed %1 blocks of transaction history.").arg(count);
    }

    // Set icon state: spinning if catching up, tick otherwise
    if(secs < 90*60 && count >= nTotalBlocks)
    {
        tooltip = tr("Up to date") + QString(".<br>") + tooltip;
        labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));

#ifdef ENABLE_WALLET
        if(walletFrame)
            walletFrame->showOutOfSyncWarning(false);
#endif

        progressBarLabel->setVisible(false);
        progressBar->setVisible(false);
    }
    else
    {
        // Represent time from last generated block in human readable text
        QString timeBehindText;
        if(secs < 48*60*60)
        {
            timeBehindText = tr("%n hour(s)","",secs/(60*60));
        }
        else if(secs < 14*24*60*60)
        {
            timeBehindText = tr("%n day(s)","",secs/(24*60*60));
        }
        else
        {
            timeBehindText = tr("%n week(s)","",secs/(7*24*60*60));
        }

        progressBarLabel->setVisible(true);
        progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
        progressBar->setMaximum(1000000000);
        progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
        progressBar->setVisible(true);

        tooltip = tr("Catching up...") + QString("<br>") + tooltip;
        if(count != prevBlocks)
        {
            labelBlocksIcon->setPixmap(QIcon(QString(
                ":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0')))
                .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
            spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
        }
        prevBlocks = count;

#ifdef ENABLE_WALLET
        if(walletFrame)
            walletFrame->showOutOfSyncWarning(true);
#endif

        tooltip += QString("<br>");
        tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
        tooltip += QString("<br>");
        tooltip += tr("Transactions after this will not yet be visible.");
    }

    // Don't word-wrap this (fixed-width) tooltip
    tooltip = QString("<nobr>") + tooltip + QString("</nobr>");

    labelBlocksIcon->setToolTip(tooltip);
    progressBarLabel->setToolTip(tooltip);
    progressBar->setToolTip(tooltip);
}
Example #9
0
void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)
{
    QString strTitle = tr("Horuscoin"); // default title
    // Default to information icon
    int nMBoxIcon = QMessageBox::Information;
    int nNotifyIcon = Notificator::Information;

    QString msgType;

    // Prefer supplied title over style based title
    if (!title.isEmpty()) {
        msgType = title;
    }
    else {
        switch (style) {
        case CClientUIInterface::MSG_ERROR:
            msgType = tr("Error");
            break;
        case CClientUIInterface::MSG_WARNING:
            msgType = tr("Warning");
            break;
        case CClientUIInterface::MSG_INFORMATION:
            msgType = tr("Information");
            break;
        default:
            break;
        }
    }
    // Append title to "Horuscoin - "
    if (!msgType.isEmpty())
        strTitle += " - " + msgType;

    // Check for error/warning icon
    if (style & CClientUIInterface::ICON_ERROR) {
        nMBoxIcon = QMessageBox::Critical;
        nNotifyIcon = Notificator::Critical;
    }
    else if (style & CClientUIInterface::ICON_WARNING) {
        nMBoxIcon = QMessageBox::Warning;
        nNotifyIcon = Notificator::Warning;
    }

    // Display message
    if (style & CClientUIInterface::MODAL) {
        // Check for buttons, use OK as default, if none was supplied
        QMessageBox::StandardButton buttons;
        if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
            buttons = QMessageBox::Ok;

        // Ensure we get users attention, but only if main window is visible
        // as we don't want to pop up the main window for messages that happen before
        // initialization is finished.
        if(!(style & CClientUIInterface::NOSHOWGUI))
            showNormalIfMinimized();
        QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
        int r = mBox.exec();
        if (ret != NULL)
            *ret = r == QMessageBox::Ok;
    }
    else
        notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
Example #10
0
void BitcoinGUI::createActions(bool fIsTestnet)
{
    QActionGroup *tabGroup = new QActionGroup(this);

    overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
    overviewAction->setStatusTip(tr("Show general overview of wallet"));
    overviewAction->setToolTip(overviewAction->statusTip());
    overviewAction->setCheckable(true);
    overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
    tabGroup->addAction(overviewAction);

    sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this);
    sendCoinsAction->setStatusTip(tr("Send coins to a Horuscoin address"));
    sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
    sendCoinsAction->setCheckable(true);
    sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
    tabGroup->addAction(sendCoinsAction);

    receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
    receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and horuscoin: URIs)"));
    receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
    receiveCoinsAction->setCheckable(true);
    receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
    tabGroup->addAction(receiveCoinsAction);

    historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
    historyAction->setStatusTip(tr("Browse transaction history"));
    historyAction->setToolTip(historyAction->statusTip());
    historyAction->setCheckable(true);
    historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
    tabGroup->addAction(historyAction);

    // These showNormalIfMinimized are needed because Send Coins and Receive Coins
    // can be triggered from the tray menu, and need to show the GUI to be useful.
    connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
    connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
    connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
    connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));

    quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
    quitAction->setStatusTip(tr("Quit application"));
    quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
    quitAction->setMenuRole(QAction::QuitRole);
    if (!fIsTestnet)
        aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About Horuscoin Core"), this);
    else
        aboutAction = new QAction(QIcon(":/icons/bitcoin_testnet"), tr("&About Horuscoin Core"), this);
    aboutAction->setStatusTip(tr("Show information about Horuscoin"));
    aboutAction->setMenuRole(QAction::AboutRole);
#if QT_VERSION < 0x050000
    aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
#else
    aboutQtAction = new QAction(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
#endif
    aboutQtAction->setStatusTip(tr("Show information about Qt"));
    aboutQtAction->setMenuRole(QAction::AboutQtRole);
    optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
    optionsAction->setStatusTip(tr("Modify configuration options for Horuscoin"));
    optionsAction->setMenuRole(QAction::PreferencesRole);
    if (!fIsTestnet)
        toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
    else
        toggleHideAction = new QAction(QIcon(":/icons/bitcoin_testnet"), tr("&Show / Hide"), this);
    toggleHideAction->setStatusTip(tr("Show or hide the main Window"));

    encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
    encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
    encryptWalletAction->setCheckable(true);
    backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
    backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
    changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
    changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
    signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
    signMessageAction->setStatusTip(tr("Sign messages with your Horuscoin addresses to prove you own them"));
    verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
    verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Horuscoin addresses"));

    openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
    openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console"));

    usedSendingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Sending addresses..."), this);
    usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels"));
    usedReceivingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Receiving addresses..."), this);
    usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels"));

    openAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_FileIcon), tr("Open &URI..."), this);
    openAction->setStatusTip(tr("Open a horuscoin: URI or payment request"));

    showHelpMessageAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Command-line options"), this);
    showHelpMessageAction->setStatusTip(tr("Show the Horuscoin Core help message to get a list with possible Horuscoin command-line options"));

    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
    connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
    connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
    connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));
#ifdef ENABLE_WALLET
    if(walletFrame)
    {
        connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
        connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
        connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
        connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
        connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
        connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));
        connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));
        connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));
    }
#endif
}
Example #11
0
BitcoinGUI::BitcoinGUI(bool fIsTestnet, QWidget *parent) :
    QMainWindow(parent),
    clientModel(0),
    walletFrame(0),
    encryptWalletAction(0),
    changePassphraseAction(0),
    aboutQtAction(0),
    trayIcon(0),
    notificator(0),
    rpcConsole(0),
    prevBlocks(0),
    spinnerFrame(0)
{
    GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this);

    QString windowTitle = tr("Horuscoin Core") + " - ";
#ifdef ENABLE_WALLET
    /* if compiled with wallet support, -disablewallet can still disable the wallet */
    bool enableWallet = !GetBoolArg("-disablewallet", false);
#else
    bool enableWallet = false;
#endif
    if(enableWallet)
    {
        windowTitle += tr("Wallet");
    } else {
        windowTitle += tr("Node");
    }

    if (!fIsTestnet)
    {
#ifndef Q_OS_MAC
        QApplication::setWindowIcon(QIcon(":icons/bitcoin"));
        setWindowIcon(QIcon(":icons/bitcoin"));
#else
        MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin"));
#endif
    }
    else
    {
        windowTitle += " " + tr("[testnet]");
#ifndef Q_OS_MAC
        QApplication::setWindowIcon(QIcon(":icons/bitcoin_testnet"));
        setWindowIcon(QIcon(":icons/bitcoin_testnet"));
#else
        MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
#endif
    }
    setWindowTitle(windowTitle);

#if defined(Q_OS_MAC) && QT_VERSION < 0x050000
    // This property is not implemented in Qt 5. Setting it has no effect.
    // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras.
    setUnifiedTitleAndToolBarOnMac(true);
#endif

    rpcConsole = new RPCConsole(enableWallet ? this : 0);
#ifdef ENABLE_WALLET
    if(enableWallet)
    {
        /** Create wallet frame and make it the central widget */
        walletFrame = new WalletFrame(this);
        setCentralWidget(walletFrame);
    } else
#endif
    {
        /* When compiled without wallet or -disablewallet is provided,
         * the central widget is the rpc console.
         */
        setCentralWidget(rpcConsole);
    }

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

    // Create actions for the toolbar, menu bar and tray/dock icon
    // Needs walletFrame to be initialized
    createActions(fIsTestnet);

    // Create application menu bar
    createMenuBar();

    // Create the toolbars
    createToolBars();

    // Create system tray icon and notification
    createTrayIcon(fIsTestnet);

    // 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();
    labelConnectionsIcon = new QLabel();
    labelBlocksIcon = new QLabel();
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelEncryptionIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelConnectionsIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelBlocksIcon);
    frameBlocksLayout->addStretch();

    // 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 = QApplication::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);

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

    // Install event filter to be able to catch status tip events (QEvent::StatusTip)
    this->installEventFilter(this);

    // Initially wallet actions should be disabled
    setWalletActionsEnabled(false);

    // Subscribe to notifications from core
    subscribeToCoreSignals();
}
Example #12
0
/**
 * Construct a settings dialog. The actions in the list should have
 * a "defaultshortcut" property for reset to default to work.
 *
 * @param actions list of customizeable actions (for shortcut editing)
 * @param parent parent widget
 */
SettingsDialog::SettingsDialog(QWidget *parent)
	: QDialog(parent)
{
	_ui = new Ui_SettingsDialog;
	_ui->setupUi(this);

	connect(_ui->buttonBox, SIGNAL(accepted()), this, SLOT(rememberSettings()));
	connect(_ui->buttonBox, SIGNAL(accepted()), this, SLOT(saveCertTrustChanges()));
	connect(_ui->buttonBox->button(QDialogButtonBox::Reset), SIGNAL(clicked()), this, SLOT(resetSettings()));

	connect(_ui->pickFfmpeg, &QToolButton::clicked, [this]() {
		QString path = QFileDialog::getOpenFileName(this, tr("Set ffmepg path"), _ui->ffmpegpath->text(),
#ifdef Q_OS_WIN
			tr("Executables (%1)").arg("*.exe") + ";;" +
#endif
			QApplication::tr("All files (*)")
		);
		if(!path.isEmpty())
			_ui->ffmpegpath->setText(path);
	});

	connect(_ui->pickRecordingFolder, &QToolButton::clicked, [this]() {
		QString path = QFileDialog::getExistingDirectory(this, tr("Recording folder"), _ui->recordingFolder->text());
		if(!path.isEmpty())
			_ui->recordingFolder->setText(path);
	});

	connect(_ui->notificationVolume, &QSlider::valueChanged, [this](int val) {
		if(val>0)
			_ui->volumeLabel->setText(QString::number(val) + "%");
		else
			_ui->volumeLabel->setText(tr("off", "notifications sounds"));
	});

	// Get available languages
	_ui->languageBox->addItem(tr("Default"), QString());
	_ui->languageBox->addItem(QStringLiteral("English"), QStringLiteral("en"));

	const QLocale localeC = QLocale::c();
	QStringList locales;
	for(const QString &datapath : DrawpileApp::dataPaths()) {
		QStringList files = QDir(datapath + "/i18n").entryList(QStringList("drawpile_*.qm"), QDir::Files, QDir::Name);
		for(const QString &file : files) {
			QString localename = file.mid(9, file.length() - 3 - 9);
			QLocale locale(localename);
			if(locale != localeC && !locales.contains(localename)) {
				locales << localename;
				_ui->languageBox->addItem(locale.nativeLanguageName(), localename);
			}
		}
	}

	// Editable shortcuts
	_customShortcuts = new CustomShortcutModel(this);
	auto filteredShortcuts = new QSortFilterProxyModel(this);
	filteredShortcuts->setSourceModel(_customShortcuts);
	connect(_ui->shortcutFilter, &QLineEdit::textChanged, filteredShortcuts, &QSortFilterProxyModel::setFilterFixedString);
	filteredShortcuts->setFilterCaseSensitivity(Qt::CaseInsensitive);
	_ui->shortcuts->setModel(filteredShortcuts);
	_ui->shortcuts->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
	_ui->shortcuts->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);

	// QKeySequence editor delegate
	QStyledItemDelegate *keyseqdel = new QStyledItemDelegate(this);
	QItemEditorFactory *itemeditorfactory = new QItemEditorFactory;
	itemeditorfactory->registerEditor(QVariant::nameToType("QKeySequence"), new KeySequenceEditFactory);
	keyseqdel->setItemEditorFactory(itemeditorfactory);
	_ui->shortcuts->setItemDelegateForColumn(1, keyseqdel);

	// Known hosts list
	connect(_ui->knownHostList, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(viewCertificate(QListWidgetItem*)));
	connect(_ui->knownHostList, SIGNAL(itemSelectionChanged()), this, SLOT(certificateSelectionChanged()));
	connect(_ui->trustKnownHosts, SIGNAL(clicked()), this, SLOT(markTrustedCertificates()));
	connect(_ui->removeKnownHosts, SIGNAL(clicked()), this, SLOT(removeCertificates()));
	connect(_ui->importTrustedButton, SIGNAL(clicked()), this, SLOT(importTrustedCertificate()));

	QStringList pemfilter; pemfilter << "*.pem";
	QDir knownHostsDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/known-hosts/");

	for(const QString &filename : knownHostsDir.entryList(pemfilter, QDir::Files)) {
		auto *i = new QListWidgetItem(filename.left(filename.length()-4), _ui->knownHostList);
		i->setData(Qt::UserRole, false);
		i->setData(Qt::UserRole+1, knownHostsDir.absoluteFilePath(filename));
	}

	QDir trustedHostsDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/trusted-hosts/");
	QIcon trustedIcon("builtin:trusted.svg");
	for(const QString &filename : trustedHostsDir.entryList(pemfilter, QDir::Files)) {
		auto *i = new QListWidgetItem(trustedIcon, filename.left(filename.length()-4), _ui->knownHostList);
		i->setData(Qt::UserRole, true);
		i->setData(Qt::UserRole+1, trustedHostsDir.absoluteFilePath(filename));
	}

	// Session listing server list
	_listservers = new sessionlisting::ListServerModel(false, this);
	_ui->listserverview->setModel(_listservers);
	_ui->listserverview->setItemDelegate(new sessionlisting::ListServerDelegate(this));

	connect(_ui->addListServer, &QPushButton::clicked, this, &SettingsDialog::addListingServer);
	connect(_ui->removeListServer, &QPushButton::clicked, this, &SettingsDialog::removeListingServer);

	// Load configuration
	restoreSettings();
}
Example #13
0
void Result::create_inf_1()
{
    
	string inputCommand = "search*_*" + Connector::search_metric.toStdString();
    int clientfd_str= client::Clie_SockEstablish();
 	string url = Connector::ip.toStdString();
	client::Clie_ClientConnect(clientfd_str, (char *)url.c_str());
    client::Clie_SendCommand(clientfd_str, inputCommand.c_str());
	
    string n = client::Clie_GetResponse(clientfd_str);
    if (n == "Emtpy favourites") {
    	cout << "Emtpy favourites" << endl;
    	client::Clie_close(clientfd_str);
    	message_favorite->setText("No matched result found.");
		return;
  	}
    
    num_5 = atoi(n.c_str());
    
    vector<vector<string> > entry;
    for(int i=0; i<num_5;i++){
        cout << i << endl;
        int clientfdx = client::Clie_SockEstablish();;
        client::Clie_ClientConnect(clientfdx, (char *)url.c_str());
        string re = client::Clie_GetResponse(clientfdx);
        vector<string> s = client::split(re, "||||");
        assert(s.size() == 3);
        entry.push_back(s);
        Connector::result_entry[i] = s[0];
        
        client::Clie_SaveContent(clientfdx, (char *)url.c_str(), s[2]);
        client::Clie_close(clientfdx);
    }
    client::Clie_close(clientfd_str);
    assert((int)entry.size() == num_5);
    
    
    
    vertical_images_5 = new QGroupBox();
    QVBoxLayout *vertical_images_5_layout = new QVBoxLayout;
    
    if(num_5 <=5){
    	horizontal_images_5_1 = new QGroupBox();
    	QHBoxLayout *horizontal_images_5_1_layout = new QHBoxLayout;
        
    	for(int i = 0; i < num_5; i++){
            const char * button_3_str = entry[i][1].c_str();
    		QPushButton *button = new QPushButton();
    		button->setIcon(QIcon(entry[i][2].c_str()));
			button->setIconSize(QSize(120,200));
			button->setToolTip(tr(button_3_str));
			button->setFlat(true);
			result_buttons.push_back(button);
 			horizontal_images_5_1_layout->addWidget(result_buttons[i]);
    	}
    	horizontal_images_5_1->setLayout(horizontal_images_5_1_layout);
    	vertical_images_5_layout->addWidget(horizontal_images_5_1);
    	vertical_images_5->setLayout(vertical_images_5_layout);
        
    }else{
    	horizontal_images_5_2 = new QGroupBox();
    	QHBoxLayout *horizontal_images_5_2_layout = new QHBoxLayout;
    	horizontal_images_5_3 = new QGroupBox();
    	QHBoxLayout *horizontal_images_5_3_layout = new QHBoxLayout;
        
    	for(int i = 0; i < 5; i++){
            const char * button_3_str = entry[i][1].c_str();
            QPushButton *button = new QPushButton();
            button->setIcon(QIcon(entry[i][2].c_str()));
            button->setIconSize(QSize(120,200));
            button->setToolTip(tr(button_3_str));
            button->setFlat(true);
            result_buttons.push_back(button);
 			horizontal_images_5_2_layout->addWidget(result_buttons[i]);
            
    	}
    	horizontal_images_5_2->setLayout(horizontal_images_5_2_layout);
		horizontal_images_5_2->setFixedHeight(220);
        
        
    	for(int i = 5; i < num_5; i++){
            const char * button_3_str = entry[i][1].c_str();
            QPushButton *button = new QPushButton();
            button->setIcon(QIcon(entry[i][2].c_str()));
            button->setIconSize(QSize(120,200));
            button->setToolTip(tr(button_3_str));
            button->setFlat(true);
            result_buttons.push_back(button);
 			horizontal_images_5_3_layout->addWidget(result_buttons[i]);
    	}
    	horizontal_images_5_3->setLayout(horizontal_images_5_3_layout);
    	horizontal_images_5_3->setFixedHeight(220);
    	vertical_images_5_layout->addWidget(horizontal_images_5_2);
    	vertical_images_5_layout->addWidget(horizontal_images_5_3);
    	vertical_images_5->setLayout(vertical_images_5_layout);
    }
    
    
    
    if(num_5 == 1){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    }
    else if(num_5 == 2){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    	QObject::connect(result_buttons[1], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_2()));
    }
    else if(num_5 == 3){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    	QObject::connect(result_buttons[1], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_2()));
    	QObject::connect(result_buttons[2], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_3()));
    }
    else if(num_5 == 4){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    	QObject::connect(result_buttons[1], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_2()));
    	QObject::connect(result_buttons[2], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_3()));
    	QObject::connect(result_buttons[3], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_4()));
    }
    else if(num_5 == 5){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    	QObject::connect(result_buttons[1], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_2()));
    	QObject::connect(result_buttons[2], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_3()));
    	QObject::connect(result_buttons[3], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_4()));
    	QObject::connect(result_buttons[4], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_5()));
    }
    else if(num_5 == 6){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    	QObject::connect(result_buttons[1], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_2()));
    	QObject::connect(result_buttons[2], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_3()));
    	QObject::connect(result_buttons[3], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_4()));
    	QObject::connect(result_buttons[4], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_5()));
    	QObject::connect(result_buttons[5], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_6()));
    }
    else if(num_5 == 7){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    	QObject::connect(result_buttons[1], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_2()));
    	QObject::connect(result_buttons[2], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_3()));
    	QObject::connect(result_buttons[3], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_4()));
    	QObject::connect(result_buttons[4], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_5()));
    	QObject::connect(result_buttons[5], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_6()));
    	QObject::connect(result_buttons[6], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_7()));
    }
    else if(num_5 == 8){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    	QObject::connect(result_buttons[1], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_2()));
    	QObject::connect(result_buttons[2], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_3()));
    	QObject::connect(result_buttons[3], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_4()));
    	QObject::connect(result_buttons[4], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_5()));
    	QObject::connect(result_buttons[5], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_6()));
    	QObject::connect(result_buttons[6], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_7()));
    	QObject::connect(result_buttons[7], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_8()));
    }
    else if(num_5 == 9){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    	QObject::connect(result_buttons[1], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_2()));
    	QObject::connect(result_buttons[2], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_3()));
    	QObject::connect(result_buttons[3], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_4()));
    	QObject::connect(result_buttons[4], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_5()));
    	QObject::connect(result_buttons[5], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_6()));
    	QObject::connect(result_buttons[6], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_7()));
    	QObject::connect(result_buttons[7], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_8()));
    	QObject::connect(result_buttons[8], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_9()));
    }
    else if(num_5 == 10){
    	QObject::connect(result_buttons[0], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_1()));
    	QObject::connect(result_buttons[1], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_2()));
    	QObject::connect(result_buttons[2], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_3()));
    	QObject::connect(result_buttons[3], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_4()));
    	QObject::connect(result_buttons[4], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_5()));
    	QObject::connect(result_buttons[5], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_6()));
    	QObject::connect(result_buttons[6], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_7()));
    	QObject::connect(result_buttons[7], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_8()));
    	QObject::connect(result_buttons[8], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_9()));
    	QObject::connect(result_buttons[9], SIGNAL(clicked()),this, SLOT(handleButton_5_pic_10()));
    }
    
    
    
}
Example #14
0
void Result::create_back(){
	back_button_5 = new QPushButton(tr("<<Back"));
	back_button_5->setFlat(true);
	QObject::connect(back_button_5, SIGNAL(clicked()),this, SLOT(handleButton_5()));
}
void Polyhedron_demo_convex_hull_plugin::on_actionConvexHull_triggered()
{
  const Scene_interface::Item_id index = scene->mainSelectionIndex();
  
  Scene_polyhedron_item* poly_item = 
    qobject_cast<Scene_polyhedron_item*>(scene->item(index));

  Scene_points_with_normal_item* pts_item =
    qobject_cast<Scene_points_with_normal_item*>(scene->item(index));
  
  Scene_polylines_item* lines_item = 
    qobject_cast<Scene_polylines_item*>(scene->item(index));
  
  Scene_polyhedron_selection_item* selection_item = 
    qobject_cast<Scene_polyhedron_selection_item*>(scene->item(index));

  if(poly_item || pts_item || lines_item || selection_item)
  {
    // wait cursor
    QApplication::setOverrideCursor(Qt::WaitCursor);
    
    QTime time;
    time.start();
    std::cout << "Convex hull...";

    // add convex hull as new polyhedron
    Polyhedron *pConvex_hull = new Polyhedron;
    if(selection_item) {
      CGAL::convex_hull_3(
        boost::make_transform_iterator(selection_item->selected_vertices.begin(), Get_point()),
        boost::make_transform_iterator(selection_item->selected_vertices.end(), Get_point()),
        *pConvex_hull);
    }
    else if ( poly_item ){
      Polyhedron* pMesh = poly_item->polyhedron();  
      CGAL::convex_hull_3(pMesh->points_begin(),pMesh->points_end(),*pConvex_hull);
    }
    else{
      if (pts_item)
        CGAL::convex_hull_3(pts_item->point_set()->begin(),pts_item->point_set()->end(),*pConvex_hull);
      else{
        std::size_t nb_points=0;
        for(std::list<std::vector<Kernel::Point_3> >::const_iterator it = lines_item->polylines.begin();
            it != lines_item->polylines.end();
            ++it)  nb_points+=it->size();

        std::vector<Kernel::Point_3> all_points;
        all_points.reserve( nb_points );

        for(std::list<std::vector<Kernel::Point_3> >::const_iterator it = lines_item->polylines.begin();
            it != lines_item->polylines.end();
            ++it)  std::copy(it->begin(), it->end(),std::back_inserter( all_points ) );
        
        CGAL::convex_hull_3(all_points.begin(),all_points.end(),*pConvex_hull);
      }
    }
    std::cout << "ok (" << time.elapsed() << " ms)" << std::endl;

    Scene_polyhedron_item* new_item = new Scene_polyhedron_item(pConvex_hull);
    new_item->setName(tr("%1 (convex hull)").arg(scene->item(index)->name()));
    new_item->setColor(Qt::magenta);
    new_item->setRenderingMode(FlatPlusEdges);
    scene->addItem(new_item);

    // default cursor
    QApplication::restoreOverrideCursor();
  }
}
// Constructor
EditWindow::EditWindow(Screenshot* screenshot, QListWidget* listWidgetImage) : QMainWindow()
{
    this->screenshot = screenshot;
    this->listWidgetImage = listWidgetImage;
    this->newDrawingsList = screenshot->getDrawings();
    this->screenshotToShow = new QPixmap(screenshot->withDrawings());
    this->painterScreenshot = new QPainter(screenshotToShow);
    painterScreenshot->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);

    // Settings
    settings = new QSettings(this);

    // Pen
    QColor drawColor;
    drawColor.setRed(settings->value("EditWindow/drawColorR", QColor(Qt::red).red()).toInt());
    drawColor.setGreen(settings->value("EditWindow/drawColorG", QColor(Qt::red).green()).toInt());
    drawColor.setBlue(settings->value("EditWindow/drawColorB", QColor(Qt::red).blue()).toInt());
    drawPen.setColor(drawColor);
    drawPen.setWidth(settings->value("EditWindow/width", 2).toInt());
    painterScreenshot->setPen(drawPen);

    // Creation of the toolbar
    toolBar = new QToolBar(this);
    toolBar->setMovable(false);
    toolBar->setContextMenuPolicy(Qt::PreventContextMenu);

        actionValidate = toolBar->addAction(QIcon("://images/editwindow/validate.ico"), tr("Validate (Enter)"));
        actionValidate->setShortcut(QKeySequence(Qt::Key_Return));
        QObject::connect(actionValidate, SIGNAL(triggered()), this, SLOT(validate()));

        actionCancel = toolBar->addAction(QIcon("://images/editwindow/cancel.ico"), tr("Cancel (Escape)"));
        actionCancel->setShortcut(QKeySequence(Qt::Key_Escape));
        QObject::connect(actionCancel, SIGNAL(triggered()), this, SLOT(cancel()));

        // If we edit a fresh new screenshot...
        if(this->listWidgetImage != 0)
        {
            // ... we add the possibility to retake it
            actionRetake = toolBar->addAction(QIcon("://images/editwindow/retakescreenshot.ico"), tr("Retake the screenshot (Ctrl+N)"));
            actionRetake->setShortcut(QKeySequence::New);
            QObject::connect(actionRetake, SIGNAL(triggered()), this, SLOT(retake()));
        }

    toolBar->addSeparator();

        actionSave = toolBar->addAction(QIcon("://images/toolbar/save.ico"), tr("Save it (Ctrl+S)"));
        actionSave->setShortcut(QKeySequence::Save);
        QObject::connect(actionSave, SIGNAL(triggered()), this, SLOT(save()));

        actionCopyIntoClipboard = toolBar->addAction(QIcon("://images/editwindow/copytoclipboard.ico"), tr("Copy to clipboard (Ctrl+C)"));
        actionCopyIntoClipboard->setShortcut(QKeySequence::Copy);
        QObject::connect(actionCopyIntoClipboard, SIGNAL(triggered()), this, SLOT(copyIntoClipboard()));

        actionUpload = toolBar->addAction(QIcon("://images/toolbar/noelshack.ico"), tr("Upload to NoelShack (Ctrl+U)"));
        actionUpload->setShortcut(QKeySequence("Ctrl+U"));
        QObject::connect(actionUpload, SIGNAL(triggered()), this, SLOT(upload()));

    toolBar->addSeparator();

        sliderPenWidth = new QSlider(Qt::Horizontal, toolBar);
            sliderPenWidth->setToolTip(tr("Size of the drawing tools"));
            sliderPenWidth->setValue(drawPen.width());
            sliderPenWidth->setRange(1,10);
            sliderPenWidth->setFixedWidth(50);

    toolBar->addWidget(sliderPenWidth);

        spinBoxPenWidth = new QSpinBox(toolBar);
            spinBoxPenWidth->setToolTip(tr("Size of the drawing tools"));
            spinBoxPenWidth->setValue(sliderPenWidth->value());
            spinBoxPenWidth->setRange(1,10);
            spinBoxPenWidth->setFixedWidth(35);
            QObject::connect(sliderPenWidth, SIGNAL(valueChanged(int)), spinBoxPenWidth, SLOT(setValue(int)));
            QObject::connect(spinBoxPenWidth, SIGNAL(valueChanged(int)), sliderPenWidth, SLOT(setValue(int)));
            QObject::connect(spinBoxPenWidth, SIGNAL(valueChanged(int)), this, SLOT(changePenWidth(int)));

    toolBar->addWidget(spinBoxPenWidth);

    actionColor = toolBar->addAction(QIcon("://images/editwindow/color.ico"), tr("Color of the drawing tools"));
    QObject::connect(actionColor, SIGNAL(triggered()), this, SLOT(changePenColor()));

    toolBar->addSeparator();

        actionGroupDrawTool = new QActionGroup(toolBar);
        QObject::connect(actionGroupDrawTool, SIGNAL(triggered(QAction*)), this, SLOT(changeDrawingTool()));

            actionFreeLine = actionGroupDrawTool->addAction(QIcon("://images/editwindow/freeline.ico"), tr("Free line"));
            actionFreeLine->setCheckable(true);

            actionStraightLine = actionGroupDrawTool->addAction(QIcon("://images/editwindow/straightline.ico"), tr("Straight line"));
            actionStraightLine->setCheckable(true);

            actionFrame = actionGroupDrawTool->addAction(QIcon("://images/editwindow/frame.ico"), tr("Frame"));
            actionFrame->setCheckable(true);

            actionEraser = actionGroupDrawTool->addAction(QIcon("://images/editwindow/eraser.ico"), tr("Eraser"));
            actionEraser->setCheckable(true);

            // Activate the last drawing tool used by the user
            switch(settings->value("EditWindow/drawingTool", typeDrawTool(FREELINE)).toInt())
            {
                case FREELINE :
                actionFreeLine->setChecked(true);
                break;

                case STRAIGHTLINE :
                actionStraightLine->setChecked(true);
                break;

                case FRAME :
                actionFrame->setChecked(true);
                break;

                case ERASER :
                actionEraser->setChecked(true);
                break;
            }

    toolBar->addActions(actionGroupDrawTool->actions());

    this->addToolBar(toolBar);


    // Creation of the main widget
    widgetMain = new QWidget(this);
    this->setCentralWidget(widgetMain);

        // Creation of the layout of the window
        layout = new QHBoxLayout(widgetMain);
        layout->setContentsMargins(10,10,10,10);

            // If the screenshot is to big
            scrollArea = new QScrollArea(widgetMain);

                // Creation of the label which contain the image to display
                labelImage = new QLabel(scrollArea);
                labelImage->setPixmap(*this->screenshotToShow);
                labelImage->setFixedSize(this->screenshot->getImage().size());

            scrollArea->setWidget(labelImage);
            scrollArea->setAlignment(Qt::AlignCenter);
            scrollArea->setMaximumSize(QApplication::desktop()->screenGeometry().size() - QSize(175,175));
            QSize minimumSize(labelImage->size() + QSize(2,2));
            if(minimumSize.width() > scrollArea->maximumSize().width())
            {
                minimumSize.setWidth(scrollArea->maximumSize().width());
                minimumSize.setHeight(minimumSize.height() + scrollArea->horizontalScrollBar()->sizeHint().height());
            }
            if(minimumSize.height() > scrollArea->maximumSize().height())
            {
                minimumSize.setHeight(scrollArea->maximumSize().height());
                minimumSize.setWidth(minimumSize.width() + scrollArea->verticalScrollBar()->sizeHint().width());
            }
            scrollArea->setMinimumSize(minimumSize);

        // Add the scroll area to the layout
        layout->addWidget(scrollArea, Qt::AlignCenter);

    // Configuration of the window
    this->setWindowTitle(tr("Edit your screenshot"));
    this->setFixedSize(this->sizeHint());
    this->setWindowModality(Qt::ApplicationModal);
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setWindowFlags(Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
    this->show();
}
    QString waypoint;
    int row = -1;

    foreach (QModelIndex index, indexes) {
        row = proxy->mapToSource(index).row();
        QModelIndex nameIndex = tabel->index(row, 0, QModelIndex());
        QVariant varName = tabel->data(nameIndex, Qt::DisplayRole);
        name = varName.toString();

        QModelIndex waypointIndex = tabel->index(row, 1, QModelIndex());
        QVariant varAddr = tabel->data(waypointIndex, Qt::DisplayRole);
        waypoint = varAddr.toString();
    }

    AddDialog aDialog;
    aDialog.setWindowTitle(tr("Edit een waypoint"));

    aDialog.nameText->setReadOnly(true);
    aDialog.nameText->setText(name);
    aDialog.waypointText->setText(waypoint);

    if (aDialog.exec()) {
        QString newwaypoint = aDialog.waypointText->toPlainText();
        if (newwaypoint != waypoint) {
            QModelIndex index = tabel->index(row, 1, QModelIndex());
            tabel->setData(index, newwaypoint, Qt::EditRole);
        }
    }
}

void WaypointWidget::verwijderEntry()
Example #18
0
void TupCanvas::wakeUpLibrary()
{
    QString graphicPath = QFileDialog::getOpenFileName (this, tr("Import a SVG file..."), QDir::homePath(),
                                                    tr("Vector") + " (*.svg *.png *.jpg *.jpeg *.gif)");
    if (graphicPath.isEmpty())
        return;

    QFile f(graphicPath);
    QFileInfo fileInfo(f);

    if (graphicPath.toLower().endsWith(".svg")) {
        QString tag = fileInfo.fileName();

        if (f.open(QIODevice::ReadOnly)) {
            QByteArray data = f.readAll();
            f.close();
            // int projectWidth = k->size.width();
            // int projectHeight = k->size.height();

            TupProjectRequest request = TupRequestBuilder::createLibraryRequest(TupProjectRequest::Add, tag,
                                        TupLibraryObject::Svg, TupProject::FRAMES_EDITION, data, QString(),
                                        k->scene->currentSceneIndex(), k->scene->currentLayerIndex(), k->scene->currentFrameIndex());
            emit requestTriggered(&request);
        }
    } else {
        QString symName = fileInfo.fileName();

        if (f.open(QIODevice::ReadOnly)) {
            QByteArray data = f.readAll();
            f.close();

            QPixmap *pixmap = new QPixmap(graphicPath);
            int picWidth = pixmap->width();
            int picHeight = pixmap->height();
            int projectWidth = k->size.width(); 
            int projectHeight = k->size.height();

            if (picWidth > projectWidth || picHeight > projectHeight) {
                QDesktopWidget desktop;
                QMessageBox msgBox;
                msgBox.setWindowTitle(tr("Information"));
                msgBox.setIcon(QMessageBox::Question);
                msgBox.setText(tr("Image is bigger than workspace."));
                msgBox.setInformativeText(tr("Do you want to resize it?"));
                msgBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
                msgBox.setDefaultButton(QMessageBox::Ok);
                msgBox.show();
                msgBox.move((int) (desktop.screenGeometry().width() - msgBox.width())/2,
                            (int) (desktop.screenGeometry().height() - msgBox.height())/2);

                int answer = msgBox.exec();

                if (answer == QMessageBox::Yes) {
                    pixmap = new QPixmap();
                    QString extension = fileInfo.suffix().toUpper();
                    QByteArray ba = extension.toAscii();
                    const char* ext = ba.data();
                    if (pixmap->loadFromData(data, ext)) {
                        QPixmap newpix;
                        if (picWidth > projectWidth)
                            newpix = QPixmap(pixmap->scaledToWidth(projectWidth, Qt::SmoothTransformation));
                        else
                            newpix = QPixmap(pixmap->scaledToHeight(projectHeight, Qt::SmoothTransformation));
                        QBuffer buffer(&data);
                        buffer.open(QIODevice::WriteOnly);
                        newpix.save(&buffer, ext);
                    }
                }
           }

           QString tag = symName;

           TupProjectRequest request = TupRequestBuilder::createLibraryRequest(TupProjectRequest::Add, tag,
                                                                               TupLibraryObject::Image, TupProject::FRAMES_EDITION, data, QString(),
                                                                               k->scene->currentSceneIndex(), k->scene->currentLayerIndex(), k->scene->currentFrameIndex());
           emit requestTriggered(&request);

           data.clear();
        }
    }
}
Example #19
0
void frmMain::UpdateData5()
{
    int value=qrand()%100;
    gauge5->setValue(value);
    ui->labValue->setText(tr("当前值:%1").arg(value));
}
Example #20
0
TupCanvas::TupCanvas(QWidget *parent, Qt::WindowFlags flags, TupGraphicsScene *scene, 
                   const QPointF centerPoint, const QSize &screenSize, TupProject *project, double scaleFactor,
                   int angle, TupBrushManager *brushManager) : QFrame(parent, flags), k(new Private)
{
    setWindowTitle(tr("Tupi: 2D Magic"));
    setWindowIcon(QIcon(QPixmap(THEME_DIR + "icons/animation_mode.png")));

    k->scene = scene;
    k->size = project->dimension();
    k->currentColor = brushManager->penColor();
    k->brushManager = brushManager;
    k->project = project;

    graphicsView = new TupCanvasView(this, screenSize, k->size, project->bgColor());

    graphicsView->setScene(scene);
    graphicsView->centerOn(centerPoint);
    graphicsView->scale(scaleFactor, scaleFactor);
    graphicsView->rotate(angle);

    TImageButton *pencil = new TImageButton(QPixmap(THEME_DIR + "icons/pencil_big.png"), 40, this, true);
    pencil->setToolTip(tr("Pencil"));
    connect(pencil, SIGNAL(clicked()), this, SLOT(wakeUpPencil()));

    TImageButton *ink = new TImageButton(QPixmap(THEME_DIR + "icons/ink_big.png"), 40, this, true);
    ink->setToolTip(tr("Ink"));
    connect(ink, SIGNAL(clicked()), this, SLOT(wakeUpInk()));

    /*
    TImageButton *polyline = new TImageButton(QPixmap(THEME_DIR + "icons/polyline_big.png"), 40, this, true);
    polyline->setToolTip(tr("Polyline"));
    connect(polyline, SIGNAL(clicked()), this, SLOT(wakeUpPolyline()));
    */

    TImageButton *ellipse = new TImageButton(QPixmap(THEME_DIR + "icons/ellipse_big.png"), 40, this, true);
    ellipse->setToolTip(tr("Ellipse"));
    connect(ellipse, SIGNAL(clicked()), this, SLOT(wakeUpEllipse()));

    TImageButton *rectangle = new TImageButton(QPixmap(THEME_DIR + "icons/square_big.png"), 40, this, true);
    rectangle->setToolTip(tr("Rectangle"));
    connect(rectangle, SIGNAL(clicked()), this, SLOT(wakeUpRectangle()));

    TImageButton *images = new TImageButton(QPixmap(THEME_DIR + "icons/bitmap_big.png"), 40, this, true);
    images->setToolTip(tr("Images"));
    connect(images, SIGNAL(clicked()), this, SLOT(wakeUpLibrary()));

    TImageButton *objects = new TImageButton(QPixmap(THEME_DIR + "icons/selection_big.png"), 40, this, true);
    objects->setToolTip(tr("Object Selection"));
    connect(objects, SIGNAL(clicked()), this, SLOT(wakeUpObjectSelection()));

    TImageButton *nodes = new TImageButton(QPixmap(THEME_DIR + "icons/nodes_big.png"), 40, this, true);
    nodes->setToolTip(tr("Nodes Selection"));
    connect(nodes, SIGNAL(clicked()), this, SLOT(wakeUpNodeSelection()));

    TImageButton *trash = new TImageButton(QPixmap(THEME_DIR + "icons/delete_big.png"), 40, this, true);
    trash->setToolTip(tr("Delete Selection"));
    connect(trash, SIGNAL(clicked()), this, SLOT(wakeUpDeleteSelection()));

    TImageButton *zoomIn = new TImageButton(QPixmap(THEME_DIR + "icons/zoom_in_big.png"), 40, this, true);
    zoomIn->setToolTip(tr("Zoom In"));
    connect(zoomIn, SIGNAL(clicked()), this, SLOT(wakeUpZoomIn()));

    TImageButton *zoomOut = new TImageButton(QPixmap(THEME_DIR + "icons/zoom_out_big.png"), 40, this, true);
    zoomOut->setToolTip(tr("Zoom Out"));
    connect(zoomOut, SIGNAL(clicked()), this, SLOT(wakeUpZoomOut()));

    TImageButton *shift = new TImageButton(QPixmap(THEME_DIR + "icons/hand_big.png"), 40, this, true);
    shift->setToolTip(tr("Shift"));
    connect(shift, SIGNAL(clicked()), this, SLOT(wakeUpShift()));

    TImageButton *undo = new TImageButton(QPixmap(THEME_DIR + "icons/undo_big.png"), 40, this, true);
    undo->setToolTip(tr("Undo"));
    connect(undo, SIGNAL(clicked()), this, SLOT(undo()));

    TImageButton *redo = new TImageButton(QPixmap(THEME_DIR + "icons/redo_big.png"), 40, this, true);
    redo->setToolTip(tr("Redo"));
    connect(redo, SIGNAL(clicked()), this, SLOT(redo()));

    TImageButton *colors = new TImageButton(QPixmap(THEME_DIR + "icons/color_palette_big.png"), 40, this, true);
    colors->setToolTip(tr("Color Palette"));
    connect(colors, SIGNAL(clicked()), this, SLOT(colorDialog()));

    TImageButton *pen = new TImageButton(QPixmap(THEME_DIR + "icons/pen_properties.png"), 40, this, true);
    pen->setToolTip(tr("Pen Size"));
    connect(pen, SIGNAL(clicked()), this, SLOT(penDialog()));

    TImageButton *exposure = new TImageButton(QPixmap(THEME_DIR + "icons/exposure_sheet_big.png"), 40, this, true);
    exposure->setToolTip(tr("Exposure Sheet"));
    connect(exposure, SIGNAL(clicked()), this, SLOT(exposureDialog()));

    QBoxLayout *controls = new QBoxLayout(QBoxLayout::TopToBottom);
    controls->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
    controls->setContentsMargins(3, 3, 3, 3);
    controls->setSpacing(7);

    controls->addWidget(pencil);
    controls->addWidget(ink);
    // controls->addWidget(polyline);
    controls->addWidget(ellipse);
    controls->addWidget(rectangle);
    controls->addWidget(images);
    controls->addWidget(objects);
    controls->addWidget(nodes);
    controls->addWidget(trash);
    controls->addWidget(zoomIn);
    controls->addWidget(zoomOut);
    controls->addWidget(hand);

    controls->addWidget(undo);
    controls->addWidget(redo);
    controls->addWidget(colors);
    controls->addWidget(pen);
    controls->addWidget(exposure);

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(2);
    layout->addLayout(controls);
    layout->addWidget(graphicsView);

    setLayout(layout);
}
Example #21
0
void DownloadManager::updateItemCount()
{
    int count = m_downloads.count();
    itemCount->setText(count == 1 ? tr("1 Download") : tr("%1 Downloads").arg(count));
}
Example #22
0
/**
 * @brief FilesWidget::FilesWidget
 * @param parent
 */
FilesWidget::FilesWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FilesWidget)
{
    m_instance = this;
    ui->setupUi(this);
    ui->statusLabel->setText(tr("%n movies", "", 0));
#ifdef Q_OS_MAC
    QFont font = ui->files->font();
    font.setPointSize(font.pointSize()-2);
    ui->files->setFont(font);
#endif

#ifdef Q_OS_WIN32
    ui->verticalLayout->setContentsMargins(0, 0, 0, 1);
#endif

    m_lastMovie = 0;
    m_mouseIsIn = false;
    m_movieProxyModel = new MovieProxyModel(this);
    m_movieProxyModel->setSourceModel(Manager::instance()->movieModel());
    m_movieProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
    m_movieProxyModel->setDynamicSortFilter(true);
    ui->files->setModel(m_movieProxyModel);
    for (int i=1, n=ui->files->model()->columnCount() ; i<n ; ++i) {
        ui->files->setColumnWidth(i, 24);
        ui->files->setColumnHidden(i, true);
    }
    ui->files->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    ui->files->setIconSize(QSize(12, 12));

    foreach (const MediaStatusColumns &column, Settings::instance()->mediaStatusColumns())
        ui->files->setColumnHidden(MovieModel::mediaStatusToColumn(column), false);

    m_alphaList = new AlphabeticalList(this, ui->files);
    m_baseLabelCss = ui->sortByYear->styleSheet();
    m_activeLabelCss = ui->sortByNew->styleSheet();

    QMenu *mediaStatusColumnsMenu = new QMenu(tr("Media Status Columns"), ui->files);
    for (int i=MediaStatusFirst, n=MediaStatusLast ; i<=n ; ++i) {
        QAction *action = new QAction(MovieModel::mediaStatusToText(static_cast<MediaStatusColumns>(i)), this);
        action->setProperty("mediaStatusColumn", i);
        action->setCheckable(true);
        action->setChecked(Settings::instance()->mediaStatusColumns().contains(static_cast<MediaStatusColumns>(i)));
        connect(action, SIGNAL(triggered()), this, SLOT(onActionMediaStatusColumn()));
        mediaStatusColumnsMenu->addAction(action);
    }

    QMenu *labelsMenu = new QMenu(tr("Label"), ui->files);
    QMapIterator<int, QString> it(Helper::instance()->labels());
    while (it.hasNext()) {
        it.next();
        QAction *action = new QAction(it.value(), this);
        action->setIcon(Helper::instance()->iconForLabel(it.key()));
        action->setProperty("color", it.key());
        connect(action, SIGNAL(triggered()), this, SLOT(onLabel()));
        labelsMenu->addAction(action);
    }

    QAction *actionMultiScrape = new QAction(tr("Load Information"), this);
    QAction *actionMarkAsWatched = new QAction(tr("Mark as watched"), this);
    QAction *actionMarkAsUnwatched = new QAction(tr("Mark as unwatched"), this);
    QAction *actionLoadStreamDetails = new QAction(tr("Load Stream Details"), this);
    QAction *actionMarkForSync = new QAction(tr("Add to Synchronization Queue"), this);
    QAction *actionUnmarkForSync = new QAction(tr("Remove from Synchronization Queue"), this);
    QAction *actionOpenFolder = new QAction(tr("Open Movie Folder"), this);
    m_contextMenu = new QMenu(ui->files);
    m_contextMenu->addAction(actionMultiScrape);
    m_contextMenu->addSeparator();
    m_contextMenu->addAction(actionMarkAsWatched);
    m_contextMenu->addAction(actionMarkAsUnwatched);
    m_contextMenu->addSeparator();
    m_contextMenu->addAction(actionLoadStreamDetails);
    m_contextMenu->addSeparator();
    m_contextMenu->addAction(actionMarkForSync);
    m_contextMenu->addAction(actionUnmarkForSync);
    m_contextMenu->addSeparator();
    m_contextMenu->addAction(actionOpenFolder);
    m_contextMenu->addSeparator();
    m_contextMenu->addMenu(labelsMenu);
    m_contextMenu->addMenu(mediaStatusColumnsMenu);

    connect(actionMultiScrape, SIGNAL(triggered()), this, SLOT(multiScrape()));
    connect(actionMarkAsWatched, SIGNAL(triggered()), this, SLOT(markAsWatched()));
    connect(actionMarkAsUnwatched, SIGNAL(triggered()), this, SLOT(markAsUnwatched()));
    connect(actionLoadStreamDetails, SIGNAL(triggered()), this, SLOT(loadStreamDetails()));
    connect(actionMarkForSync, SIGNAL(triggered()), this, SLOT(markForSync()));
    connect(actionUnmarkForSync, SIGNAL(triggered()), this, SLOT(unmarkForSync()));
    connect(actionOpenFolder, SIGNAL(triggered()), this, SLOT(openFolder()));

    connect(ui->files, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint)));
    connect(ui->files->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(itemActivated(QModelIndex, QModelIndex)));
    connect(ui->files->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setAlphaListData()));
    connect(ui->files, SIGNAL(sigLeftEdge(bool)), this, SLOT(onLeftEdge(bool)));
    connect(ui->files, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(playMovie(QModelIndex)));

    connect(m_alphaList, SIGNAL(sigAlphaClicked(QString)), this, SLOT(scrollToAlpha(QString)));

    connect(ui->sortByNew, SIGNAL(clicked()), this, SLOT(onSortByNew()));
    connect(ui->sortByName, SIGNAL(clicked()), this, SLOT(onSortByName()));
    connect(ui->sortByLastAdded, SIGNAL(clicked()), this, SLOT(onSortByAdded()));
    connect(ui->sortBySeen, SIGNAL(clicked()), this, SLOT(onSortBySeen()));
    connect(ui->sortByYear, SIGNAL(clicked()), this, SLOT(onSortByYear()));

    connect(m_movieProxyModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(onViewUpdated()));
    connect(m_movieProxyModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(onViewUpdated()));
}
void JabberAddAccountWidget::createGui(bool showButtons)
{
  	QVBoxLayout *mainLayout = new QVBoxLayout(this);

	QWidget *formWidget = new QWidget(this);
	mainLayout->addWidget(formWidget);

	QFormLayout *layout = new QFormLayout(formWidget);

	QWidget *jidWidget = new QWidget(this);
	QGridLayout *jidLayout = new QGridLayout(jidWidget);
	jidLayout->setSpacing(0);
	jidLayout->setMargin(0);
	jidLayout->setColumnStretch(0, 2);
	jidLayout->setColumnStretch(2, 2);

	Username = new QLineEdit(this);
	connect(Username, SIGNAL(textEdited(QString)), this, SLOT(dataChanged()));
	jidLayout->addWidget(Username);

	AtLabel = new QLabel("@", this);
	jidLayout->addWidget(AtLabel, 0, 1);

	Domain = new QComboBox();
	Domain->setEditable(true);
	if (!Factory->allowChangeServer())
	{
		Domain->setVisible(false);
		AtLabel->setVisible(false);

		QString toolTip = Factory->whatIsMyUsername();
		if (!toolTip.isEmpty())
		{
			QLabel *whatIsMyUsernameLabel = new QLabel(tr("<a href='#'>What is my username?</a>"), this);
			whatIsMyUsernameLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse);
			jidLayout->addWidget(whatIsMyUsernameLabel, 0, 2, Qt::AlignRight);

			connect(whatIsMyUsernameLabel, SIGNAL(linkActivated(QString)), this, SLOT(showWhatIsMyUsername()));
		}
	}
	else
	{
		connect(Domain, SIGNAL(currentIndexChanged(QString)), this, SLOT(dataChanged()));
		connect(Domain, SIGNAL(editTextChanged(QString)), this, SLOT(dataChanged()));
	}
	jidLayout->addWidget(Domain, 0, 2);

	layout->addRow(tr("Username") + ':', jidWidget);

	AccountPassword = new QLineEdit(this);
	connect(AccountPassword, SIGNAL(textEdited(QString)), this, SLOT(dataChanged()));
	AccountPassword->setEchoMode(QLineEdit::Password);
	layout->addRow(tr("Password") + ':', AccountPassword);

	RememberPassword = new QCheckBox(tr("Remember Password"), this);
	layout->addRow(0, RememberPassword);

	Identity = new IdentitiesComboBox(this);
	connect(Identity, SIGNAL(currentIndexChanged(int)), this, SLOT(dataChanged()));
	layout->addRow(tr("Account Identity") + ':', Identity);

	QLabel *infoLabel = new QLabel(tr("<font size='-1'><i>Select or enter the identity that will be associated with this account.</i></font>"), this);
	infoLabel->setWordWrap(true);
	infoLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft);
	infoLabel->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
	layout->addRow(0, infoLabel);

	mainLayout->addStretch(100);

	QDialogButtonBox *buttons = new QDialogButtonBox(Qt::Horizontal, this);
	mainLayout->addWidget(buttons);

	AddAccountButton = new QPushButton(qApp->style()->standardIcon(QStyle::SP_DialogApplyButton), tr("Add Account"), this);
	QPushButton *cancelButton = new QPushButton(qApp->style()->standardIcon(QStyle::SP_DialogCancelButton), tr("Cancel"), this);

	buttons->addButton(AddAccountButton, QDialogButtonBox::AcceptRole);
	buttons->addButton(cancelButton, QDialogButtonBox::DestructiveRole);

	connect(AddAccountButton, SIGNAL(clicked(bool)), this, SLOT(apply()));
	connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(cancel()));

	if (!showButtons)
		buttons->hide();
}
Example #24
0
void XZProcessExecute::run()
{
    xzconfig.Log(LOG_INFO,"begin to process xz_execute item");
    emit this->ChangeStatus(QString("Running..."));
    if(lisExecute == 0 || lisHostInfo == 0)
    {
        xzconfig.Log(LOG_ERROR,"XZProcessExecute::process : input parameter not corrent!");
        return;
    }

    xzconfig.Log(LOG_INFO, QString("sizeof(lisExecute) = ") + QString::number(lisExecute->size()));
    for(QList<DB_XZ_EXECUTE>::Iterator cur = this->lisExecute->begin();
        cur != this->lisExecute->end();
        cur ++)
    {
        if(this->stop_flag == 1)
        {
            this->stop_flag = 0;
            break;
        }

        xzconfig.Log(LOG_OUTPUT,QString(tr("Current Item: ") + QString::number(cur - this->lisExecute->begin() + 1) + '|' + cur->Name));

        emit this->CurrentExecuteNo(cur - this->lisExecute->begin() + 1);

        //xzconfig.Log(LOG_INFO, QString("sizeof(lisHostInfo) = ") + QString::number(lisHostInfo->size()));
        QList<DB_XZ_HOSTINFO>::Iterator iter;
        for(iter = lisHostInfo->begin();
            iter != lisHostInfo->end();
            iter ++)
        {
            //xzconfig.Log(LOG_INFO, QString("iter->key = ") + QString::number(iter->Key) + "; cur->Key = " + QString::number(cur->Key));
            if (iter->Key == cur->Host)
            {
                if(cssh->xzssh_connect(iter->IP,22,iter->User,iter->Passwd))
                {
                    xzconfig.Log(LOG_ERROR,QString(tr("Cannot connect to the server:")) + iter->IP);
                    return;
                }
                xzconfig.Log(LOG_OUTPUT,QString(tr("Connected to the server:")) + iter->Name);
                if(cur->Type == 1)
                {
                    QFileInfo fi(cur->Command);
                    if(cssh->xzssh_sftpGet(cur->Command,(QString("recv/") + fi.fileName())))
                    {
                        xzconfig.Log(LOG_ERROR,QString(tr("Cannot get the file:"))
                                     + cur->Command
                                     + tr(", ErrDesc: ") + cssh->xzssh_getErrMsg());
                        emit this->ChangeStatus(QString("ready"));
                        emit this->CurrentExecuteNo(0);
                        return;
                    }
                    xzconfig.Log(LOG_OUTPUT,QString("Successfully get file: ") + cur->Command);
                }
                else if(cur->Type == 0)
                {
                    if(cssh->xzssh_exec(cur->Command,NULL))
                    {
                        xzconfig.Log(LOG_ERROR,QString(tr("Cannot execute the command:"))
                                     + cur->Command
                                     + tr(", ErrDesc: ") + cssh->xzssh_getErrMsg());
                        emit this->ChangeStatus(QString("ready"));
                        emit this->CurrentExecuteNo(0);
                        return;
                    }
                    xzconfig.Log(LOG_OUTPUT,QString("Successfully execute command: ") + cur->Command);
                }

                break;
            }
        }
        if (iter == lisHostInfo->end())
        {
            xzconfig.Log(LOG_ERROR,QString(tr("Cannot find Hostinfo ID: ")) + QString:: number(cur->Host));
        }
    }
    emit this->CurrentExecuteNo(0);
    emit this->ChangeStatus(QString("ready"));
    return;
}
Example #25
0
void AskPassphraseDialog::accept()
{
    SecureString oldpass, newpass1, newpass2;
    if(!model)
        return;
    oldpass.reserve(MAX_PASSPHRASE_SIZE);
    newpass1.reserve(MAX_PASSPHRASE_SIZE);
    newpass2.reserve(MAX_PASSPHRASE_SIZE);
    // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    // Alternately, find a way to make this input mlock()'d to begin with.
    oldpass.assign(ui->passEdit1->text().toStdString().c_str());
    newpass1.assign(ui->passEdit2->text().toStdString().c_str());
    newpass2.assign(ui->passEdit3->text().toStdString().c_str());

    switch(mode)
    {
    case Encrypt: {
        if(newpass1.empty() || newpass2.empty())
        {
            // Cannot encrypt with empty passphrase
            break;
        }
        QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
                 tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SOMAECULECOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
                 QMessageBox::Yes|QMessageBox::Cancel,
                 QMessageBox::Cancel);
        if(retval == QMessageBox::Yes)
        {
            if(newpass1 == newpass2)
            {
                if(model->setWalletEncrypted(true, newpass1))
                {
                    QMessageBox::warning(this, tr("Wallet encrypted"),
                                         "<qt>" +
                                         tr("Somacoin will close now to finish the encryption process. "
                                         "Remember that encrypting your wallet cannot fully protect "
                                         "your coins from being stolen by malware infecting your computer.") +
                                         "<br><br><b>" +
                                         tr("IMPORTANT: Any previous backups you have made of your wallet file "
                                         "should be replaced with the newly generated, encrypted wallet file. "
                                         "For security reasons, previous backups of the unencrypted wallet file "
                                         "will become useless as soon as you start using the new, encrypted wallet.") +
                                         "</b></qt>");
                    QApplication::quit();
                }
                else
                {
                    QMessageBox::critical(this, tr("Wallet encryption failed"),
                                         tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
                }
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The supplied passphrases do not match."));
            }
        }
        else
        {
            QDialog::reject(); // Cancelled
        }
        } break;
    case Unlock:
        if(!model->setWalletLocked(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet unlock failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            QDialog::accept(); // Success
        }
        break;
    case Decrypt:
        if(!model->setWalletEncrypted(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet decryption failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            QDialog::accept(); // Success
        }
        break;
    case ChangePass:
        if(newpass1 == newpass2)
        {
            if(model->changePassphrase(oldpass, newpass1))
            {
                QMessageBox::information(this, tr("Wallet encrypted"),
                                     tr("Wallet passphrase was successfully changed."));
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The passphrase entered for the wallet decryption was incorrect."));
            }
        }
        else
        {
            QMessageBox::critical(this, tr("Wallet encryption failed"),
                                 tr("The supplied passphrases do not match."));
        }
        break;
    }
}
Example #26
0
/**
 * Initializes all the elements in the Soldier Armor window.
 * @param game Pointer to the core game.
 * @param base Pointer to the base to get info from.
 * @param soldier ID of the selected soldier.
 */
SoldierArmorState::SoldierArmorState(Base *base, size_t soldier) : _base(base), _soldier(soldier)
{
	_screen = false;

	// Create objects
	_window = new Window(this, 192, 120, 64, 40, POPUP_BOTH);
	_btnCancel = new TextButton(140, 16, 90, 136);
	_txtTitle = new Text(182, 16, 69, 48);
	_txtType = new Text(90, 9, 80, 72);
	_txtQuantity = new Text(70, 9, 190, 72);
	_lstArmor = new TextList(160, 40, 73, 88);

	// Set palette
	setInterface("soldierArmor");

	add(_window, "window", "soldierArmor");
	add(_btnCancel, "button", "soldierArmor");
	add(_txtTitle, "text", "soldierArmor");
	add(_txtType, "text", "soldierArmor");
	add(_txtQuantity, "text", "soldierArmor");
	add(_lstArmor, "list", "soldierArmor");

	centerAllSurfaces();

	// Set up objects
	_window->setBackground(_game->getMod()->getSurface("BACK14.SCR"));

	_btnCancel->setText(tr("STR_CANCEL_UC"));
	_btnCancel->onMouseClick((ActionHandler)&SoldierArmorState::btnCancelClick);
	_btnCancel->onKeyboardPress((ActionHandler)&SoldierArmorState::btnCancelClick, Options::keyCancel);

	Soldier *s = _base->getSoldiers()->at(_soldier);
	_txtTitle->setAlign(ALIGN_CENTER);
	_txtTitle->setText(tr("STR_SELECT_ARMOR_FOR_SOLDIER").arg(s->getName()));

	_txtType->setText(tr("STR_TYPE"));

	_txtQuantity->setText(tr("STR_QUANTITY_UC"));

	_lstArmor->setColumns(2, 132, 21);
	_lstArmor->setSelectable(true);
	_lstArmor->setBackground(_window);
	_lstArmor->setMargin(8);

	const std::vector<std::string> &armors = _game->getMod()->getArmorsList();
	for (std::vector<std::string>::const_iterator i = armors.begin(); i != armors.end(); ++i)
	{
		Armor *a = _game->getMod()->getArmor(*i);
		if (_base->getItems()->getItem(a->getStoreItem()) > 0)
		{
			_armors.push_back(a);
			std::wostringstream ss;
			if (_game->getSavedGame()->getMonthsPassed() > -1)
			{
				ss << _base->getItems()->getItem(a->getStoreItem());
			}
			else
			{
				ss << "-";
			}
			_lstArmor->addRow(2, tr(a->getType()).c_str(), ss.str().c_str());
		}
		else if (a->getStoreItem() == "STR_NONE")
		{
			_armors.push_back(a);
			_lstArmor->addRow(1, tr(a->getType()).c_str());
		}
	}
	_lstArmor->onMouseClick((ActionHandler)&SoldierArmorState::lstArmorClick);
}
Example #27
0
STMainWindow::STMainWindow(QWidget *parent) : QMainWindow(parent) {
	ui.setupUi(this);
	
	ui.tabWidget->clear();
	
	ui.actionExportToScanner->setEnabled(exports_are_enabled());
	
	//ui.actionOpenSequenceFromWeb->setEnabled(false);
	
	connect(ui.actionNewSequence,SIGNAL(triggered()),this,SLOT(slot_new_sequence()));
	connect(ui.actionOpenSequence,SIGNAL(triggered()),this,SLOT(slot_open_sequence()));
	//connect(ui.actionOpenSequenceFromWeb,SIGNAL(triggered()),this,SLOT(slot_open_sequence_from_web()));
	connect(ui.actionCloseSequence,SIGNAL(triggered()),this,SLOT(slot_close_sequence()));
	connect(ui.actionSaveSequence,SIGNAL(triggered()),this,SLOT(slot_save_sequence()));
	connect(ui.actionSaveSequenceAs,SIGNAL(triggered()),this,SLOT(slot_save_sequence_as()));
	connect(ui.actionUploadSequenceToWeb,SIGNAL(triggered()),this,SLOT(slot_upload_sequence_to_web()));
	
	connect(ui.actionCopyNode,SIGNAL(triggered()),this,SLOT(slot_copy_node()));
	connect(ui.actionPasteNode,SIGNAL(triggered()),this,SLOT(slot_paste_node()));
	
	connect(ui.actionCompile,SIGNAL(triggered()),this,SLOT(slot_compile()));
	
	connect(ui.actionAddResource,SIGNAL(triggered()),this,SLOT(slot_add_resource()));
	connect(ui.actionImportRFPulseWaveform,SIGNAL(triggered()),this,SLOT(slot_import_rf_pulse_waveform()));
	
	connect(ui.actionConfiguration,SIGNAL(triggered()),this,SLOT(slot_configuration()));
	connect(ui.actionExportToScanner,SIGNAL(triggered()),this,SLOT(slot_export_to_scanner()));
	connect(ui.actionUpdateExportToScanner,SIGNAL(triggered()),this,SLOT(slot_update_export_to_scanner()));
	connect(ui.actionExportToVirtualScanner,SIGNAL(triggered()),this,SLOT(slot_export_to_virtual_scanner()));
	connect(ui.actionReadRawData,SIGNAL(triggered()),this,SLOT(slot_read_raw_data()));
	connect(ui.actionCreateParameterFile,SIGNAL(triggered()),this,SLOT(slot_create_parameter_file()));
	//connect(ui.actionUpdateCodeFromWeb,SIGNAL(triggered()),this,SLOT(slot_update_code_from_web()));
	ui.actionUpdateCodeFromWeb->setEnabled(false);
	
	connect(ui.actionChainLink,SIGNAL(triggered()),this,SLOT(slot_chainlink()));
	connect(ui.actionRTST,SIGNAL(triggered()),this,SLOT(slot_rtst()));
	connect(ui.actionMRPulseTool,SIGNAL(triggered()),this,SLOT(slot_mr_pulse_tool()));
	
	connect(ui.actionPreferences,SIGNAL(triggered()),this,SLOT(slot_preferences()));
	
	connect(ui.actionAboutSequenceTree,SIGNAL(triggered()),this,SLOT(slot_about_sequencetree()));
	connect(ui.actionSequenceTreeWiki,SIGNAL(triggered()),this,SLOT(slot_sequencetree_wiki()));
	
	connect(ui.tabWidget,SIGNAL(currentChanged(int)),this,SLOT(slot_current_changed()));
	
	#ifndef QT_WEB_KIT
	ui.actionOpenSequenceFromWeb->setEnabled(false);
	#endif
	
	ui.actionNewSequence->setShortcut(tr("Ctrl+N"));
	ui.actionOpenSequence->setShortcut(tr("Ctrl+O"));
	ui.actionSaveSequence->setShortcut(tr("Ctrl+S"));
	
	ui.actionCopyNode->setShortcut(tr("Ctrl+C"));
	ui.actionPasteNode->setShortcut(tr("Ctrl+V"));
	
	ui.actionCompile->setShortcut(tr("F9"));
	
	QToolButton *close_button=new QToolButton;
	close_button->setIcon(QIcon(":/images/cross.png"));
	connect(close_button,SIGNAL(clicked()),this,SLOT(slot_close_sequence()));
	ui.tabWidget->setCornerWidget(close_button);
	
	update_recent_file_menu();
	update_actions();
	
}
//virtual
void MTServerDetails::AddButtonClicked()
{
    MTWizardAddContract theWizard(this);

    theWizard.setWindowTitle(tr("Add Server Contract"));

    QString qstrDefaultValue("https://raw.github.com/FellowTraveler/Open-Transactions/master/sample-data/sample-contracts/cloud.otc");
    QVariant varDefault(qstrDefaultValue);

    theWizard.setField(QString("URL"), varDefault);

    if (QDialog::Accepted == theWizard.exec())
    {
        bool bIsImporting = theWizard.field("isImporting").toBool();
        bool bIsCreating  = theWizard.field("isCreating").toBool();

        if (bIsImporting)
        {
            bool bIsURL      = theWizard.field("isURL").toBool();
            bool bIsFilename = theWizard.field("isFilename").toBool();
            bool bIsContents = theWizard.field("isContents").toBool();

            if (bIsURL)
            {
                QString qstrURL = theWizard.field("URL").toString();
                // --------------------------------
                if (qstrURL.isEmpty())
                {
                    QMessageBox::warning(this, tr("URL is Empty"),
                        tr("No URL was provided."));

                    return;
                }

                QUrl theURL(qstrURL);
                // --------------------------------
                if (m_pDownloader)
                {
                    m_pDownloader->setParent(NULL);
                    m_pDownloader->disconnect();
                    m_pDownloader->deleteLater();

                    m_pDownloader = NULL;
                }
                // --------------------------------
                m_pDownloader = new FileDownloader(theURL, this);

                connect(m_pDownloader, SIGNAL(downloaded()), SLOT(DownloadedURL()));
            }
            // --------------------------------
            else if (bIsFilename)
            {
                QString fileName = theWizard.field("Filename").toString();

                if (fileName.isEmpty())
                {
                    QMessageBox::warning(this, tr("Filename is Empty"),
                        tr("No filename was provided."));

                    return;
                }
                // -----------------------------------------------
                QString qstrContents;
                QFile plainFile(fileName);

                if (plainFile.open(QIODevice::ReadOnly))//| QIODevice::Text)) // Text flag translates /n/r to /n
                {
                    QTextStream in(&plainFile); // Todo security: check filesize here and place a maximum size.
                    qstrContents = in.readAll();

                    plainFile.close();
                    // ----------------------------
                    if (qstrContents.isEmpty())
                    {
                        QMessageBox::warning(this, tr("File Was Empty"),
                                             QString("%1: %2").arg(tr("File was apparently empty")).arg(fileName));
                        return;
                    }
                    // ----------------------------
                }
                else
                {
                    QMessageBox::warning(this, tr("Failed Reading File"),
                                         QString("%1: %2").arg(tr("Failed trying to read file")).arg(fileName));
                    return;
                }
                // -----------------------------------------------
                ImportContract(qstrContents);
            }
            // --------------------------------
            else if (bIsContents)
            {
                QString qstrContents = theWizard.getContents();

                if (qstrContents.isEmpty())
                {
                    QMessageBox::warning(this, tr("Empty Contract"),
                        tr("Failure Importing: Contract is Empty."));
                    return;
                }
                // -------------------------
                ImportContract(qstrContents);
            }
        }
        // --------------------------------
        else if (bIsCreating)
        {

        }
    }
}
Tracker::Tracker(QWidget *parent)
    : QWidget(parent)
{
 //****************construct putton and widget************************//
    //Calendar Setting
    calendar = new QCalendarWidget;
    calendar->setGridVisible(true);

    QLabel *listname=new QLabel("                   Detail  Table");
    listname->setFont(QFont("Times", 16, QFont::Bold));

    listname->setStyleSheet("QLabel { background-color : rgb(255, 165, 0); color : black; }");
    detailList=new QListWidget;
    detailList->setStyleSheet( "QListWidget::item { background-color: white;border-bottom: 1px solid black; }"
                                  "QListWidget::item:selected{color: #333538;background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #cdcdcd, stop: 1 #ababab); border-top: 1px solid;border-top-color: #a8abad;border-bottom: 1px solid;border-bottom-color: #bfc7ce;}");

    removeButton=new QPushButton(tr("&REMOVE"));
    removeButton->setFont(QFont("Cambria", 14, QFont::Bold));
    QVBoxLayout *LayoutRight=new QVBoxLayout;
    LayoutRight->addWidget(listname,1);
    LayoutRight->addWidget(detailList,12);
    LayoutRight->setSpacing(3);
    LayoutRight->addWidget(removeButton,2);

    QHBoxLayout *Layout1=new QHBoxLayout;
    Layout1->addWidget(calendar,3);
    Layout1->addLayout(LayoutRight,2);

//Background Setting

    QString newpath (":/image/images/2.jpg");
    QPixmap pixmap = QPixmap(newpath).scaled(this->size());
    QPalette palette(this->palette());
    palette.setBrush(QPalette::Background, QBrush(pixmap));
    this->setPalette(palette);

//pushbutton declaration
    addExpenseButton = new QPushButton(tr("&Expense"));
    addExpenseButton->setFont(QFont("Cambria", 13, QFont::Bold));
    addIncomeButton= new QPushButton(tr("&Income"));
    addIncomeButton->setFont(QFont("Cambria", 13, QFont::Bold));
    shoppingListButton= new QPushButton(tr("&Shopping List"));
    shoppingListButton->setFont(QFont("Cambria", 13, QFont::Bold));
    reportButton = new QPushButton(tr("&Report"));
    reportButton->setFont(QFont("Cambria", 13, QFont::Bold));
    searchButton = new QPushButton(tr("&Search"));
    searchButton->setFont(QFont("Cambria", 13, QFont::Bold));
    searchLine = new QLineEdit;

    // Button horizontal layout
    QHBoxLayout *buttonLayout1 = new QHBoxLayout;
    buttonLayout1->addWidget(addExpenseButton,1);
    buttonLayout1->addWidget(addIncomeButton,1);
    buttonLayout1->addWidget(reportButton,1);
    buttonLayout1->addWidget(shoppingListButton,1);


    QHBoxLayout *searcharea = new QHBoxLayout;
    searcharea->addWidget(searchLine,3);
    searcharea->addWidget(searchButton,1);

    QVBoxLayout *left = new QVBoxLayout;
    left->addLayout(buttonLayout1);
    left->addLayout(searcharea);
   //right area

    settingbudget=new QPushButton(tr("Monthly Budget"));
    settingbudget->setFont(QFont("Times", 15, QFont::Bold));

    budget=new QLCDNumber;
    budget->setSegmentStyle(QLCDNumber::Filled);
    //budget->display(budgetAmount);

    QPushButton *ratiobar=new QPushButton(tr("Expense Ratio"));
    ratiobar->setFont(QFont("Times", 15, QFont::Bold));
    ratio=new QProgressBar;


   QGridLayout *showarea=new QGridLayout;
   showarea->setSpacing(20);
   showarea->addWidget(settingbudget,0,0);
   showarea->addWidget(budget,0,1);
   showarea->addWidget(ratiobar,1,0);
   showarea->addWidget(ratio,1,1);

   QHBoxLayout *Layout2=new QHBoxLayout;
   Layout2->addLayout(left,3);
   Layout2->addLayout(showarea,2);

   QVBoxLayout *mainLayout=new QVBoxLayout;
   mainLayout->addLayout(Layout1,10);
   mainLayout->addLayout(Layout2,3);
   setLayout(mainLayout);
   setWindowTitle("Basic Model");

//! [grid layout]
    setLayout(mainLayout);
    setWindowTitle(tr("Basic Model"));
    
//****************construct items and labels************************//
    
//        QDir currentDir;
//        QString path = currentDir.currentPath();
//    QString filePathE = path + "/../../../expense_data.csv";
//    QString filePathI = path + "/../../../income_data.csv";
//    QString filePathEL = path + "/../../../expense_labels.txt";
//    QString filePathIL = path + "/../../../income_labels.txt";
    QString homePath = QString(getenv("HOME"));
    //std::cout<<homePath.toStdString().c_str()<<std::endl;

    QDir *temp = new QDir;
    bool exist = temp->exists(homePath + "/.ExpenseTracker_withData");
    if(exist == 0)   temp->mkdir(homePath + "/.ExpenseTracker_withData");

    QString filePathE = homePath + "/.ExpenseTracker_withData/expense_data.csv";
    QString filePathI = homePath + "/.ExpenseTracker_withData/income_data.csv";
    QString filePathEL = homePath + "/.ExpenseTracker_withData/expense_labels.txt";
    QString filePathIL = homePath + "/.ExpenseTracker_withData/income_labels.txt";
    QString filePathB = homePath + "/.ExpenseTracker_withData/budget.txt";
    QString filePathSL = homePath + "/.ExpenseTracker_withData/shoppingList.csv";



    std::ifstream fin(filePathE.toStdString().c_str());
    if(!fin){

        QString dataPath (":/data/resource");
        QString filePathEd = dataPath + "/expense_data.csv";
        QString filePathId = dataPath + "/income_data.csv";
        QString filePathELd = dataPath + "/expense_labels.txt";
        QString filePathILd = dataPath + "/income_labels.txt";
        QString filePathBd = dataPath + "/budget.txt";
        QString filePathSLd = dataPath + "/shoppingList.csv";


        expenseItems = readData(filePathEd);
        incomeItems = readData(filePathId);
        expenseLabels = readLabel(filePathELd);
        incomeLabels = readLabel(filePathILd);
        budgetAmount = readBudget(filePathBd);
        shoppingItems = readShoppingList(filePathSLd);
        writeData(expenseItems, filePathE.toStdString().c_str());
        writeData(incomeItems, filePathI.toStdString().c_str());
        writeLabel(expenseLabels, filePathEL.toStdString().c_str());
        writeLabel(incomeLabels, filePathIL.toStdString().c_str());
        writeBudget(budgetAmount, filePathB.toStdString().c_str());
        writeShoppingList(shoppingItems, filePathSL.toStdString().c_str());


    }
    else{
        expenseItems = readData(filePathE.toStdString().c_str());
        incomeItems = readData(filePathI.toStdString().c_str());
        expenseLabels = readLabel(filePathEL.toStdString().c_str());
        incomeLabels = readLabel(filePathIL.toStdString().c_str());
        budgetAmount = readBudget(filePathB.toStdString().c_str());
        std::ifstream finSL(filePathSL.toStdString().c_str());
        if(finSL){
            shoppingItems = readShoppingList(filePathSL.toStdString().c_str());
        }
        else{
            shoppingItems = NULL;
        }
    }
    budget->display(budgetAmount);
    selectedDateChanged();
    double ratioValue = report_sum_M(QDate::currentDate().month(),QDate::currentDate().year(),expenseItems)/budgetAmount;
    if(ratioValue < 1){
       ratio->setValue(100*ratioValue);
    }
    else ratio->setValue(100);
    searchFlag = 0;
//******************connecting signals and slots***************************//
    connect(addExpenseButton, SIGNAL(clicked()), this, SLOT(addexpensewindow()));
    connect(addIncomeButton, SIGNAL(clicked()), this, SLOT(addincomewindow()));
    connect(reportButton, SIGNAL(clicked()), this, SLOT(report()));
    connect(calendar, SIGNAL(selectionChanged()), this, SLOT(selectedDateChanged()));
    connect(settingbudget, SIGNAL(clicked()), this, SLOT(settingBudget()));
    connect(removeButton, SIGNAL(clicked()), this, SLOT(removeItem()));
    connect(shoppingListButton, SIGNAL(clicked()), this, SLOT(checkShoppingList()));
    connect(searchButton, SIGNAL(clicked()), this, SLOT(searchItem()));
    connect(searchLine, SIGNAL(returnPressed()), this, SLOT(searchItem()));
}
Example #30
0
bool QuaMainWindow::IBFNewDocument()
{
    if ( this->isWindowModified() )
    {
        QMessageBox::StandardButton tStandardButton;

        tStandardButton = QMessageBox::warning(this, tr("Save document?"), tr("The document has been modified. Do you want to save your changes? Your changes will be lost if you don't save them."), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);

        if ( tStandardButton == QMessageBox::Save )
        {
            if ( !this->IBFSaveDocument() )
            {
                QMessageBox::critical(NULL, "Critical Error", "Something went wrong with this->IBFSaveDocument()...", QMessageBox::Ok);
                return false;
            }
        }
        else if ( tStandardButton == QMessageBox::Cancel )
        {
            return false;
        }
    }

    //QMessageBox::critical(NULL, "Critical Error", "So far so good...", QMessageBox::Ok);

    if ( !this->QuaCloseDocument() )
    {
        QMessageBox::critical(NULL, "Critical Error", "Something went wrong with this->QuaCloseDocument()...", QMessageBox::Ok);
        return false;
    }

    mIBFTemporaryDir = new QTemporaryDir();

    if ( !mIBFTemporaryDir->isValid() )
    {
        return false;
    }

    // create one folder and one file.

    mIBFFileSystemModel = new QFileSystemModel();
    mIBFFileSystemModel->setRootPath(mIBFTemporaryDir->path());
    mIBFFileSystemModel->setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
    mIBFFileSystemModel->setReadOnly(false);

    mIBFTreeView->setModel(mIBFFileSystemModel);
    mIBFTreeView->setRootIndex(mIBFFileSystemModel->index(mIBFTemporaryDir->path()));
    mIBFTreeView->setHeaderHidden(true);
    mIBFTreeView->setColumnHidden(1, true);
    mIBFTreeView->setColumnHidden(2, true);
    mIBFTreeView->setColumnHidden(3, true);
    mIBFTreeView->setWordWrap(true);

    QObject::connect(mIBFTreeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(on_mIBFTreeView_selectionChanged_triggered(const QModelIndex &, const QModelIndex &)));

    mIBFTreeView->setEnabled(true);
    mIBFTreeView->setFocus();

    this->setWindowModified(true);
    this->setWindowFilePath("");
    this->IBFUpdateTitle();

    return true;
}