/*! \fn void QTextTable::removeColumns(int index, int columns) Removes a number of \a columns starting with the column at the specified \a index. \sa insertRows() insertColumns() removeRows() resize() appendRows() appendColumns() */ void QTextTable::removeColumns(int pos, int num) { Q_D(QTextTable); // qDebug() << "-------- removeCols" << pos << num; if (num <= 0 || pos < 0) return; if (d->dirty) d->update(); if (pos >= d->nCols) return; if (pos + num > d->nCols) pos = d->nCols - num; QTextDocumentPrivate *p = d->pieceTable; QTextFormatCollection *collection = p->formatCollection(); p->beginEditBlock(); // delete whole table? if (pos == 0 && num == d->nCols) { const int pos = p->fragmentMap().position(d->fragment_start); p->remove(pos, p->fragmentMap().position(d->fragment_end) - pos + 1); p->endEditBlock(); return; } p->aboutToRemoveCell(cellAt(0, pos).firstPosition(), cellAt(d->nRows - 1, pos + num - 1).lastPosition()); QList<int> touchedCells; for (int r = 0; r < d->nRows; ++r) { for (int c = pos; c < pos + num; ++c) { int cell = d->grid[r*d->nCols + c]; QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell); QTextCharFormat fmt = collection->charFormat(it->format); int span = fmt.tableCellColumnSpan(); if (touchedCells.contains(cell) && span <= 1) continue; touchedCells << cell; if (span > 1) { fmt.setTableCellColumnSpan(span - 1); p->setCharFormat(it.position(), 1, fmt); } else { // remove cell int index = d->cells.indexOf(cell) + 1; int f_end = index < d->cells.size() ? d->cells.at(index) : d->fragment_end; p->remove(it.position(), p->fragmentMap().position(f_end) - it.position()); } } } QTextTableFormat tfmt = format(); tfmt.setColumns(tfmt.columns()-num); QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints(); if (columnWidths.count() > pos) { columnWidths.remove(pos, num); tfmt.setColumnWidthConstraints (columnWidths); } QTextObject::setFormat(tfmt); p->endEditBlock(); // qDebug() << "-------- end removeCols" << pos << num; }
ErrorList topolTest::checkDuplicates( double tolerance, QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent ) { Q_UNUSED( tolerance ); Q_UNUSED( layer2 ); //TODO: multilines - check all separate pieces int i = 0; ErrorList errorList; QList<QgsFeatureId> duplicateIds; QgsSpatialIndex* index = mLayerIndexes[layer1->id()]; QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( theQgsInterface->mapCanvas()->extent().asWktPolygon() ); QMap<QgsFeatureId, FeatureLayer>::const_iterator it; for ( it = mFeatureMap2.constBegin(); it != mFeatureMap2.constEnd(); ++it ) { if ( !( ++i % 100 ) ) emit progress( i ); QgsFeatureId currentId = it->feature.id(); if ( duplicateIds.contains( currentId ) ) { //is already a duplicate geometry..skip.. continue; } if ( testCancelled() ) break; QgsGeometry g1 = it->feature.geometry(); QgsRectangle bb = g1.boundingBox(); QList<QgsFeatureId> crossingIds; crossingIds = index->intersects( bb ); QList<QgsFeatureId>::Iterator cit = crossingIds.begin(); QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.end(); bool duplicate = false; for ( ; cit != crossingIdsEnd; ++cit ) { duplicate = false; // skip itself if ( mFeatureMap2[*cit].feature.id() == it->feature.id() ) continue; QgsGeometry g2 = mFeatureMap2[*cit].feature.geometry(); if ( g2.isEmpty() ) { QgsMessageLog::logMessage( tr( "Invalid second geometry in duplicate geometry test." ), tr( "Topology plugin" ) ); continue; } if ( !_canExportToGeos( g2 ) ) { QgsMessageLog::logMessage( tr( "Failed to import second geometry into GEOS in duplicate geometry test." ), tr( "Topology plugin" ) ); continue; } if ( g1.equals( g2 ) ) { duplicate = true; duplicateIds.append( mFeatureMap2[*cit].feature.id() ); } if ( duplicate ) { QList<FeatureLayer> fls; fls << *it << *it; QgsGeometry conflict( g1 ); if ( isExtent ) { if ( canvasExtentPoly.disjoint( conflict ) ) { continue; } if ( canvasExtentPoly.crosses( conflict ) ) { conflict = conflict.intersection( canvasExtentPoly ); } } TopolErrorDuplicates* err = new TopolErrorDuplicates( bb, conflict, fls ); errorList << err; } } } return errorList; }
QHash<QByteArray, QByteArray> QAuthenticatorPrivate::parseDigestAuthenticationChallenge(const QByteArray &challenge) { QHash<QByteArray, QByteArray> options; // parse the challenge const char *d = challenge.constData(); const char *end = d + challenge.length(); while (d < end) { while (d < end && (*d == ' ' || *d == '\n' || *d == '\r')) ++d; const char *start = d; while (d < end && *d != '=') ++d; QByteArray key = QByteArray(start, d - start); ++d; if (d >= end) break; bool quote = (*d == '"'); if (quote) ++d; if (d >= end) break; start = d; QByteArray value; while (d < end) { bool backslash = false; if (*d == '\\' && d < end - 1) { ++d; backslash = true; } if (!backslash) { if (quote) { if (*d == '"') break; } else { if (*d == ',') break; } } value += *d; ++d; } while (d < end && *d != ',') ++d; ++d; options[key] = value; } QByteArray qop = options.value("qop"); if (!qop.isEmpty()) { QList<QByteArray> qopoptions = qop.split(','); if (!qopoptions.contains("auth")) return QHash<QByteArray, QByteArray>(); // #### can't do auth-int currently // if (qop.contains("auth-int")) // qop = "auth-int"; // else if (qop.contains("auth")) // qop = "auth"; // else // qop = QByteArray(); options["qop"] = "auth"; } return options; }
QList<Abi> Abi::abisOfBinary(const Utils::FileName &path) { QList<Abi> tmp; if (path.isEmpty()) return tmp; QFile f(path.toString()); if (!f.exists()) return tmp; if (!f.open(QFile::ReadOnly)) return tmp; QByteArray data = f.read(1024); if (data.size() >= 67 && getUint8(data, 0) == '!' && getUint8(data, 1) == '<' && getUint8(data, 2) == 'a' && getUint8(data, 3) == 'r' && getUint8(data, 4) == 'c' && getUint8(data, 5) == 'h' && getUint8(data, 6) == '>' && getUint8(data, 7) == 0x0a) { // We got an ar file: possibly a static lib for ELF, PE or Mach-O data = data.mid(8); // Cut of ar file magic quint64 offset = 8; while (!data.isEmpty()) { if ((getUint8(data, 58) != 0x60 || getUint8(data, 59) != 0x0a)) { qWarning() << path.toString() << ": Thought it was an ar-file, but it is not!"; break; } const QString fileName = QString::fromLocal8Bit(data.mid(0, 16)); quint64 fileNameOffset = 0; if (fileName.startsWith(QLatin1String("#1/"))) fileNameOffset = fileName.mid(3).toInt(); const QString fileLength = QString::fromLatin1(data.mid(48, 10)); int toSkip = 60 + fileNameOffset; offset += fileLength.toInt() + 60 /* header */; tmp.append(abiOf(data.mid(toSkip))); if (tmp.isEmpty() && fileName == QLatin1String("/0 ")) tmp = parseCoffHeader(data.mid(toSkip, 20)); // This might be windws... if (!tmp.isEmpty() && tmp.at(0).binaryFormat() != Abi::MachOFormat) break; offset += (offset % 2); // ar is 2 byte aligned f.seek(offset); data = f.read(1024); } } else { tmp = abiOf(data); } f.close(); // Remove duplicates: QList<Abi> result; foreach (const Abi &a, tmp) { if (!result.contains(a)) result.append(a); } return result; }
QList<fugio::NodeControlInterface::AvailablePinEntry> NamespacePin::oscPins( const QStringList &pCurDir ) const { QList<fugio::NodeControlInterface::AvailablePinEntry> PinLst; for( QHash<QString,QVariant>::const_iterator it = mDataNames.begin() ; it != mDataNames.end() ; it++ ) { QSharedPointer<fugio::PinInterface> CurPin; QStringList CurLst = it.key().split( '/', QString::SkipEmptyParts ); if( !pCurDir.isEmpty() ) { if( CurLst.size() <= pCurDir.size() ) { continue; } bool CurFnd = true; for( int i = 0 ; i < pCurDir.size() ; i++ ) { if( CurLst.first() != pCurDir.at( i ) ) { CurFnd = false; break; } CurLst.removeFirst(); } if( !CurFnd ) { continue; } } QStringList NewLst = QStringList( CurLst.takeFirst() ); while( true ) { QString CurNam = NewLst.join( '/' ).prepend( '/' ); CurPin = mPin->node()->findOutputPinByName( CurNam ); if( CurPin ) { break; } fugio::NodeControlInterface::AvailablePinEntry PE( "" ); if( CurLst.isEmpty() ) { QUuid PinUid = PID_FLOAT; switch( QMetaType::Type( it.value().type() ) ) { case QMetaType::Float: case QMetaType::Double: PinUid = PID_FLOAT; break; case QMetaType::Bool: PinUid = PID_BOOL; break; case QMetaType::Int: case QMetaType::Long: PinUid = PID_INTEGER; break; case QMetaType::QByteArray: PinUid = PID_BYTEARRAY; break; case QMetaType::QColor: PinUid = PID_COLOUR; break; case QMetaType::QString: PinUid = PID_STRING; break; case QMetaType::QVariantList: PinUid = PID_LIST; break; default: break; } PE = fugio::NodeControlInterface::AvailablePinEntry( CurNam, PinUid ); } else { PE = fugio::NodeControlInterface::AvailablePinEntry( CurNam, PID_OSC_SPLIT ); } if( !PinLst.contains( PE ) ) { PinLst << PE; } if( CurLst.isEmpty() ) { break; } NewLst.push_back( CurLst.takeFirst() ); } } std::sort( PinLst.begin(), PinLst.end() ); return( PinLst ); }
Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const CommandContainer &cont, ResponseContainer &rc) { static QList<GameCommand::GameCommandType> antifloodCommandsWhiteList = QList<GameCommand::GameCommandType>() // draw/undo card draw (example: drawing 10 cards one by one from the deck) << GameCommand::DRAW_CARDS << GameCommand::UNDO_DRAW // create, delete arrows (example: targeting with 10 cards during an attack) << GameCommand::CREATE_ARROW << GameCommand::DELETE_ARROW // set card attributes (example: tapping 10 cards at once) << GameCommand::SET_CARD_ATTR // increment / decrement counter (example: -10 life points one by one) << GameCommand::INC_COUNTER // mulling lots of hands in a row << GameCommand::MULLIGAN // allows a user to sideboard without receiving flooding message << GameCommand::MOVE_CARD; if (authState == NotLoggedIn) return Response::RespLoginNeeded; QMap<int, QPair<int, int> > gameMap = getGames(); if (!gameMap.contains(cont.game_id())) return Response::RespNotInRoom; const QPair<int, int> roomIdAndPlayerId = gameMap.value(cont.game_id()); QReadLocker roomsLocker(&server->roomsLock); Server_Room *room = server->getRooms().value(roomIdAndPlayerId.first); if (!room) return Response::RespNotInRoom; QReadLocker roomGamesLocker(&room->gamesLock); Server_Game *game = room->getGames().value(cont.game_id()); if (!game) { if (room->getExternalGames().contains(cont.game_id())) { server->sendIsl_GameCommand(cont, room->getExternalGames().value(cont.game_id()).server_id(), userInfo->session_id(), roomIdAndPlayerId.first, roomIdAndPlayerId.second ); return Response::RespNothing; } return Response::RespNotInRoom; } QMutexLocker gameLocker(&game->gameMutex); Server_Player *player = game->getPlayers().value(roomIdAndPlayerId.second); if (!player) return Response::RespNotInRoom; int commandCountingInterval = server->getCommandCountingInterval(); int maxCommandCountPerInterval = server->getMaxCommandCountPerInterval(); GameEventStorage ges; Response::ResponseCode finalResponseCode = Response::RespOk; for (int i = cont.game_command_size() - 1; i >= 0; --i) { const GameCommand &sc = cont.game_command(i); logDebugMessage(QString("game %1 player %2: ").arg(cont.game_id()).arg(roomIdAndPlayerId.second) + QString::fromStdString(sc.ShortDebugString())); if (commandCountingInterval > 0) { int totalCount = 0; if (commandCountOverTime.isEmpty()) commandCountOverTime.prepend(0); if(!antifloodCommandsWhiteList.contains((GameCommand::GameCommandType) getPbExtension(sc))) ++commandCountOverTime[0]; for (int i = 0; i < commandCountOverTime.size(); ++i) totalCount += commandCountOverTime[i]; if (totalCount > maxCommandCountPerInterval) return Response::RespChatFlood; } Response::ResponseCode resp = player->processGameCommand(sc, rc, ges); if (resp != Response::RespOk) finalResponseCode = resp; } ges.sendToGame(game); return finalResponseCode; }
void QAbstractButtonPrivate::moveFocus(int key) { QList<QAbstractButton *> buttonList = queryButtonList();; #ifndef QT_NO_BUTTONGROUP bool exclusive = group ? group->d_func()->exclusive : autoExclusive; #else bool exclusive = autoExclusive; #endif QWidget *f = QApplication::focusWidget(); QAbstractButton *fb = qobject_cast<QAbstractButton *>(f); if (!fb || !buttonList.contains(fb)) return; QAbstractButton *candidate = 0; int bestScore = -1; QRect target = f->rect().translated(f->mapToGlobal(QPoint(0,0))); QPoint goal = target.center(); uint focus_flag = qt_tab_all_widgets() ? Qt::TabFocus : Qt::StrongFocus; for (int i = 0; i < buttonList.count(); ++i) { QAbstractButton *button = buttonList.at(i); if (button != f && button->window() == f->window() && button->isEnabled() && !button->isHidden() && (autoExclusive || (button->focusPolicy() & focus_flag) == focus_flag)) { QRect buttonRect = button->rect().translated(button->mapToGlobal(QPoint(0,0))); QPoint p = buttonRect.center(); //Priority to widgets that overlap on the same coordinate. //In that case, the distance in the direction will be used as significant score, //take also in account orthogonal distance in case two widget are in the same distance. int score; if ((buttonRect.x() < target.right() && target.x() < buttonRect.right()) && (key == Qt::Key_Up || key == Qt::Key_Down)) { //one item's is at the vertical of the other score = (qAbs(p.y() - goal.y()) << 16) + qAbs(p.x() - goal.x()); } else if ((buttonRect.y() < target.bottom() && target.y() < buttonRect.bottom()) && (key == Qt::Key_Left || key == Qt::Key_Right) ) { //one item's is at the horizontal of the other score = (qAbs(p.x() - goal.x()) << 16) + qAbs(p.y() - goal.y()); } else { score = (1 << 30) + (p.y() - goal.y()) * (p.y() - goal.y()) + (p.x() - goal.x()) * (p.x() - goal.x()); } if (score > bestScore && candidate) continue; switch(key) { case Qt::Key_Up: if (p.y() < goal.y()) { candidate = button; bestScore = score; } break; case Qt::Key_Down: if (p.y() > goal.y()) { candidate = button; bestScore = score; } break; case Qt::Key_Left: if (p.x() < goal.x()) { candidate = button; bestScore = score; } break; case Qt::Key_Right: if (p.x() > goal.x()) { candidate = button; bestScore = score; } break; } } } if (exclusive #ifdef QT_KEYPAD_NAVIGATION && !QApplication::keypadNavigationEnabled() #endif && candidate && fb->d_func()->checked && candidate->d_func()->checkable) candidate->click(); if (candidate) { if (key == Qt::Key_Up || key == Qt::Key_Left) candidate->setFocus(Qt::BacktabFocusReason); else candidate->setFocus(Qt::TabFocusReason); } }
bool UIMachineSettingsSerialPage::validate(QString &strWarning, QString &strTitle) { bool valid = true; QList<QPair<QString, QString> > ports; QStringList paths; int index = 0; for (; index < mTabWidget->count(); ++ index) { QWidget *tab = mTabWidget->widget (index); UIMachineSettingsSerial *page = static_cast<UIMachineSettingsSerial*> (tab); if (!page->mGbSerial->isChecked()) continue; /* Check the predefined port attributes uniqueness: */ { QString strIRQ = page->mLeIRQ->text(); QString strIOPort = page->mLeIOPort->text(); QPair<QString, QString> pair(strIRQ, strIOPort); valid = !strIRQ.isEmpty() && !strIOPort.isEmpty() && !ports.contains(pair); if (!valid) { if (strIRQ.isEmpty()) strWarning = tr("IRC not specified."); else if (strIOPort.isEmpty()) strWarning = tr("IO port not specified."); else strWarning = tr ("duplicate port attributes specified."); strTitle += ": " + vboxGlobal().removeAccelMark(mTabWidget->tabText(mTabWidget->indexOf(tab))); } ports << pair; } /* Check the port path emptiness & unicity */ KPortMode mode = gpConverter->fromString<KPortMode> (page->mCbMode->currentText()); if (mode != KPortMode_Disconnected) { QString path = page->mLePath->text(); valid = !path.isEmpty() && !paths.contains (path); if (!valid) { if (!page->mGbSerial->isChecked()) page->mCbMode->setCurrentIndex (KPortMode_Disconnected); else { strWarning = path.isEmpty() ? tr ("port path not specified.") : tr ("duplicate port path entered."); strTitle += ": " + vboxGlobal().removeAccelMark (mTabWidget->tabText (mTabWidget->indexOf (tab))); break; } } paths << path; } } return valid; }
// Build Library void tAt5CategoryLibrary::BuildLibrary( std::vector< boost::shared_ptr< tAt5FeatureDefinition > >& featureDefinitionList, tAt5CategoryTranslatorXPtr xCategoryTranslator, const bool& quit ) { ResetLibrary(); QList<QString> majorCategoriesDisabled; for ( unsigned int fdl = 0; fdl < featureDefinitionList.size(); ++ fdl ) { if ( quit ) return; // For some reason Jeppesen is naming their block array features. We dont want these showing up in the category list, // so dont include block features here. if(featureDefinitionList[fdl]->xFeatureDefinition->FeatureType() != At5::eFT_BlockArray) { QString catName = featureDefinitionList[fdl]->xFeatureDefinition->MajorCategoryName() + "." + featureDefinitionList[fdl]->xFeatureDefinition->MinorCategoryName(); At5::tUShort majorVersion = 0; try { tAt5AtlasIoAccess dataAccess = featureDefinitionList[fdl]->xOriginalAtlas->GetAt5DataThreadSafe(); majorVersion = dataAccess->GetMajorVersion(); } catch(QString errMsg) { qDebug() << QString("Build library failed. At5 could not be read. %1").arg(errMsg); qDebug() << (AT5_EXCEPTION_WHERE_INFO.toAscii().data()); return; } At5::tFeatureDefinition::eInitialCategories initialCategorySetting = featureDefinitionList[fdl]->xFeatureDefinition->InitialCategorySettings(); if(majorVersion > 13) { if(initialCategorySetting & At5::tFeatureDefinition::eIC_StandardMajCatOff) { majorCategoriesDisabled.append(featureDefinitionList[fdl]->xFeatureDefinition->MajorCategoryName()); } if(initialCategorySetting & At5::tFeatureDefinition::eIC_StandardMinCatOff) { m_InitiallyDisabledCategoryNames[catName] |= featureDefinitionList[fdl]->xOriginalAtlas->GetMapFilter(); } } // Tag translation takes priority over category translation QString displayName = xCategoryTranslator->TranslateTagName(featureDefinitionList[fdl]->groupTag, tAt5CategoryTranslator::Display); // Translator returns same name if no translation is found if (displayName == featureDefinitionList[fdl]->groupTag) displayName = xCategoryTranslator->TranslateCategoryName(catName, tAt5CategoryTranslator::Display); Insert(displayName, featureDefinitionList[fdl].get(), m_MajorCategoryList); } } // Loop the list again and if the major cat name is disabled, then disable all the minor cat names for ( unsigned int fdl = 0; fdl < featureDefinitionList.size(); ++ fdl ) { if ( quit ) return; // For some reason Jeppesen is naming their block array features. We dont want these showing up in the category list, // so dont include block features here. if(featureDefinitionList[fdl]->xFeatureDefinition->FeatureType() != At5::eFT_BlockArray) { QString catName = featureDefinitionList[fdl]->xFeatureDefinition->MajorCategoryName() + "." + featureDefinitionList[fdl]->xFeatureDefinition->MinorCategoryName(); if(majorCategoriesDisabled.contains(featureDefinitionList[fdl]->xFeatureDefinition->MajorCategoryName())) { m_InitiallyDisabledCategoryNames[catName] |= featureDefinitionList[fdl]->xOriginalAtlas->GetMapFilter(); } } } }
QTORGANIZER_USE_NAMESPACE TodoEditPage::TodoEditPage(QWidget *parent) :QWidget(parent), m_manager(0), m_subjectEdit(0), m_startTimeEdit(0), m_dueTimeEdit(0), m_priorityEdit(0), m_statusEdit(0), m_alarmComboBox(0) { // Create widgets QLabel *subjectLabel = new QLabel("Subject:", this); m_subjectEdit = new QLineEdit(this); QLabel *startTimeLabel = new QLabel("Start time:", this); m_startTimeEdit = new QDateTimeEdit(this); m_startTimeEdit->setDisplayFormat(QString("yyyy-MM-dd hh:mm:ss AP")); QLabel *dueTimeLabel = new QLabel("Due time:", this); m_dueTimeEdit = new QDateTimeEdit(this); m_dueTimeEdit->setDisplayFormat(QString("yyyy-MM-dd hh:mm:ss AP")); QLabel *priorityLabel = new QLabel("Priority:", this); m_priorityEdit = new QComboBox(this); QLabel *statusLabel = new QLabel("Status:", this); m_statusEdit = new QComboBox(this); QLabel *alarmLabel = new QLabel("Alarm:", this); m_alarmComboBox = new QComboBox(this); QLabel *calendarLabel = new QLabel("Calendar:", this); QStringList alarmList; alarmList << "None" << "0 minutes before" << "5 minutes before" << "15 minutes before" << "30 minutes before" << "1 hour before"; m_alarmComboBox->addItems(alarmList); connect(m_alarmComboBox, SIGNAL(currentIndexChanged(const QString)), this, SLOT(handleAlarmIndexChanged(const QString))); m_calendarComboBox = new QComboBox(this); // the calendar names are not know here, fill the combo box later... // Add push buttons QHBoxLayout* hbLayout = new QHBoxLayout(); QPushButton *okButton = new QPushButton("Save", this); connect(okButton,SIGNAL(clicked()),this,SLOT(saveClicked())); hbLayout->addWidget(okButton); QPushButton *cancelButton = new QPushButton("Cancel", this); connect(cancelButton,SIGNAL(clicked()),this,SLOT(cancelClicked())); hbLayout->addWidget(cancelButton); // check to see whether we support alarms. QOrganizerManager defaultManager; QList<QOrganizerItemDetail::DetailType> supportedDetails = defaultManager.supportedItemDetails(QOrganizerItemType::TypeTodo); QVBoxLayout *scrollAreaLayout = new QVBoxLayout(); scrollAreaLayout->addWidget(subjectLabel); scrollAreaLayout->addWidget(m_subjectEdit); scrollAreaLayout->addWidget(startTimeLabel); scrollAreaLayout->addWidget(m_startTimeEdit); scrollAreaLayout->addWidget(dueTimeLabel); scrollAreaLayout->addWidget(m_dueTimeEdit); scrollAreaLayout->addWidget(priorityLabel); scrollAreaLayout->addWidget(m_priorityEdit); scrollAreaLayout->addWidget(statusLabel); scrollAreaLayout->addWidget(m_statusEdit); if (supportedDetails.contains(QOrganizerItemDetail::TypeVisualReminder)) { scrollAreaLayout->addWidget(alarmLabel); scrollAreaLayout->addWidget(m_alarmComboBox); } scrollAreaLayout->addWidget(calendarLabel); scrollAreaLayout->addWidget(m_calendarComboBox); scrollAreaLayout->addStretch(); scrollAreaLayout->addLayout(hbLayout); QScrollArea *scrollArea = new QScrollArea(this); scrollArea->setWidgetResizable(true); QWidget *formContainer = new QWidget(scrollArea); formContainer->setLayout(scrollAreaLayout); scrollArea->setWidget(formContainer); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->addWidget(scrollArea); setLayout(mainLayout); // Fill priority combo m_priorityEdit->addItem("Unknown", QVariant(QOrganizerItemPriority::UnknownPriority)); m_priorityEdit->addItem("Highest", QVariant(QOrganizerItemPriority::HighestPriority)); m_priorityEdit->addItem("Extremely high", QVariant(QOrganizerItemPriority::ExtremelyHighPriority)); m_priorityEdit->addItem("Very high", QVariant(QOrganizerItemPriority::VeryHighPriority)); m_priorityEdit->addItem("High", QVariant(QOrganizerItemPriority::HighPriority)); m_priorityEdit->addItem("Medium", QVariant(QOrganizerItemPriority::MediumPriority)); m_priorityEdit->addItem("Low", QVariant(QOrganizerItemPriority::LowPriority)); m_priorityEdit->addItem("Very low", QVariant(QOrganizerItemPriority::VeryLowPriority)); m_priorityEdit->addItem("Extremely low", QVariant(QOrganizerItemPriority::ExtremelyLowPriority)); m_priorityEdit->addItem("Lowest", QVariant(QOrganizerItemPriority::LowestPriority)); // Fill status combo m_statusEdit->addItem("Not started", QVariant(QOrganizerTodoProgress::StatusNotStarted)); m_statusEdit->addItem("In progress", QVariant(QOrganizerTodoProgress::StatusInProgress)); m_statusEdit->addItem("Complete", QVariant(QOrganizerTodoProgress::StatusComplete)); }
void Uploading::uploadingProcess(const QString &actionId) { { QProgressDialog progressDialog; progressDialog.setWindowModality(Qt::WindowModal); progressDialog.setWindowTitle(tr("Выгрузка базы данных")); progressDialog.setLabelText(tr("Процесс выгрузки базы данных")); progressDialog.setCancelButton(0); progressDialog.setMinimumDuration(0); progressDialog.setMaximum(6); progressDialog.setValue(0); QSqlDatabase db = QSqlDatabase::database(UPLOADING); createDBScheme(); progressDialog.setValue(1); QApplication::processEvents(QEventLoop::ExcludeUserInputEvents); QSqlQuery selectDataQuery(QSqlDatabase::database(mConnection)); QSqlQuery insertDataQuery(db); if(selectDataQuery.exec("SELECT id, title, performer FROM Actions WHERE id = " + actionId)) { insertDataQuery.prepare("INSERT INTO Actions VALUES(:id, :title, :performer);"); while(selectDataQuery.next()) { insertDataQuery.bindValue(":id", selectDataQuery.value(0)); insertDataQuery.bindValue(":title", selectDataQuery.value(1)); insertDataQuery.bindValue(":performer", selectDataQuery.value(2)); insertDataQuery.exec(); } } progressDialog.setValue(2); QList<int> placeSchemeIds; QList<int> clientIds; if(selectDataQuery.exec("SELECT id, id_action, id_placeScheme, id_client, identifier FROM Tickets WHERE id_action = " + actionId)) { insertDataQuery.prepare("INSERT INTO Tickets VALUES(NULL, :id_action, :id_placeScheme, :id_client, :identifier, :passedFlag);"); while(selectDataQuery.next()) { insertDataQuery.bindValue(":id_action", selectDataQuery.value(1)); insertDataQuery.bindValue(":id_placeScheme", selectDataQuery.value(2)); insertDataQuery.bindValue(":id_client", selectDataQuery.value(3)); insertDataQuery.bindValue(":identifier", selectDataQuery.value(4)); insertDataQuery.bindValue(":passedFlag", "false"); insertDataQuery.exec(); if(selectDataQuery.isNull(2) == false) placeSchemeIds.append(selectDataQuery.value(2).toInt()); if(selectDataQuery.isNull(3) == false) clientIds.append(selectDataQuery.value(4).toInt()); } } progressDialog.setValue(3); if(placeSchemeIds.isEmpty() == false) { if(selectDataQuery.exec("SELECT id, seatNumber, row FROM PlaceSchemes")) { insertDataQuery.prepare("INSERT INTO PlaceSchemes VALUES(:id, :seatNumber, :row)"); while(selectDataQuery.next()) { if(placeSchemeIds.contains( selectDataQuery.value(0).toInt()) ) { insertDataQuery.bindValue(":id", selectDataQuery.value(0)); insertDataQuery.bindValue(":seatNumber", selectDataQuery.value(1)); insertDataQuery.bindValue(":row", selectDataQuery.value(2)); insertDataQuery.exec(); } } } } progressDialog.setValue(4); if(clientIds.isEmpty() == false) { if(selectDataQuery.exec("SELECT id, name, login FROM Clients")) { insertDataQuery.prepare("INSERT INTO Clients VALUES(:id, :name, :login)"); while(selectDataQuery.next()) { if(clientIds.contains( selectDataQuery.value(0).toInt() )) { insertDataQuery.bindValue(":id", selectDataQuery.value(0)); insertDataQuery.bindValue(":name", selectDataQuery.value(1)); insertDataQuery.bindValue(":login", selectDataQuery.value(2)); insertDataQuery.exec(); } } } } progressDialog.setValue(5); if(selectDataQuery.exec("SELECT id, id_client, identifier FROM ReturnedTickets WHERE id_action = " + actionId)) { insertDataQuery.prepare("INSERT INTO ReturnedTickets VALUES(NULL, :id_client, :identifier);"); while(selectDataQuery.next()) { insertDataQuery.bindValue(":id_client", selectDataQuery.value(1)); insertDataQuery.bindValue(":identifier", selectDataQuery.value(2)); insertDataQuery.exec(); } } progressDialog.setValue(6); progressDialog.close(); db.close(); } QSqlDatabase::removeDatabase(UPLOADING); }
void RmShaderDialog::fillTabsWithPass(int index) { clearTabs(); if (index < 0 || eff_selected == NULL || index >= eff_selected->size()) return; pass_selected = &(eff_selected->at(index)); // Set the source code of vertex shader ui.textVertex->setText(pass_selected->getVertex()); // Set the source code of fragment shader ui.textFragment->setText(pass_selected->getFragment()); // General Info in the first tab QString info; if (pass_selected->hasRenderTarget()) info += "Render Target: " + pass_selected->getRenderTarget().name + "\n"; for (int i = 0; i < 2; i++) for (int j = 0; j < (i == 0 ? pass_selected->vertexUniformVariableSize() : pass_selected->fragmentUniformVariableSize()); j++) { UniformVar v = pass_selected->getUniform(j, i == 0 ? RmPass::VERTEX : RmPass::FRAGMENT); if(v.representerTagName == "RmRenderTarget") { if (i == 0) info += "Vertex"; else info += "Fragment"; info += " render Input: " + v.name; for (int k = 0; k < eff_selected -> size(); k++) if (eff_selected->at(k).getRenderTarget().name == v.textureName) { info += " (from pass: "******")"; break; } info += "\n"; } } if (!info.isEmpty()) { QLabel *lblinfo = new QLabel(info); layoutUniform->addWidget(lblinfo, 0, 0, 1, 5); shown.append(lblinfo); } // any value change is sent to the state holder with this mapper // Signal are send from signaler in the form "varnameNM" where // NM is the index of row and column in case of matrix. (00 if // it is a simple variable). delete signaler; signaler = new QSignalMapper(); connect(signaler, SIGNAL(mapped(const QString &)), this, SLOT(valuesChanged(const QString &))); // Uniform Variables in the first Tab QList<QString> usedVarables; // parser can give same variable twice in the vertex and fragment int row = 1; for (int ii = 0; ii < 2; ii++) for (int jj = 0; jj < (ii == 0 ? pass_selected->vertexUniformVariableSize() : pass_selected->fragmentUniformVariableSize()); jj++) { UniformVar v = pass_selected->getUniform(jj, ii == 0 ? RmPass::VERTEX : RmPass::FRAGMENT); if (v.representerTagName == "RmRenderTarget" || usedVarables.contains(v.name)) continue; usedVarables.append(v.name); QString varname = (ii == 0 ? "Vertex: " : "Fragment: "); varname += UniformVar::getStringFromUniformType(v.type) + " " + v.name + (v.minSet || v.maxSet ? "\n" : ""); switch (v.type) { case UniformVar::INT: case UniformVar::IVEC2: case UniformVar::IVEC3: case UniformVar::IVEC4: { int n = v.type == UniformVar::INT ? 1 : (v.type == UniformVar::IVEC2 ? 2 : (v.type == UniformVar::IVEC3 ? 3 : 4 )); for (int i = 0; i < n; i++) { QSpinBox *input = new QSpinBox(); input->setObjectName(v.name + "0" + QString().setNum(i)); if (v.minSet) input->setMinimum(v.fmin); else input -> setMinimum(-1000); if (v.maxSet) input->setMaximum(v.fmax); else input->setMaximum(1000); input->setSingleStep((v.minSet && v.maxSet )? std::max(( v.imax - v.imin )/10, 1) : 1 ); input->setValue(v.ivec4[i]); layoutUniform->addWidget(input, row, 1 + i, 1, ((i + 1)==n ? 5-n : 1)); shown.append(input); connect(input, SIGNAL(valueChanged(int)), signaler, SLOT(map())); signaler->setMapping(input, v.name + "0" + QString().setNum(i)); } if (v.minSet) { varname += "min: " + QString().setNum(v.imin) + " "; } if (v.maxSet) { varname += " max: " + QString().setNum(v.imax); } break; } case UniformVar::BOOL: case UniformVar::BVEC2: case UniformVar::BVEC3: case UniformVar::BVEC4: { int n = v.type == UniformVar::BOOL ? 1 : (v.type == UniformVar::BVEC2 ? 2 : (v.type == UniformVar::BVEC3 ? 3 : 4 )); for( int i = 0; i < n; i++ ) { QCheckBox * input = new QCheckBox(); input -> setObjectName( v.name + "0" + QString().setNum(i) ); input -> setCheckState( v.bvec4[i] ? Qt::Checked : Qt::Unchecked ); layoutUniform->addWidget(input, row, 1+i, 1, ((i+1)==n ? 5-n : 1)); shown.append(input); connect(input, SIGNAL(stateChanged(int)), signaler, SLOT(map())); signaler->setMapping(input, v.name + "0" + QString().setNum(i) ); } break; } case UniformVar::FLOAT: case UniformVar::VEC2: case UniformVar::VEC3: case UniformVar::VEC4: { int n = v.type == UniformVar::FLOAT ? 1 : (v.type == UniformVar::VEC2 ? 2 : (v.type == UniformVar::VEC3 ? 3 : 4 )); for( int i = 0; i < n; i++ ) { QDoubleSpinBox * input = new QDoubleSpinBox(); input -> setObjectName( v.name + "0" + QString().setNum(i) ); input -> setDecimals(4); if( v.minSet ) input -> setMinimum( v.fmin ); else input -> setMinimum( -1000 ); if( v.maxSet ) input -> setMaximum( v.fmax ); else input -> setMaximum( 1000 ); input -> setSingleStep( (v.minSet && v.maxSet ) ? std::max(( v.fmax - v.fmin )/10., 0.0001) : 0.0001 ); input -> setValue( v.vec4[i] ); layoutUniform->addWidget( input, row, 1+i, 1, ((i+1)==n ? 5-n : 1) ); shown.append(input); connect(input, SIGNAL(valueChanged(double)), signaler, SLOT(map())); signaler->setMapping(input, v.name + "0" + QString().setNum(i) ); } if( v.minSet ) { varname += "min: " + QString().setNum(v.fmin) + " "; } if( v.maxSet ) { varname += " max: " + QString().setNum(v.fmax); } break; } case UniformVar::MAT2: case UniformVar::MAT3: case UniformVar::MAT4: { int n = v.type == UniformVar::MAT2 ? 2 : (v.type == UniformVar::MAT3 ? 3 : 4 ); for( int i = 0; i < n; i++ ) { for( int j = 0; j < n; j++ ) { QDoubleSpinBox * input = new QDoubleSpinBox(); input -> setObjectName( v.name + QString().setNum(i) + QString().setNum(j)); input -> setDecimals(4); if( v.minSet ) input -> setMinimum( v.fmin ); else input -> setMinimum( -1000 ); if( v.maxSet ) input -> setMaximum( v.fmax ); else input -> setMaximum( 1000 ); input -> setSingleStep( (v.minSet && v.maxSet ) ? std::max(( v.fmax - v.fmin )/10., 0.0001) : 0.0001 ); input -> setValue( v.vec4[(i*n)+j] ); layoutUniform->addWidget(input, row, 1+j, 1, ((j+1)==n ? 5-n : 1)); shown.append(input); connect(input, SIGNAL(valueChanged(double)), signaler, SLOT(map())); signaler->setMapping(input, v.name + QString().setNum(i) + QString().setNum(j)); } if( (i+1) < n ) row += 1; } if( v.minSet ) { varname += "min: " + QString().setNum(v.fmin) + " "; } if( v.maxSet ) { varname += " max: " + QString().setNum(v.fmax); } break; } case UniformVar::SAMPLER1D: case UniformVar::SAMPLER2D: case UniformVar::SAMPLER3D: case UniformVar::SAMPLERCUBE: case UniformVar::SAMPLER1DSHADOW: case UniformVar::SAMPLER2DSHADOW: { QLabel * link = new QLabel( "<font color=\"blue\">See texture tab</font>" ); layoutUniform->addWidget(link, row, 1, 1, 4); shown.append(link); break; } case UniformVar::OTHER: { QLabel * unimpl = new QLabel( "[Unimplemented mask]" ); layoutUniform->addWidget( unimpl, row, 1, 1, 4); shown.append(unimpl); } } QLabel * lblvar = new QLabel(varname); layoutUniform->addWidget( lblvar, row, 0 ); shown.append(lblvar); row += 1; } // Texture in the second tab for( int ii = 0, row = 0; ii < 2; ii++ ) for( int jj = 0; jj < ( ii == 0 ? pass_selected -> vertexUniformVariableSize() : pass_selected -> fragmentUniformVariableSize()); jj++ ) { UniformVar v = pass_selected -> getUniform( jj, ii == 0 ? RmPass::VERTEX : RmPass::FRAGMENT ); if( v.textureFilename.isNull() ) continue; QFileInfo finfo(v.textureFilename); QDir textureDir = QDir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) if (textureDir.dirName() == "debug" || textureDir.dirName() == "release" || textureDir.dirName() == "plugins" ) textureDir.cdUp(); #elif defined(Q_OS_MAC) if (textureDir.dirName() == "MacOS") { for(int i=0;i<4;++i){ textureDir.cdUp(); if(textureDir.exists("textures")) break; } } #endif textureDir.cd("textures"); QFile f( textureDir.absoluteFilePath(finfo.fileName())); QString varname = ( ii == 0 ? "Vertex texture: " : "Fragment texture: "); varname += UniformVar::getStringFromUniformType(v.type) + " " + v.name + "<br>"; varname += "Filename: " + finfo.fileName() + (f.exists() ? "" : " [<font color=\"red\">not found</font>]"); for( int k = 0; k < v.textureGLStates.size(); k++ ) { varname += "<br>OpenGL state: " + v.textureGLStates[k].getName() + ": " + parser->convertGlStateToString(v.textureGLStates[k]); } QLabel * lblvar = new QLabel(varname); lblvar -> setTextFormat( Qt::RichText ); lblvar -> setObjectName( v.name + "00" ); layoutTextures->addWidget( lblvar, row++, 0, 1, 2 ); shown.append(lblvar); QLineEdit * txtChoose = new QLineEdit( textureDir.absoluteFilePath(finfo.fileName()) ); txtChoose -> setObjectName( v.name + "11" ); layoutTextures->addWidget( txtChoose, row, 0 ); shown.append(txtChoose); connect(txtChoose, SIGNAL(editingFinished()), signaler, SLOT(map())); signaler->setMapping(txtChoose, v.name + "11"); QPushButton * btnChoose = new QPushButton( "Browse" ); btnChoose -> setObjectName( v.name + "22" ); layoutTextures->addWidget( btnChoose, row, 1 ); shown.append(btnChoose); connect(btnChoose, SIGNAL(clicked()), signaler, SLOT(map())); signaler->setMapping(btnChoose, v.name + "22"); row++; } // OpenGL Status if( pass_selected -> openGLStatesSize() == 0 ) { QLabel * lblgl = new QLabel( "No openGL states set" ); layoutOpengl->addWidget( lblgl, row, 0 ); shown.append(lblgl); } else { for( int i = 0, row = 0; i < pass_selected -> openGLStatesSize(); i++ ) { QString str = "OpenGL state: " + pass_selected -> getOpenGLState(i).getName(); str += " (" + QString().setNum(pass_selected -> getOpenGLState(i).getState()) + "): " + QString().setNum(pass_selected -> getOpenGLState(i).getValue()); QLabel * lblgl = new QLabel(str); layoutOpengl->addWidget( lblgl, row++, 0 ); shown.append(lblgl); } } }
void BFSForest::buildForest() { QList<RoadVertexDesc> seeds; QList<int> groups; QMap<RoadEdgeDesc, bool> visitedEdge; QMap<RoadVertexDesc, bool> visitedVertex; // ルートとして与えられた頂点について for (int i = 0; i < roots.size() / 2; i++) { RoadVertexDesc src = roots[i * 2]; RoadVertexDesc tgt = roots[i * 2 + 1]; // エッジの取得 RoadEdgeDesc e_desc = GraphUtil::getEdge(roads, src, tgt); // エッジのグループ、seedフラグを設定 roads->graph[e_desc]->group = i; roads->graph[e_desc]->seed = true; // 頂点srcが既存のシードと重複している場合 if (seeds.contains(src)) { // 頂点srcをコピーする RoadVertex* v = new RoadVertex(roads->graph[src]->pt); RoadVertexDesc new_src = boost::add_vertex(roads->graph); roads->graph[new_src] = v; // 古いエッジを削除 roads->graph[e_desc]->valid = false; // 新しいエッジを追加 e_desc = GraphUtil::addEdge(roads, new_src, tgt, roads->graph[e_desc]); src = new_src; } // 頂点tgtが既存のシードと重複している場合 if (seeds.contains(tgt)) { // 頂点tgtをコピーする RoadVertex* v = new RoadVertex(roads->graph[tgt]->pt); RoadVertexDesc new_tgt = boost::add_vertex(roads->graph); roads->graph[new_tgt] = v; // 古いエッジを削除 roads->graph[e_desc]->valid = false; // 新しいエッジを追加 e_desc = GraphUtil::addEdge(roads, src, new_tgt, roads->graph[e_desc]); tgt = new_tgt; } // src、tgtが更新されたかも知れないので、おおもとのデータも更新しておく roots[i * 2] = src; roots[i * 2 + 1] = tgt; // シードを登録する seeds.push_back(src); seeds.push_back(tgt); groups.push_back(i); groups.push_back(i); // ルートエッジ・頂点を訪問済みとマークする visitedEdge[e_desc] = true; visitedVertex[src] = true; visitedVertex[tgt] = true; } // ルート頂点リストからスタートして、BFSで全頂点を訪問する while (!seeds.empty()) { RoadVertexDesc parent = seeds.front(); seeds.pop_front(); int group = groups.front(); groups.pop_front(); std::vector<RoadVertexDesc> children; // 隣接ノードリストを先に洗い出す std::vector<RoadVertexDesc> nodes; std::vector<RoadEdgeDesc> edges; RoadOutEdgeIter ei, eend; for (boost::tie(ei, eend) = boost::out_edges(parent, roads->graph); ei != eend; ++ei) { if (!roads->graph[*ei]->valid) continue; if (visitedEdge[*ei]) continue; // 隣接ノードを取得 RoadVertexDesc child = boost::target(*ei, roads->graph); if (!roads->graph[child]->valid) continue; if (getParent(parent).contains(child)) continue; nodes.push_back(child); edges.push_back(*ei); // 当該エッジを通過したとマークする visitedEdge[*ei] = true; } // 洗い出した隣接ノードに対して、訪問する for (int i = 0; i < nodes.size(); i++) { RoadVertexDesc child = nodes[i]; if (visitedVertex.contains(child)) { // 訪問済みの場合 RoadEdgeDesc orig_e_desc = GraphUtil::getEdge(roads, parent, child); // もともとのエッジを無効にする roads->graph[orig_e_desc]->valid = false; // 対象ノードが訪問済みの場合、対象ノードをコピーして子ノードにする RoadVertexDesc child2 = GraphUtil::addVertex(roads, roads->graph[child]); roads->graph[child2]->virt = false; // エッジ作成 RoadEdgeDesc e_desc = GraphUtil::addEdge(roads, parent, child2, roads->graph[orig_e_desc]); roads->graph[e_desc]->group = group; children.push_back(child2); } else { // 未訪問の場合 visitedVertex[child] = true; roads->graph[edges[i]]->group = group; children.push_back(child); seeds.push_back(child); groups.push_back(group); } } this->children.insert(parent, children); } }
void InsertLinkTableDialog::on_addButton_clicked() { QList<QTableWidgetItem *> aItems=ui->sourceTableWidget->selectedItems(); QList<int> rows; for (int i=0; i<aItems.length(); i++) { if (!rows.contains(aItems.at(i)->row())) { rows.append(aItems.at(i)->row()); } } for (int e=0; e<rows.length()-1; e++) { int min=rows.at(e); int minIndex=e; for (int i=e+1; i<rows.length(); i++) { if (rows.at(i)<min) { min=rows.at(i); minIndex=i; } } rows.swap(e, minIndex); } for (int i=0; i<rows.length(); i++) { int aSourceRow=rows.at(i); int aDestRow=-1; if (ui->beginRadioButton->isChecked()) { aDestRow=mBeginPos; mBeginPos++; } else if (ui->beforeRadioButton->isChecked()) { aDestRow=mDestTable->ui->dataTableWidget->currentRow(); mBeginPos=0; } else if (ui->afterRadioButton->isChecked()) { aDestRow=mDestTable->ui->dataTableWidget->currentRow()+1; mBeginPos=0; } else if (ui->endRadioButton->isChecked()) { aDestRow=mDestTable->ui->dataTableWidget->rowCount(); mBeginPos=0; } if (ui->sourceTableWidget->itemDelegateForRow(aSourceRow)) { mDestTable->insertMiddleRow(aDestRow); mDestTable->ui->dataTableWidget->item(aDestRow, 0)->setText(ui->sourceTableWidget->item(aSourceRow, 0)->text()); } else { mDestTable->insertRow(aDestRow); for (int j=0; j<ui->sourceTableWidget->columnCount() && j<mDestTable->ui->dataTableWidget->columnCount(); j++) { EColumnType aDestColumnType=mDestTable->typeColumns.at(j).column->type(); EColumnType aSourceColumnType=mSourceTable->typeColumns.at(j).column->type(); if (aDestColumnType==ctInteger) { if (!((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mIsAutoInc) { if (aSourceColumnType==ctInteger) { QString aText=ui->sourceTableWidget->item(aSourceRow, j)->text(); int removeBefore=0; int removeAfter=0; if (!((IntegerColumn*)mSourceTable->typeColumns.at(j).column)->mSplitRows) { removeBefore=((IntegerColumn*)mSourceTable->typeColumns.at(j).column)->mPrefix.length(); removeAfter=((IntegerColumn*)mSourceTable->typeColumns.at(j).column)->mPostfix.length(); } aText.remove(aText.length()-removeAfter, removeAfter); aText.remove(0, removeBefore); double aValue=aText.toDouble(); if (((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mSplitRows) { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(QString::number(aValue, 'f', ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mDecimals)); } else { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText( ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mPrefix+ QString::number(aValue, 'f', ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mDecimals)+ ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mPostfix); } } else { bool ok=true; double aValue; if (aSourceColumnType==ctBool) { if (ui->sourceTableWidget->item(aSourceRow, j)->checkState()==Qt::Checked) { aValue=1; } else { aValue=0; } } else { aValue=ui->sourceTableWidget->item(aSourceRow, j)->text().toDouble(&ok); } if (ok) { if (((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mSplitRows) { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(QString::number(aValue, 'f', ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mDecimals)); } else { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText( ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mPrefix+ QString::number(aValue, 'f', ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mDecimals)+ ((IntegerColumn*)mDestTable->typeColumns.at(j).column)->mPostfix); } } } } } else if (aDestColumnType==ctString || aDestColumnType==ctList || aDestColumnType==ctExtendedList) { if (aSourceColumnType==ctBool) { if (ui->sourceTableWidget->item(aSourceRow, j)->checkState()==Qt::Checked) { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText("1"); } else { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText("0"); } } else { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(ui->sourceTableWidget->item(aSourceRow, j)->text()); } } else if (aDestColumnType==ctBool) { if (aSourceColumnType==ctBool) { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setCheckState(ui->sourceTableWidget->item(aSourceRow, j)->checkState()); } else { if (ui->sourceTableWidget->item(aSourceRow, j)->text()=="1") { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setCheckState(Qt::Checked); } else if (ui->sourceTableWidget->item(aSourceRow, j)->text()=="0") { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setCheckState(Qt::Unchecked); } } } else if (aDestColumnType==ctDate) { QDate aDate=QDate::fromString(ui->sourceTableWidget->item(aSourceRow, j)->text(), "dd.MM.yyyy"); if (aDate.isValid()) { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(ui->sourceTableWidget->item(aSourceRow, j)->text()); } } else if (aDestColumnType==ctTime) { QTime aTime=QTime::fromString(ui->sourceTableWidget->item(aSourceRow, j)->text(), "h:mm:ss"); if (aTime.isValid()) { mDestTable->ui->dataTableWidget->item(aDestRow, j)->setText(ui->sourceTableWidget->item(aSourceRow, j)->text()); } } } } } }
void appendUnique(QList<T> &left, const QList<T> &right) { foreach (const T &value, right) if (!left.contains(value)) left += value; }
void Plugin::checkDates () { if (!XmlSettingsManager::Instance ().property ("NotifyEnabled").toBool ()) return; const auto& ranges = XmlSettingsManager::Instance () .property ("NotificationDays").toString ().split (',', QString::SkipEmptyParts); QList<int> allowedDays; Q_FOREACH (const auto& range, ranges) { if (!range.contains ('-')) { bool ok = false; const int day = range.toInt (&ok); if (ok) allowedDays << day; continue; } const auto& ends = range.split ('-', QString::SkipEmptyParts); if (ends.size () != 2) continue; bool bOk = false, eOk = false; const int begin = ends.at (0).toInt (&bOk); const int end = ends.at (1).toInt (&eOk); if (!bOk || !eOk) continue; for (int i = begin; i <= end; ++i) allowedDays << i; } const auto& today = QDate::currentDate (); auto accs = AzothProxy_->GetAllAccounts (); Q_FOREACH (auto accObj, AzothProxy_->GetAllAccounts ()) { auto acc = qobject_cast<IAccount*> (accObj); auto extSelf = qobject_cast<IExtSelfInfoAccount*> (accObj); Q_FOREACH (auto entryObj, acc->GetCLEntries ()) { auto entry = qobject_cast<ICLEntry*> (entryObj); if (!entry || entry->GetEntryType () != ICLEntry::ETChat) continue; if (extSelf && extSelf->GetSelfContact () == entryObj) continue; auto meta = qobject_cast<IMetaInfoEntry*> (entryObj); if (!meta) continue; auto dt = meta->GetMetaInfo (IMetaInfoEntry::DataField::BirthDate).toDate (); if (!dt.isValid ()) continue; dt.setDate (today.year (), dt.month (), dt.day ()); if (!dt.isValid ()) continue; int days = today.daysTo (dt); if (days < 0) { dt.setDate (today.year () + 1, dt.month (), dt.day ()); if (!dt.isValid ()) continue; days = today.daysTo (dt); } if (allowedDays.contains (days)) NotifyBirthday (entry, days); } } }
//============== // PRIVATE SLOTS //============== void LTaskManagerPlugin::UpdateButtons(){ updating = QDateTime::currentDateTime(); //global time stamp QDateTime ctime = updating; //current thread time stamp //Get the current window list QList<WId> winlist = LSession::handle()->XCB->WindowList(); // Ignore the windows which don't want to be listed for (int i = 0; i < winlist.length(); i++) { QList<LXCB::WINDOWSTATE> states = LSession::handle()->XCB->WM_Get_Window_States(winlist[i]); for (int j = 0; j < states.length(); j++) { if (states[j] == LXCB::S_SKIP_TASKBAR) { // Skip taskbar window winlist.removeAt(i); i--; break; } } } //Do not change the status of the previously active window if it just changed to a non-visible window //WId activeWin = LSession::handle()->XCB->ActiveWindow(); //bool skipActive = !winlist.contains(activeWin); //qDebug() << "Update Buttons:" << winlist; if(updating > ctime){ return; } //another thread kicked off already - stop this one //Now go through all the current buttons first for(int i=0; i<BUTTONS.length(); i++){ //Get the windows managed in this button QList<WId> WI = BUTTONS[i]->windows(); bool updated=false; if(updating > ctime){ return; } //another thread kicked off already - stop this one //Loop over all the windows for this button for(int w=0; w<WI.length(); w++){ if(updating > ctime){ return; } //another thread kicked off already - stop this one if( winlist.contains( WI[w] ) ){ //Still current window - update it later winlist.removeAll(WI[w] ); //remove this window from the list since it is done }else{ //Window was closed - remove it if(WI.length()==1){ //Remove the entire button //qDebug() << "Window Closed: Remove Button" ; this->layout()->takeAt(i); //remove from the layout BUTTONS.takeAt(i)->deleteLater(); i--; updated = true; //prevent updating a removed button break; //break out of the button->window loop }else{ //qDebug() << "Window Closed: Remove from button:" << WI[w].windowID() << "Button:" << w; BUTTONS[i]->rmWindow(WI[w]); // one of the multiple windows for the button WI.removeAt(w); //remove this window from the list w--; } updated=true; //button already changed } if(updating > ctime){ return; } //another thread kicked off already - stop this one } if(!updated){ //qDebug() << "Update Button:" << i; if(updating > ctime){ return; } //another thread kicked off already - stop this one //if(!skipActive || !BUTTONS[i]->isActive()){ QTimer::singleShot(1,BUTTONS[i], SLOT(UpdateButton()) ); //keep moving on //} } } //Now go through the remaining windows for(int i=0; i<winlist.length(); i++){ //New windows, create buttons for each (add grouping later) if(updating > ctime){ return; } //another thread kicked off already - stop this one //Check for a button that this can just be added to QString ctxt = LSession::handle()->XCB->WindowClass(winlist[i]); bool found = false; for(int b=0; b<BUTTONS.length(); b++){ if(updating > ctime){ return; } //another thread kicked off already - stop this one if(BUTTONS[b]->classname()== ctxt && usegroups){ //This adds a window to an existing group found = true; //qDebug() << "Add Window to Button:" << b; BUTTONS[b]->addWindow(winlist[i]); break; } } if(!found){ if(updating > ctime){ return; } //another thread kicked off already - stop this one //No group, create a new button //qDebug() << "New Button"; LTaskButton *but = new LTaskButton(this, usegroups); but->addWindow( winlist[i] ); if(this->layout()->direction()==QBoxLayout::LeftToRight){ but->setIconSize(QSize(this->height(), this->height())); but->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); }else{ but->setIconSize(QSize(this->width(), this->width())); but->setToolButtonStyle(Qt::ToolButtonIconOnly); } this->layout()->addWidget(but); connect(but, SIGNAL(MenuClosed()), this, SIGNAL(MenuClosed())); BUTTONS << but; } } }
bool MeshGenerator::writeToHermes() { // edges XMLSubdomains::edges_type edges; for (int i = 0; i < edgeList.count(); i++) if (edgeList[i].isUsed && edgeList[i].marker != -1) edges.ed().push_back(XMLSubdomains::ed(edgeList[i].node[0], edgeList[i].node[1], QString::number(edgeList[i].marker).toStdString(), i)); // curved edges XMLMesh::curves_type curves; for (int i = 0; i<edgeList.count(); i++) { if (edgeList[i].marker != -1) { // curve if (Agros2D::scene()->edges->at(edgeList[i].marker)->angle() > 0.0 && Agros2D::scene()->edges->at(edgeList[i].marker)->isCurvilinear()) { int segments = Agros2D::scene()->edges->at(edgeList[i].marker)->segments(); // subdivision angle and chord double theta = deg2rad(Agros2D::scene()->edges->at(edgeList[i].marker)->angle()) / double(segments); double chord = 2 * Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * sin(theta / 2.0); // length of short chord double chordShort = (nodeList[edgeList[i].node[1]] - nodeList[edgeList[i].node[0]]).magnitude(); // direction Point center = Agros2D::scene()->edges->at(edgeList[i].marker)->center(); int direction = (((nodeList[edgeList[i].node[0]].x-center.x)*(nodeList[edgeList[i].node[1]].y-center.y) - (nodeList[edgeList[i].node[0]].y-center.y)*(nodeList[edgeList[i].node[1]].x-center.x)) > 0) ? 1 : -1; double angle = direction * theta * chordShort / chord; curves.arc().push_back(XMLMesh::arc(edgeList[i].node[0], edgeList[i].node[1], rad2deg(angle))); } } } // move nodes (arcs) for (int i = 0; i<edgeList.count(); i++) { // assert(edgeList[i].marker >= 0); // markers changed to marker - 1, check... if (edgeList[i].marker != -1) { // curve if (Agros2D::scene()->edges->at(edgeList[i].marker)->angle() > 0.0 && Agros2D::scene()->edges->at(edgeList[i].marker)->isCurvilinear()) { // angle Point center = Agros2D::scene()->edges->at(edgeList[i].marker)->center(); double pointAngle1 = atan2(center.y - nodeList[edgeList[i].node[0]].y, center.x - nodeList[edgeList[i].node[0]].x) - M_PI; double pointAngle2 = atan2(center.y - nodeList[edgeList[i].node[1]].y, center.x - nodeList[edgeList[i].node[1]].x) - M_PI; nodeList[edgeList[i].node[0]].x = center.x + Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * cos(pointAngle1); nodeList[edgeList[i].node[0]].y = center.y + Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * sin(pointAngle1); nodeList[edgeList[i].node[1]].x = center.x + Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * cos(pointAngle2); nodeList[edgeList[i].node[1]].y = center.y + Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * sin(pointAngle2); } } } // vertices XMLMesh::vertices_type vertices; for (int i = 0; i<nodeList.count(); i++) vertices.v().push_back(std::auto_ptr<XMLMesh::v>(new XMLMesh::v(QString::number(nodeList[i].x).toStdString(), QString::number(nodeList[i].y).toStdString(), i))); // elements XMLSubdomains::elements_type elements; for (int i = 0; i<elementList.count(); i++) if (elementList[i].isUsed) if (elementList[i].isTriangle()) elements.el().push_back(XMLSubdomains::t_t(elementList[i].node[0], elementList[i].node[1], elementList[i].node[2], QString::number(elementList[i].marker).toStdString(), i)); else elements.el().push_back(XMLSubdomains::q_t(elementList[i].node[0], elementList[i].node[1], elementList[i].node[2], QString::number(elementList[i].marker).toStdString(), i, elementList[i].node[3])); // find edge neighbours // for each vertex list elements that it belogns to QList<QSet<int> > vertexElements; vertexElements.reserve(nodeList.count()); for (int i = 0; i < nodeList.count(); i++) vertexElements.push_back(QSet<int>()); for (int i = 0; i < elementList.count(); i++) if (elementList[i].isUsed) for(int elemNode = 0; elemNode < (elementList[i].isTriangle() ? 3 : 4); elemNode++) vertexElements[elementList[i].node[elemNode]].insert(i); for (int i = 0; i < edgeList.count(); i++) { if (edgeList[i].isUsed && edgeList[i].marker != -1) { QSet<int> neighbours = vertexElements[edgeList[i].node[0]]; neighbours.intersect(vertexElements[edgeList[i].node[1]]); assert((neighbours.size() > 0) && (neighbours.size() <= 2)); edgeList[i].neighElem[0] = neighbours.values()[0]; if(neighbours.size() == 2) edgeList[i].neighElem[1] = neighbours.values()[1]; } } // subdomains XMLSubdomains::subdomains subdomains; if (Agros2D::problem()->fieldInfos().isEmpty()) { // one domain XMLSubdomains::subdomain subdomain(Agros2D::problem()->fieldInfos().begin().value()->fieldId().toStdString()); subdomains.subdomain().push_back(subdomain); } else { // more subdomains foreach (FieldInfo* fieldInfo, Agros2D::problem()->fieldInfos()) { XMLSubdomains::subdomain subdomain(fieldInfo->fieldId().toStdString()); subdomain.elements().set(XMLSubdomains::subdomain::elements_type()); subdomain.boundary_edges().set(XMLSubdomains::subdomain::boundary_edges_type()); subdomain.inner_edges().set(XMLSubdomains::subdomain::inner_edges_type()); for (int i = 0; i<elementList.count(); i++) if (elementList[i].isUsed && (Agros2D::scene()->labels->at(elementList[i].marker)->marker(fieldInfo) != SceneMaterialContainer::getNone(fieldInfo))) subdomain.elements()->i().push_back(i); QList<int> unassignedEdges; for (int i = 0; i < edgeList.count(); i++) { if (edgeList[i].isUsed && edgeList[i].marker != -1) { int numNeighWithField = 0; for (int neigh_i = 0; neigh_i < 2; neigh_i++) { int neigh = edgeList[i].neighElem[neigh_i]; if (neigh != -1) { if (Agros2D::scene()->labels->at(elementList[neigh].marker)->marker(fieldInfo) != SceneMaterialContainer::getNone(fieldInfo)) numNeighWithField++; } } // edge has boundary condition prescribed for this field bool hasFieldBoundaryCondition = (Agros2D::scene()->edges->at(edgeList[i].marker)->hasMarker(fieldInfo) && (Agros2D::scene()->edges->at(edgeList[i].marker)->marker(fieldInfo) != SceneBoundaryContainer::getNone(fieldInfo))); if (numNeighWithField == 1) { // edge is on "boundary" of the field, should have boundary condition prescribed if (!hasFieldBoundaryCondition) if (!unassignedEdges.contains(edgeList[i].marker)) unassignedEdges.append(edgeList[i].marker); subdomain.boundary_edges()->i().push_back(i); } else if (numNeighWithField == 2) { // todo: we could enforce not to have boundary conditions prescribed inside: // assert(!hasFieldBoundaryCondition); subdomain.inner_edges()->i().push_back(i); } } } // not assigned boundary if (unassignedEdges.count() > 0) { QString list; foreach (int index, unassignedEdges) list += QString::number(index) + ", "; Agros2D::log()->printError(tr("Mesh generator"), tr("Boundary condition for %1 is not assigned on following edges: %2").arg(fieldInfo->name()).arg(list.left(list.count() - 2))); return false; } subdomains.subdomain().push_back(subdomain); }
void TvShow::clear(QList<int> infos) { if (infos.contains(TvShowScraperInfos::Actors)) m_actors.clear(); if (infos.contains(TvShowScraperInfos::Banner)) { m_banners.clear(); m_imagesToRemove.remove(ImageType::TvShowBanner); m_images.insert(ImageType::TvShowBanner, QByteArray()); m_hasImageChanged.insert(ImageType::TvShowBanner, false); } if (infos.contains(TvShowScraperInfos::Certification)) m_certification.clear(); if (infos.contains(TvShowScraperInfos::FirstAired)) m_firstAired = QDate(2000, 02, 30); // invalid date if (infos.contains(TvShowScraperInfos::Genres)) m_genres.clear(); if (infos.contains(TvShowScraperInfos::Network)) m_network.clear(); if (infos.contains(TvShowScraperInfos::Overview)) m_overview.clear(); if (infos.contains(TvShowScraperInfos::Poster)) { m_posters.clear(); m_imagesToRemove.remove(ImageType::TvShowPoster); m_images.insert(ImageType::TvShowPoster, QByteArray()); m_hasImageChanged.insert(ImageType::TvShowPoster, false); } if (infos.contains(TvShowScraperInfos::Rating)) { m_rating = 0; m_votes = 0; m_top250 = 0; } if (infos.contains(TvShowScraperInfos::SeasonPoster)) { clearSeasonImageType(ImageType::TvShowSeasonPoster); m_seasonPosters.clear(); m_imagesToRemove.remove(ImageType::TvShowSeasonPoster); } if (infos.contains(TvShowScraperInfos::SeasonBackdrop)) { clearSeasonImageType(ImageType::TvShowSeasonBackdrop); m_seasonBackdrops.clear(); m_imagesToRemove.remove(ImageType::TvShowSeasonBackdrop); } if (infos.contains(TvShowScraperInfos::SeasonBanner)) { clearSeasonImageType(ImageType::TvShowSeasonBanner); m_seasonBanners.clear(); m_imagesToRemove.remove(ImageType::TvShowSeasonBanner); } if (infos.contains(TvShowScraperInfos::SeasonThumb)) { clearSeasonImageType(ImageType::TvShowSeasonThumb); m_seasonThumbs.clear(); m_imagesToRemove.remove(ImageType::TvShowSeasonThumb); } if (infos.contains(TvShowScraperInfos::Title)) m_showTitle.clear(); if (infos.contains(TvShowScraperInfos::Tags)) m_tags.clear(); if (infos.contains(TvShowScraperInfos::Fanart)) { m_backdrops.clear(); m_imagesToRemove.remove(ImageType::TvShowBackdrop); m_images.insert(ImageType::TvShowBackdrop, QByteArray()); m_hasImageChanged.insert(ImageType::TvShowBackdrop, false); } if (infos.contains(TvShowScraperInfos::ExtraArts)) { m_images.insert(ImageType::TvShowLogos, QByteArray()); m_hasImageChanged.insert(ImageType::TvShowLogos, false); m_images.insert(ImageType::TvShowThumb, QByteArray()); m_hasImageChanged.insert(ImageType::TvShowThumb, false); m_images.insert(ImageType::TvShowClearArt, QByteArray()); m_hasImageChanged.insert(ImageType::TvShowClearArt, false); m_images.insert(ImageType::TvShowCharacterArt, QByteArray()); m_hasImageChanged.insert(ImageType::TvShowCharacterArt, false); m_imagesToRemove.remove(ImageType::TvShowLogos); m_imagesToRemove.remove(ImageType::TvShowClearArt); m_imagesToRemove.remove(ImageType::TvShowCharacterArt); m_imagesToRemove.remove(ImageType::TvShowThumb); } if (infos.contains(TvShowScraperInfos::ExtraFanarts)) { m_extraFanartsToRemove.clear(); m_extraFanartImagesToAdd.clear(); m_extraFanarts.clear(); } if (infos.contains(TvShowScraperInfos::Runtime)) m_runtime = 0; m_hasChanged = false; }
void DSDDemod::webapiReverseSendSettings(QList<QString>& channelSettingsKeys, const DSDDemodSettings& settings, bool force) { SWGSDRangel::SWGChannelSettings *swgChannelSettings = new SWGSDRangel::SWGChannelSettings(); swgChannelSettings->setTx(0); swgChannelSettings->setChannelType(new QString("DSDDemod")); swgChannelSettings->setDsdDemodSettings(new SWGSDRangel::SWGDSDDemodSettings()); SWGSDRangel::SWGDSDDemodSettings *swgDSDDemodSettings = swgChannelSettings->getDsdDemodSettings(); // transfer data that has been modified. When force is on transfer all data except reverse API data if (channelSettingsKeys.contains("inputFrequencyOffset") || force) { swgDSDDemodSettings->setInputFrequencyOffset(settings.m_inputFrequencyOffset); } if (channelSettingsKeys.contains("rfBandwidth") || force) { swgDSDDemodSettings->setRfBandwidth(settings.m_rfBandwidth); } if (channelSettingsKeys.contains("fmDeviation") || force) { swgDSDDemodSettings->setFmDeviation(settings.m_fmDeviation); } if (channelSettingsKeys.contains("demodGain") || force) { swgDSDDemodSettings->setDemodGain(settings.m_demodGain); } if (channelSettingsKeys.contains("volume") || force) { swgDSDDemodSettings->setVolume(settings.m_volume); } if (channelSettingsKeys.contains("baudRate") || force) { swgDSDDemodSettings->setBaudRate(settings.m_baudRate); } if (channelSettingsKeys.contains("squelchGate") || force) { swgDSDDemodSettings->setSquelchGate(settings.m_squelchGate); } if (channelSettingsKeys.contains("squelch") || force) { swgDSDDemodSettings->setSquelch(settings.m_squelch); } if (channelSettingsKeys.contains("audioMute") || force) { swgDSDDemodSettings->setAudioMute(settings.m_audioMute ? 1 : 0); } if (channelSettingsKeys.contains("enableCosineFiltering") || force) { swgDSDDemodSettings->setEnableCosineFiltering(settings.m_enableCosineFiltering ? 1 : 0); } if (channelSettingsKeys.contains("syncOrConstellation") || force) { swgDSDDemodSettings->setSyncOrConstellation(settings.m_syncOrConstellation ? 1 : 0); } if (channelSettingsKeys.contains("slot1On") || force) { swgDSDDemodSettings->setSlot1On(settings.m_slot1On ? 1 : 0); } if (channelSettingsKeys.contains("slot2On") || force) { swgDSDDemodSettings->setSlot2On(settings.m_slot2On ? 1 : 0); } if (channelSettingsKeys.contains("tdmaStereo") || force) { swgDSDDemodSettings->setTdmaStereo(settings.m_tdmaStereo ? 1 : 0); } if (channelSettingsKeys.contains("pllLock") || force) { swgDSDDemodSettings->setPllLock(settings.m_pllLock ? 1 : 0); } if (channelSettingsKeys.contains("rgbColor") || force) { swgDSDDemodSettings->setRgbColor(settings.m_rgbColor); } if (channelSettingsKeys.contains("title") || force) { swgDSDDemodSettings->setTitle(new QString(settings.m_title)); } if (channelSettingsKeys.contains("audioDeviceName") || force) { swgDSDDemodSettings->setAudioDeviceName(new QString(settings.m_audioDeviceName)); } if (channelSettingsKeys.contains("highPassFilter") || force) { swgDSDDemodSettings->setHighPassFilter(settings.m_highPassFilter ? 1 : 0); } if (channelSettingsKeys.contains("traceLengthMutliplier") || force) { swgDSDDemodSettings->setTraceLengthMutliplier(settings.m_traceLengthMutliplier); } if (channelSettingsKeys.contains("traceStroke") || force) { swgDSDDemodSettings->setTraceStroke(settings.m_traceStroke); } if (channelSettingsKeys.contains("traceDecay") || force) { swgDSDDemodSettings->setTraceDecay(settings.m_traceDecay); } QString channelSettingsURL = QString("http://%1:%2/sdrangel/deviceset/%3/channel/%4/settings") .arg(settings.m_reverseAPIAddress) .arg(settings.m_reverseAPIPort) .arg(settings.m_reverseAPIDeviceIndex) .arg(settings.m_reverseAPIChannelIndex); m_networkRequest.setUrl(QUrl(channelSettingsURL)); m_networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); QBuffer *buffer=new QBuffer(); buffer->open((QBuffer::ReadWrite)); buffer->write(swgChannelSettings->asJson().toUtf8()); buffer->seek(0); // Always use PATCH to avoid passing reverse API settings m_networkManager->sendCustomRequest(m_networkRequest, "PATCH", buffer); delete swgChannelSettings; }
void XSqlQuery::addErrorListener(XSqlQueryErrorListener* listener) { if(!_errorListeners.contains(listener)) _errorListeners.append(listener); }
bool Slash::IsAvailable(const Player *player, const Card *slash, bool considerSpecificAssignee) { Slash *newslash = new Slash(Card::NoSuit, 0); newslash->deleteLater(); #define THIS_SLASH (slash == NULL ? newslash : slash) if (player->isCardLimited(THIS_SLASH, Card::MethodUse)) return false; if (player->getPhase() == Player::Play && Sanguosha->getCurrentCardUseReason() == CardUseStruct::CARD_USE_REASON_PLAY) { QList<int> ids; if (slash) { if (slash->isVirtualCard()) { if (slash->subcardsLength() > 0) ids = slash->getSubcards(); } else { ids << slash->getEffectiveId(); } } bool has_weapon = (player->hasWeapon("Crossbow") || player->hasWeapon("VSCrossbow")) && ids.contains(player->getWeapon()->getEffectiveId()); if ((!has_weapon && player->hasWeapon("Crossbow")) || player->canSlashWithoutCrossbow(THIS_SLASH)) return true; int used = player->getSlashCount(); int valid = 1 + Sanguosha->correctCardTarget(TargetModSkill::Residue, player, newslash); if ((!has_weapon && player->hasWeapon("VSCrossbow")) && used < valid + 3) return true; if (considerSpecificAssignee) { QStringList assignee_list = player->property("extra_slash_specific_assignee").toString().split("+"); if (!assignee_list.isEmpty()) { foreach (const Player *p, player->getAliveSiblings()) { if (assignee_list.contains(p->objectName()) && player->canSlash(p, THIS_SLASH)) return true; } } }
KrPopupMenu::KrPopupMenu(KrPanel *thePanel, QWidget *parent) : QMenu(parent), panel(thePanel), empty(false), multipleSelections(false), actions(0), _item(0) { #ifdef __LIBKONQ__ konqMenu = 0; konqMenuActions = 0; #endif KrViewItemList items; panel->view->getSelectedKrViewItems(&items); for (KrViewItemList::Iterator it = items.begin(); it != items.end(); ++it) { vfile *file = panel->func->files()->vfs_search(((*it)->name())); QUrl url = file->vfile_getUrl(); _items.append(KFileItem(url, file->vfile_getMime(), file->vfile_getMode())); } if (items.empty()) { addCreateNewMenu(); addSeparator(); addEmptyMenuEntries(); return; } else if (items.size() > 1) multipleSelections = true; QList<QString> protocols; for (int i = 0; i < items.size(); ++i) { protocols.append(panel->func->getVFile(items[ i ]) ->vfile_getUrl().scheme()); } bool inTrash = protocols.contains("trash"); bool trashOnly = (protocols.count() == 1) && (protocols[ 0 ] == "trash"); KrViewItem *item = items.first(); vfile *vf = panel->func->getVFile(item); _item = &_items.first(); // ------------ the OPEN option - open preferred service QAction * openAct = addAction(i18n("Open/Run")); openAct->setData(QVariant(OPEN_ID)); if (!multipleSelections) { // meaningful only if one file is selected openAct->setIcon(item->icon()); openAct->setText(vf->vfile_isExecutable() && !vf->vfile_isDir() ? i18n("Run") : i18n("Open")); // open in a new tab (if folder) if (vf->vfile_isDir()) { QAction * openTab = addAction(i18n("Open in New Tab")); openTab->setData(QVariant(OPEN_TAB_ID)); openTab->setIcon(krLoader->loadIcon("tab-new", KIconLoader::Panel)); openTab->setText(i18n("Open in New Tab")); } addSeparator(); } // ------------- Preview - normal vfs only ? if (panel->func->files()->vfs_getType() == vfs::VFS_NORMAL) { // create the preview popup QStringList names; panel->gui->getSelectedNames(&names); preview.setUrls(panel->func->files() ->vfs_getFiles(names)); QAction *pAct = addMenu(&preview); pAct->setData(QVariant(PREVIEW_ID)); pAct->setText(i18n("Preview")); } // -------------- Open with: try to find-out which apps can open the file // this too, is meaningful only if one file is selected or if all the files // have the same mimetype ! QString mime = panel->func->getVFile(item)->vfile_getMime(); // check if all the list have the same mimetype for (int i = 1; i < items.size(); ++i) { if (panel->func->getVFile(items[ i ]) ->vfile_getMime() != mime) { mime.clear(); break; } } if (!mime.isEmpty()) { offers = KMimeTypeTrader::self()->query(mime); for (int i = 0; i < offers.count(); ++i) { QExplicitlySharedDataPointer<KService> service = offers[i]; if (service->isValid() && service->isApplication()) { openWith.addAction(krLoader->loadIcon(service->icon(), KIconLoader::Small), service->name())->setData(QVariant(SERVICE_LIST_ID + i)); } } openWith.addSeparator(); if (vf->vfile_isDir()) openWith.addAction(krLoader->loadIcon("utilities-terminal", KIconLoader::Small), i18n("Terminal"))->setData(QVariant(OPEN_TERM_ID)); openWith.addAction(i18n("Other..."))->setData(QVariant(CHOOSE_ID)); QAction *owAct = addMenu(&openWith); owAct->setData(QVariant(OPEN_WITH_ID)); owAct->setText(i18n("Open With")); addSeparator(); } // --------------- user actions QAction *uAct = new UserActionPopupMenu(panel->func->files()->vfs_getFile(item->name())); addAction(uAct); uAct->setText(i18n("User Actions")); #ifdef __LIBKONQ__ // -------------- konqueror menu // This section adds all Konqueror/Dolphin menu items. // It's now updated to KDE4 and working, I've just commented it out. // Section below this one adds only servicemenus. // Append only servicemenus //TODO: deprecated since KDE4.3: remove these three lines KonqPopupMenuInformation info; info.setItems(_items); info.setParentWidget(this); konqMenuActions = new KonqMenuActions(); //TODO: deprecated since KDE4.3: remove this line, use two commented lines konqMenuActions->setPopupMenuInfo(info); //konqMenuActions->setParentWidget( this ); //konqMenuActions->setItemListProperties( _items ); konqMenuActions->addActionsTo(this); addSeparator(); #endif // ------------- 'create new' submenu addCreateNewMenu(); addSeparator(); // ---------- COPY addAction(i18n("Copy..."))->setData(QVariant(COPY_ID)); if (panel->func->files() ->vfs_isWritable()) { // ------- MOVE addAction(i18n("Move..."))->setData(QVariant(MOVE_ID)); // ------- RENAME - only one file if (!multipleSelections && !inTrash) addAction(i18n("Rename"))->setData(QVariant(RENAME_ID)); // -------- MOVE TO TRASH KConfigGroup saver(krConfig, "General"); bool trash = saver.readEntry("Move To Trash", _MoveToTrash); if (trash && !inTrash) addAction(i18n("Move to Trash"))->setData(QVariant(TRASH_ID)); // -------- DELETE addAction(i18n("Delete"))->setData(QVariant(DELETE_ID)); // -------- SHRED - only one file /* if ( panel->func->files() ->vfs_getType() == vfs::VFS_NORMAL && !vf->vfile_isDir() && !multipleSelections ) addAction( i18n( "Shred" ) )->setData( QVariant( SHRED_ID ) );*/ } // ---------- link handling // create new shortcut or redirect links - only on local directories: if (panel->func->files() ->vfs_getType() == vfs::VFS_NORMAL) { addSeparator(); linkPopup.addAction(i18n("New Symlink..."))->setData(QVariant(NEW_SYMLINK_ID)); linkPopup.addAction(i18n("New Hardlink..."))->setData(QVariant(NEW_LINK_ID)); if (panel->func->getVFile(item)->vfile_isSymLink()) linkPopup.addAction(i18n("Redirect Link..."))->setData(QVariant(REDIRECT_LINK_ID)); QAction *linkAct = addMenu(&linkPopup); linkAct->setData(QVariant(LINK_HANDLING_ID)); linkAct->setText(i18n("Link Handling")); } addSeparator(); // ---------- calculate space if (panel->func->files() ->vfs_getType() == vfs::VFS_NORMAL && (vf->vfile_isDir() || multipleSelections)) addAction(panel->gui->actions()->actCalculate); // ---------- mount/umount/eject if (panel->func->files() ->vfs_getType() == vfs::VFS_NORMAL && vf->vfile_isDir() && !multipleSelections) { if (krMtMan.getStatus(panel->func->files() ->vfs_getFile(item->name()).path()) == KMountMan::MOUNTED) addAction(i18n("Unmount"))->setData(QVariant(UNMOUNT_ID)); else if (krMtMan.getStatus(panel->func->files() ->vfs_getFile(item->name()).path()) == KMountMan::NOT_MOUNTED) addAction(i18n("Mount"))->setData(QVariant(MOUNT_ID)); if (krMtMan.ejectable(panel->func->files() ->vfs_getFile(item->name()).path())) addAction(i18n("Eject"))->setData(QVariant(EJECT_ID)); } // --------- send by mail if (KrServices::supportedTools().contains("MAIL") && !vf->vfile_isDir()) { addAction(i18n("Send by Email"))->setData(QVariant(SEND_BY_EMAIL_ID)); } // --------- empty trash if (trashOnly) { addAction(i18n("Restore"))->setData(QVariant(RESTORE_TRASHED_FILE_ID)); addAction(i18n("Empty Trash"))->setData(QVariant(EMPTY_TRASH_ID)); } #ifdef SYNCHRONIZER_ENABLED // --------- synchronize if (panel->view->numSelected()) { addAction(i18n("Synchronize Selected Files..."))->setData(QVariant(SYNC_SELECTED_ID)); } #endif // --------- copy/paste addSeparator(); addAction(i18n("Copy to Clipboard"))->setData(QVariant(COPY_CLIP_ID)); if (panel->func->files() ->vfs_isWritable()) { addAction(i18n("Cut to Clipboard"))->setData(QVariant(MOVE_CLIP_ID)); addAction(i18n("Paste from Clipboard"))->setData(QVariant(PASTE_CLIP_ID)); } addSeparator(); // --------- properties addAction(panel->gui->actions()->actProperties); }
bool EGLInteropResource::ensureSurface(int w, int h) { if (dx_surface && width == w && height == h) return true; #if QTAV_HAVE(GUI_PRIVATE) QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface(); egl->dpy = static_cast<EGLDisplay>(nativeInterface->nativeResourceForContext("eglDisplay", QOpenGLContext::currentContext())); EGLConfig egl_cfg = static_cast<EGLConfig>(nativeInterface->nativeResourceForContext("eglConfig", QOpenGLContext::currentContext())); #else #ifdef Q_OS_WIN #if QT_VERSION < QT_VERSION_CHECK(5, 5, 0) #ifdef _MSC_VER #pragma message("ANGLE version in Qt<5.5 does not support eglQueryContext. You must upgrade your runtime ANGLE libraries") #else #warning "ANGLE version in Qt<5.5 does not support eglQueryContext. You must upgrade your runtime ANGLE libraries" #endif //_MSC_VER #endif #endif //Q_OS_WIN // eglQueryContext() added (Feb 2015): https://github.com/google/angle/commit/8310797003c44005da4143774293ea69671b0e2a egl->dpy = eglGetCurrentDisplay(); qDebug("EGL version: %s, client api: %s", eglQueryString(egl->dpy, EGL_VERSION), eglQueryString(egl->dpy, EGL_CLIENT_APIS)); // TODO: check runtime egl>=1.4 for eglGetCurrentContext() EGLint cfg_id = 0; EGL_ENSURE(eglQueryContext(egl->dpy, eglGetCurrentContext(), EGL_CONFIG_ID , &cfg_id) == EGL_TRUE, false); qDebug("egl config id: %d", cfg_id); EGLint nb_cfg = 0; EGL_ENSURE(eglGetConfigs(egl->dpy, NULL, 0, &nb_cfg) == EGL_TRUE, false); qDebug("eglGetConfigs number: %d", nb_cfg); QVector<EGLConfig> cfgs(nb_cfg); //check > 0 EGL_ENSURE(eglGetConfigs(egl->dpy, cfgs.data(), cfgs.size(), &nb_cfg) == EGL_TRUE, false); EGLConfig egl_cfg = NULL; for (int i = 0; i < nb_cfg; ++i) { EGLint id = 0; eglGetConfigAttrib(egl->dpy, cfgs[i], EGL_CONFIG_ID, &id); if (id == cfg_id) { egl_cfg = cfgs[i]; break; } } #endif qDebug("egl display:%p config: %p", egl->dpy, egl_cfg); // check extensions QList<QByteArray> extensions = QByteArray(eglQueryString(egl->dpy, EGL_EXTENSIONS)).split(' '); // ANGLE_d3d_share_handle_client_buffer will be used if possible const bool kEGL_ANGLE_d3d_share_handle_client_buffer = extensions.contains("EGL_ANGLE_d3d_share_handle_client_buffer"); const bool kEGL_ANGLE_query_surface_pointer = extensions.contains("EGL_ANGLE_query_surface_pointer"); if (!kEGL_ANGLE_d3d_share_handle_client_buffer && !kEGL_ANGLE_query_surface_pointer) { qWarning("EGL extension 'kEGL_ANGLE_query_surface_pointer' or 'ANGLE_d3d_share_handle_client_buffer' is required!"); return false; } GLint has_alpha = 1; //QOpenGLContext::currentContext()->format().hasAlpha() eglGetConfigAttrib(egl->dpy, egl_cfg, EGL_BIND_TO_TEXTURE_RGBA, &has_alpha); //EGL_ALPHA_SIZE EGLint attribs[] = { EGL_WIDTH, w, EGL_HEIGHT, h, EGL_TEXTURE_FORMAT, has_alpha ? EGL_TEXTURE_RGBA : EGL_TEXTURE_RGB, EGL_TEXTURE_TARGET, EGL_TEXTURE_2D, EGL_NONE }; HANDLE share_handle = NULL; if (!kEGL_ANGLE_d3d_share_handle_client_buffer && kEGL_ANGLE_query_surface_pointer) { EGL_ENSURE((egl->surface = eglCreatePbufferSurface(egl->dpy, egl_cfg, attribs)) != EGL_NO_SURFACE, false); qDebug("pbuffer surface: %p", egl->surface); PFNEGLQUERYSURFACEPOINTERANGLEPROC eglQuerySurfacePointerANGLE = reinterpret_cast<PFNEGLQUERYSURFACEPOINTERANGLEPROC>(eglGetProcAddress("eglQuerySurfacePointerANGLE")); if (!eglQuerySurfacePointerANGLE) { qWarning("EGL_ANGLE_query_surface_pointer is not supported"); return false; } EGL_ENSURE(eglQuerySurfacePointerANGLE(egl->dpy, egl->surface, EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE, &share_handle), false); } releaseDX(); // _A8 for a yuv plane /* * d3d resource share requires windows >= vista: https://msdn.microsoft.com/en-us/library/windows/desktop/bb219800(v=vs.85).aspx * from extension files: * d3d9: level must be 1, dimensions must match EGL surface's * d3d9ex or d3d10: */ DX_ENSURE_OK(d3ddev->CreateTexture(w, h, 1, D3DUSAGE_RENDERTARGET, has_alpha ? D3DFMT_A8R8G8B8 : D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &dx_texture, &share_handle) , false); DX_ENSURE_OK(dx_texture->GetSurfaceLevel(0, &dx_surface), false); if (kEGL_ANGLE_d3d_share_handle_client_buffer) { // requires extension EGL_ANGLE_d3d_share_handle_client_buffer // egl surface size must match d3d texture's // d3d9ex or d3d10 is required EGL_ENSURE((egl->surface = eglCreatePbufferFromClientBuffer(egl->dpy, EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE, share_handle, egl_cfg, attribs)), false); qDebug("pbuffer surface from client buffer: %p", egl->surface); } width = w; height = h; return true; }
void PiwigoTalker::parseResponseGetInfo(const QByteArray& data) { QString str = QString::fromUtf8(data); QXmlStreamReader ts(data); QString line; bool foundResponse = false; bool success = false; QList<int> categories; qCDebug(KIPIPLUGINS_LOG) << "parseResponseGetInfo: " << QString::fromUtf8(data); while (!ts.atEnd()) { ts.readNext(); if (ts.isStartElement()) { if (ts.name() == QString::fromLatin1("rsp")) { foundResponse = true; if (ts.attributes().value(QString::fromLatin1("stat")) == QString::fromLatin1("ok")) success = true; } if (ts.name() == QString::fromLatin1("category")) { if (ts.attributes().hasAttribute(QString::fromLatin1("id"))) { QString id(ts.attributes().value(QString::fromLatin1("id")).toString()); categories.append(id.toInt()); } } } } qCDebug(KIPIPLUGINS_LOG) << "success : " << success; if (!foundResponse) { emit signalAddPhotoFailed(i18n("Invalid response received from remote Piwigo")); return; } if (categories.contains(m_albumId)) { emit signalAddPhotoFailed(i18n("Photo '%1' already exists in this album.", m_title)); return; } else { categories.append(m_albumId); } m_state = GE_SETINFO; m_talker_buffer.resize(0); QStringList qsl_cat; for (int i = 0; i < categories.size(); ++i) { qsl_cat.append(QString::number(categories.at(i))); } QStringList qsl; qsl.append(QLatin1String("method=pwg.images.setInfo")); qsl.append(QLatin1String("image_id=") + QString::number(m_photoId)); qsl.append(QLatin1String("categories=") + QString::fromUtf8(qsl_cat.join(QLatin1String(";")).toUtf8().toPercentEncoding())); QString dataParameters = qsl.join(QLatin1String("&")); QByteArray buffer; buffer.append(dataParameters.toUtf8()); QNetworkRequest netRequest(m_url); netRequest.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/x-www-form-urlencoded")); netRequest.setRawHeader("Authorization", s_authToken.toLatin1()); m_reply = m_netMngr->post(netRequest, buffer); return; }
mresult ApptModel::checkAppt(const QList<inf_appt> &listAppt) { qint64 now = QDateTime::currentMSecsSinceEpoch(); QList <inf_appt> toRemove; QList <inf_appt> toRemoveBlack; QList <inf_appt> toAppend; inf_appt A,B; qint64 start = 0,end = 0,alarm = 0; for (int i = 0; i < black.size(); ++i) { A = black.at(i); start = A.getmalarmInstStart().toLongLong(); end = start + A.getmdur().toLongLong(); if(!listAppt.contains(A)) { if (now > end) { toRemoveBlack.append(A); } } } for (int i = 0; i < listAppt.size(); ++i) { A = listAppt.at(i); start = A.getmalarmInstStart().toLongLong(); end = start + A.getmdur().toLongLong(); alarm = A.getmnextAlarm().toLongLong(); if (black.contains(A)) { toRemove.append(A); continue; } if(alarm > now) { toRemove.append(A); } else { if(alarm > now) { toAppend.append(A); } if((alarm == 0) && ((now < start) || (now > end))) { toRemove.append(A); } else { toAppend.append(A); } } } for (int i = 0; i < Appt.size(); ++i) { A = Appt.at(i); if (!listAppt.contains(A)) { toRemove.append(A); } } for (int i = 0; i < toRemove.size(); ++i) { inf_appt rm = toRemove.at(i); if(Appt.contains(rm)) { int ind = Appt.indexOf(rm); beginRemoveRows(QModelIndex(), ind, ind); Appt.removeAll(rm); endRemoveRows(); } } int k = 0; for (int i = 0; i < toAppend.size(); ++i) { A = toAppend.at(i); k = 0; if(!Appt.contains(A)) { for ( int j = 0; j < Appt.size(); ++j) { B = Appt.at(j); //qDebug() << A.getmname() <<A.getmalarmInstStart() << B.getmalarmInstStart()<< B.getmname(); if(A.getmalarmInstStart().toLongLong() < B.getmalarmInstStart().toLongLong()) { k = j + 1; } } beginInsertRows(QModelIndex(), k, k ); //qDebug() << k<< A.getmname(); Appt.insert(k,A); endInsertRows(); } } // for (int i = 0; i < toAppend.size(); ++i) { // inf in = toAppend.at(i); // if(!Appt.contains(in)){ // beginInsertRows(QModelIndex(), Appt.size() + 1, Appt.size() +1 ); // Appt.append(in); // endInsertRows(); // } // } for (int i = 0; i < toRemoveBlack.size(); ++i) { inf_appt rm = toRemoveBlack.at(i); black.removeAll(rm); } //qDebug() <<toAppend.size()<<toRemove.size()<<black.size() << Appt.size(); mresult r; r.setresult(Appt.size(),toAppend.size(),toRemove.size(),black.size()); return r; }
ErrorList topolTest::checkOverlaps( double tolerance, QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent ) { Q_UNUSED( tolerance ); Q_UNUSED( layer2 ); int i = 0; ErrorList errorList; // could be enabled for lines and points too // so duplicate rule may be removed? if ( layer1->geometryType() != QgsWkbTypes::PolygonGeometry ) { return errorList; } QList<QgsFeatureId> *duplicateIds = new QList<QgsFeatureId>(); QgsSpatialIndex* index = mLayerIndexes[layer1->id()]; if ( !index ) { qDebug() << "no index present"; delete duplicateIds; return errorList; } QMap<QgsFeatureId, FeatureLayer>::const_iterator it; for ( it = mFeatureMap2.constBegin(); it != mFeatureMap2.constEnd(); ++it ) { if ( !( ++i % 100 ) ) emit progress( i ); QgsFeatureId currentId = it->feature.id(); if ( duplicateIds->contains( currentId ) ) { //is already a duplicate geometry..skip.. continue; } if ( testCancelled() ) break; QgsGeometry g1 = it->feature.geometry(); if ( !g1.isGeosValid() ) { qDebug() << "invalid geometry(g1) found..skipping.." << it->feature.id(); continue; } QgsRectangle bb = g1.boundingBox(); QList<QgsFeatureId> crossingIds; crossingIds = index->intersects( bb ); QList<QgsFeatureId>::Iterator cit = crossingIds.begin(); QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.end(); bool duplicate = false; QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( theQgsInterface->mapCanvas()->extent().asWktPolygon() ); for ( ; cit != crossingIdsEnd; ++cit ) { duplicate = false; // skip itself if ( mFeatureMap2[*cit].feature.id() == it->feature.id() ) continue; QgsGeometry g2 = mFeatureMap2[*cit].feature.geometry(); if ( g2.isEmpty() ) { QgsMessageLog::logMessage( tr( "Invalid second geometry in overlaps test." ), tr( "Topology plugin" ) ); continue; } if ( !_canExportToGeos( g2 ) ) { QgsMessageLog::logMessage( tr( "Failed to import second geometry into GEOS in overlaps test." ), tr( "Topology plugin" ) ); continue; } if ( !g2.isGeosValid() ) { QgsMessageLog::logMessage( tr( "Skipping invalid second geometry of feature %1 in overlaps test." ).arg( it->feature.id() ), tr( "Topology plugin" ) ); continue; } qDebug() << "checking overlap for" << it->feature.id(); if ( g1.overlaps( g2 ) ) { duplicate = true; duplicateIds->append( mFeatureMap2[*cit].feature.id() ); } if ( duplicate ) { QList<FeatureLayer> fls; fls << *it << *it; QgsGeometry conflictGeom = g1.intersection( g2 ); if ( isExtent ) { if ( canvasExtentPoly.disjoint( conflictGeom ) ) { continue; } if ( canvasExtentPoly.crosses( conflictGeom ) ) { conflictGeom = conflictGeom.intersection( canvasExtentPoly ); } } TopolErrorOverlaps* err = new TopolErrorOverlaps( bb, conflictGeom, fls ); errorList << err; } } } delete duplicateIds; return errorList; }
void Qt4BuildConfiguration::qtVersionsChanged(const QList<int> &,const QList<int> &, const QList<int> &changed) { if (changed.contains(QtKitInformation::qtVersionId(target()->kit()))) emitProFileEvaluateNeeded(); }
bool Grantlee::supportedOutputType( const QVariant &input ) { static const QList<int> primitives = getPrimitives(); return primitives.contains( input.userType() ); }
/*! \fn void QTextTable::insertColumns(int index, int columns) Inserts a number of \a columns before the column with the specified \a index. \sa insertRows() resize() removeRows() removeColumns() appendRows() appendColumns() */ void QTextTable::insertColumns(int pos, int num) { Q_D(QTextTable); if (num <= 0) return; if (d->dirty) d->update(); if (pos > d->nCols || pos < 0) pos = d->nCols; // qDebug() << "-------- insertCols" << pos << num; QTextDocumentPrivate *p = d->pieceTable; QTextFormatCollection *c = p->formatCollection(); p->beginEditBlock(); QList<int> extendedSpans; for (int i = 0; i < d->nRows; ++i) { int cell; if (i == d->nRows - 1 && pos == d->nCols) { cell = d->fragment_end; } else { int logicalGridIndexBeforePosition = pos > 0 ? d->findCellIndex(d->grid[i*d->nCols + pos - 1]) : -1; // Search for the logical insertion point by skipping past cells which are not the first // cell in a rowspan. This means any cell for which the logical grid index is // less than the logical cell index of the cell before the insertion. int logicalGridIndex; int gridArrayOffset = i*d->nCols + pos; do { cell = d->grid[gridArrayOffset]; logicalGridIndex = d->findCellIndex(cell); gridArrayOffset++; } while (logicalGridIndex < logicalGridIndexBeforePosition && gridArrayOffset < d->nRows*d->nCols); if (logicalGridIndex < logicalGridIndexBeforePosition && gridArrayOffset == d->nRows*d->nCols) cell = d->fragment_end; } if (pos > 0 && pos < d->nCols && cell == d->grid[i*d->nCols + pos - 1]) { // cell spans the insertion place, extend it if (!extendedSpans.contains(cell)) { QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell); QTextCharFormat fmt = c->charFormat(it->format); fmt.setTableCellColumnSpan(fmt.tableCellColumnSpan() + num); p->setCharFormat(it.position(), 1, fmt); d->dirty = true; extendedSpans << cell; } } else { /* If the next cell is spanned from the row above, we need to find the right position to insert to */ if (i > 0 && pos < d->nCols && cell == d->grid[(i-1) * d->nCols + pos]) { int gridIndex = i*d->nCols + pos; const int gridEnd = d->nRows * d->nCols - 1; while (gridIndex < gridEnd && cell == d->grid[gridIndex]) { ++gridIndex; } if (gridIndex == gridEnd) cell = d->fragment_end; else cell = d->grid[gridIndex]; } QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell); QTextCharFormat fmt = c->charFormat(it->format); fmt.setTableCellRowSpan(1); fmt.setTableCellColumnSpan(1); Q_ASSERT(fmt.objectIndex() == objectIndex()); int position = it.position(); int cfmt = p->formatCollection()->indexForFormat(fmt); int bfmt = p->formatCollection()->indexForFormat(QTextBlockFormat()); for (int i = 0; i < num; ++i) p->insertBlock(QTextBeginningOfFrame, position, bfmt, cfmt, QTextUndoCommand::MoveCursor); } } QTextTableFormat tfmt = format(); tfmt.setColumns(tfmt.columns()+num); QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints(); if (! columnWidths.isEmpty()) { for (int i = num; i > 0; --i) columnWidths.insert(pos, columnWidths[qMax(0, pos-1)]); } tfmt.setColumnWidthConstraints (columnWidths); QTextObject::setFormat(tfmt); // qDebug() << "-------- end insertCols" << pos << num; p->endEditBlock(); }