Example #1
0
int tacticControl::findBestPlayerForPass()
{
int index = -1;
double min = 10000;
QList<int> ourAgents = wm->kn->ActiveAgents();
QList<int> freeAgents;
while( !ourAgents.isEmpty() )
{
int index = ourAgents.takeFirst();
if(isFree(index))
freeAgents.append(index);
}
while ( !freeAgents.isEmpty() )
{
int i = freeAgents.takeFirst();
if(wm->ourRobot[i].isValid && this->id != i)
{
if( (wm->ball.pos.loc-wm->ourRobot[i].pos.loc).length() < min)
{
min = (wm->ball.pos.loc-wm->ourRobot[i].pos.loc).length();
index = i;
}
}
}
return index;
}
Example #2
0
    void pushMatrixData(QString matrixName)
    {
        QString fileName = "/home/maltanar/spm-data/graph/" + matrixName;

        // TODO load matrix once & reuse for multiple SpMV iterations
        CSCGraph matrix(fileName);


        cout << "Loaded matrix " << matrixName.toStdString() << endl;
        cout << "Vertex count = " << matrix.rowCount() << endl;
        cout << "Edge count = " << matrix.nzCount() << endl;
        cout << "Input vector pointer = " << inpVecPtr << endl;
        cout << "Result vector pointer = " << resVecPtr << endl;

        sc_assert(io_state == 0);   // make sure we are in idle

        io_colCount = matrix.colCount();
        io_memDump = false;
        io_memFill = false;
        io_start = true;
        wait(2);
        io_start = false;

        sc_assert(io_state == 4); // should be in sReadColLen

        QList<CSCPtr> colLenData = matrix.getColLengths();
        QList<CSCPtr> rowIndData = matrix.getRowIndices();

        while (!colLenData.empty() || !rowIndData.empty())
        {
            if(!colLenData.empty())
            {
                unsigned int len = colLenData.takeFirst();
                // cout << "collen: " << len << endl;
                colLen.write(len);
            }
            if(!rowIndData.empty())
            {

                unsigned int y = rowIndData.takeFirst();
                //cout << "yind: " << y << endl;
                rowInd.write(y);
            }
        }

        cout << "Finished pushing matrix data, waiting for idle @" << NOW << endl;

        // wait until we go back to idle
        while(io_state != 0)
            wait(1);

        cout << "Column length transfers = " << colLenAdp.getTransferCount() << endl;
        cout << "Row index transfers = " << rowIndAdp.getTransferCount() << endl;
    }
Example #3
0
void pki_multi::probeAnything(const QString fname)
{
	pki_base *item = NULL;
	load_base *lb;
	QList<load_base *> lbs;

	lbs <<  new load_pem() <<
		new load_cert() << new load_pkcs7() << new load_pkcs12() <<
		new load_crl() <<  new load_req() <<   new load_key() <<
		new load_temp();

	foreach(lb, lbs) {
		try {
			item = lb->loadItem(fname);
			if (item) {
				multi.append(item);
				break;
			}
		} catch (errorEx &err) {
			if (err.info == E_PASSWD) {
				MainWindow::Error(err);
				break;
			}
		}
	}
	while (!lbs.isEmpty())
		delete lbs.takeFirst();
}
void AddJobDialog::dropEvent(QDropEvent *event)
{
	QString droppedFile;
	QList<QUrl> urls = event->mimeData()->urls();

	if(urls.count() > 1)
	{
		QDragEnterEvent dragEvent(event->pos(), event->proposedAction(), event->mimeData(), Qt::NoButton, Qt::NoModifier);
		if(qApp->notify(parent(), &dragEvent))
		{
			qApp->notify(parent(), event);
			reject(); return;
		}
	}

	while((!urls.isEmpty()) && droppedFile.isEmpty())
	{
		QUrl currentUrl = urls.takeFirst();
		QFileInfo file(currentUrl.toLocalFile());
		if(file.exists() && file.isFile())
		{
			qDebug("AddJobDialog::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
			droppedFile = file.canonicalFilePath();
		}
	}
	
	if(!droppedFile.isEmpty())
	{
		const QString outFileName = generateOutputFileName(droppedFile, currentOutputPath(), currentOutputIndx(), m_preferences->getSaveToSourcePath());
		ui->editSource->setText(QDir::toNativeSeparators(droppedFile));
		ui->editOutput->setText(QDir::toNativeSeparators(outFileName));
	}
}
Example #5
0
QList<QgsLineStringV2*> QgsGeometryUtils::extractLineStrings( const QgsAbstractGeometryV2* geom )
{
  QList< QgsLineStringV2* > linestrings;
  if ( !geom )
    return linestrings;

  QList< const QgsAbstractGeometryV2 * > geometries;
  geometries << geom;
  while ( ! geometries.isEmpty() )
  {
    const QgsAbstractGeometryV2* g = geometries.takeFirst();
    if ( const QgsCurveV2* curve = dynamic_cast< const QgsCurveV2* >( g ) )
    {
      linestrings << static_cast< QgsLineStringV2* >( curve->segmentize() );
    }
    else if ( const QgsGeometryCollectionV2* collection = dynamic_cast< const QgsGeometryCollectionV2* >( g ) )
    {
      for ( int i = 0; i < collection->numGeometries(); ++i )
      {
        geometries.append( collection->geometryN( i ) );
      }
    }
    else if ( const QgsCurvePolygonV2* curvePolygon = dynamic_cast< const QgsCurvePolygonV2* >( g ) )
    {
      if ( curvePolygon->exteriorRing() )
        linestrings << static_cast< QgsLineStringV2* >( curvePolygon->exteriorRing()->segmentize() );

      for ( int i = 0; i < curvePolygon->numInteriorRings(); ++i )
      {
        linestrings << static_cast< QgsLineStringV2* >( curvePolygon->interiorRing( i )->segmentize() );
      }
    }
  }
  return linestrings;
}
Example #6
0
QModelIndexList BtTreeModel::allChildren(QModelIndex ndx)
{
   QModelIndexList leafNodes;
   QList<BtTreeItem*> folders;
   int i;

   // Don't send an invalid index or something that isn't a folder
   if ( ! ndx.isValid() || type(ndx) != BtTreeItem::FOLDER )
      return leafNodes;

   BtTreeItem* start = item(ndx);
   folders.append(start);

   while ( ! folders.isEmpty() )
   {
      BtTreeItem* target = folders.takeFirst();

      for (i=0; i < target->childCount(); ++i)
      {
         BtTreeItem* next = target->child(i);
         // If a folder, push it onto the folders stack for later processing
         if ( next->type() == BtTreeItem::FOLDER ) 
            folders.append(next);
         else // Leafnode
            leafNodes.append(createIndex(i,0,next));
      }
   }
   return leafNodes;
}
Example #7
0
// this test more or less documents the behaviour of the mysql driver which allows nested transactions, which fail, without
// reporting an error
void SqlTransactionTests::testMySqlNestedTransactions()
{
    MySqlStorage storage = prepareMySqlStorage();
    QVERIFY(storage.database().open());

    QList<Task> tasksBefore = storage.getAllTasks();
    QVERIFY(!tasksBefore.isEmpty());
    Task first = tasksBefore.takeFirst();
    // test a simple transaction that is completed and committed:
    {
        SqlRaiiTransactor transactor(storage.database());
        QSqlQuery query(storage.database());
        query.prepare("DELETE from Tasks where id=:id");
        query.bindValue("id", first.id());
        QVERIFY(storage.runQuery(query));
        {   // now before the first transaction is committed and done, a second one is started
            // this should throw an exception
            SqlRaiiTransactor transactor2(storage.database());
            QSqlError error = storage.database().lastError();
            // QFAIL( "I should not get here." );
            transactor2.commit();
        }
        QSqlError error1 = storage.database().lastError();
        transactor.commit();
        QSqlError error2 = storage.database().lastError();
        QFAIL("I should not get here.");
    }
}
Example #8
0
int GetSiteList(QList<Bookmark*>  &siteList)
{
    while (!siteList.isEmpty())
        delete siteList.takeFirst();

    MSqlQuery query(MSqlQuery::InitCon());

    if (!query.exec("SELECT category, name, url, homepage FROM websites "
               "ORDER BY category, name"))
    {
        LOG(VB_GENERAL, LOG_ERR, "BookmarkManager: Error in loading from DB");
    }
    else
    {
        while (query.next())
        {
            Bookmark *site = new Bookmark();
            site->category = query.value(0).toString();
            site->name = query.value(1).toString();
            site->url = query.value(2).toString();
            site->isHomepage = query.value(3).toBool();
            site->selected = false;
            siteList.append(site);
        }
    }

    return siteList.size();
}
void DynamicDirectoryBasedPlaylistCreator::createPlaylistFromBaseDirectory() {
    // Wait 1s to enshure that all other modules are initialized before we fire any events!
    SleeperThread::msleep(1000);

    emit startupPlaylistGenerationStarted();
    initBaseDir();

    if ( _mediaDirectories.count() == 0 ) {
        emit startupPlaylistGenerationFinished();
        return;
    } else {
        QDir directory( _mediaDirectories.at( 0 ) );

        if ( ! directory.exists() ) {
            emit startupPlaylistGenerationFinished();
            return;
        }
    }

    QList<QPair<QUuid, QString>*>* discoverdMedia = readMediaFromMediaLibrary();
    readNewMediaFromFS( discoverdMedia );
    filterVanishedMedia( discoverdMedia );

    while( !discoverdMedia->empty() ) {
        delete discoverdMedia->takeFirst();
    }

    delete discoverdMedia;
    SimpleLogger::instance()->debug( Constants::LOGGER_PLAYLISTCREATOR, QString( "Playlist Creation finished" ) );
    emit startupPlaylistGenerationFinished();
    emit playlistGenerationFinished();
}
QStringList MSettingsLanguageBinary::keys() const
{
    QStringList keys;
    QList<MSettingsLanguageNode *> nodes;

    for (nodes.append(const_cast<MSettingsLanguageBinary *>(this)); !nodes.isEmpty();) {
        // Process the first node in the node list
        const MSettingsLanguageNode *node = nodes.takeFirst();

        // Append all children of the node to the node list
        nodes.append(node->children());

        const MSettingsLanguageSelection *selectionNode;
        const MSettingsLanguageInteger *intNode;
        const MSettingsLanguageText *textNode;
        const MSettingsLanguageBoolean *booleanNode;

        // Append the key of the node being processed (if any) to the key list
        if ((selectionNode = dynamic_cast<const MSettingsLanguageSelection *>(node))) {
            keys.append(selectionNode->key());
        } else if ((intNode = dynamic_cast<const MSettingsLanguageInteger *>(node))) {
            keys.append(intNode->key());
        } else if ((textNode = dynamic_cast<const MSettingsLanguageText *>(node))) {
            keys.append(textNode->key());
        } else if ((booleanNode = dynamic_cast<const MSettingsLanguageBoolean *>(node))) {
            keys.append(booleanNode->key());
        }
    }

    return keys;
}
Example #11
0
TabbableWidget* findActiveTab()
{
	QWidget* chat = QApplication::activeWindow();
	TabbableWidget* tw = 0;
	if(chat) {
		TabDlg* td = qobject_cast<TabDlg*>(chat);
		if(td) {
			tw = td->getCurrentTab();
		}
		else {
			tw = qobject_cast<TabbableWidget*>(chat);
			if (!tw) {
				QList<TabDlg*> tmp = chat->findChildren<TabDlg*>(); // all-in-one
				while(!tmp.isEmpty()) {
					TabDlg* td = tmp.takeFirst();
					tw = td->getCurrentTab();
					if(tw) {
						break;
					}
				}
			}
		}
	}
	return tw;
}
void ObjectManipulator::removeUserFolder()
{
    ObjectTreeViewItem *item = dynamic_cast<ObjectTreeViewItem *>
        (getCurrentObjectTree()->currentItem());
    if (item == 0 || item->getUserFolderParent() == 0) return;
    ObjectTreeViewItem *parent = dynamic_cast<ObjectTreeViewItem *>
        (item->parent());
    assert(parent != 0);

    vector<FWObject *> objs;
    for (int ii = 0; ii < item->childCount(); ii++) {
        ObjectTreeViewItem *child = dynamic_cast<ObjectTreeViewItem *>
            (item->child(ii));

        FWObject *obj = child->getFWObject();
        if (obj->getRO()) {
            QMessageBox::critical(this, "Firewall Builder",
                                  tr("Folder with locked object "
                                     "cannot be deleted"));
            return;
        }

        objs.push_back(obj);
    }

    if (objs.size() > 0) {
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
        ConfirmDeleteObjectDialog confirm(this);
        confirm.load(objs);
        QApplication::restoreOverrideCursor();
        if (confirm.exec() == QDialog::Rejected) return;
    }

    FWCmdMacro *macro = new FWCmdMacro(tr("Delete user folder"));

    QList<QTreeWidgetItem *> children = item->takeChildren();
    while (!children.isEmpty()) {
        ObjectTreeViewItem *child = dynamic_cast<ObjectTreeViewItem *>
            (children.takeFirst());
        assert(child != 0);

        FWObject *obj = child->getFWObject();
        if (mw->isEditorVisible() && mw->getOpenedEditor() == obj) {
            mw->hideEditor();
        }

        deleteObject(obj, macro);
    }

    FWCmdRemoveUserFolder *cmd =
        new FWCmdRemoveUserFolder(m_project, parent->getFWObject(),
                                  item->getUserFolderName(), "", macro);
    FWObject *newObj = cmd->getNewState();
    set<string> folders = stringToSet(newObj->getStr("subfolders"));
    folders.erase(item->getUserFolderName().toUtf8().constData());
    newObj->setStr("subfolders", setToString(folders));

    m_project->undoStack->push(macro);
}
Example #13
0
bool BtTreeModel::renameFolder(BtFolder* victim, QString newName)
{
   QModelIndex ndx = findFolder(victim->fullPath(), 0, false);
   QModelIndex pInd; 
   QString targetPath = newName % "/" % victim->name();
   QPair<QString,BtTreeItem*> f;
   QList<QPair<QString, BtTreeItem*> > folders;
   // This space is important       ^
   int i, kids,src;

   if ( ! ndx.isValid() )
      return false;

   pInd = parent(ndx);
   if ( ! pInd.isValid() )
      return false;

   BtTreeItem* start = item(ndx);
   f.first  = targetPath;
   f.second = start;

   folders.append(f);

   while ( ! folders.isEmpty() )
   {
      // This looks weird, but it is needed for later
      f = folders.takeFirst();
      targetPath = f.first;
      BtTreeItem* target = f.second;

      // As we move things, childCount changes. This makes sure we loop
      // through all of the kids
      kids = target->childCount();
      src = 0;
      // Ok. We have a start and an index.
      for (i=0; i < kids; ++i)
      {
         // This looks weird and it is. As we move children out, the 0 items
         // changes to the next child. In the case of a folder, though, we
         // don't move it, so we need to get the item beyond that.
         BtTreeItem* next = target->child(src);
         // If a folder, push it onto the folders stack for latter processing
         if ( next->type() == BtTreeItem::FOLDER ) 
         {
            QPair<QString,BtTreeItem*> newTarget;
            newTarget.first = targetPath % "/" % next->name();
            newTarget.second = next;
            folders.append(newTarget);
            src++;
         }
         else // Leafnode
            next->thing()->setFolder(targetPath);
      }
   }
   // Last thing is to remove the victim. 
   i = start->childNumber();
   return removeRows(i, 1, pInd); 
}
Example #14
0
bool MiniSceneRule::trigger(TriggerEvent event, Room* room, ServerPlayer *player, QVariant &data) const
{


    if(event == PhaseChange){
        if(player == room->getTag("Starter").value<PlayerStar>()){
            if(player->getPhase() == Player::Start){
                room->setTag("Round", room->getTag("Round").toInt()+1);

                if(!ex_options["beforeStartRound"].isNull()){
                    if(ex_options["beforeStartRound"].toInt() == room->getTag("Round").toInt()){
                        room->gameOver(ex_options["beforeStartRoundWinner"].toString());
                    }
                }
            }
            else if(player->getPhase() == Player::NotActive){
                if(!ex_options["afterRound"].isNull()){
                    if(ex_options["afterRound"].toInt() == room->getTag("Round").toInt()){
                        room->gameOver(ex_options["afterRoundWinner"].toString());
                    }
                }
            }
        }

        if(player->getPhase()==Player::Start && this->players.first()["beforeNext"] != NULL){
            if(player->tag["playerHasPlayed"].toBool())
                room->gameOver(this->players.first()["beforeNext"]);
            else player->tag["playerHasPlayed"] = true;
        }

        if(player->getPhase() != Player::NotActive)return false;
        if(player->getState() == "robot" || this->players.first()["singleTurn"] == NULL)
            return false;
        room->gameOver(this->players.first()["singleTurn"]);
    }

    if(player->getRoom()->getTag("WaitForPlayer").toBool())
        return true;

    LogMessage log;
    log.type = "#MiniSceneChanged";
    log.arg = id;
    log.arg2 = objectName();
    room->sendLog(log);
    log.type = QString("#mini_%1").arg(id);
    room->sendLog(log);

    QList<ServerPlayer*> players = room->getAllPlayers();
    while(players.first()->getState() == "robot")
        players.append(players.takeFirst());

    QStringList cards= setup.split(",");
    foreach(QString id,cards)
    {
        room->moveCardTo(Sanguosha->getCard(id.toInt()),NULL,Player::Special,true);
        room->moveCardTo(Sanguosha->getCard(id.toInt()),NULL,Player::DrawPile,true);
        room->broadcastInvoke("addHistory","pushPile");
    }
bool BtBookshelfTreeModel::setData(const QModelIndex &itemIndex,
                                   const QVariant &value,
                                   int role) {
    typedef QPair<Item *, QModelIndex> IP;

    Qt::CheckState newState;
    if (role == Qt::CheckStateRole) {
        bool ok;
        newState = (Qt::CheckState) value.toInt(&ok);
        if (!ok) return false;
    }
    else {
        return false;
    }

    // Handle partially checked as checked here in setData():
    if (newState == Qt::PartiallyChecked) newState = Qt::Checked;

    Item *item(static_cast<Item*>(itemIndex.internalPointer()));
    Q_ASSERT(item != 0);
    if (item->checkState() == newState) return false;

    // Recursively (un)check all children:
    QList<IP> q;
    IP p(item, itemIndex);
    for (;;) {
        if (item->checkState() != newState) {
            item->setCheckState(newState);
            emit dataChanged(p.second, p.second);
            if (item->type() == Item::ITEM_MODULE) {
                ModuleItem *mItem(static_cast<ModuleItem*>(item));
                CSwordModuleInfo *mInfo(mItem->moduleInfo());
                if (newState == Qt::Checked) {
                    m_checkedModulesCache.insert(mInfo);
                    emit moduleChecked(mInfo, true);
                }
                else {
                    m_checkedModulesCache.remove(mInfo);
                    emit moduleChecked(mInfo, false);
                }
            }
            else {
                const QList<Item*> &children(item->children());
                for (int i(0); i < children.size(); i++) {
                    q.append(IP(children.at(i), index(i, 0, p.second)));
                }
            }
        }
        if (q.empty()) break;
        p = q.takeFirst();
        item = p.first;
    }

    // Recursively change parent check states.
    resetParentCheckStates(itemIndex.parent());

    return true;
}
Example #16
0
XCursorTheme::XCursorTheme(const QDir &themeDir)
    : CursorTheme(themeDir.dirName())
{
    // Directory information
    setName(themeDir.dirName());
    setPath(themeDir.path());
    setIsWritable(QFileInfo(themeDir.path()).isWritable()); // ### perhaps this shouldn't be cached

    if (themeDir.exists("index.theme"))
        parseIndexFile();

    QString cursorFile = path() + "/cursors/left_ptr";
    QList<int> sizeList;
    XcursorImages *images = XcursorFilenameLoadAllImages(qPrintable(cursorFile));
    if (images)
    {
        for (int i = 0; i < images->nimage; ++i)
        {
            if (!sizeList.contains(images->images[i]->size))
                sizeList.append(images->images[i]->size);
        };
        XcursorImagesDestroy(images);
        qSort(sizeList.begin(), sizeList.end());
        m_availableSizes = sizeList;
    };
    if (!sizeList.isEmpty())
    {
        QString sizeListString = QString::number(sizeList.takeFirst());
        while (!sizeList.isEmpty())
        {
            sizeListString.append(", ");
            sizeListString.append(QString::number(sizeList.takeFirst()));
        };
        QString tempString = i18nc(
            "@info The argument is the list of available sizes (in pixel). Example: "
                "'Available sizes: 24' or 'Available sizes: 24, 36, 48'",
            "(Available sizes: %1)",
            sizeListString);
        if (m_description.isEmpty())
          m_description = tempString;
        else
          m_description = m_description + ' ' + tempString;
    };
}
Example #17
0
void TabOrderEditor::initTabOrder()
{
    m_tab_order_list.clear();

    QDesignerFormEditorInterface *core = formWindow()->core();

    if (const QDesignerMetaDataBaseItemInterface *item = core->metaDataBase()->item(formWindow())) {
        m_tab_order_list = item->tabOrder();
    }

    // Remove any widgets that have been removed form the form
    for (int i = 0; i < m_tab_order_list.size(); ) {
        QWidget *w = m_tab_order_list.at(i);
        if (!formWindow()->mainContainer()->isAncestorOf(w) || skipWidget(w))
            m_tab_order_list.removeAt(i);
        else
            ++i;
    }

    // Append any widgets that are in the form but are not in the tab order
    QList<QWidget *> childQueue;
    childQueue.append(formWindow()->mainContainer());
    while (!childQueue.isEmpty()) {
        QWidget *child = childQueue.takeFirst();
        childQueue += qVariantValue<QWidgetList>(child->property("_q_widgetOrder"));

        if (skipWidget(child))
            continue;

        if (!m_tab_order_list.contains(child))
            m_tab_order_list.append(child);
    }

    // Just in case we missed some widgets
    QDesignerFormWindowCursorInterface *cursor = formWindow()->cursor();
    for (int i = 0; i < cursor->widgetCount(); ++i) {

        QWidget *widget = cursor->widget(i);
        if (skipWidget(widget))
            continue;

        if (!m_tab_order_list.contains(widget))
            m_tab_order_list.append(widget);
    }

    m_indicator_region = QRegion();
    for (int i = 0; i < m_tab_order_list.size(); ++i) {
        if (m_tab_order_list.at(i)->isVisible())
            m_indicator_region |= indicatorRect(i);
    }

    if (m_current_index >= m_tab_order_list.size())
        m_current_index = m_tab_order_list.size() - 1;
    if (m_current_index < 0)
        m_current_index = 0;
}
Example #18
0
QList<QString> parseArguments(int argc, char *argv[])
{
	QList<QString> arguments;
	for(int i = 0; i < argc; i++)
	{
		arguments.append(argv[i]);
	}
	arguments.takeFirst();
	return arguments;
}
Example #19
0
void QGUICheckBoxCtrl::saveDamage()
{
    pfGUICheckBoxCtrl* ctrl = pfGUICheckBoxCtrl::Convert(fCreatable);

    ctrl->setAnimName(~fAnimName->text());
    ctrl->clearAnimKeys();
    QList<plKey> animKeys = fAnimationKeys->keys();
    while (!animKeys.isEmpty())
        ctrl->addAnimKey(animKeys.takeFirst());

    ctrl->setChecked(fValue->isChecked());
}
void TextToSpeechPrivate::ProcessSpeech() {
	QByteArray ba;

	qmLock.lock();
	ba = qlMessages.takeFirst();
	qmLock.unlock();

	NewSpeechChannel(NULL, &scChannel);
	SetSpeechInfo(scChannel, soVolume, &fVolume);
	SetSpeechInfo(scChannel, soRefCon, this);
	SetSpeechInfo(scChannel, soSpeechDoneCallBack, reinterpret_cast<void *>(speech_done_cb));
	SpeakText(scChannel, ba.constData(), ba.size());
}
void PsdSettingsPopup::onModeChanged(const QString &mode) {
  if (mode == "Single Image") {
    m_mode = FLAT;
    m_modeDescription->setText(modesDescription[0]);
    m_createSubXSheet->setEnabled(false);
    m_levelNameType->setEnabled(false);
    QList<QAbstractButton *> buttons = m_psdFolderOptions->buttons();
    while (!buttons.isEmpty()) {
      QAbstractButton *btn = buttons.takeFirst();
      btn->setEnabled(false);
    }
  } else if (mode == "Frames") {
    m_mode = FRAMES;
    m_modeDescription->setText(modesDescription[1]);
    m_createSubXSheet->setEnabled(false);
    m_levelNameType->setEnabled(false);
    QList<QAbstractButton *> buttons = m_psdFolderOptions->buttons();
    while (!buttons.isEmpty()) {
      QAbstractButton *btn = buttons.takeFirst();
      btn->setEnabled(false);
    }
  } else if (mode == "Columns") {
    if (m_psdFolderOptions->checkedId() == 2 ||
        m_psdFolderOptions->checkedId() == 1)
      m_mode = FOLDER;
    else
      m_mode = COLUMNS;
    m_modeDescription->setText(modesDescription[2]);
    m_createSubXSheet->setEnabled(true);
    m_levelNameType->setEnabled(true);
    QList<QAbstractButton *> buttons = m_psdFolderOptions->buttons();
    while (!buttons.isEmpty()) {
      QAbstractButton *btn = buttons.takeFirst();
      btn->setEnabled(true);
    }
  } else {
    assert(false);
  }
}
Example #22
0
void QMultistageBehMod::saveDamage()
{
    plMultistageBehMod* obj = plMultistageBehMod::Convert(fCreatable);

    obj->setFreezePhys(fFreezePhys->isChecked());
    obj->setSmartSeek(fSmartSeek->isChecked());
    obj->setReverseFBControlsOnRelease(fReverseControls->isChecked());

    obj->clearReceivers();
    QList<plKey> keys = fReceivers->keys();
    while (!keys.isEmpty())
        obj->addReceiver(keys.takeFirst());
}
Example #23
0
void WebPage::handleUnsupportedContent(QNetworkReply *reply)
{
    QString errorString = reply->errorString();

    if (m_loadingUrl != reply->url()) {
        // sub resource of this page
        qWarning() << "Resource" << reply->url().toEncoded() << "has unknown Content-Type, will be ignored.";
        reply->deleteLater();
        return;
    }

    if (reply->error() == QNetworkReply::NoError && !reply->header(QNetworkRequest::ContentTypeHeader).isValid()) {
        errorString = "Unknown Content-Type";
    }

    QFile file(QLatin1String(":/notfound.html"));
    bool isOpened = file.open(QIODevice::ReadOnly);
    Q_ASSERT(isOpened);
    Q_UNUSED(isOpened)

    QString title = tr("Error loading page: %1").arg(reply->url().toString());
    QString html = QString(QLatin1String(file.readAll()))
                        .arg(title)
                        .arg(errorString)
                        .arg(reply->url().toString());

    QBuffer imageBuffer;
    imageBuffer.open(QBuffer::ReadWrite);
    QIcon icon = view()->style()->standardIcon(QStyle::SP_MessageBoxWarning, 0, view());
    QPixmap pixmap = icon.pixmap(QSize(32,32));
    if (pixmap.save(&imageBuffer, "PNG")) {
        html.replace(QLatin1String("IMAGE_BINARY_DATA_HERE"),
                     QString(QLatin1String(imageBuffer.buffer().toBase64())));
    }

    QList<QWebEngineFrame*> frames;
    frames.append(mainFrame());
    while (!frames.isEmpty()) {
        QWebEngineFrame *frame = frames.takeFirst();
        if (frame->url() == reply->url()) {
            frame->setHtml(html, reply->url());
            return;
        }
        QList<QWebEngineFrame *> children = frame->childFrames();
        foreach (QWebEngineFrame *frame, children)
            frames.append(frame);
    }
    if (m_loadingUrl == reply->url()) {
        mainFrame()->setHtml(html, reply->url());
    }
}
Example #24
0
static QString wnToHtml(const QString &word, QByteArray &text)
{
    Q_UNUSED(word)
    QList<QByteArray> splitText = text.split('\n');
    QString def;
    def += QLatin1String("<dl>\n");
    QRegExp linkRx(QStringLiteral("\\{(.*)\\}"));
    linkRx.setMinimal(true);

    bool isFirst=true;
    while (!splitText.empty()) {
        //150 n definitions retrieved - definitions follow
        //151 word database name - text follows
        //250 ok (optional timing information here)
        //552 No match
        QString currentLine = splitText.takeFirst();
        if (currentLine.startsWith(QLatin1String("151"))) {
            isFirst = true;
            continue;
        }

        if (currentLine.startsWith('.')) {
            def += QLatin1String("</dd>");
            continue;
        }

        if (!(currentLine.startsWith(QLatin1String("150"))
                || currentLine.startsWith(QLatin1String("151"))
                || currentLine.startsWith(QLatin1String("250"))
                || currentLine.startsWith(QLatin1String("552")))) {
            currentLine.replace(linkRx,QLatin1String("<a href=\"\\1\">\\1</a>"));

            if (isFirst) {
                def += "<dt><b>" + currentLine + "</b></dt>\n<dd>";
                isFirst = false;
                continue;
            } else {
                if (currentLine.contains(QRegExp(QStringLiteral("([1-9]{1,2}:)")))) {
                    def += QLatin1String("\n<br>\n");
                }
                currentLine.replace(QRegExp(QStringLiteral("^([\\s\\S]*[1-9]{1,2}:)")), QLatin1String("<b>\\1</b>"));
                def += currentLine;
                continue;
            }
        }

    }

    def += QLatin1String("</dl>");
    return def;
}
void TabDialog::addSectionsToUI(QList< QMap<QString,QString> >& sections) {

    while(!sections.isEmpty()) {
        QWidget *tab = new QWidget();
        QFormLayout* layout = new QFormLayout;
        QMap<QString,QString> section = sections.takeFirst();

        QMap<QString, QString>::const_iterator iter = section.constBegin();
        while ( iter != section.constEnd()){
            layout->addRow(iter.key(), new QLineEdit(iter.value()));
            ++iter;
        }
        tab->setLayout(layout);
        this->tabWidget->addTab(tab, section.value("name", "Unknown"));
    }
}
Example #26
0
 void View::updateImage(int id, const QString &fileName)
 {
     QList<QGraphicsItem *> items = scene->items();

     while(!items.empty()) {
         QGraphicsItem *item = items.takeFirst();

         if (ImageItem *image = qgraphicsitem_cast<ImageItem *>(item)) {
             if (image->id() == id){
                 image->setPixmap(QPixmap(":/" +fileName));
                 image->adjust();
                 break;
             }
         }
     }
 }
Example #27
0
bool tacticControl::isFree(int index)
{
QList<int> oppAgents = wm->kn->ActiveOppAgents();
bool isFree = true;
while( !oppAgents.isEmpty() )
{
int indexOPP = oppAgents.takeFirst();
if( (wm->ourRobot[index].pos.loc-wm->oppRobot[indexOPP].pos.loc).length() < DangerDist)
{
isFree = false;
}
if(!isFree)
break;
}
return isFree;
}
    foreach( const QString &key, keys )
    {
        // --- commit the albums as compilation or normal album

        QList<CollectionScanner::Album*> albums = m_albumNames.values( key );
        // debug() << "commit got" <<albums.count() << "x" << key;

        // if we have multiple albums with the same name, check if it
        // might be a compilation

        for( int i = albums.count() - 1; i >= 0; --i )
        {
            CollectionScanner::Album *album = albums.at( i );
            // commit all albums with a track with the noCompilation flag
            if( album->isNoCompilation() ||
                    nonCompilationAlbumNames.contains( album->name(), Qt::CaseInsensitive ) )
                commitAlbum( albums.takeAt( i ) );
        }

        // only one album left. It's no compilation.
        if( albums.count() == 1 )
        {
            commitAlbum( albums.takeFirst() );
        }

        // compilation
        else if( albums.count() > 1 )
        {
            CollectionScanner::Album compilation( key, QString() );
            for( int i = albums.count() - 1; i >= 0; --i )
            {
                CollectionScanner::Album *album = albums.takeAt( i );
                foreach( CollectionScanner::Track *track, album->tracks() )
                    compilation.addTrack( track );
                compilation.setCovers( album->covers() + compilation.covers() );
            }
            commitAlbum( &compilation );
        }

        // --- unblock every 5 second. Maybe not really needed, but still nice
        if( blockedTime.secsTo( QDateTime::currentDateTime() ) >= 5 )
        {
            unblockUpdates();
            blockedTime = QDateTime::currentDateTime();
            blockUpdates();
        }
    }
Example #29
0
void DictEngine::getDicts()
{
    QMap<QString, QString> theHash;
    m_tcpSocket->readAll();
    QByteArray ret;

    m_tcpSocket->write(QByteArray("SHOW DB\n"));;
    m_tcpSocket->flush();

    m_tcpSocket->waitForReadyRead();
    while (!ret.contains("250")) {
        m_tcpSocket->waitForReadyRead();
        ret += m_tcpSocket->readAll();
    }

    QList<QByteArray> retLines = ret.split('\n');
    QString tmp1, tmp2;

    while (!retLines.empty()) {
        QString curr(retLines.takeFirst());

        if (curr.startsWith(QLatin1String("554"))) {
            //TODO: What happens if no DB available?
            //TODO: Eventually there will be functionality to change the server...
            break;
        }

        // ignore status code and empty lines
        if (curr.startsWith(QLatin1String("250")) || curr.startsWith(QLatin1String("110"))
                || curr.isEmpty()) {
            continue;
        }

        if (!curr.startsWith('-') && !curr.startsWith('.')) {
            curr = curr.trimmed();
            tmp1 = curr.section(' ', 0, 0);
            tmp2 = curr.section(' ', 1);
            //          theHash.insert(tmp1, tmp2);
            //qDebug() << tmp1 + "  " + tmp2;
            setData(QStringLiteral("list-dictionaries"), tmp1, tmp2);
        }
    }

    m_tcpSocket->disconnectFromHost();
//    setData("list-dictionaries", "dictionaries", QByteArray(theHash);
}
Example #30
0
void set_branch( const QList< uint * > &touching, const BillonTpl< tlabel > *labelSkel, const BillonTpl< tlabelbranch > *labelBranch, 
                 QMap< tlabelbranch, tlabel > &NewLabelBranch, const QList< tlabel > &Labels, QMap< tlabel, QList<tlabel> > &edges ) {
	QList< uint * >::const_iterator iterVoxel = touching.begin(),
	                                iterVoxelEnd = touching.end() ;
	bool bDiscard ;
	QList< tlabelbranch > bridges ;
	while ( iterVoxel != iterVoxelEnd ) {
		tlabelbranch idBranch = (*labelBranch)( (*iterVoxel)[1], (*iterVoxel)[0], (*iterVoxel)[2] ) ;
		tlabel idComp = (*labelSkel)( (*iterVoxel)[1], (*iterVoxel)[0], (*iterVoxel)[2] ) ;
		bDiscard = false ;
		if ( !Labels.isEmpty() ) {
			bDiscard = ( !Labels.contains( idComp ) );
		}
		if ( !bDiscard ) {
			if ( !NewLabelBranch.contains( idBranch ) )
				NewLabelBranch.insert( idBranch, idComp ) ;
			else if (NewLabelBranch[idBranch] != idComp ) {
				bridges.append( idBranch ) ;
				if ( !edges.contains( idComp ) ) edges.insert( idComp, QList<tlabel>() ) ;
				if ( !edges.contains( NewLabelBranch[idBranch] ) ) edges.insert( NewLabelBranch[idBranch], QList<tlabel>() ) ;
				edges[ idComp ].append( NewLabelBranch[idBranch] ) ;
				//edges[ idComp ].append( idBranch ) ;
				edges[ NewLabelBranch[idBranch] ].append( idComp ) ;
				//edges[ NewLabelBranch[idBranch] ].append( idBranch ) ; /// it is this value that is the edge between the two
			}
		} else if ( NewLabelBranch.contains( idBranch ) ) {
			bridges.append( idBranch ) ;
		}
		iterVoxel++ ;
	}
	/// component that get their identifier in bridges are connected to at least two components
	qSort( bridges.begin(), bridges.end(), qLess< tlabelbranch >() ) ;
	while ( !bridges.isEmpty() ) {
		NewLabelBranch.take( bridges.takeFirst() ) ;
	}
	
	for ( QMap<tlabel,QList<tlabel> >::ConstIterator e_source_it = edges.begin() ; e_source_it != edges.end() ; e_source_it++ ) {
		std::cout<<(int)e_source_it.key()<<" connected to ";
		for ( QList<tlabel>::ConstIterator e_target_it = e_source_it.value().begin() ; e_target_it != e_source_it.value().end() ; e_target_it++ )
			std::cout<<(int)*e_target_it<<" " ;
		std::cout<<std::endl;
	}
	
}