bool QAudioInputPrivate::open() { #ifdef DEBUG_AUDIO QTime now(QTime::currentTime()); qDebug()<<now.second()<<"s "<<now.msec()<<"ms :open()"; #endif clockStamp.restart(); timeStamp.restart(); elapsedTimeOffset = 0; int dir; int err = 0; int count=0; unsigned int freakuency=settings.frequency(); if (!settings.isValid()) { qWarning("QAudioOutput: open error, invalid format."); } else if (settings.sampleRate() <= 0) { qWarning("QAudioOutput: open error, invalid sample rate (%d).", settings.sampleRate()); } else { err = -1; } if (err == 0) { errorState = QAudio::OpenError; deviceState = QAudio::StoppedState; emit errorChanged(errorState); return false; } QString dev = QString(QLatin1String(m_device.constData())); QList<QByteArray> devices = QAudioDeviceInfoInternal::availableDevices(QAudio::AudioInput); if(dev.compare(QLatin1String("default")) == 0) { #if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14) if (devices.size() > 0) dev = QLatin1String(devices.first()); else return false; #else dev = QLatin1String("hw:0,0"); #endif } else { #if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14) dev = QLatin1String(m_device); #else int idx = 0; char *name; QString shortName = QLatin1String(m_device.mid(m_device.indexOf('=',0)+1).constData()); while(snd_card_get_name(idx,&name) == 0) { if(qstrncmp(shortName.toLocal8Bit().constData(),name,shortName.length()) == 0) break; idx++; } dev = QString(QLatin1String("hw:%1,0")).arg(idx); #endif } // Step 1: try and open the device while((count < 5) && (err < 0)) { err=snd_pcm_open(&handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_CAPTURE,0); if(err < 0) count++; } if (( err < 0)||(handle == 0)) { errorState = QAudio::OpenError; deviceState = QAudio::StoppedState; emit stateChanged(deviceState); return false; } snd_pcm_nonblock( handle, 0 ); // Step 2: Set the desired HW parameters. snd_pcm_hw_params_alloca( &hwparams ); bool fatal = false; QString errMessage; unsigned int chunks = 8; err = snd_pcm_hw_params_any( handle, hwparams ); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_any: err = %1").arg(err); } if ( !fatal ) { err = snd_pcm_hw_params_set_rate_resample( handle, hwparams, 1 ); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_rate_resample: err = %1").arg(err); } } if ( !fatal ) { err = snd_pcm_hw_params_set_access( handle, hwparams, access ); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_access: err = %1").arg(err); } } if ( !fatal ) { err = setFormat(); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_format: err = %1").arg(err); } } if ( !fatal ) { err = snd_pcm_hw_params_set_channels( handle, hwparams, (unsigned int)settings.channels() ); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_channels: err = %1").arg(err); } } if ( !fatal ) { err = snd_pcm_hw_params_set_rate_near( handle, hwparams, &freakuency, 0 ); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_rate_near: err = %1").arg(err); } } if ( !fatal ) { err = snd_pcm_hw_params_set_buffer_time_near(handle, hwparams, &buffer_time, &dir); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_buffer_time_near: err = %1").arg(err); } } if ( !fatal ) { err = snd_pcm_hw_params_set_period_time_near(handle, hwparams, &period_time, &dir); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_period_time_near: err = %1").arg(err); } } if ( !fatal ) { err = snd_pcm_hw_params_set_periods_near(handle, hwparams, &chunks, &dir); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_periods_near: err = %1").arg(err); } } if ( !fatal ) { err = snd_pcm_hw_params(handle, hwparams); if ( err < 0 ) { fatal = true; errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params: err = %1").arg(err); } } if( err < 0) { qWarning()<<errMessage; errorState = QAudio::OpenError; deviceState = QAudio::StoppedState; emit stateChanged(deviceState); return false; } snd_pcm_hw_params_get_buffer_size(hwparams,&buffer_frames); buffer_size = snd_pcm_frames_to_bytes(handle,buffer_frames); snd_pcm_hw_params_get_period_size(hwparams,&period_frames, &dir); period_size = snd_pcm_frames_to_bytes(handle,period_frames); snd_pcm_hw_params_get_buffer_time(hwparams,&buffer_time, &dir); snd_pcm_hw_params_get_period_time(hwparams,&period_time, &dir); // Step 3: Set the desired SW parameters. snd_pcm_sw_params_t *swparams; snd_pcm_sw_params_alloca(&swparams); snd_pcm_sw_params_current(handle, swparams); snd_pcm_sw_params_set_start_threshold(handle,swparams,period_frames); snd_pcm_sw_params_set_stop_threshold(handle,swparams,buffer_frames); snd_pcm_sw_params_set_avail_min(handle, swparams,period_frames); snd_pcm_sw_params(handle, swparams); // Step 4: Prepare audio ringBuffer.resize(buffer_size); snd_pcm_prepare( handle ); snd_pcm_start(handle); // Step 5: Setup timer bytesAvailable = checkBytesReady(); if(pullMode) connect(audioSource,SIGNAL(readyRead()),this,SLOT(userFeed())); // Step 6: Start audio processing chunks = buffer_size/period_size; timer->start(period_time*chunks/2000); errorState = QAudio::NoError; totalTimeValue = 0; return true; }
QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* parent ) : QWidget( parent ) { mLayer = layer; if ( !layer ) { return; } setupUi( this ); mBackgroundColorButton->setColorDialogTitle( tr( "Background color" ) ); mBackgroundColorButton->setColorDialogOptions( QColorDialog::ShowAlphaChannel ); mDiagramPenColorButton->setColorDialogTitle( tr( "Pen color" ) ); mDiagramPenColorButton->setColorDialogOptions( QColorDialog::ShowAlphaChannel ); mValueLineEdit->setValidator( new QDoubleValidator( mValueLineEdit ) ); mMinimumDiagramScaleLineEdit->setValidator( new QDoubleValidator( mMinimumDiagramScaleLineEdit ) ); mMaximumDiagramScaleLineEdit->setValidator( new QDoubleValidator( mMaximumDiagramScaleLineEdit ) ); mDiagramUnitComboBox->insertItem( 0, tr( "mm" ), QgsDiagramSettings::MM ); mDiagramUnitComboBox->insertItem( 1, tr( "Map units" ), QgsDiagramSettings::MapUnits ); QGis::GeometryType layerType = layer->geometryType(); if ( layerType == QGis::UnknownGeometry || layerType == QGis::NoGeometry ) { mDisplayDiagramsGroupBox->setChecked( false ); mDisplayDiagramsGroupBox->setEnabled( false ); } //insert placement options if ( layerType == QGis::Point || layerType == QGis::Polygon ) { mPlacementComboBox->addItem( tr( "Around Point" ), QgsDiagramLayerSettings::AroundPoint ); mPlacementComboBox->addItem( tr( "Over Point" ), QgsDiagramLayerSettings::OverPoint ); } if ( layerType == QGis::Line || layerType == QGis::Polygon ) { mPlacementComboBox->addItem( tr( "Line" ), QgsDiagramLayerSettings::Line ); mPlacementComboBox->addItem( tr( "Horizontal" ), QgsDiagramLayerSettings::Horizontal ); } if ( layerType == QGis::Polygon ) { mPlacementComboBox->addItem( tr( "Free" ), QgsDiagramLayerSettings::Free ); } if ( layerType == QGis::Line ) { mLineOptionsComboBox->addItem( tr( "On line" ), QgsDiagramLayerSettings::OnLine ); mLineOptionsComboBox->addItem( tr( "Above line" ), QgsDiagramLayerSettings::AboveLine ); mLineOptionsComboBox->addItem( tr( "Below Line" ), QgsDiagramLayerSettings::BelowLine ); mLineOptionsComboBox->addItem( tr( "Map orientation" ), QgsDiagramLayerSettings::MapOrientation ); } else { mLineOptionsComboBox->setVisible( false ); mLineOptionsLabel->setVisible( false ); } QPixmap pix = QgsApplication::getThemePixmap( "pie-chart" ); mDiagramTypeComboBox->addItem( pix, tr( "Pie chart" ), DIAGRAM_NAME_PIE ); pix = QgsApplication::getThemePixmap( "text" ); mDiagramTypeComboBox->addItem( pix, tr( "Text diagram" ), DIAGRAM_NAME_TEXT ); pix = QgsApplication::getThemePixmap( "histogram" ); mDiagramTypeComboBox->addItem( pix, tr( "Histogram" ), DIAGRAM_NAME_HISTOGRAM ); mLabelPlacementComboBox->addItem( tr( "Height" ), QgsDiagramSettings::Height ); mLabelPlacementComboBox->addItem( tr( "x-height" ), QgsDiagramSettings::XHeight ); mScaleDependencyComboBox->addItem( tr( "Area" ), true ); mScaleDependencyComboBox->addItem( tr( "Diameter" ), false ); mDataDefinedXComboBox->addItem( tr( "None" ), -1 ); mDataDefinedYComboBox->addItem( tr( "None" ), -1 ); //insert all attributes into the combo boxes const QgsFields& layerFields = layer->pendingFields(); for ( int idx = 0; idx < layerFields.count(); ++idx ) { QTreeWidgetItem *newItem = new QTreeWidgetItem( mAttributesTreeWidget ); newItem->setText( 0, layerFields[idx].name() ); newItem->setData( 0, Qt::UserRole, idx ); newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled ); if ( layerFields[idx].type() != QVariant::String ) { mSizeAttributeComboBox->addItem( layerFields[idx].name(), idx ); } mDataDefinedXComboBox->addItem( layerFields[idx].name(), idx ); mDataDefinedYComboBox->addItem( layerFields[idx].name(), idx ); } const QgsDiagramRendererV2* dr = layer->diagramRenderer(); if ( !dr ) //no diagram renderer yet, insert reasonable default { mDisplayDiagramsGroupBox->setChecked( false ); mFixedSizeCheckBox->setChecked( true ); mDiagramUnitComboBox->setCurrentIndex( mDiagramUnitComboBox->findText( tr( "mm" ) ) ); mLabelPlacementComboBox->setCurrentIndex( mLabelPlacementComboBox->findText( tr( "x-height" ) ) ); mDiagramSizeSpinBox->setValue( 30 ); mBarWidthSpinBox->setValue( 5 ); mVisibilityGroupBox->setChecked( false ); switch ( layerType ) { case QGis::Point: mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) ); break; case QGis::Line: mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 3 ) ); mLineOptionsComboBox->setCurrentIndex( mLineOptionsComboBox->findData( 2 ) ); break; case QGis::Polygon: mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) ); break; case QGis::UnknownGeometry: case QGis::NoGeometry: break; } mBackgroundColorButton->setColor( QColor( 255, 255, 255, 255 ) ); } else // already a diagram renderer present { mDisplayDiagramsGroupBox->setChecked( true ); //single category renderer or interpolated one? mFixedSizeCheckBox->setChecked( dr->rendererName() == "SingleCategory" ); //assume single category or linearly interpolated diagram renderer for now QList<QgsDiagramSettings> settingList = dr->diagramSettings(); if ( settingList.size() > 0 ) { mDiagramFont = settingList.at( 0 ).font; QSizeF size = settingList.at( 0 ).size; mBackgroundColorButton->setColor( settingList.at( 0 ).backgroundColor ); mTransparencySlider->setValue( settingList.at( 0 ).transparency ); mDiagramPenColorButton->setColor( settingList.at( 0 ).penColor ); mPenWidthSpinBox->setValue( settingList.at( 0 ).penWidth ); mDiagramSizeSpinBox->setValue(( size.width() + size.height() ) / 2.0 ); mMinimumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).minScaleDenominator, 'f' ) ); mMaximumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).maxScaleDenominator, 'f' ) ); mVisibilityGroupBox->setChecked( settingList.at( 0 ).minScaleDenominator != -1 && settingList.at( 0 ).maxScaleDenominator != -1 ); if ( settingList.at( 0 ).sizeType == QgsDiagramSettings::MM ) { mDiagramUnitComboBox->setCurrentIndex( 0 ); } else { mDiagramUnitComboBox->setCurrentIndex( 1 ); } if ( settingList.at( 0 ).labelPlacementMethod == QgsDiagramSettings::Height ) { mLabelPlacementComboBox->setCurrentIndex( 0 ); } else { mLabelPlacementComboBox->setCurrentIndex( 1 ); } mOrientationLeftButton->setProperty( "direction", QgsDiagramSettings::Left ); mOrientationRightButton->setProperty( "direction", QgsDiagramSettings::Right ); mOrientationUpButton->setProperty( "direction", QgsDiagramSettings::Up ); mOrientationDownButton->setProperty( "direction", QgsDiagramSettings::Down ); switch ( settingList.at( 0 ).diagramOrientation ) { case QgsDiagramSettings::Left: mOrientationLeftButton->setChecked( true ); break; case QgsDiagramSettings::Right: mOrientationRightButton->setChecked( true ); break; case QgsDiagramSettings::Up: mOrientationUpButton->setChecked( true ); break; case QgsDiagramSettings::Down: mOrientationDownButton->setChecked( true ); break; } mBarWidthSpinBox->setValue( settingList.at( 0 ).barWidth ); mIncreaseSmallDiagramsGroupBox->setChecked( settingList.at( 0 ).minimumSize != 0 ); mIncreaseMinimumSizeSpinBox->setValue( settingList.at( 0 ).minimumSize ); if ( settingList.at( 0 ).scaleByArea ) { mScaleDependencyComboBox->setCurrentIndex( 0 ); } else { mScaleDependencyComboBox->setCurrentIndex( 1 ); } QList< QColor > categoryColors = settingList.at( 0 ).categoryColors; QList< int > categoryIndices = settingList.at( 0 ).categoryIndices; QList< int >::const_iterator catIt = categoryIndices.constBegin(); QList< QColor >::const_iterator coIt = categoryColors.constBegin(); for ( ;catIt != categoryIndices.constEnd(); ++catIt, ++coIt ) { QTreeWidgetItem *newItem = new QTreeWidgetItem( mDiagramAttributesTreeWidget ); newItem->setText( 0, layer->pendingFields()[*catIt].name() ); newItem->setData( 0, Qt::UserRole, *catIt ); newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled ); QColor col( *coIt ); col.setAlpha( 255 ); newItem->setBackground( 1, QBrush( col ) ); } } if ( dr->rendererName() == "LinearlyInterpolated" ) { const QgsLinearlyInterpolatedDiagramRenderer* lidr = dynamic_cast<const QgsLinearlyInterpolatedDiagramRenderer*>( dr ); if ( lidr ) { mDiagramSizeSpinBox->setEnabled( false ); mValueLineEdit->setText( QString::number( lidr->upperValue(), 'f' ) ); mSizeSpinBox->setValue(( lidr->upperSize().width() + lidr->upperSize().height() ) / 2 ); mSizeAttributeComboBox->setCurrentIndex( mSizeAttributeComboBox->findData( lidr->classificationAttribute() ) ); } } const QgsDiagramLayerSettings *dls = layer->diagramLayerSettings(); if ( dls ) { mDiagramDistanceSpinBox->setValue( dls->dist ); mPrioritySlider->setValue( dls->priority ); mDataDefinedXComboBox->setCurrentIndex( mDataDefinedXComboBox->findData( dls->xPosColumn ) ); mDataDefinedYComboBox->setCurrentIndex( mDataDefinedYComboBox->findData( dls->yPosColumn ) ); if ( dls->xPosColumn != -1 || dls->yPosColumn != -1 ) { mDataDefinedPositionGroupBox->setChecked( true ); } mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( dls->placement ) ); mLineOptionsComboBox->setCurrentIndex( mLineOptionsComboBox->findData( dls->placementFlags ) ); } if ( dr->diagram() ) { QString diagramName = dr->diagram()->diagramName(); mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( diagramName ) ); if ( mDiagramTypeComboBox->currentIndex() == -1 ) { QMessageBox::warning( this, tr( "Unknown diagram type." ), tr( "The diagram type '%1' is unknown. A default type is selected for you." ).arg( diagramName ), QMessageBox::Ok ); mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( DIAGRAM_NAME_PIE ) ); } } } // if ( !dr ) // Trigger a clicked event, so all the items get properly enabled and disabled on_mDisplayDiagramsGroupBox_toggled( mDisplayDiagramsGroupBox->isChecked() ); }
void ParserTests::testMemcheckSample1() { initTest(QLatin1String("memcheck-output-sample1.xml")); QList<Error> expectedErrors; { Error error; error.setKind(InvalidRead); error.setWhat(QLatin1String("Invalid read of size 4")); error.setUnique(0x9); error.setTid(1); Frame f1; f1.setInstructionPointer(0x6E47964); f1.setObject(QLatin1String("/usr/lib/libQtGui.so.4.7.0")); f1.setFunctionName(QLatin1String("QFrame::frameStyle() const")); f1.setDirectory(QLatin1String("/build/buildd/qt4-x11-4.7.0/src/gui/widgets")); f1.setFile(QLatin1String("qframe.cpp")); f1.setLine(252); Frame f2; f2.setInstructionPointer(0x118F2AF7); f2.setObject(QLatin1String("/usr/lib/kde4/plugins/styles/oxygen.so")); Frame f3; f3.setInstructionPointer(0x6A81671); f3.setObject(QLatin1String("/usr/lib/libQtGui.so.4.7.0")); f3.setFunctionName(QLatin1String("QWidget::event(QEvent*)")); f3.setDirectory(QLatin1String("/build/buildd/qt4-x11-4.7.0/src/gui/kernel")); f3.setFile(QLatin1String("qwidget.cpp")); f3.setLine(8273); Frame f4; f4.setInstructionPointer(0x6A2B6EB); f4.setObject(QLatin1String("/usr/lib/libQtGui.so.4.7.0")); f4.setDirectory(QLatin1String("/build/buildd/qt4-x11-4.7.0/src/gui/kernel")); f4.setFile(QLatin1String("qapplication.cpp")); f4.setFunctionName(QLatin1String("QApplicationPrivate::notify_helper(QObject*, QEvent*)")); f4.setLine(4396); Stack s1; s1.setAuxWhat(QLatin1String("Address 0x11527cb8 is not stack'd, malloc'd or (recently) free'd")); s1.setFrames(QVector<Frame>() << f1 << f2 << f3 << f4); error.setStacks( QVector<Stack>() << s1 ); expectedErrors << error; } QVector<QPair<qint64,qint64> > expectedErrorCounts; expectedErrorCounts.push_back(QPair<qint64,qint64>(9, 2)); QVector<QPair<QString,qint64> > expectedSuppCounts; expectedSuppCounts.push_back(qMakePair(QString::fromLatin1("X on SUSE11 writev uninit padding"), static_cast<qint64>(12))); expectedSuppCounts.push_back(qMakePair(QString::fromLatin1("dl-hack3-cond-1"), static_cast<qint64>(2))); expectedSuppCounts.push_back(qMakePair(QString::fromLatin1("glibc-2.5.x-on-SUSE-10.2-(PPC)-2a"), static_cast<qint64>(2))); Valgrind::XmlProtocol::Parser parser; Recorder rec(&parser); parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->exitStatus(), QProcess::NormalExit); QCOMPARE(m_process->state(), QProcess::NotRunning); QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString())); const QList<Error> actualErrors = rec.errors; if (actualErrors.first() != expectedErrors.first()) { dumpError(actualErrors.first()); dumpError(expectedErrors.first()); } QCOMPARE(actualErrors.first(), expectedErrors.first()); QCOMPARE(actualErrors.size(), 3); QCOMPARE(rec.errorcounts, expectedErrorCounts); QCOMPARE(rec.suppcounts, expectedSuppCounts); }
void VMdEditor::insertFromMimeData(const QMimeData *p_source) { VSelectDialog dialog(tr("Insert From Clipboard"), this); dialog.addSelection(tr("Insert As Image"), 0); dialog.addSelection(tr("Insert As Text"), 1); if (p_source->hasHtml()) { // Handle <img>. QRegExp reg("<img ([^>]*)src=\"([^\"]+)\"([^>]*)>"); if (reg.indexIn(p_source->html()) != -1) { m_editOps->insertImageFromURL(QUrl(reg.cap(2))); return; } } if (p_source->hasImage()) { // Image data in the clipboard if (p_source->hasText()) { if (dialog.exec() == QDialog::Accepted) { if (dialog.getSelection() == 1) { // Insert as text. Q_ASSERT(p_source->hasText() && p_source->hasImage()); VTextEdit::insertFromMimeData(p_source); return; } } else { return; } } m_editOps->insertImageFromMimeData(p_source); return; } if (p_source->hasUrls()) { QList<QUrl> urls = p_source->urls(); if (urls.size() == 1 && VUtils::isImageURL(urls[0])) { if (dialog.exec() == QDialog::Accepted) { // FIXME: After calling dialog.exec(), p_source->hasUrl() returns false. if (dialog.getSelection() == 0) { // Insert as image. m_editOps->insertImageFromURL(urls[0]); return; } QMimeData newSource; newSource.setUrls(urls); VTextEdit::insertFromMimeData(&newSource); return; } else { return; } } } if (p_source->hasText()) { QString text = p_source->text(); if (VUtils::isImageURLText(text)) { // The text is a URL to an image. if (dialog.exec() == QDialog::Accepted) { if (dialog.getSelection() == 0) { // Insert as image. QUrl url(text); if (url.isValid()) { m_editOps->insertImageFromURL(QUrl(text)); } return; } } else { return; } } Q_ASSERT(p_source->hasText()); } VTextEdit::insertFromMimeData(p_source); }
/* Update our model of the wallet incrementally, to synchronize our model of the wallet with that of the core. Call with transaction that was added, removed or changed. */ void updateWallet(const uint256 &hash, int status) { OutputDebugStringF("updateWallet %s %i\n", hash.ToString().c_str(), status); { LOCK(wallet->cs_wallet); // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); bool inWallet = mi != wallet->mapWallet.end(); // Find bounds of this transaction in model QList<TransactionRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<TransactionRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); // Determine whether to show transaction or not bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second)); if(status == CT_UPDATED) { if(showTransaction && !inModel) status = CT_NEW; /* Not in model, but want to show, treat as new */ if(!showTransaction && inModel) status = CT_DELETED; /* In model, but want to hide, treat as deleted */ } OutputDebugStringF(" inWallet=%i inModel=%i Index=%i-%i showTransaction=%i derivedStatus=%i\n", inWallet, inModel, lowerIndex, upperIndex, showTransaction, status); switch(status) { case CT_NEW: if(inModel) { OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is already in model\n"); break; } if(!inWallet) { OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is not in wallet\n"); break; } if(showTransaction) { // Added -- insert at the right position QList<TransactionRecord> toInsert = TransactionRecord::decomposeTransaction(wallet, mi->second); if(!toInsert.isEmpty()) /* only if something to insert */ { parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1); int insert_idx = lowerIndex; foreach(const TransactionRecord &rec, toInsert) { cachedWallet.insert(insert_idx, rec); insert_idx += 1; } parent->endInsertRows(); } } break; case CT_DELETED: if(!inModel) { OutputDebugStringF("Warning: updateWallet: Got CT_DELETED, but transaction is not in model\n"); break; } // Removed -- remove entire transaction from table parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedWallet.erase(lower, upper); parent->endRemoveRows(); break; case CT_UPDATED: // Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for // visible transactions. break; }
QRegion TilePainter::computeFillRegion(const QPoint &fillOrigin) const { //create that region that will hold the fill QRegion fillRegion; //silently quit if parameters are unsatisfactory if (!isDrawable(fillOrigin.x(), fillOrigin.y())) return fillRegion; //cache cell that we will match other cells against const Cell matchCell = cellAt(fillOrigin.x(), fillOrigin.y()); //grab map dimensions for later use. const int mapWidth = mMapEditor->map()->width(); const int mapHeight = mMapEditor->map()->height(); const int mapSize = mapWidth * mapHeight; //create a queue to hold cells that need filling QList<QPoint> fillPositions; fillPositions.append(fillOrigin); qDebug() << "fix " << fillPositions.at(0).x(); qDebug() << "fiy " << fillPositions.at(0).y(); //create an array that will store which cells have been processed //this is faster than checking if a given cell is in the region/list QVector<quint8> processedCellsVec(mapSize); quint8 *processedCells = processedCellsVec.data(); //loop through queued positions and fill them, while at the same time //checking adjacent positions to see if they should be added while (!fillPositions.isEmpty()) { for (int i = 0; i < fillPositions.size(); ++i) { qDebug() << "fx " << fillPositions.at(i).x(); qDebug() << "fy " << fillPositions.at(i).y(); } const QPoint currentPoint = fillPositions.takeFirst(); //qDebug() << "cpx" << currentPoint.x(); //qDebug() << "cpy" << currentPoint.y(); const int startOfLine = currentPoint.y() * mapWidth; //seek as far left as we can int left = currentPoint.x(); while (cellAt(left - 1, currentPoint.y()) == matchCell && isDrawable(left - 1, currentPoint.y())) --left; //seek as far right as we can int right = currentPoint.x(); while (cellAt(right + 1, currentPoint.y()) == matchCell && isDrawable(right + 1, currentPoint.y())) ++right; qDebug() << left; //add cells between left and right to the region fillRegion += QRegion(left, currentPoint.y(), right - left + 1, 1); //add cell strip to processed cells memset(&processedCells[startOfLine + left], 1, right - left); //these variables cache whether the last cell was added to the queue //or not as an optimization, since adjacent cells on the x axis //do not need to be added to the queue. bool lastAboveCell = false; bool lastBelowCell = false; //loop between left and right and check if cells above or //below need to be added to the queue for (int x = left; x <= right; ++x) { const QPoint fillPoint(x, currentPoint.y()); //check cell above if (fillPoint.y() > 0) { QPoint aboveCell(fillPoint.x(), fillPoint.y() - 1); if (!processedCells[aboveCell.y() * mapWidth + aboveCell.x()] && cellAt(aboveCell.x(), aboveCell.y()) == matchCell && isDrawable(aboveCell.x(), aboveCell.y())) { //do not add the above cell to the queue if its //x-adjacent cell was added. if (!lastAboveCell) fillPositions.append(aboveCell); lastAboveCell = true; } else lastAboveCell = false; processedCells[aboveCell.y() * mapWidth + aboveCell.x()] = 1; } //check cell below if (fillPoint.y() + 1 < mapHeight) { QPoint belowCell(fillPoint.x(), fillPoint.y() + 1); if (!processedCells[belowCell.y()*mapWidth + belowCell.x()] && cellAt(belowCell.x(), belowCell.y()) == matchCell && isDrawable(belowCell.x(), belowCell.y())) { //do not add the below cell to the queue if its //x-adjacent cell was added. if (!lastBelowCell) fillPositions.append(belowCell); lastBelowCell = true; } else lastBelowCell = false; processedCells[belowCell.y() * mapWidth + belowCell.x()] = 1; } } } return fillRegion; }
bool loadPlayerScript(QString path, int player, int difficulty) { ASSERT_OR_RETURN(false, player < MAX_PLAYERS, "Player index %d out of bounds", player); QScriptEngine *engine = new QScriptEngine(); UDWORD size; char *bytes = NULL; if (!loadFile(path.toAscii().constData(), &bytes, &size)) { debug(LOG_ERROR, "Failed to read script file \"%s\"", path.toAscii().constData()); return false; } QString source = QString::fromAscii(bytes, size); free(bytes); QScriptSyntaxCheckResult syntax = QScriptEngine::checkSyntax(source); ASSERT_OR_RETURN(false, syntax.state() == QScriptSyntaxCheckResult::Valid, "Syntax error in %s line %d: %s", path.toAscii().constData(), syntax.errorLineNumber(), syntax.errorMessage().toAscii().constData()); // Special functions engine->globalObject().setProperty("setTimer", engine->newFunction(js_setTimer)); engine->globalObject().setProperty("queue", engine->newFunction(js_queue)); engine->globalObject().setProperty("removeTimer", engine->newFunction(js_removeTimer)); engine->globalObject().setProperty("include", engine->newFunction(js_include)); engine->globalObject().setProperty("bind", engine->newFunction(js_bind)); // Special global variables //== \item[version] Current version of the game, set in \emph{major.minor} format. engine->globalObject().setProperty("version", "3.2", QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[selectedPlayer] The player ontrolled by the client on which the script runs. engine->globalObject().setProperty("selectedPlayer", selectedPlayer, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[gameTime] The current game time. Updated before every invokation of a script. engine->globalObject().setProperty("gameTime", gameTime, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[difficulty] The currently set campaign difficulty, or the current AI's difficulty setting. It will be one of //== EASY, MEDIUM, HARD or INSANE. if (game.type == SKIRMISH) { engine->globalObject().setProperty("difficulty", difficulty, QScriptValue::ReadOnly | QScriptValue::Undeletable); } else // campaign { engine->globalObject().setProperty("difficulty", (int)getDifficultyLevel(), QScriptValue::ReadOnly | QScriptValue::Undeletable); } //== \item[mapName] The name of the current map. engine->globalObject().setProperty("mapName", game.map, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[baseType] The type of base that the game starts with. It will be one of CAMP_CLEAN, CAMP_BASE or CAMP_WALLS. engine->globalObject().setProperty("baseType", game.base, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[alliancesType] The type of alliances permitted in this game. It will be one of NO_ALLIANCES, ALLIANCES or ALLIANCES_TEAMS. engine->globalObject().setProperty("alliancesType", game.alliance, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[powerType] The power level set for this game. engine->globalObject().setProperty("powerType", game.power, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[maxPlayers] The number of active players in this game. engine->globalObject().setProperty("maxPlayers", game.maxPlayers, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[scavengers] Whether or not scavengers are activated in this game. engine->globalObject().setProperty("scavengers", game.scavengers, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[mapWidth] Width of map in tiles. engine->globalObject().setProperty("mapWidth", mapWidth, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[mapHeight] Height of map in tiles. engine->globalObject().setProperty("mapHeight", mapHeight, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[scavengerPlayer] Index of scavenger player. (3.2+ only) engine->globalObject().setProperty("scavengerPlayer", scavengerPlayer(), QScriptValue::ReadOnly | QScriptValue::Undeletable); // Regular functions QFileInfo basename(path); registerFunctions(engine, basename.baseName()); // Remember internal, reserved names QScriptValueIterator it(engine->globalObject()); while (it.hasNext()) { it.next(); internalNamespace.insert(it.name(), 1); } // We need to always save the 'me' special variable. //== \item[me] The player the script is currently running as. engine->globalObject().setProperty("me", player, QScriptValue::ReadOnly | QScriptValue::Undeletable); QScriptValue result = engine->evaluate(source, path); ASSERT_OR_RETURN(false, !engine->hasUncaughtException(), "Uncaught exception at line %d, file %s: %s", engine->uncaughtExceptionLineNumber(), path.toAscii().constData(), result.toString().toAscii().constData()); // We also need to save the special 'scriptName' variable. //== \item[scriptName] Base name of the script that is running. engine->globalObject().setProperty("scriptName", basename.baseName(), QScriptValue::ReadOnly | QScriptValue::Undeletable); // Register script scripts.push_back(engine); debug(LOG_SAVE, "Created script engine %d for player %d from %s", scripts.size() - 1, player, path.toUtf8().constData()); return true; }
void QDeclarativeGraphicsGeoMap::hoverMoveEvent(QGraphicsSceneHoverEvent *event) { if (!mapData_) return; QList<QGeoMapObject*> objectsThen = mapData_->mapObjectsAtScreenPosition(event->lastPos()); QList<QGeoMapObject*> objectsNow = mapData_->mapObjectsAtScreenPosition(event->pos()); QSet<QGeoMapObject*> enter = objectsNow.toSet(); enter -= objectsThen.toSet(); for (int i = 0; i < objectsNow.size(); ++i) { if (!enter.contains(objectsNow.at(i))) continue; QDeclarativeGeoMapObject* mapObject = objectMap_.value(objectsNow.at(i), 0); if (mapObject) mapObject->enterEvent(); } QSet<QGeoMapObject*> exit = objectsThen.toSet(); exit -= objectsNow.toSet(); for (int i = 0; i < objectsThen.size(); ++i) { if (!exit.contains(objectsThen.at(i))) continue; QDeclarativeGeoMapObject* mapObject = objectMap_.value(objectsThen.at(i), 0); if (mapObject) mapObject->exitEvent(); } QSet<QGeoMapObject*> move = objectsNow.toSet(); move += objectsThen.toSet(); QList<QGeoMapObject*> objects = mapData_->mapObjectsInViewport(); QDeclarativeGeoMapMouseEvent *mouseEvent = createMapMouseEvent(event); for (int i = 0; i < objects.size(); ++i) { if (!move.contains(objects.at(i))) continue; QDeclarativeGeoMapObject* mapObject = objectMap_.value(objects.at(i), 0); if (mapObject) mapObject->moveEvent(mouseEvent); } /* QList<QGeoMapObject*> objects = mapData_->mapObjectsAtScreenPosition(event->pos()); for (int i = objects.size() - 1; i >= 0; --i) { QDeclarativeGeoMapObject* mapObject = objectMap_.value(objects.at(i), 0); if (mapObject) mapObject->moveEvent(mouseEvent); } */ for (int i = 0; i < mouseAreas_.size(); ++i) mouseAreas_.at(i)->moveEvent(mouseEvent); delete mouseEvent; }
void System::layout(qreal xo1) { if (isVbox()) // ignore vbox return; static const Spatium instrumentNameOffset(1.0); int nstaves = _staves.size(); if (nstaves != score()->nstaves()) qDebug("System::layout: nstaves %d != %d", nstaves, score()->nstaves()); //--------------------------------------------------- // find x position of staves // create brackets //--------------------------------------------------- qreal xoff2 = 0.0; // x offset for instrument name int bracketLevels = 0; for (int idx = 0; idx < nstaves; ++idx) bracketLevels = qMax(bracketLevels, score()->staff(idx)->bracketLevels()); qreal bracketWidth[bracketLevels]; for (int i = 0; i < bracketLevels; ++i) bracketWidth[i] = 0.0; QList<Bracket*> bl = _brackets; _brackets.clear(); for (int staffIdx = 0; staffIdx < nstaves; ++staffIdx) { Staff* s = score()->staff(staffIdx); for (int i = 0; i < bracketLevels; ++i) { if (s->bracket(i) == BracketType::NO_BRACKET) continue; int firstStaff = staffIdx; int lastStaff = staffIdx + s->bracketSpan(i) - 1; if (lastStaff >= nstaves) lastStaff = nstaves - 1; for (; firstStaff <= lastStaff; ++firstStaff) { if (score()->staff(firstStaff)->show()) break; } for (; lastStaff >= firstStaff; --lastStaff) { if (score()->staff(lastStaff)->show()) break; } int span = lastStaff - firstStaff + 1; // // do not show bracket if it only spans one // system due to some invisible staves // if ((span > 1) || (s->bracketSpan(i) == span)) { // // this bracket is visible // Bracket* b = 0; int track = staffIdx * VOICES; for (int k = 0; k < bl.size(); ++k) { if (bl[k]->track() == track && bl[k]->level() == i) { b = bl.takeAt(k); break; } } if (b == 0) { b = new Bracket(score()); b->setGenerated(true); b->setParent(this); b->setTrack(track); b->setLevel(i); b->setBracketType(s->bracket(i)); b->setSpan(s->bracketSpan(i)); score()->undoAddElement(b); } else _brackets.append(b); b->setFirstStaff(firstStaff); b->setLastStaff(lastStaff); bracketWidth[i] = qMax(bracketWidth[i], b->width()); } } if (!s->show()) continue; for (InstrumentName* t : _staves[staffIdx]->instrumentNames) { t->layout(); qreal w = t->width() + point(instrumentNameOffset); if (w > xoff2) xoff2 = w; } } for (Bracket* b : bl) score()->undoRemoveElement(b); //--------------------------------------------------- // layout SysStaff and StaffLines //--------------------------------------------------- // xoff2 += xo1; _leftMargin = xoff2; qreal bd = point(score()->styleS(StyleIdx::bracketDistance)); if ( _brackets.size() > 0) { for (int i = 0; i < bracketLevels; ++i) _leftMargin += bracketWidth[i] + bd; } for (int staffIdx = 0; staffIdx < nstaves; ++staffIdx) { SysStaff* s = _staves[staffIdx]; Staff* staff = score()->staff(staffIdx); if (!staff->show() || !s->show()) { s->setbbox(QRectF()); continue; } qreal staffMag = staff->mag(); qreal h; if (staff->lines() == 1) h = 2; else h = (staff->lines()-1) * staff->lineDistance(); h = h * staffMag * spatium(); s->bbox().setRect(_leftMargin + xo1, 0.0, 0.0, h); } if ((nstaves > 1 && score()->styleB(StyleIdx::startBarlineMultiple)) || (nstaves <= 1 && score()->styleB(StyleIdx::startBarlineSingle))) { if (_barLine == 0) { BarLine* bl = new BarLine(score()); bl->setParent(this); bl->setTrack(0); bl->setGenerated(true); score()->undoAddElement(bl); } } else if (_barLine) score()->undoRemoveElement(_barLine); if (_barLine) _barLine->rxpos() = _leftMargin + xo1; //--------------------------------------------------- // layout brackets //--------------------------------------------------- for (Bracket* b : _brackets) { qreal xo = -xo1; for (const Bracket* b2 : _brackets) { if (b->level() > b2->level() && ((b->firstStaff() >= b2->firstStaff() && b->firstStaff() <= b2->lastStaff()) || (b->lastStaff() >= b2->firstStaff() && b->lastStaff() <= b2->lastStaff()))) xo += b2->width() + bd; } b->rxpos() = _leftMargin - xo - b->width(); } //--------------------------------------------------- // layout instrument names x position //--------------------------------------------------- int idx = 0; for (const Part* p : score()->parts()) { SysStaff* s = staff(idx); if (s->show() && p->show()) { for (InstrumentName* t : s->instrumentNames) { switch (t->textStyle().align() & AlignmentFlags::HMASK) { case int(AlignmentFlags::LEFT): t->rxpos() = 0; break; case int(AlignmentFlags::HCENTER): t->rxpos() = (xoff2 - point(instrumentNameOffset) + xo1) * .5; break; case int(AlignmentFlags::RIGHT): default: t->rxpos() = xoff2 - point(instrumentNameOffset) + xo1; break; } t->rxpos() += t->textStyle().offset(t->spatium()).x(); } } idx += p->nstaves(); } }
void makeTable(const Keyword keywords[]) { int i,c; bool pre = (keywords == pp_keywords); QList<State> states; states += State(pre?"PP_NOTOKEN":"NOTOKEN"); // identifiers for (c = 'a'; c <= 'z'; ++c) newState(states, pre?"PP_CHARACTER":"CHARACTER", c); for (c = 'A'; c <= 'Z'; ++c) newState(states, pre?"PP_CHARACTER":"CHARACTER", c); c = '_'; newState(states, pre?"PP_CHARACTER":"CHARACTER", c); // add digits for (c = '0'; c <= '9'; ++c) newState(states, pre?"PP_DIGIT":"DIGIT", c); // keywords for (i = 0; keywords[i].lexem; ++i) newState(states, keywords[i].token, keywords[i].lexem, pre); // some floats for (c = '0'; c <= '9'; ++c) newState(states, pre?"PP_FLOATING_LITERAL":"FLOATING_LITERAL", QByteArray(".") + char(c), pre); // simplify table with default transitions int transindex = -1; for (i = 0; i < states.size(); ++i) { int n = 0; int defchar = -1; for (c = 0; c < 128; ++c) if (states[i].next[c]) { ++n; defchar = c; } if (!n) continue; if (n == 1) { states[i].defnext = states[i].next[defchar]; states[i].defchar = defchar; continue; } states[i].nextindex = ++transindex; } #if 1 // compress table int j, k; for (i = 0; i < states.size(); ++i) { for (j = i + 1; j < states.size(); ++j) { if ( states[i] == states[j] ) { for (k = 0; k < states.size(); ++k) { if (states[k].defnext == j) states[k].defnext = i; if (states[k].defnext > j) --states[k].defnext; for (c = 0; c < 128; ++c) { if (states[k].next[c] == j) states[k].next[c] = i; if (states[k].next[c] > j) --states[k].next[c]; } } states.removeAt(j); --j; } } } #endif printf("static const short %skeyword_trans[][128] = {\n", pre?"pp_":""); for (i = 0; i < states.size(); ++i) { if (i && !states[i].nextindex) continue; printf("%s {", i?",\n":""); for (c = 0; c < 128; ++c) printf("%s%s%d", c?",":"", (!c || c%16)?"":"\n ", states[i].next[c] ); printf("}"); } printf("\n};\n\n"); printf("static const struct\n{\n" " %sToken token;\n" " short next;\n" " char defchar;\n" " short defnext;\n" " %sToken ident;\n" "} %skeywords[] = {\n", pre ? "PP_":"", pre ? "PP_":"", pre ? "pp_":""); for (i = 0; i < states.size(); ++i) { printf("%s {%s, %d, %d, %d, %s}", i?",\n":"", states[i].token.data(), states[i].nextindex, states[i].defchar, states[i].defnext, states[i].ident?states[i].ident:(pre?"PP_NOTOKEN":"NOTOKEN")); } printf("\n};\n"); }
void DrawingView::printPdf() { Gui::FileOptionsDialog dlg(this, 0); dlg.setFileMode(QFileDialog::AnyFile); dlg.setAcceptMode(QFileDialog::AcceptSave); dlg.setWindowTitle(tr("Export PDF")); dlg.setNameFilters(QStringList() << QString::fromLatin1("%1 (*.pdf)").arg(tr("PDF file"))); QGridLayout *gridLayout; QGridLayout *formLayout; QGroupBox *groupBox; QListWidget *listWidget; QListWidgetItem* item; QWidget *form = new QWidget(&dlg); form->resize(40, 300); formLayout = new QGridLayout(form); groupBox = new QGroupBox(form); gridLayout = new QGridLayout(groupBox); listWidget = new QListWidget(groupBox); gridLayout->addWidget(listWidget, 0, 0, 1, 1); formLayout->addWidget(groupBox, 0, 0, 1, 1); groupBox->setTitle(tr("Page sizes")); item = new QListWidgetItem(tr("A0"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A0)); item = new QListWidgetItem(tr("A1"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A1)); item = new QListWidgetItem(tr("A2"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A2)); item = new QListWidgetItem(tr("A3"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A3)); item = new QListWidgetItem(tr("A4"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A4)); item = new QListWidgetItem(tr("A5"), listWidget); item->setData(Qt::UserRole, QVariant(QPrinter::A5)); int index = 4; // by default A4 for (int i=0; i<listWidget->count(); i++) { if (listWidget->item(i)->data(Qt::UserRole).toInt() == m_pageSize) { index = i; break; } } listWidget->item(index)->setSelected(true); dlg.setOptionsWidget(Gui::FileOptionsDialog::ExtensionRight, form, false); if (dlg.exec() == QDialog::Accepted) { Gui::WaitCursor wc; QString filename = dlg.selectedFiles().front(); QPrinter printer(QPrinter::HighResolution); printer.setFullPage(true); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(filename); printer.setOrientation(m_orientation); QList<QListWidgetItem*> items = listWidget->selectedItems(); if (items.size() == 1) { int AX = items.front()->data(Qt::UserRole).toInt(); printer.setPaperSize(QPrinter::PageSize(AX)); } print(&printer); } }
void RayDisplayScene::initLeds() { QList<int> sizes; //sizes << 64 << 40 << 64 << 40; sizes << 48 << 32 << 48 << 32; Q_ASSERT(4 == sizes.size()); QVector<QVector<QPointF>> sidedReceiversPos; QVector<QVector<QPointF>> sidedSendersPos; sidedReceiversPos.resize(sizes.size()); mSidedReceivers.resize(sizes.size()); sidedSendersPos.resize(sizes.size()); int allReceivers = 0; for (int i = 0; i < sizes.size(); i++) { Q_ASSERT(sizes.at(i) % 8 == 0); sidedReceiversPos[i].reserve(sizes.at(i)); mSidedReceivers[i].reserve(sizes.at(i)); sidedSendersPos[i].reserve(sizes.at(i) / 8); allReceivers += sizes.at(i) / 8; } mReceivers.reserve(allReceivers * 8); mSenders.reserve(allReceivers); // top left-to-right for (int i = 0; i < sizes.at(0); i++) { QGraphicsEllipseItem *r; const int x = i * 10; const int y = 0; r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::black), 2)); const int sideId = 0; const QPointF p(x, y); sidedReceiversPos[sideId] << p; r->setPos(p); mReceivers.append(r); mSidedReceivers[sideId] << r; } // right top-to-bottom for (int i = 0; i < sizes.at(1); i++) { QGraphicsEllipseItem *r; const int x = sizes.at(0) * 10; const int y = i * 10 - (0 - 5); r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::black), 2)); const int sideId = 1; const QPointF p(x, y); sidedReceiversPos[sideId] << p; r->setPos(p); mReceivers.append(r); mSidedReceivers[sideId] << r; } // bottom right-to-left for (int i = 0; i < sizes.at(2); i++) { QGraphicsEllipseItem *r; const int x = i * -10 + sizes.at(0) * 10 - 10; const int y = sizes.at(1) * 10; r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::black), 2)); const int sideId = 2; const QPointF p(x, y); sidedReceiversPos[sideId] << p; r->setPos(p); mReceivers.append(r); mSidedReceivers[sideId] << r; } // left bottom-to-top for (int i = 0; i < sizes.at(3); i++) { QGraphicsEllipseItem *r; const int x = -5; const int y = i * -10 + ((sizes.at(1)) * 10 - 5); r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::black), 2)); const int sideId = 3; const QPointF p(x, y); sidedReceiversPos[sideId] << p; r->setPos(p); mReceivers.append(r); mSidedReceivers[sideId] << r; } // top left-to-right for (int i = 0; i < (sizes.at(0) / 8); i++) { QGraphicsEllipseItem *r; const int x = i * 80 + 35; const int y = 0; r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::red), 2)); const int sideId = 0; const QPointF p(x, y); sidedSendersPos[sideId] << p; r->setPos(p); mSenders.append(Sender{r, 270, sideId}); } // right top-to-bottom for (int i = 0; i < (sizes.at(1) / 8); i++) { QGraphicsEllipseItem *r; const int x = sizes.at(0) * 10; const int y = i * 80 - (0 - 40); r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::red), 2)); const int sideId = 1; const QPointF p(x, y); sidedSendersPos[sideId] << p; r->setPos(p); mSenders.append(Sender{r, 180, sideId}); } // bottom right-to-left for (int i = 0; i < (sizes.at(2) / 8); i++) { QGraphicsEllipseItem *r; const int x = i * -80 + (sizes.at(0) * 10 - 40 - 5); const int y = sizes.at(1) * 10; r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::red), 2)); const int sideId = 2; const QPointF p(x, y); sidedSendersPos[sideId] << p; r->setPos(p); mSenders.append(Sender{r, 90, sideId}); } // left bottom-to-top for (int i = 0; i < (sizes.at(3) / 8); i++) { QGraphicsEllipseItem *r; const int x = -5; const int y = i * -80 + ((sizes.at(1) * 10) - 40); r = addEllipse(0, 0, 5, 5, QPen(QBrush(Qt::red), 2)); const int sideId = 3; const QPointF p(x, y); sidedSendersPos[sideId] << p; r->setPos(p); mSenders.append(Sender{r, 0, sideId}); } // mTI = new CvTracker(sidedReceiversPos, sidedSendersPos, this); emit publishSizes(sidedReceiversPos, sidedSendersPos); mCollidedRays.clear(); mCollidedRays.resize(mSenders.size()); mCollidedRaysGraphics.clear(); mCollidedRaysGraphics.resize(mSenders.size()); mTriangles.clear(); mTriangles.resize(mSenders.size()); /*QVector<cv::Point> points; points << cv::Point2i(0, 0); points << cv::Point2i(0, 100); points << cv::Point2i(100, 0); const cv::Point *pointsPtr[1] = {points.data()}; int size = points.size(); cv::Scalar color = cv::Scalar(127); cv::Mat m = mMats[0]; cv::line(m, cv::Point2i(0, 0), cv::Point2i(100, 100), color, 22); cv::imshow("plepleple", m); cv::fillConvexPoly(m, points.data(), size, color); qDebug() << "before"; T::sleep(4); qDebug() << "after"; cv::imshow("plepleple", m);*/ }
QString GeneratorSetDylan::generate() { // Code generation QList<Generator *> generators; LibraryGenerator *libraryGenerator = new LibraryGenerator; LidGenerator *lidGenerator = new LidGenerator; DylanGenerator *dylan_generator = 0; PlainCppHeaderGenerator *cpp_header_generator = 0; PlainCppImplGenerator *cpp_impl_generator = 0; QStringList contexts; dylan_generator = new DylanGenerator(libraryGenerator, lidGenerator); if (!javaOutDir.isNull()) dylan_generator->setDylanOutputDirectory(javaOutDir); if (!outDir.isNull()) dylan_generator->setLogOutputDirectory(outDir); generators << dylan_generator; contexts << "DylanGenerator"; cpp_header_generator = new PlainCppHeaderGenerator(lidGenerator); if (!cppOutDir.isNull()) cpp_header_generator->setCppOutputDirectory(cppOutDir); generators << cpp_header_generator; contexts << "PlainCppHeaderGenerator"; cpp_impl_generator = new PlainCppImplGenerator(lidGenerator); if (!cppOutDir.isNull()) cpp_impl_generator->setCppOutputDirectory(cppOutDir); generators << cpp_impl_generator; contexts << "PlainCppImplGenerator"; if (!cppOutDir.isNull()) lidGenerator->setCppOutputDirectory(cppOutDir); generators << lidGenerator; contexts << "LidGenerator"; if (!cppOutDir.isNull()) libraryGenerator->setOutputDirectory(cppOutDir); generators << libraryGenerator; contexts << "LibraryGenerator"; for (int i = 0; i < generators.size(); ++i) { Generator *generator = generators.at(i); ReportHandler::setContext(contexts.at(i)); if (generator->outputDirectory().isNull()) generator->setOutputDirectory(outDir); generator->setClasses(builder.classes()); if (printStdout) generator->printClasses(); else generator->generate(); } QString res; res = QString("Classes in typesystem: %1\n" "Generated:\n" " - dylan.....: %2 (%3)\n" " - cpp-impl..: %4 (%5)\n" " - cpp-h.....: %6 (%7)\n" " - library...: %8 (%9)\n" " - lid.......: %10 (%11)\n" ) .arg(builder.classes().size()) .arg(dylan_generator ? dylan_generator->numGenerated() : 0) .arg(dylan_generator ? dylan_generator->numGeneratedAndWritten() : 0) .arg(cpp_impl_generator ? cpp_impl_generator->numGenerated() : 0) .arg(cpp_impl_generator ? cpp_impl_generator->numGeneratedAndWritten() : 0) .arg(cpp_header_generator ? cpp_header_generator->numGenerated() : 0) .arg(cpp_header_generator ? cpp_header_generator->numGeneratedAndWritten() : 0) .arg(libraryGenerator->numGenerated()) .arg(libraryGenerator->numGeneratedAndWritten()) .arg(lidGenerator->numGenerated()) .arg(lidGenerator->numGeneratedAndWritten()); return res; }
RenderOptionsDialog::RenderOptionsDialog() : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint) { setWindowOpacity(0.75); setWindowTitle(tr("Options (double click to flip)")); QGridLayout *layout = new QGridLayout; setLayout(layout); layout->setColumnStretch(1, 1); int row = 0; QCheckBox *check = new QCheckBox(tr("Dynamic cube map")); check->setCheckState(Qt::Unchecked); // Dynamic cube maps are only enabled when multi-texturing and render to texture are available. check->setEnabled(glActiveTexture && glGenFramebuffersEXT); connect(check, SIGNAL(stateChanged(int)), this, SIGNAL(dynamicCubemapToggled(int))); layout->addWidget(check, 0, 0, 1, 2); ++row; QPalette palette; // Load all .par files // .par files have a simple syntax for specifying user adjustable uniform variables. QSet<QByteArray> uniforms; QList<QString> filter = QStringList("*.par"); QList<QFileInfo> files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); foreach (QFileInfo fileInfo, files) { QFile file(fileInfo.absoluteFilePath()); if (file.open(QIODevice::ReadOnly)) { while (!file.atEnd()) { QList<QByteArray> tokens = file.readLine().simplified().split(' '); QList<QByteArray>::const_iterator it = tokens.begin(); if (it == tokens.end()) continue; QByteArray type = *it; if (++it == tokens.end()) continue; QByteArray name = *it; bool singleElement = (tokens.size() == 3); // type, name and one value char counter[10] = "000000000"; int counterPos = 8; // position of last digit while (++it != tokens.end()) { m_parameterNames << name; if (!singleElement) { m_parameterNames.back() += "["; m_parameterNames.back() += counter + counterPos; m_parameterNames.back() += "]"; int j = 8; // position of last digit ++counter[j]; while (j > 0 && counter[j] > '9') { counter[j] = '0'; ++counter[--j]; } if (j < counterPos) counterPos = j; } if (type == "color") { layout->addWidget(new QLabel(m_parameterNames.back())); bool ok; ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1); m_parameterEdits << colorEdit; layout->addWidget(colorEdit); connect(colorEdit, SIGNAL(colorChanged(QRgb,int)), this, SLOT(setColorParameter(QRgb,int))); ++row; } else if (type == "float") { layout->addWidget(new QLabel(m_parameterNames.back())); bool ok; FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1); m_parameterEdits << floatEdit; layout->addWidget(floatEdit); connect(floatEdit, SIGNAL(valueChanged(float,int)), this, SLOT(setFloatParameter(float,int))); ++row; } }
int main(int argc, char *argv[]) { QCoreApplication application(argc, argv); const QStringList &args(application.arguments()); const bool quickMode(args.contains(QStringLiteral("-q")) || args.contains(QStringLiteral("--quick"))); QMap<QString, QString> parameters; parameters.insert(QString::fromLatin1("mergePresenceChanges"), QString::fromLatin1("false")); QContactManager manager(QString::fromLatin1("org.nemomobile.contacts.sqlite"), parameters); QContactFetchRequest request; request.setManager(&manager); // Perform an initial request to ensure the database has been created before we start timing request.start(); request.waitForFinished(); qint64 elapsedTimeTotal = 0; QElapsedTimer asyncTotalTimer; asyncTotalTimer.start(); // Fetch all, no optimization hints for (int i = 0; i < 3; ++i) { QElapsedTimer timer; timer.start(); request.start(); request.waitForFinished(); qint64 elapsed = timer.elapsed(); qDebug() << i << ": Fetch completed in" << elapsed << "ms"; elapsedTimeTotal += elapsed; } // Skip relationships QContactFetchHint hint; hint.setOptimizationHints(QContactFetchHint::NoRelationships); request.setFetchHint(hint); for (int i = 0; i < 3; ++i) { QElapsedTimer timer; timer.start(); request.start(); request.waitForFinished(); qint64 elapsed = timer.elapsed(); qDebug() << i << ": No-relationships fetch completed in" << elapsed << "ms"; elapsedTimeTotal += elapsed; } // Reduce data access hint.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactName::Type << QContactAddress::Type); request.setFetchHint(hint); for (int i = 0; i < 3; ++i) { QElapsedTimer timer; timer.start(); request.start(); request.waitForFinished(); qint64 elapsed = timer.elapsed(); qDebug() << i << ": Reduced data fetch completed in" << elapsed << "ms"; elapsedTimeTotal += elapsed; } // Reduce number of results hint.setMaxCountHint(request.contacts().count() / 8); request.setFetchHint(hint); for (int i = 0; i < 3; ++i) { QElapsedTimer timer; timer.start(); request.start(); request.waitForFinished(); qint64 elapsed = timer.elapsed(); qDebug() << i << ": Max count fetch completed in" << elapsed << "ms"; elapsedTimeTotal += elapsed; } qint64 asyncTotalElapsed = asyncTotalTimer.elapsed(); // Time some synchronous operations. First, generate the test data. qsrand((int)asyncTotalElapsed); QList<int> nbrContacts; if (quickMode) { nbrContacts << 200; } else { nbrContacts << 10 << 100 << 500 << 1000 << 2000; } QList<QList<QContact> > testData; qDebug() << "\n\nGenerating test data for timings..."; for (int i = 0; i < nbrContacts.size(); ++i) { int howMany = nbrContacts.at(i); QList<QContact> newTestData; newTestData.reserve(howMany); for (int j = 0; j < howMany; ++j) { // Use testing sync target, so 'local' won't be modified into 'was_local' via aggregation newTestData.append(generateContact(QString::fromLatin1("testing"))); } testData.append(newTestData); } // Perform the timings - these all create new contacts and assume an "empty" initial database QElapsedTimer syncTimer; for (int i = 0; i < testData.size(); ++i) { QList<QContact> td = testData.at(i); qint64 ste = 0; qDebug() << "Performing tests for" << td.size() << "contacts:"; syncTimer.start(); manager.saveContacts(&td); ste = syncTimer.elapsed(); qDebug() << " saving took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; QContactDetailFilter testingFilter; testingFilter.setDetailType(QContactSyncTarget::Type, QContactSyncTarget::FieldSyncTarget); testingFilter.setValue(QString::fromLatin1("testing")); QContactFetchHint fh; syncTimer.start(); QList<QContact> readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all (" << readContacts.size() << "), all details, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type << QContactName::Type << QContactAvatar::Type << QContactPhoneNumber::Type << QContactEmailAddress::Type); syncTimer.start(); readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all, common details, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; fh.setOptimizationHints(QContactFetchHint::NoRelationships); fh.setDetailTypesHint(QList<QContactDetail::DetailType>()); syncTimer.start(); readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all, no relationships, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type << QContactName::Type << QContactAvatar::Type); syncTimer.start(); readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; // Read the contacts, selected by ID QList<QContactId> idsToRetrieve; for (int j = 0; j < td.size(); ++j) { idsToRetrieve.append(retrievalId(td.at(j))); } syncTimer.start(); readContacts = manager.contacts(idsToRetrieve, fh, 0); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all by IDs, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; // Read the same set using ID filtering QContactIdFilter idFilter; idFilter.setIds(idsToRetrieve); syncTimer.start(); readContacts = manager.contacts(idFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all by ID filter, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; // Read the same set, but filter everything out using syncTarget QContactDetailFilter aggregateFilter; aggregateFilter.setDetailType(QContactSyncTarget::Type, QContactSyncTarget::FieldSyncTarget); aggregateFilter.setValue(QString::fromLatin1("aggregate")); syncTimer.start(); readContacts = manager.contacts(idFilter & aggregateFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != 0) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << 0; } qDebug() << " reading all by ID filter & aggregate, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; QContactDetailFilter firstNameStartsA; firstNameStartsA.setDetailType(QContactName::Type, QContactName::FieldFirstName); firstNameStartsA.setValue("A"); firstNameStartsA.setMatchFlags(QContactDetailFilter::MatchStartsWith); fh.setDetailTypesHint(QList<QContactDetail::DetailType>()); syncTimer.start(); readContacts = manager.contacts(firstNameStartsA, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading filtered (" << readContacts.size() << "), no relationships, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; QList<QContactId> idsToRemove; for (int j = 0; j < td.size(); ++j) { idsToRemove.append(retrievalId(td.at(j))); } syncTimer.start(); manager.removeContacts(idsToRemove); ste = syncTimer.elapsed(); qDebug() << " removing test data took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; } // these tests are slightly different to those above. They operate on much smaller // batches, but occur after the database has already been prefilled with some data. QList<int> smallerNbrContacts; if (quickMode) { smallerNbrContacts << 20; } else { smallerNbrContacts << 1 << 2 << 5 << 10 << 20 << 50; } QList<QList<QContact> > smallerTestData; qDebug() << "\n\nGenerating smaller test data for prefilled timings..."; for (int i = 0; i < smallerNbrContacts.size(); ++i) { int howMany = smallerNbrContacts.at(i); QList<QContact> newTestData; newTestData.reserve(howMany); for (int j = 0; j < howMany; ++j) { newTestData.append(generateContact()); } smallerTestData.append(newTestData); } // prefill the database QList<QContact> prefillData; for (int i = 0; i < testData.size() && testData.at(i).size() < 1001; ++i) { prefillData = testData.at(i); } qDebug() << "Prefilling database with" << prefillData.size() << "contacts... this will take a while..."; manager.saveContacts(&prefillData); qDebug() << "Now performing timings (shouldn't get aggregated)..."; for (int i = 0; i < smallerTestData.size(); ++i) { QList<QContact> td = smallerTestData.at(i); qint64 ste = 0; qDebug() << "Performing tests for" << td.size() << "contacts:"; syncTimer.start(); manager.saveContacts(&td); ste = syncTimer.elapsed(); qDebug() << " saving took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; QContactFetchHint fh; syncTimer.start(); QList<QContact> readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading all (" << readContacts.size() << "), all details, took" << ste << "milliseconds"; elapsedTimeTotal += ste; fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type << QContactName::Type << QContactAvatar::Type << QContactPhoneNumber::Type << QContactEmailAddress::Type); syncTimer.start(); readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading all, common details, took" << ste << "milliseconds"; elapsedTimeTotal += ste; fh.setOptimizationHints(QContactFetchHint::NoRelationships); fh.setDetailTypesHint(QList<QContactDetail::DetailType>()); syncTimer.start(); readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading all, no relationships, took" << ste << "milliseconds"; elapsedTimeTotal += ste; fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type << QContactName::Type << QContactAvatar::Type); syncTimer.start(); readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading all, display details + no rels, took" << ste << "milliseconds"; elapsedTimeTotal += ste; QContactDetailFilter firstNameStartsA; firstNameStartsA.setDetailType(QContactName::Type, QContactName::FieldFirstName); firstNameStartsA.setValue("A"); firstNameStartsA.setMatchFlags(QContactDetailFilter::MatchStartsWith); fh.setDetailTypesHint(QList<QContactDetail::DetailType>()); syncTimer.start(); readContacts = manager.contacts(firstNameStartsA, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading filtered (" << readContacts.size() << "), no relationships, took" << ste << "milliseconds"; elapsedTimeTotal += ste; QList<QContactId> idsToRemove; for (int j = 0; j < td.size(); ++j) { idsToRemove.append(retrievalId(td.at(j))); } syncTimer.start(); manager.removeContacts(idsToRemove); ste = syncTimer.elapsed(); qDebug() << " removing test data took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; } // The next test is about saving contacts which should get aggregated into others. // Aggregation is an expensive operation, so we expect these save operations to take longer. qDebug() << "\n\nPerforming aggregation tests"; QList<QContact> contactsToAggregate; for (int i = 0; i < 100; ++i) { QContact existingContact = prefillData.at(prefillData.size() - 1 - i); QContact contactToAggregate; QContactSyncTarget newSyncTarget; newSyncTarget.setSyncTarget(QString(QLatin1String("fetchtimes-aggregation"))); QContactName aggName = existingContact.detail<QContactName>(); // ensures it'll get aggregated QContactOnlineAccount newOnlineAcct; // new data, which should get promoted up etc. newOnlineAcct.setAccountUri(QString(QLatin1String("test-aggregation-%1@fetchtimes")).arg(i)); contactToAggregate.saveDetail(&newSyncTarget); contactToAggregate.saveDetail(&aggName); contactToAggregate.saveDetail(&newOnlineAcct); contactsToAggregate.append(contactToAggregate); } syncTimer.start(); manager.saveContacts(&contactsToAggregate); qint64 aggregationElapsed = syncTimer.elapsed(); int totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << "Average time for aggregation of" << contactsToAggregate.size() << "contacts (with" << totalAggregatesInDatabase << "existing in database):" << aggregationElapsed << "milliseconds (" << ((1.0 * aggregationElapsed) / (1.0 * contactsToAggregate.size())) << " msec per aggregated contact )"; elapsedTimeTotal += aggregationElapsed; // Now perform the test again, this time with more aggregates, to test nonlinearity. contactsToAggregate.clear(); const int high = prefillData.size() / 2, low = high / 2; for (int i = low; i < high; ++i) { QContact existingContact = prefillData.at(prefillData.size() - 1 - i); QContact contactToAggregate; QContactSyncTarget newSyncTarget; newSyncTarget.setSyncTarget(QString(QLatin1String("fetchtimes-aggregation"))); QContactName aggName = existingContact.detail<QContactName>(); // ensures it'll get aggregated QContactOnlineAccount newOnlineAcct; // new data, which should get promoted up etc. newOnlineAcct.setAccountUri(QString(QLatin1String("test-aggregation-%1@fetchtimes")).arg(i)); contactToAggregate.saveDetail(&newSyncTarget); contactToAggregate.saveDetail(&aggName); contactToAggregate.saveDetail(&newOnlineAcct); contactsToAggregate.append(contactToAggregate); } syncTimer.start(); manager.saveContacts(&contactsToAggregate); aggregationElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << "Average time for aggregation of" << contactsToAggregate.size() << "contacts (with" << totalAggregatesInDatabase << "existing in database):" << aggregationElapsed << "milliseconds (" << ((1.0 * aggregationElapsed) / (1.0 * contactsToAggregate.size())) << " msec per aggregated contact )"; elapsedTimeTotal += aggregationElapsed; // The next test is about updating existing contacts, amongst a large set. // We're especially interested in presence updates, as these are common. qDebug() << "\n\nPerforming presence update tests:"; // in the first presence update test, we update a small number of contacts. QStringList presenceAvatars = generateAvatarsList(); QList<QContact> contactsToUpdate; for (int i = 0; i < 10; ++i) { contactsToUpdate.append(prefillData.at(prefillData.size() - 1 - i)); } // modify the presence, nickname and avatar of the test data for (int j = 0; j < contactsToUpdate.size(); ++j) { QString genstr = QString::number(j); QContact curr = contactsToUpdate[j]; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(QDateTime::currentDateTime()); cp.setPresenceState(static_cast<QContactPresence::PresenceState>(qrand() % 4)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.replace(j, curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); qint64 presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // in the second presence update test, we update ALL of the contacts // This simulates having a large number of contacts from a single source (eg, a social network) // where (due to changed connectivity status) presence updates for the entire set become available. contactsToUpdate.clear(); QDateTime timestamp = QDateTime::currentDateTime(); for (int j = 0; j < prefillData.size(); ++j) { QContact curr = prefillData.at(j); QString genstr = QString::number(j) + "2"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // the third presence update test is identical to the previous, but with 2000 prefilled contacts in database. qDebug() << " Adding more prefill data, please wait..."; QList<QContact> morePrefillData; for (int i = 0; i < contactsToUpdate.size(); ++i) { morePrefillData.append(generateContact(QString::fromLatin1("testing"))); } manager.saveContacts(&morePrefillData); // now do the updates and save. contactsToUpdate.clear(); timestamp = QDateTime::currentDateTime(); for (int j = 0; j < prefillData.size(); ++j) { QContact curr = prefillData.at(j); QString genstr = QString::number(j) + "3"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QString genstr = QString::number(j) + "3"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // clean up the "more prefill data" qDebug() << " cleaning up extra prefill data, please wait..."; QList<QContactId> morePrefillIds; for (int j = 0; j < morePrefillData.size(); ++j) { morePrefillIds.append(retrievalId(morePrefillData.at(j))); } manager.removeContacts(morePrefillIds); // the fourth presence update test checks update time for non-overlapping sets of data. qDebug() << " generating non-overlapping / aggregated prefill data, please wait..."; morePrefillData.clear(); for (int i = 0; i < prefillData.size(); ++i) { morePrefillData.append(generateContact("test-presence-4", false)); // false = don't aggregate. } manager.saveContacts(&morePrefillData); // now do the update contactsToUpdate.clear(); timestamp = QDateTime::currentDateTime(); for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QString genstr = QString::number(j) + "4"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, no overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // clean up the "more prefill data" qDebug() << " cleaning up extra prefill data, please wait..."; morePrefillIds.clear(); for (int j = 0; j < morePrefillData.size(); ++j) { morePrefillIds.append(morePrefillData.at(j).id()); } manager.removeContacts(morePrefillIds); // the fifth presence update test is similar to the above except that half of // the extra contacts have a (high) chance of being aggregated into an existing contact. // So, database should have 2000 constituents, 1000 from "local", 1000 from "test-presence-5" // with 1500 aggregates (about 500 of test-presence-5 contacts will share an aggregate with // a local contact). TODO: check what happens if multiple aggregates for local contacts // could possibly match a given test-presence-5 contact (which is possible, since the backend // never aggregates two contacts from the same sync source...) qDebug() << " generating partially-overlapping / aggregated prefill data, please wait..."; morePrefillData.clear(); for (int i = 0; i < prefillData.size(); ++i) { if (i < (prefillData.size() / 2)) { morePrefillData.append(generateContact("test-presence-5", false)); // false = don't aggregate. } else { morePrefillData.append(generateContact("test-presence-5", true)); // true = possibly aggregate. } } manager.saveContacts(&morePrefillData); // now do the update contactsToUpdate.clear(); timestamp = QDateTime::currentDateTime(); for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QString genstr = QString::number(j) + "5"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, partial overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // the sixth presence update test is identical to the fifth test, except that we ONLY // update the presence status (not nickname or avatar). morePrefillData = contactsToUpdate; contactsToUpdate.clear(); for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QContactPresence cp = curr.detail<QContactPresence>(); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); curr.saveDetail(&cp); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence only (with" << totalAggregatesInDatabase << "existing in database, partial overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // the seventh presence update test is identical to the 6th test, except that // we also pass a "detail type mask" to the update. This allows the backend // to perform optimisation based upon which details are modified. morePrefillData = contactsToUpdate; contactsToUpdate.clear(); for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QContactPresence cp = curr.detail<QContactPresence>(); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); curr.saveDetail(&cp); contactsToUpdate.append(curr); } // perform a batch save. QList<QContactDetail::DetailType> typeMask; typeMask << QContactDetail::TypePresence; syncTimer.start(); manager.saveContacts(&contactsToUpdate, typeMask); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") masked presence only (with" << totalAggregatesInDatabase << "existing in database, partial overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // clean up the "more prefill data" qDebug() << " cleaning up extra prefill data, please wait..."; morePrefillIds.clear(); for (int j = 0; j < morePrefillData.size(); ++j) { morePrefillIds.append(morePrefillData.at(j).id()); } manager.removeContacts(morePrefillIds); qDebug() << "\n\nCumulative elapsed time:" << elapsedTimeTotal << "milliseconds"; return 0; }
void HrPwPlot::recalc() { if (timeArray.count() == 0) return; int rideTimeSecs = (int) ceil(timeArray[arrayLength - 1]); if (rideTimeSecs > SECONDS_IN_A_WEEK) { return; } // ------ smoothing ----- double totalWatts = 0.0; double totalHr = 0.0; QList<DataPoint*> list; int i = 0; QVector<double> smoothWatts(rideTimeSecs + 1); QVector<double> smoothHr(rideTimeSecs + 1); QVector<double> smoothTime(rideTimeSecs + 1); int decal=0; //int interval = 0; int smooth = hrPwWindow->smooth; for (int secs = smooth; secs <= rideTimeSecs; ++secs) { while ((i < arrayLength) && (timeArray[i] <= secs)) { DataPoint *dp = new DataPoint(timeArray[i], hrArray[i], wattsArray[i], interArray[i]); totalWatts += wattsArray[i]; totalHr += hrArray[i]; list.append(dp); ++i; } while (!list.empty() && (list.front()->time < secs - smooth)) { DataPoint *dp = list.front(); list.removeFirst(); totalWatts -= dp->watts; totalHr -= dp->hr; delete dp; } if (list.empty()) ++decal; else { smoothWatts[secs-decal] = totalWatts / list.size(); smoothHr[secs-decal] = totalHr / list.size(); } smoothTime[secs] = secs / 60.0; } // Delete temporary list qDeleteAll(list); list.clear(); rideTimeSecs = rideTimeSecs-decal; smoothWatts.resize(rideTimeSecs); smoothHr.resize(rideTimeSecs); // Clip to max QVector<double> clipWatts(rideTimeSecs); QVector<double> clipHr(rideTimeSecs); decal = 0; for (int secs = 0; secs < rideTimeSecs; ++secs) { if (smoothHr[secs]>= minHr && smoothWatts[secs]>= minWatt && smoothWatts[secs]<maxWatt) { clipWatts[secs-decal] = smoothWatts[secs]; clipHr[secs-decal] = smoothHr[secs]; } else decal ++; } rideTimeSecs = rideTimeSecs-decal; clipWatts.resize(rideTimeSecs); clipHr.resize(rideTimeSecs); // Find Hr Delay if (delay == -1) delay = hrPwWindow->findDelay(clipWatts, clipHr, clipWatts.size()); else if (delay>rideTimeSecs) delay=rideTimeSecs; // Apply delay QVector<double> delayWatts(rideTimeSecs-delay); QVector<double> delayHr(rideTimeSecs-delay); for (int secs = 0; secs < rideTimeSecs-delay; ++secs) { delayWatts[secs] = clipWatts[secs]; delayHr[secs] = clipHr[secs+delay]; } rideTimeSecs = rideTimeSecs-delay; double rslope = hrPwWindow->slope(delayWatts, delayHr, delayWatts.size()); double rintercept = hrPwWindow->intercept(delayWatts, delayHr, delayWatts.size()); double maxr = hrPwWindow->corr(delayWatts, delayHr, delayWatts.size()); // ----- limit plotted points --- int intpoints = 10; // could be ride length dependent int nbpoints = (int)floor(rideTimeSecs/intpoints); QVector<double> plotedWatts(nbpoints); QVector<double> plotedHr(nbpoints); for (int secs = 0; secs < nbpoints; ++secs) { plotedWatts[secs] = clipWatts[secs*intpoints]; plotedHr[secs] = clipHr[secs*intpoints]; } int nbpoints2 = (int)floor(nbpoints/36)+2; double *plotedWattsArray[36]; double *plotedHrArray[36]; for (int i = 0; i < 36; ++i) { plotedWattsArray[i]= new double[nbpoints2]; plotedHrArray[i]= new double[nbpoints2]; } for (int secs = 0; secs < nbpoints; ++secs) { for (int i = 0; i < 36; ++i) { if (secs >= i*nbpoints2 && secs< (i+1)*nbpoints2) { plotedWattsArray[i][secs-i*nbpoints2] = plotedWatts[secs-i]; plotedHrArray[i][secs-i*nbpoints2] = plotedHr[secs-i]; } } } for (int i = 0; i < 36; ++i) { if (nbpoints-i*nbpoints2>0) { hrCurves[i]->setSamples(plotedWattsArray[i], plotedHrArray[i], (nbpoints-i*nbpoints2<nbpoints2?nbpoints-i*nbpoints2:nbpoints2)); hrCurves[i]->setVisible(true); } else hrCurves[i]->setVisible(false); } // Clean up memory for (int i = 0; i < 36; ++i) { delete plotedWattsArray[i]; delete plotedHrArray[i]; } setAxisScale(xBottom, 0.0, maxWatt); setYMax(); refreshZoneLabels(); QString labelp; labelp.setNum(rslope, 'f', 3); QString labelo; labelo.setNum(rintercept, 'f', 1); QString labelr; labelr.setNum(maxr, 'f', 3); QString labeldelay; labeldelay.setNum(delay); int power150 = (int)floor((150-rintercept)/rslope); QString labelpower150; labelpower150.setNum(power150); QwtText textr = QwtText(labelp+"*x+"+labelo+" : R "+labelr+" ("+labeldelay+") \n Power@150:"+labelpower150+"W"); textr.setFont(QFont("Helvetica", 10, QFont::Bold)); textr.setColor(GColor(CPLOTMARKER)); r_mrk1->setValue(0,0); r_mrk1->setLineStyle(QwtPlotMarker::VLine); r_mrk1->setLabelAlignment(Qt::AlignRight | Qt::AlignBottom); r_mrk1->setLinePen(QPen(GColor(CPLOTMARKER), 0, Qt::DashDotLine)); double averagewatt = hrPwWindow->average(clipWatts, clipWatts.size()); r_mrk1->setValue(averagewatt, 0.0); r_mrk1->setLabel(textr); r_mrk2->setValue(0,0); r_mrk2->setLineStyle(QwtPlotMarker::HLine); r_mrk2->setLabelAlignment(Qt::AlignRight | Qt::AlignTop); r_mrk2->setLinePen(QPen(GColor(CPLOTMARKER), 0, Qt::DashDotLine)); double averagehr = hrPwWindow->average(clipHr, clipHr.size()); r_mrk2->setValue(0.0,averagehr); addWattStepCurve(clipWatts, clipWatts.size()); addHrStepCurve(clipHr, clipHr.size()); addRegLinCurve(rslope, rintercept); setJoinLine(joinLine); replot(); }
/*! \brief Render an image from data and color map. For each pixel of area the value is mapped into a color. \param xMap X-Scale Map \param yMap Y-Scale Map \param area Requested area for the image in scale coordinates \param imageSize Size of the requested image \return A QImage::Format_Indexed8 or QImage::Format_ARGB32 depending on the color map. \sa QwtRasterData::value(), QwtColorMap::rgb(), QwtColorMap::colorIndex() */ QImage QwtPlotSpectrogram::renderImage( const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &area, const QSize &imageSize ) const { if ( imageSize.isEmpty() || d_data->data == NULL || d_data->colorMap == NULL ) { return QImage(); } const QwtInterval intensityRange = d_data->data->interval( Qt::ZAxis ); if ( !intensityRange.isValid() ) return QImage(); QImage::Format format = ( d_data->colorMap->format() == QwtColorMap::RGB ) ? QImage::Format_ARGB32 : QImage::Format_Indexed8; QImage image( imageSize, format ); if ( d_data->colorMap->format() == QwtColorMap::Indexed ) image.setColorTable( d_data->colorMap->colorTable( intensityRange ) ); d_data->data->initRaster( area, image.size() ); #if DEBUG_RENDER QElapsedTimer time; time.start(); #endif #if QT_VERSION >= 0x040400 && !defined(QT_NO_QFUTURE) uint numThreads = renderThreadCount(); if ( numThreads <= 0 ) numThreads = QThread::idealThreadCount(); if ( numThreads <= 0 ) numThreads = 1; const int numRows = imageSize.height() / numThreads; QList< QFuture<void> > futures; for ( uint i = 0; i < numThreads; i++ ) { QRect tile( 0, i * numRows, image.width(), numRows ); if ( i == numThreads - 1 ) { tile.setHeight( image.height() - i * numRows ); renderTile( xMap, yMap, tile, &image ); } else { futures += QtConcurrent::run( this, &QwtPlotSpectrogram::renderTile, xMap, yMap, tile, &image ); } } for ( int i = 0; i < futures.size(); i++ ) futures[i].waitForFinished(); #else // QT_VERSION < 0x040400 const QRect tile( 0, 0, image.width(), image.height() ); renderTile( xMap, yMap, tile, &image ); #endif #if DEBUG_RENDER const qint64 elapsed = time.elapsed(); qDebug() << "renderImage" << imageSize << elapsed; #endif d_data->data->discardRaster(); return image; }
// superKeyframe contains all super masters generated by folded units SuperShapeKf::SuperShapeKf(Scaffold* superKeyframe, StringSetMap moc_g) { // clone all nodes for (Structure::Node* n : superKeyframe->nodes) Structure::Graph::addNode(n->clone()); // super masters and their enclosed regular masters QVector<SuperPatchNode*> superMasters; QVector<QSet<QString> > enclosedMasters, enclosedMastersNew; for(Structure::Node* n : getNodesWithTag(MASTER_TAG)){ if (n->hasTag(SUPER_PATCH_TAG)) { SuperPatchNode* sp = (SuperPatchNode*)n; superMasters << sp; enclosedMasters << sp->enclosedPatches; } } // merge super nodes which share children QVector<QSet<int> > superIdxClusters = mergeIsctSets(enclosedMasters, enclosedMastersNew); // merge to create new super patches for (int i = 0; i < superIdxClusters.size(); i++) { // merged set indices QList<int> superIndices = superIdxClusters[i].toList(); // pick up the first SuperPatchNode* firstSP = superMasters[superIndices[0]]; firstSP->mID = QString("MP_%1").arg(i); Geom::Rectangle base_rect = firstSP->mPatch; // replace others with the first if (superIndices.size() > 1) { QVector<Vector2> pnts2 = base_rect.get2DConners(); for (int otherIdxIdx = 1; otherIdxIdx < superIndices.size(); otherIdxIdx++) { SuperPatchNode* otherSP = superMasters[superIndices[otherIdxIdx]]; Geom::Rectangle2 rect2 = base_rect.get2DRectangle(otherSP->mPatch); pnts2 << rect2.getConners(); // remove other removeNode(otherSP->mID); } Geom::Rectangle2 aabb2 = Geom::computeAABB(pnts2); firstSP->resize(aabb2); } // update master_super_map firstSP->enclosedPatches = enclosedMastersNew[i]; for (QString mid : enclosedMastersNew[i]) master2SuperMap[mid] = firstSP->mID; } // ***update moc_greater // change name of keys mocGreater = moc_g; for (QSet<QString> child_mids : enclosedMastersNew) { QString child = child_mids.toList().front(); QString key_new = master2SuperMap[child]; QSet<QString> values_union; for (QString cmid : child_mids){ values_union += mocGreater[cmid]; mocGreater.remove(cmid); } mocGreater[key_new] = values_union; } // change name of values for (QString key : mocGreater.keys()) { QSet<QString> values_new; for (QString v : mocGreater[key]){ if (master2SuperMap.contains(v)) v = master2SuperMap[v]; // change name values_new << v; } mocGreater[key] = values_new; } // moc_less for (QString key : mocGreater.keys()) for (QString value : mocGreater[key]) mocLess[value] << key; }
int size() { return cachedAddressTable.size(); }
/*! This virtual function removes all items in the scene index. */ void QGraphicsSceneIndex::clear() { const QList<QGraphicsItem *> allItems = items(); for (int i = 0 ; i < allItems.size(); ++i) removeItem(allItems.at(i)); }
void quotes::sConvert() { if (QMessageBox::question(this, tr("Convert Selected Quote(s)"), tr("<p>Are you sure that you want to convert " "the selected Quote(s) to Sales Order(s)?"), QMessageBox::Yes, QMessageBox::No | QMessageBox::Default) == QMessageBox::Yes) { XSqlQuery convert; convert.prepare("SELECT convertQuote(:quhead_id) AS sohead_id;"); XSqlQuery prospectq; prospectq.prepare("SELECT convertProspectToCustomer(quhead_cust_id) AS result " "FROM quhead " "WHERE (quhead_id=:quhead_id);"); bool tryagain = false; do { int soheadid = -1; QList<QTreeWidgetItem*> selected = _quote->selectedItems(); QList<QTreeWidgetItem*> notConverted; for (int i = 0; i < selected.size(); i++) { int quheadid = ((XTreeWidgetItem*)(selected[i]))->id(); convert.bindValue(":quhead_id", quheadid); convert.exec(); if (convert.first()) { soheadid = convert.value("sohead_id").toInt(); if (soheadid == -3) { if (QMessageBox::question(this, tr("Quote for Prospect"), tr("<p>This Quote is for a Prospect, not " "a Customer. Do you want to convert " "the Prospect to a Customer?"), QMessageBox::Yes, QMessageBox::No | QMessageBox::Default) == QMessageBox::Yes) { prospectq.bindValue(":quhead_id", quheadid); prospectq.exec(); if (prospectq.first()) { int result = prospectq.value("result").toInt(); if (result < 0) { systemError(this, storedProcErrorLookup("convertProspectToCustomer", result), __FILE__, __LINE__); notConverted.append(selected[i]); continue; } customer *newdlg = new customer(0, "customer", Qt::Dialog); newdlg->setWindowModality(Qt::WindowModal); ParameterList params; params.append("cust_id", result); params.append("mode", "edit"); newdlg->set(params); omfgThis->handleNewWindow(newdlg); return; } else if (prospectq.lastError().type() != QSqlError::None) { systemError(this, prospectq.lastError().databaseText(), __FILE__, __LINE__); notConverted.append(selected[i]); continue; } } } else if (soheadid < 0) { QMessageBox::warning(this, tr("Cannot Convert Quote"), storedProcErrorLookup("convertQuote", soheadid) .arg(selected[i] ? selected[i]->text(0) : "")); notConverted.append(selected[i]); continue; } omfgThis->sQuotesUpdated(quheadid); omfgThis->sSalesOrdersUpdated(soheadid); salesOrder::editSalesOrder(soheadid, true); } else if (convert.lastError().type() != QSqlError::None) { notConverted.append(selected[i]); systemError(this, convert.lastError().databaseText(), __FILE__, __LINE__); continue; } } if (notConverted.size() > 0) { failedPostList newdlg(this, "", true); newdlg.setLabel(tr("<p>The following Quotes could not be converted.")); newdlg.sSetList(notConverted, _quote->headerItem(), _quote->header()); tryagain = (newdlg.exec() == QDialog::Accepted); selected = notConverted; notConverted.clear(); } } while (tryagain); } // if user wants to convert }
/** * Shows the context menu for map objects. The menu allows you to duplicate and * remove the map objects, or to edit their properties. */ void AbstractObjectTool::showContextMenu(MapObjectItem *clickedObjectItem, QPoint screenPos) { QSet<MapObjectItem *> selection = mMapScene->selectedObjectItems(); if (clickedObjectItem && !selection.contains(clickedObjectItem)) { selection.clear(); selection.insert(clickedObjectItem); mMapScene->setSelectedObjectItems(selection); } if (selection.isEmpty()) return; const QList<MapObject*> &selectedObjects = mapDocument()->selectedObjects(); const QList<ObjectGroup*> objectGroups = mapDocument()->map()->objectGroups(); QMenu menu; QAction *duplicateAction = menu.addAction(tr("Duplicate %n Object(s)", "", selection.size()), this, SLOT(duplicateObjects())); QAction *removeAction = menu.addAction(tr("Remove %n Object(s)", "", selection.size()), this, SLOT(removeObjects())); duplicateAction->setIcon(QIcon(QLatin1String(":/images/16x16/stock-duplicate-16.png"))); removeAction->setIcon(QIcon(QLatin1String(":/images/16x16/edit-delete.png"))); bool anyTileObjectSelected = std::any_of(selectedObjects.begin(), selectedObjects.end(), isTileObject); if (anyTileObjectSelected) { auto resetTileSizeAction = menu.addAction(tr("Reset Tile Size"), this, SLOT(resetTileSize())); resetTileSizeAction->setEnabled(std::any_of(selectedObjects.begin(), selectedObjects.end(), isResizedTileObject)); } menu.addSeparator(); menu.addAction(tr("Flip Horizontally"), this, SLOT(flipHorizontally()), QKeySequence(tr("X"))); menu.addAction(tr("Flip Vertically"), this, SLOT(flipVertically()), QKeySequence(tr("Y"))); ObjectGroup *objectGroup = RaiseLowerHelper::sameObjectGroup(selection); if (objectGroup && objectGroup->drawOrder() == ObjectGroup::IndexOrder) { menu.addSeparator(); menu.addAction(tr("Raise Object"), this, SLOT(raise()), QKeySequence(tr("PgUp"))); menu.addAction(tr("Lower Object"), this, SLOT(lower()), QKeySequence(tr("PgDown"))); menu.addAction(tr("Raise Object to Top"), this, SLOT(raiseToTop()), QKeySequence(tr("Home"))); menu.addAction(tr("Lower Object to Bottom"), this, SLOT(lowerToBottom()), QKeySequence(tr("End"))); } if (objectGroups.size() > 1) { menu.addSeparator(); QMenu *moveToLayerMenu = menu.addMenu(tr("Move %n Object(s) to Layer", "", selectedObjects.size())); for (ObjectGroup *objectGroup : objectGroups) { QAction *action = moveToLayerMenu->addAction(objectGroup->name()); action->setData(QVariant::fromValue(objectGroup)); } } menu.addSeparator(); QIcon propIcon(QLatin1String(":images/16x16/document-properties.png")); QAction *propertiesAction = menu.addAction(propIcon, tr("Object &Properties...")); Utils::setThemeIcon(removeAction, "edit-delete"); Utils::setThemeIcon(propertiesAction, "document-properties"); QAction *action = menu.exec(screenPos); if (!action) return; if (action == propertiesAction) { MapObject *mapObject = selectedObjects.first(); mapDocument()->setCurrentObject(mapObject); emit mapDocument()->editCurrentObject(); return; } if (ObjectGroup *objectGroup = action->data().value<ObjectGroup*>()) { mapDocument()->moveObjectsToGroup(mapDocument()->selectedObjects(), objectGroup); } }
QVariant QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const { if (!paste) return QVariant(); sync(); ItemCount cnt = 0; if(PasteboardGetItemCount(paste, &cnt) || !cnt) return QByteArray(); #ifdef DEBUG_PASTEBOARD qDebug("Pasteboard: retrieveData [%s]", qPrintable(format)); #endif const QList<QMacPasteboardMime *> mimes = QMacPasteboardMime::all(mime_type); for(int mime = 0; mime < mimes.size(); ++mime) { QMacPasteboardMime *c = mimes.at(mime); QString c_flavor = c->flavorFor(format); if(!c_flavor.isEmpty()) { // Handle text/plain a little differently. Try handling Unicode first. bool checkForUtf16 = (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text") || c_flavor == QLatin1String("public.utf8-plain-text")); if (checkForUtf16 || c_flavor == QLatin1String("public.utf16-plain-text")) { // Try to get the NSStringPboardType from NSPasteboard, newlines are mapped // correctly (as '\n') in this data. The 'public.utf16-plain-text' type // usually maps newlines to '\r' instead. QString str = qt_mac_get_pasteboardString(paste); if (!str.isEmpty()) return str; } if (checkForUtf16 && hasFlavor(QLatin1String("public.utf16-plain-text"))) c_flavor = QLatin1String("public.utf16-plain-text"); QVariant ret; QList<QByteArray> retList; for(uint index = 1; index <= cnt; ++index) { PasteboardItemID id; if(PasteboardGetItemIdentifier(paste, index, &id) != noErr) continue; QCFType<CFArrayRef> types; if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr) continue; const int type_count = CFArrayGetCount(types); for(int i = 0; i < type_count; ++i) { CFStringRef flavor = static_cast<CFStringRef>(CFArrayGetValueAtIndex(types, i)); if(c_flavor == QCFString::toQString(flavor)) { QCFType<CFDataRef> macBuffer; if(PasteboardCopyItemFlavorData(paste, id, flavor, &macBuffer) == noErr) { QByteArray buffer((const char *)CFDataGetBytePtr(macBuffer), CFDataGetLength(macBuffer)); if(!buffer.isEmpty()) { #ifdef DEBUG_PASTEBOARD qDebug(" - %s [%s] (%s)", qPrintable(format), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName())); #endif buffer.detach(); //detach since we release the macBuffer retList.append(buffer); break; //skip to next element } } } else { #ifdef DEBUG_PASTEBOARD qDebug(" - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName())); #endif } } } if (!retList.isEmpty()) { ret = c->convertToMime(format, retList, c_flavor); return ret; } } } return QVariant(); }
void QgsMapToolNodeTool::canvasMoveEvent( QMouseEvent * e ) { if ( !mSelectedFeature || !mClicked ) return; QgsVectorLayer* vlayer = mSelectedFeature->vlayer(); Q_ASSERT( vlayer ); mSelectAnother = false; if ( mMoving ) { // create rubberband, if none exists if ( mRubberBands.empty() ) { if ( mIsPoint ) { QList<QgsVertexEntry*> &vertexMap = mSelectedFeature->vertexMap(); for ( int i = 0; i < vertexMap.size(); i++ ) { if ( vertexMap[i]->isSelected() ) { QgsRubberBand* rb = createRubberBandMarker( vertexMap[i]->point(), vlayer ); mRubberBands.append( rb ); } } } createMovingRubberBands(); QList<QgsSnappingResult> snapResults; QgsPoint posMapCoord = snapPointFromResults( snapResults, e->pos() ); mPosMapCoordBackup = posMapCoord; } else { // move rubberband QList<QgsSnappingResult> snapResults; mSnapper.snapToBackgroundLayers( e->pos(), snapResults, QList<QgsPoint>() << mClosestMapVertex ); // get correct coordinates to move to QgsPoint posMapCoord = snapPointFromResults( snapResults, e->pos() ); QgsPoint pressMapCoords; if ( snapResults.size() > 0 ) { pressMapCoords = mClosestMapVertex; } else { pressMapCoords = toMapCoordinates( mPressCoordinates ); } QgsVector offset = posMapCoord - pressMapCoords; // handle points if ( mIsPoint ) { for ( int i = 0; i < mRubberBands.size(); i++ ) { mRubberBands[i]->setTranslationOffset( offset.x(), offset.y() ); } return; } // move points QList<QgsVertexEntry*> &vertexMap = mSelectedFeature->vertexMap(); for ( int i = 0; i < vertexMap.size(); i++ ) { if ( !vertexMap[i]->isSelected() ) continue; QgsPoint p = toMapCoordinates( vlayer, vertexMap[i]->point() ) + offset; mRubberBands[vertexMap[i]->rubberBandNr()]->movePoint( vertexMap[i]->rubberBandIndex(), p ); if ( vertexMap[i]->rubberBandIndex() == 0 ) { mRubberBands[vertexMap[i]->rubberBandNr()]->movePoint( 0, p ); } } // topological editing offset = posMapCoord - mPosMapCoordBackup; for ( int i = 0; i < mTopologyRubberBand.size(); i++ ) { for ( int pointIndex = 0; pointIndex < mTopologyRubberBand[i]->numberOfVertices(); pointIndex++ ) { if ( mTopologyRubberBandVertexes[i]->contains( pointIndex ) ) { const QgsPoint* point = mTopologyRubberBand[i]->getPoint( 0, pointIndex ); if ( point == 0 ) { break; } mTopologyRubberBand[i]->movePoint( pointIndex, *point + offset ); } } } mPosMapCoordBackup = posMapCoord; } } else { if ( !mSelectionRectangle ) { mSelectionRectangle = true; mSelectionRubberBand = new QRubberBand( QRubberBand::Rectangle, mCanvas ); mRect = new QRect(); mRect->setTopLeft( mPressCoordinates ); } mRect->setBottomRight( e->pos() ); QRect normalizedRect = mRect->normalized(); mSelectionRubberBand->setGeometry( normalizedRect ); mSelectionRubberBand->show(); } }
UIYabause::UIYabause( QWidget* parent ) : QMainWindow( parent ) { mInit = false; search.clear(); searchType = 0; // setup dialog setupUi( this ); toolBar->insertAction( aFileSettings, mFileSaveState->menuAction() ); toolBar->insertAction( aFileSettings, mFileLoadState->menuAction() ); toolBar->insertSeparator( aFileSettings ); setAttribute( Qt::WA_DeleteOnClose ); #ifdef USE_UNIFIED_TITLE_TOOLBAR setUnifiedTitleAndToolBarOnMac( true ); #endif fSound->setParent( 0, Qt::Popup ); fVideoDriver->setParent( 0, Qt::Popup ); fSound->installEventFilter( this ); fVideoDriver->installEventFilter( this ); // Get Screen res list getSupportedResolutions(); // fill combo driver cbVideoDriver->blockSignals( true ); for ( int i = 0; VIDCoreList[i] != NULL; i++ ) cbVideoDriver->addItem( VIDCoreList[i]->Name, VIDCoreList[i]->id ); cbVideoDriver->blockSignals( false ); // create glcontext mYabauseGL = new YabauseGL( this ); // and set it as central application widget setCentralWidget( mYabauseGL ); // create log widget teLog = new QTextEdit( this ); teLog->setReadOnly( true ); teLog->setWordWrapMode( QTextOption::NoWrap ); teLog->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn ); teLog->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOn ); mLogDock = new QDockWidget( this ); mLogDock->setWindowTitle( "Log" ); mLogDock->setWidget( teLog ); addDockWidget( Qt::BottomDockWidgetArea, mLogDock ); mLogDock->setVisible( false ); // create emulator thread mYabauseThread = new YabauseThread( this ); // create hide mouse timer hideMouseTimer = new QTimer(); // connectionsdd connect( mYabauseThread, SIGNAL( requestSize( const QSize& ) ), this, SLOT( sizeRequested( const QSize& ) ) ); connect( mYabauseThread, SIGNAL( requestFullscreen( bool ) ), this, SLOT( fullscreenRequested( bool ) ) ); connect( mYabauseThread, SIGNAL( requestVolumeChange( int ) ), this, SLOT( on_sVolume_valueChanged( int ) ) ); connect( aViewLog, SIGNAL( toggled( bool ) ), mLogDock, SLOT( setVisible( bool ) ) ); connect( mLogDock->toggleViewAction(), SIGNAL( toggled( bool ) ), aViewLog, SLOT( setChecked( bool ) ) ); connect( mYabauseThread, SIGNAL( error( const QString&, bool ) ), this, SLOT( errorReceived( const QString&, bool ) ) ); connect( mYabauseThread, SIGNAL( pause( bool ) ), this, SLOT( pause( bool ) ) ); connect( mYabauseThread, SIGNAL( reset() ), this, SLOT( reset() ) ); connect( hideMouseTimer, SIGNAL( timeout() ), this, SLOT( hideMouse() )); // Load shortcuts VolatileSettings* vs = QtYabause::volatileSettings(); QList<QAction *> actions = findChildren<QAction *>(); foreach ( QAction* action, actions ) { if (action->text().isEmpty()) continue; QString text = vs->value(QString("Shortcuts/") + action->text(), "").toString(); if (text.isEmpty()) continue; action->setShortcut(text); } // retranslate widgets QtYabause::retranslateWidget( this ); QList<QAction *> actionList = menubar->actions(); for(int i = 0;i < actionList.size();i++) { addAction(actionList.at(i)); } restoreGeometry( vs->value("General/Geometry" ).toByteArray() ); mYabauseGL->setMouseTracking(true); setMouseTracking(true); showMenuBarHeight = menubar->height(); translations = QtYabause::getTranslationList(); }
int size() { return cachedNameTable.size(); }
void ParserTests::testHelgrindSample1() { QSKIP("testfile does not exist"); initTest(QLatin1String("helgrind-output-sample1.xml")); QList<Error> expectedErrors; { Error error1; error1.setUnique(0x0); error1.setTid(1); error1.setKind(LockOrder); error1.setWhat(QLatin1String("Thread #1: lock order \"0xA39C270 before 0xA3AC010\" violated")); error1.setHelgrindThreadId(1); Stack stack1; Frame frame11; frame11.setInstructionPointer(0x4C2B806); frame11.setObject(QLatin1String("/usr/lib/valgrind/vgpreload_helgrind-amd64-linux.so")); frame11.setFunctionName(QLatin1String("QMutex::lock()")); frame11.setDirectory(QLatin1String("/build/buildd/valgrind-3.6.0~svn20100212/helgrind")); frame11.setFile(QLatin1String("hg_intercepts.c")); frame11.setLine(1988); Frame frame12; frame12.setInstructionPointer(0x72E57EE); frame12.setObject(QLatin1String("/home/frank/local/qt4-4.6.3-shared-debug/lib/libQtCore.so.4.6.3")); frame12.setFunctionName(QLatin1String("QMutexLocker::relock()")); frame12.setDirectory(QLatin1String("/home/frank/source/tarballs/qt-4.6.3-build/src/corelib/../../include/QtCore/../../src/corelib/thread")); frame12.setFile(QLatin1String("qmutex.h")); frame12.setLine(120); stack1.setFrames(QVector<Frame>() << frame11 << frame12); Stack stack2; stack2.setAuxWhat(QLatin1String("Required order was established by acquisition of lock at 0xA39C270")); Frame frame21; frame21.setInstructionPointer(0x4C2B806); frame21.setObject(QLatin1String("/usr/lib/valgrind/vgpreload_helgrind-amd64-linux.so")); frame21.setFunctionName(QLatin1String("QMutex::lock()")); frame21.setDirectory(QLatin1String("/build/buildd/valgrind-3.6.0~svn20100212/helgrind")); frame21.setFile(QLatin1String("hg_intercepts.c")); frame21.setLine(1989); Frame frame22; frame22.setInstructionPointer(0x72E57EE); frame22.setObject(QLatin1String("/home/frank/local/qt4-4.6.3-shared-debug/lib/libQtCore.so.4.6.3")); frame22.setFunctionName(QLatin1String("QMutexLocker::relock()")); frame22.setDirectory(QLatin1String("/home/frank/source/tarballs/qt-4.6.3-build/src/corelib/../../include/QtCore/../../src/corelib/thread")); frame22.setFile(QLatin1String("qmutex.h")); frame22.setLine(121); stack2.setFrames(QVector<Frame>() << frame21 << frame22); Stack stack3; stack3.setAuxWhat(QLatin1String("followed by a later acquisition of lock at 0xA3AC010")); Frame frame31; frame31.setInstructionPointer(0x4C2B806); frame31.setObject(QLatin1String("/usr/lib/valgrind/vgpreload_helgrind-amd64-linux.so")); frame31.setFunctionName(QLatin1String("QMutex::lock()")); frame31.setDirectory(QLatin1String("/build/buildd/valgrind-3.6.0~svn20100212/helgrind")); frame31.setFile(QLatin1String("hg_intercepts.c")); frame31.setLine(1990); Frame frame32; frame32.setInstructionPointer(0x72E57EE); frame32.setObject(QLatin1String("/home/frank/local/qt4-4.6.3-shared-debug/lib/libQtCore.so.4.6.3")); frame32.setFunctionName(QLatin1String("QMutexLocker::relock()")); frame32.setDirectory(QLatin1String("/home/frank/source/tarballs/qt-4.6.3-build/src/corelib/../../include/QtCore/../../src/corelib/thread")); frame32.setFile(QLatin1String("qmutex.h")); frame32.setLine(122); stack3.setFrames(QVector<Frame>() << frame31 << frame32); error1.setStacks(QVector<Stack>() << stack1 << stack2 << stack3); expectedErrors.append(error1); } Valgrind::XmlProtocol::Parser parser; Recorder rec(&parser); parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->exitStatus(), QProcess::NormalExit); QCOMPARE(m_process->state(), QProcess::NotRunning); QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString())); const QList<Error> actualErrors = rec.errors; if (actualErrors.first() != expectedErrors.first()) { dumpError(actualErrors.first()); dumpError(expectedErrors.first()); } QCOMPARE(actualErrors.first(), expectedErrors.first()); QCOMPARE(actualErrors.size(), 1); // QCOMPARE(rec.errorcounts, expectedErrorCounts); // QCOMPARE(rec.suppcounts, expectedSuppCounts); }
Void ModulesHandle::activateModule() { QAction *pcAction = qobject_cast<QAction *>( sender() ); Qt::KeyboardModifiers keyModifiers = QApplication::keyboardModifiers(); Bool bTmpForceNewWindow = false; VideoSubWindow* pcVideoSubWindow = qobject_cast<VideoSubWindow *>( m_pcMainWindowManager->activeSubWindow() ); if( !pcVideoSubWindow ) { return; } if( ( keyModifiers & Qt::ControlModifier ) || pcVideoSubWindow->checkCategory( VideoSubWindow::MODULE_SUBWINDOW ) ) { bTmpForceNewWindow = true; } QString ModuleIfName = pcAction->data().toString(); PlaYUVerModuleIf* pcCurrModuleIf = PlaYUVerModuleFactory::Get()->CreateModule( ModuleIfName.toLocal8Bit().constData() ); PlaYUVerAppModuleIf* pcCurrAppModuleIf = new PlaYUVerAppModuleIf( this, pcAction, pcCurrModuleIf ); QList<VideoSubWindow*> videoSubWindowList; Int numberOfFrames = pcCurrAppModuleIf->m_pcModule->m_uiNumberOfFrames; if( numberOfFrames > MODULE_REQUIRES_ONE_FRAME ) // Show dialog to select sub windows { Int minNumFrames = numberOfFrames; Int maxNumFrames = numberOfFrames; if( numberOfFrames == MODULE_REQUIRES_SEVERAL_FRAMES ) { minNumFrames = 0; maxNumFrames = 255; } DialogSubWindowSelector dialogWindowsSelection( m_pcParent, m_pcMainWindowManager, SubWindowAbstract::VIDEO_SUBWINDOW, minNumFrames, maxNumFrames ); QList<SubWindowAbstract*> windowsList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW ); if( windowsList.size() == minNumFrames && windowsList.size() == maxNumFrames ) { for( Int i = 0; i < windowsList.size(); i++ ) { videoSubWindowList.append( qobject_cast<VideoSubWindow*>( windowsList.at( i ) ) ); } } else { if( windowsList.size() <= minNumFrames ) { for( Int i = 0; i < windowsList.size(); i++ ) { dialogWindowsSelection.selectSubWindow( windowsList.at( i ) ); } } else { dialogWindowsSelection.selectSubWindow( pcVideoSubWindow ); } if( dialogWindowsSelection.exec() == QDialog::Accepted ) { VideoSubWindow *videoSubWindow; QList<SubWindowAbstract*> subWindowList = dialogWindowsSelection.getSelectedWindows(); for( Int i = 0; i < subWindowList.size(); i++ ) { videoSubWindow = qobject_cast<VideoSubWindow*>( subWindowList.at( i ) ); videoSubWindowList.append( videoSubWindow ); } } } if( pcCurrAppModuleIf->m_pcModule->m_iModuleAPI == MODULE_API_1 ) { // Check for same fmt in more than one frame modules for( Int i = 1; i < videoSubWindowList.size(); i++ ) { if( !videoSubWindowList.at( i )->getCurrFrame()->haveSameFmt( videoSubWindowList.at( 0 )->getCurrFrame() ) ) { videoSubWindowList.clear(); qobject_cast<PlaYUVerApp*>( m_pcParent )->printMessage( "Error! Incompatible frames", LOG_ERROR ); destroyModuleIf( pcCurrAppModuleIf ); return; } } } } else { videoSubWindowList.append( pcVideoSubWindow ); } if( videoSubWindowList.size() == 0 ) { qobject_cast<PlaYUVerApp*>( m_pcParent )->printMessage( "Error! There is no windows to apply the module", LOG_ERROR ); destroyModuleIf( pcCurrAppModuleIf ); return; } for( Int i = 0; i < videoSubWindowList.size(); i++ ) { pcCurrAppModuleIf->m_pcSubWindow[i] = videoSubWindowList.at( i ); } if( pcCurrAppModuleIf->m_pcModule->m_uiModuleRequirements & MODULE_REQUIRES_OPTIONS ) { ModulesHandleOptDialog moduleOptDialog( m_pcParent, pcCurrAppModuleIf ); if( moduleOptDialog.runConfiguration() == QDialog::Rejected ) { qobject_cast<PlaYUVerApp*>( m_pcParent )->printMessage( "Module canceled by user!", LOG_WARNINGS ); destroyModuleIf( pcCurrAppModuleIf ); return; } } Bool bShowModulesNewWindow = m_arrayActions[FORCE_NEW_WINDOW_ACT]->isChecked() | bTmpForceNewWindow; QString windowName; VideoSubWindow* pcModuleSubWindow = NULL; if( pcCurrAppModuleIf->m_pcModule->m_iModuleType == FRAME_PROCESSING_MODULE ) { if( ( pcCurrAppModuleIf->m_pcModule->m_uiModuleRequirements & MODULE_REQUIRES_NEW_WINDOW ) || bShowModulesNewWindow ) { pcModuleSubWindow = new VideoSubWindow( VideoSubWindow::MODULE_SUBWINDOW ); windowName.append( QStringLiteral( "Module " ) ); windowName.append( pcCurrAppModuleIf->m_pcModule->m_pchModuleName ); connect( pcModuleSubWindow->getViewArea(), SIGNAL( selectionChanged( QRect ) ), m_appModuleVideo, SLOT( updateSelectionArea( QRect ) ) ); connect( pcModuleSubWindow, SIGNAL( zoomFactorChanged_SWindow( const double, const QPoint ) ), m_appModuleVideo, SLOT( zoomToFactorAll( double, QPoint ) ) ); connect( pcModuleSubWindow, SIGNAL( scrollBarMoved_SWindow( const QPoint ) ), m_appModuleVideo, SLOT( moveAllScrollBars( const QPoint ) ) ); pcCurrAppModuleIf->m_pcDisplaySubWindow = pcModuleSubWindow; } } else if( pcCurrAppModuleIf->m_pcModule->m_iModuleType == FRAME_MEASUREMENT_MODULE ) { pcCurrAppModuleIf->m_pcDisplaySubWindow = NULL; pcCurrAppModuleIf->m_pcModuleDock = new ModuleHandleDock( m_pcParent, pcCurrAppModuleIf ); QString titleDockWidget; titleDockWidget.append( pcCurrAppModuleIf->m_pcModule->m_pchModuleName ); titleDockWidget.append( " Information" ); pcCurrAppModuleIf->m_pcDockWidget = new QDockWidget( titleDockWidget, m_pcParent ); pcCurrAppModuleIf->m_pcDockWidget->setFeatures( QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable ); pcCurrAppModuleIf->m_pcDockWidget->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); pcCurrAppModuleIf->m_pcDockWidget->setWidget( pcCurrAppModuleIf->m_pcModuleDock ); qobject_cast<QMainWindow*>( m_pcParent )->addDockWidget( Qt::RightDockWidgetArea, pcCurrAppModuleIf->m_pcDockWidget ); } // Associate module with subwindows if( !pcCurrAppModuleIf->m_pcDisplaySubWindow && !pcCurrAppModuleIf->m_pcModuleDock ) { pcCurrAppModuleIf->m_pcSubWindow[0]->enableModule( pcCurrAppModuleIf ); } else { if( pcCurrAppModuleIf->m_pcDisplaySubWindow ) pcCurrAppModuleIf->m_pcDisplaySubWindow->enableModule( pcCurrAppModuleIf ); for( Int i = 0; i < videoSubWindowList.size(); i++ ) { pcCurrAppModuleIf->m_pcSubWindow[i]->associateModule( pcCurrAppModuleIf ); } } // Create Module Bool moduleCreated = false; if( pcCurrAppModuleIf->m_pcModule->m_iModuleAPI == MODULE_API_2 ) { std::vector<PlaYUVerFrame*> apcFrameList; for( UInt i = 0; i < videoSubWindowList.size(); i++ ) { apcFrameList.push_back( pcCurrAppModuleIf->m_pcSubWindow[i]->getCurrFrame() ); } moduleCreated = pcCurrAppModuleIf->m_pcModule->create( apcFrameList ); } else if( pcCurrAppModuleIf->m_pcModule->m_iModuleAPI == MODULE_API_1 ) { pcCurrAppModuleIf->m_pcModule->create( pcCurrAppModuleIf->m_pcSubWindow[0]->getCurrFrame() ); moduleCreated = true; } if( !moduleCreated ) { qobject_cast<PlaYUVerApp*>( m_pcParent )->printMessage( "Error! Module cannot be created", LOG_ERROR ); destroyModuleIf( pcCurrAppModuleIf ); return; } pcCurrAppModuleIf->apply( false, true ); QCoreApplication::processEvents(); if( pcModuleSubWindow ) { pcModuleSubWindow->setWindowName( windowName ); m_pcMainWindowManager->addSubWindow( pcModuleSubWindow ); pcModuleSubWindow->show(); } else { windowName = videoSubWindowList.at( 0 )->getWindowName(); windowName.append( QStringLiteral( " - Module " ) ); windowName.append( pcCurrAppModuleIf->m_pcModule->m_pchModuleName ); videoSubWindowList.at( 0 )->setWindowName( windowName ); } m_pcPlaYUVerAppModuleIfList.append( pcCurrAppModuleIf ); emit changed(); }
void FavoritesView::loadData() { QHashIterator<qint32, FavoritesViewItem *> i(dataStore); // Cleanup old items in the tree. We go through // it twice. The first time is to remove children // not in root (i.e. notebooks in a stack). The // second time is to remove items at a root level. while(i.hasNext()) { i.next(); if (i.value() != NULL && i.value()->parent() != root) { i.value()->parent()->removeChild(i.value()); } } i.toFront(); while(i.hasNext()) { i.next(); if (i.value() != NULL) { i.value()->setHidden(true); root->removeChild(i.value()); delete i.value(); dataStore.remove(i.key()); } } // Now start rebuilding the table FavoritesTable ftable(global.db); dataStore.clear(); targetStore.clear(); QList<qint32> lids; ftable.getAll(lids); QList<qint32> children; // First pass, we just get the top level ones for (int i=0; i<lids.size(); i++) { FavoritesRecord record; if (ftable.get(record, lids[i])) { if (record.parent == 0) { if (record.type == FavoritesRecord::LinkedStack || record.type == FavoritesRecord::NotebookStack) { if (!ftable.childrenFound(lids[i])) { ftable.expunge(lids[i]); } else { buildTreeEntry(root, &record); } } else { buildTreeEntry(root, &record); } } else { children.append(lids[i]); } } } // // Second pass we get any children for (int i=0; i<children.size(); i++) { FavoritesRecord record; if (ftable.get(record, children[i])) { FavoritesViewItem *parent = dataStore[record.parent]; if (parent != NULL) buildTreeEntry(parent, &record); } } emit updateCounts(); sortByColumn(NAME_POSITION, Qt::AscendingOrder); resetSize(); }
void reprintInvoices::sPrint() { QPrinter printer(QPrinter::HighResolution); bool setupPrinter = TRUE; bool userCanceled = false; if (orReport::beginMultiPrint(&printer, userCanceled) == false) { if(!userCanceled) systemError(this, tr("Could not initialize printing system for multiple reports.")); return; } QList<QTreeWidgetItem*> selected = _invoice->selectedItems(); for (int i = 0; i < selected.size(); i++) { XTreeWidgetItem *cursor = (XTreeWidgetItem*)selected[i]; for (int j = 0; j < _watermarks->topLevelItemCount(); j++) { q.prepare("SELECT findCustomerForm(:cust_id, 'I') AS _reportname;"); q.bindValue(":cust_id", cursor->altId()); q.exec(); if (q.first()) { ParameterList params; params.append("invchead_id", cursor->id()); params.append("showcosts", ((_watermarks->topLevelItem(j)->text(2) == tr("Yes")) ? "TRUE" : "FALSE") ); params.append("watermark", _watermarks->topLevelItem(j)->text(1)); orReport report(q.value("_reportname").toString(), params); if (report.isValid()) { if (report.print(&printer, setupPrinter)) setupPrinter = FALSE; else { report.reportError(this); orReport::endMultiPrint(&printer); return; } } else QMessageBox::critical( this, tr("Cannot Find Invoice Form"), tr( "The Invoice Form '%1' cannot be found.\n" "One or more of the selected Invoices cannot be printed until a Customer Form Assignment\n" "is updated to remove any references to this Invoice Form or this Invoice Form is created." ) .arg(q.value("_reportname").toString()) ); } else if (q.lastError().type() != QSqlError::None) { systemError(this, q.lastError().databaseText(), __FILE__, __LINE__); return; } } if (_metrics->boolean("EnableBatchManager")) { // TODO: Check for EDI and handle submission to Batch here q.prepare("SELECT CASE WHEN (COALESCE(shipto_ediprofile_id, -2) = -2)" " THEN COALESCE(cust_ediprofile_id,-1)" " ELSE COALESCE(shipto_ediprofile_id,-2)" " END AS result," " COALESCE(cust_emaildelivery, false) AS custom" " FROM cust, invchead" " LEFT OUTER JOIN shipto" " ON (invchead_shipto_id=shipto_id)" " WHERE ((invchead_cust_id=cust_id)" " AND (invchead_id=:invchead_id)); "); q.bindValue(":invchead_id", cursor->id()); q.exec(); if(q.first()) { if(q.value("result").toInt() == -1) { if(q.value("custom").toBool()) { ParameterList params; params.append("invchead_id", cursor->id()); deliverInvoice newdlg(this, "", TRUE); newdlg.set(params); newdlg.exec(); } } else { ParameterList params; params.append("action_name", "TransmitInvoice"); params.append("invchead_id", cursor->id()); submitAction newdlg(this, "", TRUE); newdlg.set(params); newdlg.exec(); } } } else if (q.lastError().type() != QSqlError::None) { systemError(this, q.lastError().databaseText(), __FILE__, __LINE__); return; } } orReport::endMultiPrint(&printer); _invoice->clearSelection(); _close->setText(tr("&Close")); _print->setEnabled(FALSE); }