FrmAlbaranProveedor::FrmAlbaranProveedor(QWidget *parent, bool showCerrar) : MayaModule(module_zone(),module_name(),parent), ui(new Ui::FrmAlbaranProveedor), helper(this), prov(this), menuButton(QIcon(":/Icons/PNG/albaran_pro.png"),tr("Albaranes Prov."),this), push(new QPushButton(QIcon(":/Icons/PNG/albaran_pro.png"),"",this)) { ui->setupUi(this); oAlbPro = new AlbaranProveedor(this); push->setStyleSheet("background-color: rgb(133, 170, 142)"); push->setToolTip(tr("Gestión de albaranes de proveedor")); ui->cbo_pais->setModel(Configuracion_global->paises_model); //ui->cbo_pais->setModelColumn(Configuracion_global->paises_model->fieldIndex("pais")); helper.set_Tipo(true); helper.help_table(ui->Lineas); helper.set_tarifa(1); helper.setDatabase("empresa","lin_alb_pro"); helper.setidHeader(1); helper.blockTable(true); connect(ui->btnAnadirLinea,SIGNAL(clicked()),&helper,SLOT(addRow())); connect(ui->btn_borrarLinea,SIGNAL(clicked()),&helper,SLOT(removeRow())); connect(ui->chklporc_rec,SIGNAL(toggled(bool)),&helper,SLOT(set_UsarRE(bool))); connect(&helper,SIGNAL(lineaReady(lineaDetalle*)),this,SLOT(lineaReady(lineaDetalle*))); connect(&helper,SIGNAL(lineaDeleted(int)),this,SLOT(lieaDeleted(int))); connect(ui->tabWidget_2,SIGNAL(currentChanged(int)),this,SLOT(resizeTable(int))); connect(&helper,SIGNAL(totalChanged(double,double,double,double,double,double,QString)), this,SLOT(totalChanged(double,double,double,double,double,double,QString))); connect(&helper,SIGNAL(desglose1Changed(double,double,double,double)), this,SLOT(desglose1Changed(double,double,double,double))); connect(&helper,SIGNAL(desglose2Changed(double,double,double,double)), this,SLOT(desglose2Changed(double,double,double,double))); connect(&helper,SIGNAL(desglose3Changed(double,double,double,double)), this,SLOT(desglose3Changed(double,double,double,double))); connect(&helper,SIGNAL(desglose4Changed(double,double,double,double)), this,SLOT(desglose4Changed(double,double,double,double))); ui->txtporc_iva1->setText(Configuracion_global->ivaList.at(0)); ui->txtporc_iva2->setText(Configuracion_global->ivaList.at(1)); ui->txtporc_iva3->setText(Configuracion_global->ivaList.at(2)); ui->txtporc_iva4->setText(Configuracion_global->ivaList.at(3)); ui->txtporc_rec1->setText(Configuracion_global->reList.at(0)); ui->txtporc_rec2->setText(Configuracion_global->reList.at(1)); ui->txtporc_rec3->setText(Configuracion_global->reList.at(2)); ui->txtporc_rec4->setText(Configuracion_global->reList.at(3)); ui->btn_cerrar->setVisible(showCerrar); // ------------------------------ // control estado widgets //------------------------------- ui->btnAnterior->setEnabled(false); ui->btnBorrar->setEnabled(false); ui->btnImprimir->setEnabled(false); ui->btnFacturar->setEnabled(false); oAlbPro->id = 0; ui->lblAlbaran->setText(""); ui->lblproveedor->setText(""); ui->lbfacturado->setVisible(false); ui->lblNumFactura->setVisible(false); ui->txtfecha_factura->setVisible(false); ui->txtcNumFra->setVisible(false); //---------------------- // Modelo Tabla //---------------------- m = new QSqlQueryModel(this); m->setQuery("select id,albaran,fecha,cif_proveedor,proveedor from alb_pro order by albaran desc",Configuracion_global->empresaDB); ui->tabla->setModel(m); formato_tabla(); ui->tabla->selectRow(0); ui->stackedWidget->setCurrentIndex(1); setUpBusqueda(); bloquearcampos(true); //-------------------- // CONTROL DE EVENTOS //-------------------- QList<QWidget*> l = this->findChildren<QWidget*>(); QList<QWidget*> ::Iterator it; for( it = l.begin() ;it!= l.end();++it ) (*it)->installEventFilter(this); }
bool QgsComposerModel::dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent ) { if ( column != ItemId ) { return false; } if ( action == Qt::IgnoreAction ) { return true; } if ( !data->hasFormat( "application/x-vnd.qgis.qgis.composeritemid" ) ) { return false; } if ( parent.isValid() ) { return false; } int beginRow = row != -1 ? row : rowCount( QModelIndex() ); QByteArray encodedData = data->data( "application/x-vnd.qgis.qgis.composeritemid" ); QDataStream stream( &encodedData, QIODevice::ReadOnly ); QList<QgsComposerItem*> droppedItems; int rows = 0; while ( !stream.atEnd() ) { QString text; stream >> text; const QgsComposerItem* item = mComposition->getComposerItemByUuid( text ); if ( item ) { droppedItems << const_cast<QgsComposerItem*>( item ); ++rows; } } if ( droppedItems.length() == 0 ) { //no dropped items return false; } //move dropped items //first sort them by z-order qSort( droppedItems.begin(), droppedItems.end(), zOrderDescending ); //calculate position in z order list to drop items at int destPos = 0; if ( beginRow < rowCount() ) { QgsComposerItem* itemBefore = mItemsInScene.at( beginRow ); destPos = mItemZList.indexOf( itemBefore ); } else { //place items at end destPos = mItemZList.size(); } //calculate position to insert moved rows to int insertPos = destPos; QList<QgsComposerItem*>::iterator itemIt = droppedItems.begin(); for ( ; itemIt != droppedItems.end(); ++itemIt ) { int listPos = mItemZList.indexOf( *itemIt ); if ( listPos == -1 ) { //should be impossible continue; } if ( listPos < destPos ) { insertPos--; } } //remove rows from list itemIt = droppedItems.begin(); for ( ; itemIt != droppedItems.end(); ++itemIt ) { mItemZList.removeOne( *itemIt ); } //insert items itemIt = droppedItems.begin(); for ( ; itemIt != droppedItems.end(); ++itemIt ) { mItemZList.insert( insertPos, *itemIt ); insertPos++; } rebuildSceneItemList(); mComposition->updateZValues( false ); return true; }
void QgsComposerView::mousePressEvent( QMouseEvent* e ) { if ( !composition() ) { return; } if ( mRubberBandItem || mRubberBandLineItem || mKeyPanning || mMousePanning || mToolPanning || mMovingItemContent ) { //ignore clicks during certain operations return; } if ( composition()->selectionHandles()->isDragging() || composition()->selectionHandles()->isResizing() ) { //ignore clicks while dragging/resizing items return; } QPointF scenePoint = mapToScene( e->pos() ); QPointF snappedScenePoint = composition()->snapPointToGrid( scenePoint ); mMousePressStartPos = e->pos(); //lock/unlock position of item with right click if ( e->button() == Qt::RightButton ) { QgsComposerItem* selectedItem = composition()->composerItemAt( scenePoint ); if ( selectedItem ) { bool lock = selectedItem->positionLock() ? false : true; selectedItem->setPositionLock( lock ); selectedItem->update(); } return; } else if ( e->button() == Qt::MidButton ) { //pan composer with middle button mMousePanning = true; mMouseLastXY = e->pos(); if ( composition() ) { //lock cursor to closed hand cursor composition()->setPreventCursorChange( true ); } viewport()->setCursor( Qt::ClosedHandCursor ); return; } switch ( mCurrentTool ) { //select/deselect items and pass mouse event further case Select: { //check if we are clicking on a selection handle if ( composition()->selectionHandles()->isVisible() ) { //selection handles are being shown, get mouse action for current cursor position QgsComposerMouseHandles::MouseAction mouseAction = composition()->selectionHandles()->mouseActionForScenePos( scenePoint ); if ( mouseAction != QgsComposerMouseHandles::MoveItem && mouseAction != QgsComposerMouseHandles::NoAction && mouseAction != QgsComposerMouseHandles::SelectItem ) { //mouse is over a resize handle, so propagate event onward QGraphicsView::mousePressEvent( e ); return; } } QgsComposerItem* selectedItem = 0; QgsComposerItem* previousSelectedItem = 0; if ( e->modifiers() & Qt::ControlModifier ) { //CTRL modifier, so we are trying to select the next item below the current one //first, find currently selected item QList<QgsComposerItem*> selectedItems = composition()->selectedComposerItems(); if ( selectedItems.size() > 0 ) { previousSelectedItem = selectedItems.at( 0 ); } } if ( previousSelectedItem ) { //select highest item just below previously selected item at position of event selectedItem = composition()->composerItemAt( scenePoint, previousSelectedItem ); //if we didn't find a lower item we'll use the top-most as fall-back //this duplicates mapinfo/illustrator/etc behaviour where ctrl-clicks are "cyclic" if ( !selectedItem ) { selectedItem = composition()->composerItemAt( scenePoint ); } } else { //select topmost item at position of event selectedItem = composition()->composerItemAt( scenePoint ); } if ( !selectedItem ) { //not clicking over an item, so start marquee selection startMarqueeSelect( scenePoint ); break; } if (( !selectedItem->selected() ) && //keep selection if an already selected item pressed !( e->modifiers() & Qt::ShiftModifier ) ) //keep selection if shift key pressed { composition()->clearSelection(); } if (( e->modifiers() & Qt::ShiftModifier ) && ( selectedItem->selected() ) ) { //SHIFT-clicking a selected item deselects it selectedItem->setSelected( false ); //Check if we have any remaining selected items, and if so, update the item panel QList<QgsComposerItem*> selectedItems = composition()->selectedComposerItems(); if ( selectedItems.size() > 0 ) { emit selectedItemChanged( selectedItems.at( 0 ) ); } } else { selectedItem->setSelected( true ); QGraphicsView::mousePressEvent( e ); emit selectedItemChanged( selectedItem ); } break; } case Zoom: { if ( !( e->modifiers() & Qt::ShiftModifier ) ) { //zoom in action startMarqueeZoom( scenePoint ); } else { //zoom out action, so zoom out and recenter on clicked point double scaleFactor = 2; //get current visible part of scene QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() ); QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() ); //transform the mouse pos to scene coordinates QPointF scenePoint = mapToScene( e->pos() ); visibleRect.scale( scaleFactor, scenePoint.x(), scenePoint.y() ); QRectF boundsRect = visibleRect.toRectF(); //zoom view to fit desired bounds fitInView( boundsRect, Qt::KeepAspectRatio ); } break; } case Pan: { //pan action mToolPanning = true; mMouseLastXY = e->pos(); viewport()->setCursor( Qt::ClosedHandCursor ); break; } case MoveItemContent: { //get a list of items at clicked position QList<QGraphicsItem *> itemsAtCursorPos = items( e->pos() ); if ( itemsAtCursorPos.size() == 0 ) { //no items at clicked position return; } //find highest QgsComposerItem at clicked position //(other graphics items may be higher, eg selection handles) QList<QGraphicsItem*>::iterator itemIter = itemsAtCursorPos.begin(); for ( ; itemIter != itemsAtCursorPos.end(); ++itemIter ) { QgsComposerItem* item = dynamic_cast<QgsComposerItem *>(( *itemIter ) ); if ( item ) { //we've found the highest QgsComposerItem mMoveContentStartPos = scenePoint; mMoveContentItem = item; mMovingItemContent = true; break; } } //no QgsComposerItem at clicked position return; } case AddArrow: { mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() ); mRubberBandLineItem = new QGraphicsLineItem( snappedScenePoint.x(), snappedScenePoint.y(), snappedScenePoint.x(), snappedScenePoint.y() ); mRubberBandLineItem->setZValue( 1000 ); scene()->addItem( mRubberBandLineItem ); scene()->update(); break; } //create rubber band for map and ellipse items case AddMap: case AddRectangle: case AddTriangle: case AddEllipse: case AddHtml: { QTransform t; mRubberBandItem = new QGraphicsRectItem( 0, 0, 0, 0 ); mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() ); t.translate( snappedScenePoint.x(), snappedScenePoint.y() ); mRubberBandItem->setTransform( t ); mRubberBandItem->setZValue( 1000 ); scene()->addItem( mRubberBandItem ); scene()->update(); } break; case AddLabel: if ( composition() ) { QgsComposerLabel* newLabelItem = new QgsComposerLabel( composition() ); newLabelItem->setText( tr( "QGIS" ) ); newLabelItem->adjustSizeToText(); newLabelItem->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), newLabelItem->rect().width(), newLabelItem->rect().height() ) ); composition()->addComposerLabel( newLabelItem ); composition()->clearSelection(); newLabelItem->setSelected( true ); emit selectedItemChanged( newLabelItem ); emit actionFinished(); composition()->pushAddRemoveCommand( newLabelItem, tr( "Label added" ) ); } break; case AddScalebar: if ( composition() ) { QgsComposerScaleBar* newScaleBar = new QgsComposerScaleBar( composition() ); newScaleBar->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 20, 20 ) ); composition()->addComposerScaleBar( newScaleBar ); QList<const QgsComposerMap*> mapItemList = composition()->composerMapItems(); if ( mapItemList.size() > 0 ) { newScaleBar->setComposerMap( mapItemList.at( 0 ) ); } newScaleBar->applyDefaultSize(); //4 segments, 1/5 of composer map width composition()->clearSelection(); newScaleBar->setSelected( true ); emit selectedItemChanged( newScaleBar ); emit actionFinished(); composition()->pushAddRemoveCommand( newScaleBar, tr( "Scale bar added" ) ); } break; case AddLegend: { if ( composition() ) { QgsComposerLegend* newLegend = new QgsComposerLegend( composition() ); newLegend->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), newLegend->rect().width(), newLegend->rect().height() ) ); composition()->addComposerLegend( newLegend ); newLegend->updateLegend(); composition()->clearSelection(); newLegend->setSelected( true ); emit selectedItemChanged( newLegend ); emit actionFinished(); composition()->pushAddRemoveCommand( newLegend, tr( "Legend added" ) ); } break; } case AddPicture: if ( composition() ) { QgsComposerPicture* newPicture = new QgsComposerPicture( composition() ); newPicture->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 30, 30 ) ); composition()->addComposerPicture( newPicture ); composition()->clearSelection(); newPicture->setSelected( true ); emit selectedItemChanged( newPicture ); emit actionFinished(); composition()->pushAddRemoveCommand( newPicture, tr( "Picture added" ) ); } break; case AddTable: if ( composition() ) { QgsComposerAttributeTable* newTable = new QgsComposerAttributeTable( composition() ); newTable->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 50, 50 ) ); composition()->addComposerTable( newTable ); composition()->clearSelection(); newTable->setSelected( true ); emit selectedItemChanged( newTable ); emit actionFinished(); composition()->pushAddRemoveCommand( newTable, tr( "Table added" ) ); } break; default: break; } }
void QgsAtlasComposition::prepareForFeature( int featureI ) { if ( !mComposerMap || !mCoverageLayer ) { return; } // retrieve the next feature, based on its id mCoverageLayer->getFeatures( QgsFeatureRequest().setFilterFid( mFeatureIds[ featureI ] ) ).nextFeature( mCurrentFeature ); QgsExpression::setSpecialColumn( "$atlasfeatureid", mCurrentFeature.id() ); QgsExpression::setSpecialColumn( "$atlasgeometry", QVariant::fromValue( *mCurrentFeature.geometry() ) ); if ( !mSingleFile && mFilenamePattern.size() > 0 ) { QgsExpression::setSpecialColumn( "$feature", QVariant(( int )featureI + 1 ) ); QVariant filenameRes = mFilenameExpr->evaluate( &mCurrentFeature, mCoverageLayer->pendingFields() ); if ( mFilenameExpr->hasEvalError() ) { throw std::runtime_error( tr( "Filename eval error: %1" ).arg( mFilenameExpr->evalErrorString() ).toLocal8Bit().data() ); } mCurrentFilename = filenameRes.toString(); } // // compute the new extent // keep the original aspect ratio // and apply a margin // QgsGeometry::boundingBox is expressed in the geometry"s native CRS // We have to transform the grometry to the destination CRS and ask for the bounding box // Note: we cannot directly take the transformation of the bounding box, since transformations are not linear QgsGeometry tgeom( *mCurrentFeature.geometry() ); tgeom.transform( mTransform ); QgsRectangle geom_rect = tgeom.boundingBox(); double xa1 = geom_rect.xMinimum(); double xa2 = geom_rect.xMaximum(); double ya1 = geom_rect.yMinimum(); double ya2 = geom_rect.yMaximum(); QgsRectangle new_extent = geom_rect; // restore the original extent // (successive calls to setNewExtent tend to deform the original rectangle) mComposerMap->setNewExtent( mOrigExtent ); if ( mFixedScale ) { // only translate, keep the original scale (i.e. width x height) double geom_center_x = ( xa1 + xa2 ) / 2.0; double geom_center_y = ( ya1 + ya2 ) / 2.0; double xx = geom_center_x - mOrigExtent.width() / 2.0; double yy = geom_center_y - mOrigExtent.height() / 2.0; new_extent = QgsRectangle( xx, yy, xx + mOrigExtent.width(), yy + mOrigExtent.height() ); } else { // auto scale double geom_ratio = geom_rect.width() / geom_rect.height(); double map_ratio = mOrigExtent.width() / mOrigExtent.height(); // geometry height is too big if ( geom_ratio < map_ratio ) { // extent the bbox's width double adj_width = ( map_ratio * geom_rect.height() - geom_rect.width() ) / 2.0; xa1 -= adj_width; xa2 += adj_width; } // geometry width is too big else if ( geom_ratio > map_ratio ) { // extent the bbox's height double adj_height = ( geom_rect.width() / map_ratio - geom_rect.height() ) / 2.0; ya1 -= adj_height; ya2 += adj_height; } new_extent = QgsRectangle( xa1, ya1, xa2, ya2 ); if ( mMargin > 0.0 ) { new_extent.scale( 1 + mMargin ); } } // evaluate label expressions QList<QgsComposerLabel*> labels; mComposition->composerItems( labels ); QgsExpression::setSpecialColumn( "$feature", QVariant(( int )featureI + 1 ) ); for ( QList<QgsComposerLabel*>::iterator lit = labels.begin(); lit != labels.end(); ++lit ) { ( *lit )->setExpressionContext( &mCurrentFeature, mCoverageLayer ); } // set the new extent (and render) mComposerMap->setNewExtent( new_extent ); }
void WordPredict::updateWords() { WeightedList list(m_max); int bestWord = -1; qreal bestWordWeight = -1.0f; DawgReduction<WPWord>::WordList words = reduction->words(); for(int ii = 0; ii < words.count(); ++ii) { #ifndef PRED_NO_INCREMENTAL_CALCULATIONS qreal weight = incrWeightForWord(words.at(ii)); if(weight == -1) { words.at(ii)->isValid = false; continue; } if(words.at(ii)->isWord) list.addWord(weight, words.at(ii)->word); if(bestWord == -1 || weight < bestWordWeight) { bestWord = ii; bestWordWeight = weight; } #else Word word; word.frequency = words.at(ii)->frequency; word.word = words.at(ii)->word; qreal weight = weightForWord(word); words.at(ii)->weight = weight; if(weight == -1) { words.at(ii)->isValid = false; continue; } if(words.at(ii)->isWord) list.addWord(weight, word.word); if(bestWord == -1 || weight < bestWordWeight) { bestWord = ii; bestWordWeight = weight; } #endif } if(bestWord != -1) m_prefixedWord = words.at(bestWord)->word; else m_prefixedWord = QString(); qreal baseWordScore = list.minWeight() * 10.0f; QStringList l_words = list.words(); QList<qreal> l_weights = list.weights(); QList<QPair<QString, qreal> > finalwords; for(int ii = 0; ii < l_words.count(); ++ii) if(l_weights.at(ii) <= baseWordScore) finalwords << qMakePair(l_words.at(ii), l_weights.at(ii)); qSort(finalwords.begin(), finalwords.end()); m_words = QStringList(); m_weights = QList<qreal>(); for(int ii = 0; ii < finalwords.count(); ++ii) { m_words << finalwords.at(ii).first; m_weights << finalwords.at(ii).second; } if(!m_words.isEmpty()) m_word = m_words.first(); else m_word = QString(); #ifdef PRED_DEBUG qWarning() << "Top words are" << l_words; qWarning() << "Best word is" << m_word; qWarning() << "Best words are" << m_words; qWarning() << "Best word weights are" << m_weights; //qWarning() << "Best word freqs are" << l_freq; QString xstr; QString ystr; for(int ii = 0; ii < m_points.count(); ++ii) { if(!ii) { xstr += "(" + QString::number(m_points.at(ii).x()) + ") "; ystr += "(" + QString::number(m_points.at(ii).y()) + ") "; } else { xstr += QString::number(m_points.at(ii).x() - m_points.at(ii - 1).x()) + " "; ystr += QString::number(m_points.at(ii - 1).y() - m_points.at(ii).y()) + " "; } } qWarning() << "X motion" << xstr; qWarning() << "Y motion" << ystr; qWarning() << "Movement: " << movementDesc(); #endif }
void sortByLexeme(QStringList &sortList) { // Карта для хранения строк с начальной текстовой строкой // Ключ карты - начальная строка, значения - остаток строки QMap<QString, QStringList> strMap; // Карта для хранения строк с начальной числовой строкой // Ключ карты - начальная строка, значения - остаток строки QMap<double, QStringList> numMap; QList<double> sortingKeyNum; // Лист для сортировки числовых ключей QStringList sortingKeyStr; // Лист для сортировки строковых ключей QStringList res; // Результирующий лист QString temp; // Буфер для текущей обрабатываемой строки QString buf; // Буфер для ключа - домена QString str; // Буфер для одного из значений ключа - имени адреса QString aIter; // Буфер для строкого ключа при формировании выходного списка QString aIterKlein; // Буфер для строки из списка для каждой строки из списка double num; // Буфер для хранения ключа для числовой карты double aIterNum; // Буфер для числового ключа при формировании выходного списка // Заполнение карты путей for(int i=0; i<sortList.count(); i++) { // Загрузка в бущер текущей строки для сортировки temp=sortList[i]; // Заполнение карты по числовому ключу if(temp[0].isNumber()) { // Получение ключа buf=temp.section(QRegExp("[A-z]"), 0, 0); // Перевод ключа из строки в число num=buf.toDouble(); // Получение значения str=temp.remove(buf); /*// Заполнение карты, если остаток строки не пустой if(!str.isEmpty()) {*/ if(numMap.contains(num)) { numMap[num]<<str; } else { numMap.insert(num, QStringList(str)); } //} } // Заполнение карты по нечисловому ключу else { // Получение ключа buf=temp.section(QRegExp("\\d"), 0, 0); // Получение значения str=temp.remove(buf); /*// Заполнение карты, если остаток строки не пустой if(!str.isEmpty()) {*/ if(strMap.contains(buf)) { strMap[buf]<<str; } else { strMap.insert(buf, QStringList(str)); } //} } } // Сортировка карты с числовым ключом // Сортировка значений для каждого ключа QMap<double, QStringList>::iterator itn=numMap.begin(); for(;itn!=numMap.end(); itn++) { if(itn.value().count()>1) { sortByLexeme(itn.value()); } } // Записей ключей в лист itn=numMap.begin(); for(;itn!=numMap.end(); itn++) { sortingKeyNum<<itn.key(); } // Сортировка ключей //sortingKeyNum.sort(); qStableSort(sortingKeyNum.begin(), sortingKeyNum.end()); // Сортировка карты со строковым ключом // Сортировка значений для каждого ключа QMap<QString, QStringList>::iterator its=strMap.begin(); for(;its!=strMap.end(); its++) { if(its.value().count()>1) { sortByLexeme(its.value()); } } // Записей ключей в лист its=strMap.begin(); for(;its!=strMap.end(); its++) { sortingKeyStr<<its.key(); } // Сортировка ключей //sortingKeyStr.sort(); qStableSort(sortingKeyStr.begin(), sortingKeyStr.end(), caseInsensitiveLessThan); // Заполнение выходного листа полями из числовой карты for(int j=0; j<sortingKeyNum.count(); j++) { // Загрузка в бущер текущей строки для ключа aIterNum=sortingKeyNum[j]; // Загрузка в выходной лист значений для определенного ключа for(int k=0; k<numMap[aIterNum].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein=QString::number(aIterNum)+numMap[aIterNum][k]; // Добавление строки в выходной лист res<<aIterKlein; } } // Заполнение выходного листа полями из строковой карты for(int j=0; j<sortingKeyStr.count(); j++) { // Загрузка в бущер текущей строки для ключа aIter=sortingKeyStr[j]; // Загрузка в выходной лист значений для определенного ключа for(int k=0; k<strMap[aIter].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein=aIter+strMap[aIter][k]; // Добавление строки в выходной лист res<<aIterKlein; } } // Замена данного листа на возвращаемый sortList=res; }
void NetTree::fillTree() { // First let's add all the RSS m_rssGeneric = new MythGenericTree( RSSNode, kSubFolder, false); // Add an upfolder if (m_type != DLG_TREE) { m_rssGeneric->addNode(tr("Back"), kUpFolder, true, false); } m_rssGeneric->SetData(QString("%1/mythnetvision/icons/rss.png") .arg(GetShareDir())); RSSSite::rssList::iterator i = m_rssList.begin(); for (; i != m_rssList.end(); ++i) { ResultItem::resultList items = getRSSArticles((*i)->GetTitle(), VIDEO_PODCAST); MythGenericTree *ret = new MythGenericTree( (*i)->GetTitle(), kSubFolder, false); ret->SetData(qVariantFromValue(*i)); m_rssGeneric->addNode(ret); // Add an upfolder if (m_type != DLG_TREE) { ret->addNode(tr("Back"), kUpFolder, true, false); } ResultItem::resultList::iterator it = items.begin(); for (; it != items.end(); ++it) { AddFileNode(ret, *it); } } if (m_rssList.count() > 0) m_siteGeneric->addNode(m_rssGeneric); else { delete m_rssGeneric; m_rssGeneric = NULL; } // Now let's add all the grabber trees for (GrabberScript::scriptList::iterator i = m_grabberList.begin(); i != m_grabberList.end(); ++i) { QMultiMap<QPair<QString,QString>, ResultItem*> treePathsNodes = getTreeArticles((*i)->GetTitle(), VIDEO_FILE); QList< QPair<QString,QString> > paths = treePathsNodes.uniqueKeys(); MythGenericTree *ret = new MythGenericTree( (*i)->GetTitle(), kSubFolder, false); QString thumb = QString("%1mythnetvision/icons/%2").arg(GetShareDir()) .arg((*i)->GetImage()); ret->SetData(qVariantFromValue(thumb)); // Add an upfolder if (m_type != DLG_TREE) { ret->addNode(tr("Back"), kUpFolder, true, false); } for (QList<QPair<QString, QString> >::iterator i = paths.begin(); i != paths.end(); ++i) { QStringList curPaths = (*i).first.split("/"); QString dirthumb = (*i).second; QList<ResultItem*> videos = treePathsNodes.values(*i); buildGenericTree(ret, curPaths, dirthumb, videos); } m_siteGeneric->addNode(ret); } }
//----------------------------------------------------------------------------- void ctkTransferFunctionRepresentation::computeCurve() { Q_D(ctkTransferFunctionRepresentation); int count = d->TransferFunction ? d->TransferFunction->count() : 0; if (count <= 0) { return; } d->TransferFunction->range(d->WorldRangeX[0], d->WorldRangeX[1]); d->WorldRangeY[0] = this->posY(d->TransferFunction->minValue()); d->WorldRangeY[1] = this->posY(d->TransferFunction->maxValue()); d->RangeXDiff = this->computeRangeXDiff(d->rect(), d->WorldRangeX); d->RangeXOffSet = this->computeRangeXOffset(d->WorldRangeX); d->RangeYDiff = this->computeRangeYDiff(d->rect(), d->WorldRangeY); d->RangeYOffSet = this->computeRangeYOffset(d->WorldRangeY); ctkControlPoint* startCP = d->TransferFunction->controlPoint(0); ctkControlPoint* nextCP = 0; QPointF startPos = this->mapPointToScene(startCP); d->Points.clear(); d->Points << startPos; d->Path = QPainterPath(); d->Path.moveTo(startPos); for(int i = 1; i < count; ++i) { nextCP = d->TransferFunction->controlPoint(i); if (this->transferFunction()->isDiscrete()) { QPointF nextPos = this->mapPointToScene(nextCP); qreal midPosX = (startPos.x() + nextPos.x()) / 2.; d->Path.lineTo(QPointF(midPosX, startPos.y())); d->Path.lineTo(QPointF(midPosX, nextPos.y())); d->Points << nextPos; startPos = nextPos; if (i == count -1) { d->Path.lineTo(nextPos); } } else if (dynamic_cast<ctkNonLinearControlPoint*>(startCP)) { QList<ctkPoint> points = this->nonLinearPoints(startCP, nextCP); int j; for (j = 1; j < points.count(); ++j) { d->Path.lineTo(this->mapPointToScene(points[j])); } j = points.count() - 1; d->Points << this->mapPointToScene(points[j]); } else //dynamic_cast<ctkBezierControlPoint*>(startCP)) { QList<ctkPoint> points = this->bezierParams(startCP, nextCP); QList<ctkPoint>::iterator it = points.begin(); QList<QPointF> bezierPoints; foreach(const ctkPoint& p, points) { bezierPoints << this->mapPointToScene(p); } d->Path.cubicTo(bezierPoints[1], bezierPoints[2], bezierPoints[3]); d->Points << bezierPoints[3]; } //qDebug() << i << points[0] << points[1] << points[2] << points[3]; delete startCP; startCP = nextCP; }
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; } }
void CTimelineWidget::UpdateTimeline() { QLayoutItem *child; if(layout() != Q_NULLPTR) { while (((child = layout()->takeAt(0)) != 0)) { // delete child->widget(); delete child; } delete layout(); } m_pLoader->start(); QHBoxLayout* pHBLayout = new QHBoxLayout(this); pHBLayout->setSpacing(6); pHBLayout->setContentsMargins(3, 3, 3, 3); QPalette Pal(palette()); Pal.setColor(QPalette::Background, QColor(240,240,240)); setAutoFillBackground(true); setPalette(Pal); int iLayout1 = 0; int iLayout2 = 0; QList<int> lPendingGames = QList<int>(); for (int i = 0; i < m_pThumbnailList->length(); i++) { if (m_pThumbnailList->at(i)->GetSyncedID() != QString("")) { int j = FindThumbnailIndex(m_pThumbnailList->at(i)->GetSyncedID()); if (j >= 0) { if (i < j) { pHBLayout->addWidget(NewColumn(true)); AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(pHBLayout->count()-1)->widget()); AddThumbnail(m_pThumbnailList->at(j), pHBLayout->itemAt(pHBLayout->count()-1)->widget()); if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_1) { iLayout1 = pHBLayout->count(); lPendingGames.append(iLayout1); } else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_2) { iLayout2 = pHBLayout->count(); lPendingGames.append(iLayout2); } } else { if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_1) { iLayout1 = lPendingGames.takeFirst(); } else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_2) { iLayout2 = lPendingGames.takeFirst(); } } } } else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_1) { if (iLayout1 >= pHBLayout->count()) { pHBLayout->addWidget(NewColumn(false)); } if (!AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(iLayout1)->widget())) { pHBLayout->insertWidget(iLayout1, NewColumn(false)); AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(iLayout1)->widget()); iLayout2++; for (QList<int>::Iterator g = lPendingGames.begin(); g != lPendingGames.end(); g++) { (*g)++; } } iLayout1++; } else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_2) { if (iLayout2 >= pHBLayout->count()) { pHBLayout->addWidget(NewColumn(false)); } if (!AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(iLayout2)->widget())) { pHBLayout->insertWidget(iLayout2, NewColumn(false)); AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(iLayout2)->widget()); iLayout1++; for (QList<int>::Iterator g = lPendingGames.begin(); g != lPendingGames.end(); g++) { (*g)++; } } iLayout2++; } else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::BOTH_PLAYER) { pHBLayout->addWidget(NewColumn(false)); AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(pHBLayout->count()-1)->widget()); iLayout1 = pHBLayout->count(); iLayout2 = pHBLayout->count(); } } setLayout(pHBLayout); }
void MesytecMadc32UI::applySettings() { applyingSettings = true; QList<QGroupBox*> gbs = findChildren<QGroupBox*>(); if(!gbs.empty()) { QList<QGroupBox*>::const_iterator it = gbs.begin(); while(it != gbs.end()) { QGroupBox* w = (*it); for(int ch=0; ch < MADC32V2_NUM_CHANNELS; ch++) { if(w->objectName() == tr("enable_channel%1").arg(ch)) w->setChecked(module->conf_.enable_channel[ch]); } it++; } } QList<QCheckBox*> cbs = findChildren<QCheckBox*>(); if(!cbs.empty()) { QList<QCheckBox*>::const_iterator it = cbs.begin(); while(it != cbs.end()) { QCheckBox* w = (*it); if(w->objectName() == "enable_multi_event_send_different_eob_marker") w->setChecked(module->conf_.enable_multi_event_send_different_eob_marker); if(w->objectName() == "enable_multi_event_compare_with_max_transfer_data") w->setChecked(module->conf_.enable_multi_event_compare_with_max_transfer_data); if(w->objectName() == "enable_adc_override") w->setChecked(module->conf_.enable_adc_override); if(w->objectName() == "enable_switch_off_sliding_scale") w->setChecked(module->conf_.enable_switch_off_sliding_scale); if(w->objectName() == "enable_skip_out_of_range") w->setChecked(module->conf_.enable_skip_out_of_range); if(w->objectName() == "enable_ignore_thresholds") w->setChecked(module->conf_.enable_ignore_thresholds); if(w->objectName() == "enable_termination_input_gate0") w->setChecked(module->conf_.enable_termination_input_gate0); if(w->objectName() == "enable_termination_input_fast_clear") w->setChecked(module->conf_.enable_termination_input_fast_clear); if(w->objectName() == "enable_external_time_stamp_reset") w->setChecked(module->conf_.enable_external_time_stamp_reset); it++; } } QList<QComboBox*> cbbs = findChildren<QComboBox*>(); if(!cbbs.empty()) { QList<QComboBox*>::const_iterator it = cbbs.begin(); while(it != cbbs.end()) { QComboBox* w = (*it); //printf("Found combobox with the name %s\n",w->objectName().toStdString().c_str()); if(w->objectName() == "addr_source") w->setCurrentIndex(module->conf_.addr_source); if(w->objectName() == "multi_event_mode") w->setCurrentIndex(module->conf_.multi_event_mode); if(w->objectName() == "vme_mode") w->setCurrentIndex(module->conf_.vme_mode); if(w->objectName() == "data_length_format") w->setCurrentIndex(module->conf_.data_length_format); if(w->objectName() == "time_stamp_source") w->setCurrentIndex(module->conf_.time_stamp_source); if(w->objectName() == "adc_resolution") w->setCurrentIndex(module->conf_.adc_resolution); if(w->objectName() == "output_format") w->setCurrentIndex(module->conf_.output_format); if(w->objectName() == "gate_generator_mode") w->setCurrentIndex(module->conf_.gate_generator_mode); if(w->objectName() == "ecl_gate1_mode") w->setCurrentIndex(module->conf_.ecl_gate1_mode); if(w->objectName() == "ecl_fclear_mode") w->setCurrentIndex(module->conf_.ecl_fclear_mode); if(w->objectName() == "ecl_busy_mode") w->setCurrentIndex(module->conf_.ecl_busy_mode); if(w->objectName() == "nim_gate1_mode") w->setCurrentIndex(module->conf_.nim_gate1_mode); if(w->objectName() == "nim_fclear_mode") w->setCurrentIndex(module->conf_.nim_fclear_mode); if(w->objectName() == "input_range") { switch (module->conf_.input_range){ case MesytecMadc32ModuleConfig::ir4V: w->setCurrentIndex(0); break; case MesytecMadc32ModuleConfig::ir8V: w->setCurrentIndex(1); break; case MesytecMadc32ModuleConfig::ir10V: w->setCurrentIndex(2); break; default: w->setCurrentIndex(2); break; } } if(w->objectName() == "marking_type") w->setCurrentIndex(module->conf_.marking_type); if(w->objectName() == "bank_operation") w->setCurrentIndex(module->conf_.bank_operation); if(w->objectName() == "test_pulser_mode") w->setCurrentIndex(module->conf_.test_pulser_mode); it++; } } QList<QSpinBox*> csb = findChildren<QSpinBox*>(); if(!csb.empty()) { QList<QSpinBox*>::const_iterator it = csb.begin(); while(it != csb.end()) { QSpinBox* w = (*it); //printf("Found spinbox with the name %s\n",w->objectName().toStdString().c_str()); if(w->objectName() == "irq_level") w->setValue(module->conf_.irq_level); if(w->objectName() == "irq_vector") w->setValue(module->conf_.irq_vector); if(w->objectName() == "irq_threshold") w->setValue(module->conf_.irq_threshold); if(w->objectName() == "base_addr_register") w->setValue(module->conf_.base_addr_register); if(w->objectName() == "time_stamp_divisor") w->setValue(module->conf_.time_stamp_divisor); if(w->objectName() == "max_transfer_data") w->setValue(module->conf_.max_transfer_data); if(w->objectName() == "rc_module_id_read") w->setValue(module->conf_.rc_module_id_read); if(w->objectName() == "rc_module_id_write") w->setValue(module->conf_.rc_module_id_write); for(int ch=0; ch<2; ch++) { if(w->objectName() == tr("hold_delay_%1").arg(ch)) w->setValue(module->conf_.hold_delay[ch]); if(w->objectName() == tr("hold_width_%1").arg(ch)) w->setValue(module->conf_.hold_width[ch]); } for(int ch=0; ch<MADC32V2_NUM_CHANNELS; ch++) { if(w->objectName() == tr("thresholds%1").arg(ch)) w->setValue(module->conf_.thresholds[ch]); } it++; } } QList<QRadioButton*> crb = findChildren<QRadioButton*>(); if(!crb.empty()) { QList<QRadioButton*>::const_iterator it = crb.begin(); while(it != crb.end()) { QRadioButton* w = (*it); if(w->objectName() == "mcst_cblt_none") w->setChecked(module->conf_.mcst_cblt_none); if(w->objectName() == "enable_cblt_mode") w->setChecked(module->conf_.enable_cblt_mode); if(w->objectName() == "enable_mcst_mode") w->setChecked(module->conf_.enable_mcst_mode); if(w->objectName() == "enable_cblt_first") w->setChecked(module->conf_.enable_cblt_first); if(w->objectName() == "enable_cblt_last") w->setChecked(module->conf_.enable_cblt_last); if(w->objectName() == "enable_cblt_middle") w->setChecked(module->conf_.enable_cblt_middle); it++; } } \ QLabel* b_addr = (QLabel*) uif.getWidgets()->find("base_addr").value(); b_addr->setText(tr("0x%1").arg(module->conf_.base_addr,2,16,QChar('0'))); applyingSettings = false; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- DataContainerArrayProxy DataContainerArrayProxy::MergeProxies(DataContainerArrayProxy fileProxy, DataContainerArrayProxy cacheProxy) { QMap<QString, DataContainerProxy> fDcMap = fileProxy.dataContainers; QMap<QString, DataContainerProxy>& cDcMap = cacheProxy.dataContainers; // Add extra items in the file to the cache for (QMap<QString, DataContainerProxy>::iterator fDcIter = fDcMap.begin(); fDcIter != fDcMap.end(); ++fDcIter) { QString fileDcName = fDcIter.key(); DataContainerProxy fileDcProxy = fDcIter.value(); // If the cache does not have the file dc proxy, add it to the cache if (cDcMap.contains(fileDcName) == false) { cDcMap.insert(fileDcName, fileDcProxy); } QMap<QString, AttributeMatrixProxy> fAmMap = fileDcProxy.attributeMatricies; QMap<QString, AttributeMatrixProxy>& cAmMap = cDcMap.find(fileDcName).value().attributeMatricies; for (QMap<QString, AttributeMatrixProxy>::iterator fAmIter = fAmMap.begin(); fAmIter != fAmMap.end(); ++fAmIter) { QString fileAmName = fAmIter.key(); AttributeMatrixProxy fileAmProxy = fAmIter.value(); // If the cache does not have the file am proxy, add it to the cache if (cAmMap.contains(fileAmName) == false) { cAmMap.insert(fileAmName, fileAmProxy); } QMap<QString, DataArrayProxy> fDaMap = fileAmProxy.dataArrays; QMap<QString, DataArrayProxy>& cDaMap = cAmMap.find(fileAmName).value().dataArrays; for (QMap<QString, DataArrayProxy>::iterator fDaIter = fDaMap.begin(); fDaIter != fDaMap.end(); ++fDaIter) { QString fileDaName = fDaIter.key(); DataArrayProxy fileDaProxy = fDaIter.value(); // If the cache does not have the file da proxy, add it to the cache if (cDaMap.contains(fileDaName) == false) { cDaMap.insert(fileDaName, fileDaProxy); } } } } // Remove items from the cache that are no longer in the file QList<QString> dcItemsToDelete; for (QMap<QString, DataContainerProxy>::iterator cDcIter = cDcMap.begin(); cDcIter != cDcMap.end(); ++cDcIter) { QString cacheDcName = cDcIter.key(); DataContainerProxy& cacheDcProxy = cDcIter.value(); // If the file does not have the cached dc proxy, remove it from the cache if (fDcMap.contains(cacheDcName) == false) { dcItemsToDelete.push_back(cacheDcName); } else { QMap<QString, AttributeMatrixProxy>& cAmMap = cacheDcProxy.attributeMatricies; QMap<QString, AttributeMatrixProxy> fAmMap = fDcMap.find(cacheDcName).value().attributeMatricies; QList<QString> amItemsToDelete; for (QMap<QString, AttributeMatrixProxy>::iterator amIter = cAmMap.begin(); amIter != cAmMap.end(); ++amIter) { QString cacheAmName = amIter.key(); AttributeMatrixProxy& cacheAmProxy = amIter.value(); // If the file does not have the cached am proxy, remove it from the cache if (fAmMap.contains(cacheAmName) == false) { amItemsToDelete.push_back(cacheAmName); } else { QMap<QString, DataArrayProxy>& cDaMap = cacheAmProxy.dataArrays; QMap<QString, DataArrayProxy> fDaMap = fAmMap.find(cacheAmName).value().dataArrays; QList<QString> daItemsToDelete; for (QMap<QString, DataArrayProxy>::iterator daIter = cDaMap.begin(); daIter != cDaMap.end(); ++daIter) { QString cacheDaName = daIter.key(); DataArrayProxy cacheDaProxy = daIter.value(); // If the file does not have the cached da proxy, remove it from the cache if (fDaMap.contains(cacheDaName) == false) { daItemsToDelete.push_back(cacheDaName); } } // Remove extra da entries from cache for (QList<QString>::iterator iter = daItemsToDelete.begin(); iter != daItemsToDelete.end(); ++iter) { cDaMap.remove(*iter); } } } // Remove extra am entries from cache for (QList<QString>::iterator iter = amItemsToDelete.begin(); iter != amItemsToDelete.end(); ++iter) { cAmMap.remove(*iter); } } } // Remove extra dc entries from cache for (QList<QString>::iterator iter = dcItemsToDelete.begin(); iter != dcItemsToDelete.end(); ++iter) { cDcMap.remove(*iter); } return cacheProxy; }
bool UnixMakefileGenerator::findLibraries() { ProString libArg = project->first("QMAKE_L_FLAG"); if (libArg == "-L") libArg.clear(); QList<QMakeLocalFileName> libdirs; int libidx = 0; foreach (const ProString &dlib, project->values("QMAKE_DEFAULT_LIBDIRS")) libdirs.append(QMakeLocalFileName(dlib.toQString())); static const char * const lflags[] = { "QMAKE_LIBS", "QMAKE_LIBS_PRIVATE", 0 }; for (int i = 0; lflags[i]; i++) { ProStringList &l = project->values(lflags[i]); for (ProStringList::Iterator it = l.begin(); it != l.end(); ) { QString stub, dir, extn, opt = (*it).trimmed().toQString(); if(opt.startsWith("-")) { if(opt.startsWith("-L")) { QString lib = opt.mid(2); QMakeLocalFileName f(lib); int idx = libdirs.indexOf(f); if (idx >= 0 && idx < libidx) { it = l.erase(it); continue; } libdirs.insert(libidx++, f); if (!libArg.isEmpty()) *it = libArg + lib; } else if(opt.startsWith("-l")) { if (project->isActiveConfig("rvct_linker") || project->isActiveConfig("armcc_linker")) { (*it) = "lib" + opt.mid(2) + ".so"; } else if (project->isActiveConfig("ti_linker")) { (*it) = opt.mid(2); } else { stub = opt.mid(2); } } else if (target_mode == TARG_MAC_MODE && opt.startsWith("-framework")) { if (opt.length() == 10) ++it; // Skip } } else { extn = dir = ""; stub = opt; int slsh = opt.lastIndexOf(Option::dir_sep); if(slsh != -1) { dir = opt.left(slsh); stub = opt.mid(slsh+1); } QRegExp stub_reg("^.*lib(" + stub + "[^./=]*)\\.(.*)$"); if(stub_reg.exactMatch(stub)) { stub = stub_reg.cap(1); extn = stub_reg.cap(2); } } if(!stub.isEmpty()) { stub += project->first(ProKey("QMAKE_" + stub.toUpper() + "_SUFFIX")).toQString(); bool found = false; ProStringList extens; if(!extn.isNull()) extens << extn; else extens << project->values("QMAKE_EXTENSION_SHLIB").first() << "a"; for (ProStringList::Iterator extit = extens.begin(); extit != extens.end(); ++extit) { if(dir.isNull()) { for(QList<QMakeLocalFileName>::Iterator dep_it = libdirs.begin(); dep_it != libdirs.end(); ++dep_it) { QString pathToLib = ((*dep_it).local() + Option::dir_sep + project->values("QMAKE_PREFIX_SHLIB").first() + stub + "." + (*extit)); if(exists(pathToLib)) { (*it) = "-l" + stub; found = true; break; } } } else { QString lib = dir + project->values("QMAKE_PREFIX_SHLIB").first() + stub + "." + (*extit); if (exists(lib)) { (*it) = lib; found = true; break; } } } if(!found && project->isActiveConfig("compile_libtool")) { for(int dep_i = 0; dep_i < libdirs.size(); ++dep_i) { if(exists(libdirs[dep_i].local() + Option::dir_sep + project->values("QMAKE_PREFIX_SHLIB").first() + stub + Option::libtool_ext)) { (*it) = libdirs[dep_i].real() + Option::dir_sep + project->values("QMAKE_PREFIX_SHLIB").first() + stub + Option::libtool_ext; found = true; break; } } } } ++it; } } return false; }
void IngredientMatcherDialog::findRecipes( void ) { KApplication::setOverrideCursor( Qt::WaitCursor ); START_TIMER("Ingredient Matcher: loading database data"); RecipeList rlist; database->loadRecipes( &rlist, RecipeDB::Title | RecipeDB::NamesOnly | RecipeDB::Ingredients | RecipeDB::IngredientAmounts ); END_TIMER(); START_TIMER("Ingredient Matcher: analyzing data for matching recipes"); // Clear the list recipeListView->listView() ->clear(); // Now show the recipes with ingredients that are contained in the previous set // of ingredients RecipeList incompleteRecipes; QList <int> missingNumbers; Q3ValueList <IngredientList> missingIngredients; RecipeList::Iterator it; for ( it = rlist.begin();it != rlist.end();++it ) { IngredientList il = ( *it ).ingList; if ( il.isEmpty() ) continue; IngredientList missing; if ( m_ingredientList.containsSubSet( il, missing, true, database ) ) { new CustomRecipeListItem( recipeListView->listView(), *it ); } else { incompleteRecipes.append( *it ); missingIngredients.append( missing ); missingNumbers.append( missing.count() ); } } END_TIMER(); //Check if the user wants to show missing ingredients if ( missingNumberSpinBox->value() == 0 ) { KApplication::restoreOverrideCursor(); return ; } //"None" START_TIMER("Ingredient Matcher: searching for and displaying partial matches"); IngredientList requiredIngredients; for ( Q3ListViewItem *it = ingListView->listView()->firstChild(); it; it = it->nextSibling() ) { if ( ((Q3CheckListItem*)it)->isOn() ) requiredIngredients << *m_item_ing_map[it]; } // Classify recipes with missing ingredients in different lists by amount QList<int>::Iterator nit; Q3ValueList<IngredientList>::Iterator ilit; int missingNoAllowed = missingNumberSpinBox->value(); if ( missingNoAllowed == -1 ) // "Any" { for ( nit = missingNumbers.begin();nit != missingNumbers.end();++nit ) if ( ( *nit ) > missingNoAllowed ) missingNoAllowed = ( *nit ); } for ( int missingNo = 1; missingNo <= missingNoAllowed; missingNo++ ) { nit = missingNumbers.begin(); ilit = missingIngredients.begin(); bool titleShownYet = false; for ( it = incompleteRecipes.begin();it != incompleteRecipes.end();++it, ++nit, ++ilit ) { if ( !( *it ).ingList.containsAny( m_ingredientList ) ) continue; if ( !( *it ).ingList.containsSubSet( requiredIngredients ) ) continue; if ( ( *nit ) == missingNo ) { if ( !titleShownYet ) { new SectionItem( recipeListView->listView(), i18ncp( "@label:textbox", "You are missing 1 ingredient for:", "You are missing %1 ingredients for:", missingNo ) ); titleShownYet = true; } new CustomRecipeListItem( recipeListView->listView(), *it, *ilit ); } } } END_TIMER(); KApplication::restoreOverrideCursor(); }
K3AboutApplication::K3AboutApplication( const KAboutData *aboutData, QWidget *parent, bool modal ) :K3AboutDialog( Tabbed|Product, aboutData->programName(), parent ), d( 0 ) { setButtons( Close ); setDefaultButton( Close ); setModal( modal ); if( aboutData == 0 ) aboutData = KGlobal::mainComponent().aboutData(); if( !aboutData ) { // Recovery setProduct(KGlobal::caption(), i18n("??"), QString(), QString()); K3AboutContainer *appPage = addContainerPage( i18n("&About")); QString appPageText = i18n("No information available.\n" "The supplied KAboutData object does not exist."); QLabel *appPageLabel = new QLabel( "\n\n\n\n"+appPageText+"\n\n\n\n", 0 ); appPage->addWidget( appPageLabel ); return; } setProduct( aboutData->programName(), aboutData->version(), QString(), QString() ); if ( aboutData->programLogo().canConvert<QPixmap>() ) setProgramLogo( aboutData->programLogo().value<QPixmap>() ); else if ( aboutData->programLogo().canConvert<QImage>() ) setProgramLogo( QPixmap::fromImage(aboutData->programLogo().value<QImage>() ) ); QString appPageText = aboutData->shortDescription() + '\n'; if (!aboutData->otherText().isEmpty()) appPageText += '\n' + aboutData->otherText() + '\n'; if (!aboutData->copyrightStatement().isEmpty()) appPageText += '\n' + aboutData->copyrightStatement() + '\n'; K3AboutContainer *appPage = addContainerPage( i18n("&About")); QLabel *appPageLabel = new QLabel( appPageText, 0 ); appPage->addWidget( appPageLabel ); if (!aboutData->homepage().isEmpty()) { QLabel *url = new QLabel(appPage); url->setOpenExternalLinks(true); url->setTextInteractionFlags(Qt::LinksAccessibleByMouse); url->setText(QString("<a href=\"%1\">%1</a>").arg(aboutData->homepage())); appPage->addWidget( url ); } int authorCount = aboutData->authors().count(); if (authorCount) { QString authorPageTitle = authorCount == 1 ? i18n("A&uthor") : i18n("A&uthors"); K3AboutContainer *authorPage = addScrolledContainerPage( authorPageTitle, Qt::AlignLeft, Qt::AlignLeft ); if (!aboutData->customAuthorTextEnabled() || !aboutData->customAuthorRichText().isEmpty ()) { QString text; QLabel* activeLabel = new QLabel( authorPage ); activeLabel->setOpenExternalLinks(true); activeLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse); if (!aboutData->customAuthorTextEnabled()) { if ( aboutData->bugAddress().isEmpty() || aboutData->bugAddress() == "*****@*****.**") text = i18n( "Please use <a href=\"http://bugs.kde.org\">http://bugs.kde.org</a> to report bugs.\n" ); else { if( aboutData->authors().count() == 1 && ( aboutData->authors().first().emailAddress() == aboutData->bugAddress() ) ) { text = i18n( "Please report bugs to <a href=\"mailto:%1\">%2</a>.\n" , aboutData->authors().first().emailAddress() , aboutData->authors().first().emailAddress() ); } else { text = i18n( "Please report bugs to <a href=\"mailto:%1\">%2</a>.\n" , aboutData->bugAddress(), aboutData->bugAddress() ); } } } else { text = aboutData->customAuthorRichText(); } activeLabel->setText( text ); authorPage->addWidget( activeLabel ); } QList<KAboutPerson> lst = aboutData->authors(); for (int i = 0; i < lst.size(); ++i) { authorPage->addPerson( lst.at(i).name(), lst.at(i).emailAddress(), lst.at(i).webAddress(), lst.at(i).task() ); } } int creditsCount = aboutData->credits().count(); if (creditsCount) { K3AboutContainer *creditsPage = addScrolledContainerPage( i18n("&Thanks To") ); QList<KAboutPerson> lst = aboutData->credits(); for (int i = 0; i < lst.size(); ++i) { creditsPage->addPerson( lst.at(i).name(), lst.at(i).emailAddress(), lst.at(i).webAddress(), lst.at(i).task() ); } } const QList<KAboutPerson> translatorList = aboutData->translators(); if(translatorList.count() > 0) { QString text = "<qt>"; QList<KAboutPerson>::ConstIterator it; for(it = translatorList.begin(); it != translatorList.end(); ++it) { text += QString("<p>%1<br> " "<a href=\"mailto:%2\">%2</a></p>") .arg((*it).name()) .arg((*it).emailAddress()) .arg((*it).emailAddress()); } text += KAboutData::aboutTranslationTeam() + "</qt>"; addTextPage( i18n("T&ranslation"), text, true); } if (!aboutData->license().isEmpty() ) { addLicensePage( i18n("&License Agreement"), aboutData->license() ); } // Make sure the dialog has a reasonable width setInitialSize( QSize(400,1) ); }
void performJourney(std::ostream &output, const OsmAnd::Voyager::Configuration& cfg) #endif { if(cfg.generateXml) { #if defined(_UNICODE) || defined(UNICODE) output << xT("<?xml version=\"1.0\" encoding=\"UTF-16\"?>") << std::endl; #else output << xT("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") << std::endl; #endif } QList< std::shared_ptr<OsmAnd::ObfReader> > obfData; for(auto itObf = cfg.obfs.begin(); itObf != cfg.obfs.end(); ++itObf) { auto obf = *itObf; std::shared_ptr<OsmAnd::ObfReader> obfReader(new OsmAnd::ObfReader(std::shared_ptr<QIODevice>(new QFile(obf->absoluteFilePath())))); obfData.push_back(obfReader); } OsmAnd::RoutePlannerContext plannerContext(obfData, cfg.routingConfig, cfg.vehicle, false); std::shared_ptr<OsmAnd::Model::Road> startRoad; if(!OsmAnd::RoutePlanner::findClosestRoadPoint(&plannerContext, cfg.startLatitude, cfg.startLongitude, &startRoad)) { if(cfg.generateXml) output << xT("<!--"); output << xT("Failed to find road near start point"); if(cfg.generateXml) output << xT("-->"); output << std::endl; return; } std::shared_ptr<OsmAnd::Model::Road> endRoad; if(!OsmAnd::RoutePlanner::findClosestRoadPoint(&plannerContext, cfg.endLatitude, cfg.endLongitude, &endRoad)) { if(cfg.generateXml) output << xT("<!--"); output << xT("Failed to find road near end point"); if(cfg.generateXml) output << xT("-->"); output << std::endl; return; } if(cfg.verbose) { if(cfg.generateXml) output << xT("<!--"); output << xT("Start point (LAT ") << cfg.startLatitude << xT("; LON ") << cfg.startLongitude << xT("):"); if(cfg.generateXml) output << xT("-->"); output << std::endl; if(cfg.generateXml) output << xT("<!--"); output << xT("\tRoad name(s): "); if(startRoad->names.size() == 0) { output << xT("\t[none] (") << startRoad->id << xT(")"); if(cfg.generateXml) output << xT("-->"); output << std::endl; } else { for(auto itName = startRoad->names.begin(); itName != startRoad->names.end(); ++itName) output << QStringToStlString(itName.value()) << xT("; "); output << xT(" (") << startRoad->id << xT(")"); if(cfg.generateXml) output << xT("-->"); output << std::endl; } output << std::endl; if(cfg.generateXml) output << xT("<!--"); output << xT("End point (LAT ") << cfg.endLatitude << xT("; LON ") << cfg.endLongitude << xT("):"); if(cfg.generateXml) output << xT("-->"); output << std::endl; if(cfg.generateXml) output << xT("<!--"); output << xT("\tRoad name(s): "); if(endRoad->names.size() == 0) { output << xT("\t[none] (") << endRoad->id << xT(")"); if(cfg.generateXml) output << xT("-->"); output << std::endl; } else { for(auto itName = endRoad->names.begin(); itName != endRoad->names.end(); ++itName) output << QStringToStlString(itName.value()) << xT("; "); output << xT(" (") << endRoad->id << xT(")"); if(cfg.generateXml) output << xT("-->"); output << std::endl; } output << std::endl; } QList< std::pair<double, double> > points; points.push_back(std::pair<double, double>(cfg.startLatitude, cfg.startLongitude)); for(auto itIntermediatePoint = cfg.waypoints.begin(); itIntermediatePoint != cfg.waypoints.end(); ++itIntermediatePoint) points.push_back(*itIntermediatePoint); points.push_back(std::pair<double, double>(cfg.endLatitude, cfg.endLongitude)); QList< std::shared_ptr<OsmAnd::RouteSegment> > route; auto routeCalculationStart = std::chrono::steady_clock::now(); if(cfg.verbose) { if(cfg.generateXml) output << xT("<!--"); output << xT("Started route calculation ") << QStringToStlString(QTime::currentTime().toString()); if(cfg.generateXml) output << xT("-->"); output << std::endl; } OsmAnd::RouteCalculationResult routeFound = OsmAnd::RoutePlanner::calculateRoute(&plannerContext, points, cfg.leftSide, nullptr); route = routeFound.list; auto routeCalculationFinish = std::chrono::steady_clock::now(); if(cfg.verbose) { if(cfg.generateXml) output << xT("<!--"); output << xT("Finished route calculation ") << QStringToStlString(QTime::currentTime().toString()) << xT(", took ") << std::chrono::duration<double, std::milli> (routeCalculationFinish - routeCalculationStart).count() << xT(" ms"); if(cfg.generateXml) output << xT("-->"); output << std::endl; } if(cfg.doRecalculate) { auto routeRecalculationStart = std::chrono::steady_clock::now(); if(cfg.verbose) { if(cfg.generateXml) output << xT("<!--"); output << xT("Started route recalculation ") << QStringToStlString(QTime::currentTime().toString()); if(cfg.generateXml) output << xT("-->"); output << std::endl; } routeFound = OsmAnd::RoutePlanner::calculateRoute(&plannerContext, points, cfg.leftSide, nullptr); route = routeFound.list; auto routeRecalculationFinish = std::chrono::steady_clock::now(); if(cfg.verbose) { if(cfg.generateXml) output << xT("<!--"); output << xT("Finished route recalculation ") << QStringToStlString(QTime::currentTime().toString()) << xT(", took ") << std::chrono::duration<double, std::milli> (routeRecalculationFinish - routeRecalculationStart).count() << xT(" ms"); if(cfg.generateXml) output << xT("-->"); output << std::endl; } } if(routeFound.warnMessage == "") { if(cfg.generateXml) output << xT("<!--"); output << xT("FAILED TO FIND ROUTE!") << QStringToStlString(routeFound.warnMessage); if(cfg.generateXml) output << xT("-->"); output << std::endl; } float totalTime = 0.0f; float totalDistance = 0.0f; for(auto itSegment = route.begin(); itSegment != route.end(); ++itSegment) { auto segment = *itSegment; totalTime += segment->time; totalDistance += segment->distance; } if(cfg.generateXml) output << xT("<test") << std::endl; else output << xT("ROUTE:") << std::endl; output << xT("\tregions=\"\"") << std::endl; output << xT("\tdescription=\"\"") << std::endl; output << xT("\tbest_percent=\"\"") << std::endl; output << xT("\tvehicle=\"") << QStringToStlString(cfg.vehicle) << xT("\"") << std::endl; output << xT("\tstart_lat=\"") << cfg.startLatitude << xT("\"") << std::endl; output << xT("\tstart_lon=\"") << cfg.startLongitude << xT("\"") << std::endl; output << xT("\ttarget_lat=\"") << cfg.endLatitude << xT("\"") << std::endl; output << xT("\ttarget_lon=\"") << cfg.endLongitude << xT("\"") << std::endl; output << xT("\tloadedTiles=\"") << 0 << xT("\"") << std::endl; output << xT("\tvisitedSegments=\"") << 0 << xT("\"") << std::endl; output << xT("\tcomplete_distance=\"") << totalDistance << xT("\"") << std::endl; output << xT("\tcomplete_time=\"") << totalTime << xT("\"") << std::endl; output << xT("\trouting_time=\"") << 0 << xT("\"") << std::endl; if(cfg.generateXml) output << xT(">") << std::endl; else output << std::endl; std::unique_ptr<QFile> gpxFile; std::unique_ptr<QTextStream> gpxStream; if(!cfg.gpxPath.isEmpty()) { gpxFile.reset(new QFile(cfg.gpxPath)); gpxFile->open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text); gpxStream.reset(new QTextStream(gpxFile.get())); } if(gpxFile && gpxFile->isOpen()) { *(gpxStream.get()) << "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>\n"; *(gpxStream.get()) << "<gpx version=\"1.0\" creator=\"OsmAnd Voyager tool\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n"; *(gpxStream.get()) << "\t<trk>\n"; *(gpxStream.get()) << "\t\t<trkseg>\n"; } for(auto itSegment = route.begin(); itSegment != route.end(); ++itSegment) { auto segment = *itSegment; if(cfg.generateXml) output << xT("\t<segment") << std::endl; else output << xT("\tSEGMENT:") << std::endl; output << xT("\t\tid=\"") << segment->road->id << xT("\"") << std::endl; output << xT("\t\tstart=\"") << segment->startPointIndex << xT("\"") << std::endl; output << xT("\t\tend=\"") << segment->endPointIndex << xT("\"") << std::endl; QString name; if(!segment->road->names.isEmpty()) name += segment->road->names.begin().value(); /*String ref = res.getObject().getRef(); if (ref != null) { name += " (" + ref + ") "; }*/ output << xT("\t\tname=\"") << QStringToStlString(name) << xT("\"") << std::endl; output << xT("\t\ttime=\"") << segment->time << xT("\"") << std::endl; output << xT("\t\tdistance=\"") << segment->distance << xT("\"") << std::endl; /*float ms = res.getObject().getMaximumSpeed(); if(ms > 0) { additional.append("maxspeed = \"").append(ms * 3.6f).append("\" ").append(res.getObject().getHighway()).append(" "); }*/ /* if (res.getTurnType() != null) { additional.append("turn = \"").append(res.getTurnType()).append("\" "); additional.append("turn_angle = \"").append(res.getTurnType().getTurnAngle()).append("\" "); if (res.getTurnType().getLanes() != null) { additional.append("lanes = \"").append(Arrays.toString(res.getTurnType().getLanes())).append("\" "); } }*/ output << xT("\t\tstart_bearing=\"") << segment->getBearingBegin() << xT("\"") << std::endl; output << xT("\t\tend_bearing=\"") << segment->getBearingEnd() << xT("\"") << std::endl; //additional.append("description = \"").append(res.getDescription()).append("\" "); if(cfg.generateXml) output << xT("\t/>") << std::endl; else output << std::endl; if(gpxFile && gpxFile->isOpen()) { output << xT("\t\tstart=\"") << segment->startPointIndex << xT("\"") << std::endl; output << xT("\t\tend=\"") << segment->endPointIndex << xT("\"") << std::endl; for(auto pointIdx = segment->startPointIndex; pointIdx < segment->endPointIndex; pointIdx++) { const auto& point = segment->road->points[pointIdx]; *(gpxStream.get()) << "\t\t\t<trkpt lon=\"" << OsmAnd::Utilities::get31LongitudeX(point.x) << "\" lat=\"" << OsmAnd::Utilities::get31LatitudeY(point.y) << "\"/>\n"; } } } if(gpxFile && gpxFile->isOpen()) { *(gpxStream.get()) << "\t\t</trkseg>\n"; *(gpxStream.get()) << "\t</trk>\n"; *(gpxStream.get()) << "</gpx>\n"; gpxStream->flush(); gpxFile->close(); } if(cfg.generateXml) output << xT("</test>") << std::endl; }
void QgsSingleBandPseudoColorRendererWidget::on_mClassifyButton_clicked() { int bandComboIndex = mBandComboBox->currentIndex(); if ( bandComboIndex == -1 || !mRasterLayer ) { return; } //int bandNr = mBandComboBox->itemData( bandComboIndex ).toInt(); //QgsRasterBandStats myRasterBandStats = mRasterLayer->dataProvider()->bandStatistics( bandNr ); int numberOfEntries = mNumberOfEntriesSpinBox->value(); QList<double> entryValues; QList<QColor> entryColors; double min = lineEditValue( mMinLineEdit ); double max = lineEditValue( mMaxLineEdit ); if ( mClassificationModeComboBox->currentText() == tr( "Equal interval" ) ) { //double currentValue = myRasterBandStats.minimumValue; double currentValue = min; double intervalDiff; if ( numberOfEntries > 1 ) { //because the highest value is also an entry, there are (numberOfEntries - 1) //intervals //intervalDiff = ( myRasterBandStats.maximumValue - myRasterBandStats.minimumValue ) / intervalDiff = ( max - min ) / ( numberOfEntries - 1 ); } else { //intervalDiff = myRasterBandStats.maximumValue - myRasterBandStats.minimumValue; intervalDiff = max - min; } for ( int i = 0; i < numberOfEntries; ++i ) { entryValues.push_back( currentValue ); currentValue += intervalDiff; } } #if 0 //hard code color range from blue -> red for now. Allow choice of ramps in future int colorDiff = 0; if ( numberOfEntries != 0 ) { colorDiff = ( int )( 255 / numberOfEntries ); } for ( int i = 0; i < numberOfEntries; ++i ) { QColor currentColor; currentColor.setRgb( colorDiff*i, 0, 255 - colorDiff * i ); entryColors.push_back( currentColor ); } #endif QgsVectorColorRampV2* colorRamp = mColorRampComboBox->currentColorRamp(); if ( ! colorRamp ) { //hard code color range from blue -> red (previous default) int colorDiff = 0; if ( numberOfEntries != 0 ) { colorDiff = ( int )( 255 / numberOfEntries ); } for ( int i = 0; i < numberOfEntries; ++i ) { QColor currentColor; currentColor.setRgb( colorDiff*i, 0, 255 - colorDiff * i ); entryColors.push_back( currentColor ); } } else { for ( int i = 0; i < numberOfEntries; ++i ) { entryColors.push_back( colorRamp->color((( double ) i ) / numberOfEntries ) ); } } mColormapTreeWidget->clear(); QList<double>::const_iterator value_it = entryValues.begin(); QList<QColor>::const_iterator color_it = entryColors.begin(); for ( ; value_it != entryValues.end(); ++value_it, ++color_it ) { QTreeWidgetItem* newItem = new QTreeWidgetItem( mColormapTreeWidget ); newItem->setText( 0, QString::number( *value_it, 'f' ) ); newItem->setBackground( 1, QBrush( *color_it ) ); newItem->setText( 2, QString::number( *value_it, 'f' ) ); newItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable ); } }
/** * User have moved his mouse in this widget */ void SearchListView::mouseMoveEvent(QMouseEvent *event) { event->accept(); // Should we start dragging? if (!dragEnabled()) { // We change selection: don't stop dragging and restore extendedselection setSelection(QRect(mDragStartPosition, event->pos()), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); return; } if (!(event->buttons() & Qt::LeftButton)) return; if ((event->pos() - mDragStartPosition).manhattanLength() < QApplication::startDragDistance()) return; // Create drag object QDrag *drag = new QDrag(this); QMimeData *mimeData = new QMimeData; QList<QUrl> urls; QStringList users; QList<QTreeWidgetItem*> items = selectedItems(); QList<QTreeWidgetItem*>::const_iterator it = items.begin(); for(; it != items.end(); ++it) { SearchListItem * item = dynamic_cast<SearchListItem*>(*it); if(item && item->isSelected() && !item->isHidden()) { if(users.indexOf(item->user()) == -1) users << item->user(); // slsk protocol: in QUrl, hostname is always lower case. // So we put username as hostname for compatibility, and as username to have the correct case. // Ex: slsk://MuSeEk:filesize@museek/path/to/a/file // Code should first look at QUrl::userName() and if not present, try QUrl::host() QUrl url("slsk://" + item->user()); url.setUserName(item->user()); url.setPath(item->path().replace("\\", "/")); url.setPassword(QString::number(item->size())); // There may be spaces in username so url may not be valid. It will work, but QUrl::isValid() should not be used urls.push_back(url); } } if(urls.count() == 0) return; // Add the urls to the mimedata mimeData->setUrls(urls); // Add them too in text format if we want to paste it in a text area QString textUrls; QList<QUrl>::const_iterator uit; for(uit = urls.begin(); uit != urls.end(); uit++) textUrls += uit->toString() + "\n"; mimeData->setText(textUrls); // And now set this mimedata into drag object drag->setMimeData(mimeData); QString x(tr("%n search result(s)", "", urls.count()) + tr(" (%n user(s))", "", users.count())); QSize s = viewport()->fontMetrics().size(Qt::TextSingleLine, x) + QSize(6, 4); QPixmap pix(s); QPainter p(&pix); p.setFont(viewport()->font()); p.setPen(viewport()->palette().color(QPalette::WindowText)); p.fillRect(QRect(QPoint(0, 0), s), viewport()->palette().color(QPalette::Background)); p.drawRect(QRect(QPoint(0, 0), s)); p.drawText(QRect(QPoint(3, 3), s - QSize(3, 3)), Qt::AlignLeft | Qt::AlignVCenter, x); p.end(); drag->setHotSpot(QPoint(20, 20)); drag->setPixmap(pix); // Begin dragging drag->exec(); }
int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<QgsSnappingResult>& results, const QList<QgsPoint>& excludePoints ) { results.clear(); if ( !mSnapper ) return 5; //topological editing on? int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); //snapping on intersection on? int intersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 ); if ( topologicalEditing == 0 ) { if ( intersectionSnapping == 0 ) mSnapper->setSnapMode( QgsSnapper::SnapWithOneResult ); else mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances ); } else if ( intersectionSnapping == 0 ) { mSnapper->setSnapMode( QgsSnapper::SnapWithResultsForSamePosition ); } else { mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances ); } //read snapping settings from project bool snappingDefinedInProject, ok; QStringList layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &snappingDefinedInProject ); QStringList enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok ); QStringList toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok ); QStringList toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok ); QStringList snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &ok ); if ( !( layerIdList.size() == enabledList.size() && layerIdList.size() == toleranceList.size() && layerIdList.size() == toleranceUnitList.size() && layerIdList.size() == snapToList.size() ) ) { // lists must have the same size, otherwise something is wrong return 1; } QList<QgsSnapper::SnapLayer> snapLayers; QgsSnapper::SnapLayer snapLayer; // Use snapping information from the project if ( snappingDefinedInProject ) { // set layers, tolerances, snap to segment/vertex to QgsSnapper QStringList::const_iterator layerIt( layerIdList.constBegin() ); QStringList::const_iterator tolIt( toleranceList.constBegin() ); QStringList::const_iterator tolUnitIt( toleranceUnitList.constBegin() ); QStringList::const_iterator snapIt( snapToList.constBegin() ); QStringList::const_iterator enabledIt( enabledList.constBegin() ); for ( ; layerIt != layerIdList.constEnd(); ++layerIt, ++tolIt, ++tolUnitIt, ++snapIt, ++enabledIt ) { if ( *enabledIt != "enabled" ) { // skip layer if snapping is not enabled continue; } //layer QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( QgsMapLayerRegistry::instance()->mapLayer( *layerIt ) ); if ( !vlayer || !vlayer->hasGeometryType() ) continue; snapLayer.mLayer = vlayer; //tolerance snapLayer.mTolerance = tolIt->toDouble(); snapLayer.mUnitType = ( QgsTolerance::UnitType ) tolUnitIt->toInt(); // segment or vertex if ( *snapIt == "to_vertex" ) { snapLayer.mSnapTo = QgsSnapper::SnapToVertex; } else if ( *snapIt == "to_segment" ) { snapLayer.mSnapTo = QgsSnapper::SnapToSegment; } else { // to vertex and segment snapLayer.mSnapTo = QgsSnapper::SnapToVertexAndSegment; } snapLayers.append( snapLayer ); } } else { // nothing in project. Use default snapping tolerance to vertex of current layer QgsMapLayer* currentLayer = mMapCanvas->currentLayer(); if ( !currentLayer ) return 2; QgsVectorLayer* currentVectorLayer = qobject_cast<QgsVectorLayer *>( currentLayer ); if ( !currentVectorLayer ) return 3; snapLayer.mLayer = currentVectorLayer; //default snap mode QSettings settings; QString defaultSnapString = settings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString(); if ( defaultSnapString == "to segment" ) { snapLayer.mSnapTo = QgsSnapper::SnapToSegment; } else if ( defaultSnapString == "to vertex and segment" ) { snapLayer.mSnapTo = QgsSnapper::SnapToVertexAndSegment; } else if ( defaultSnapString == "to vertex" ) { snapLayer.mSnapTo = QgsSnapper::SnapToVertex; } else { return 0; } //default snapping tolerance (returned in map units) snapLayer.mTolerance = QgsTolerance::defaultTolerance( currentVectorLayer, mMapCanvas->mapSettings() ); snapLayer.mUnitType = QgsTolerance::MapUnits; snapLayers.append( snapLayer ); } mSnapper->setSnapLayers( snapLayers ); if ( mSnapper->snapPoint( point, results, excludePoints ) != 0 ) return 4; if ( intersectionSnapping != 1 ) return 0; QList<QgsSnappingResult> segments; QList<QgsSnappingResult> points; for ( QList<QgsSnappingResult>::const_iterator it = results.constBegin(); it != results.constEnd(); ++it ) { if ( it->snappedVertexNr == -1 ) { QgsDebugMsg( "segment" ); segments.push_back( *it ); } else { QgsDebugMsg( "no segment" ); points.push_back( *it ); } } if ( segments.length() < 2 ) return 0; QList<QgsSnappingResult> myResults; for ( QList<QgsSnappingResult>::const_iterator oSegIt = segments.constBegin(); oSegIt != segments.constEnd(); ++oSegIt ) { QgsDebugMsg( QString::number( oSegIt->beforeVertexNr ) ); QVector<QgsPoint> vertexPoints; vertexPoints.append( oSegIt->beforeVertex ); vertexPoints.append( oSegIt->afterVertex ); QgsGeometry* lineA = QgsGeometry::fromPolyline( vertexPoints ); for ( QList<QgsSnappingResult>::iterator iSegIt = segments.begin(); iSegIt != segments.end(); ++iSegIt ) { QVector<QgsPoint> vertexPoints; vertexPoints.append( iSegIt->beforeVertex ); vertexPoints.append( iSegIt->afterVertex ); QgsGeometry* lineB = QgsGeometry::fromPolyline( vertexPoints ); QgsGeometry* intersectionPoint = lineA->intersection( lineB ); if ( intersectionPoint->type() == QGis::Point ) { //We have to check the intersection point is inside the tolerance distance for both layers double toleranceA = 0; double toleranceB = 0; for ( int i = 0 ;i < snapLayers.size();++i ) { if ( snapLayers[i].mLayer == oSegIt->layer ) { toleranceA = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType ); } if ( snapLayers[i].mLayer == iSegIt->layer ) { toleranceB = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType ); } } QgsGeometry* cursorPoint = QgsGeometry::fromPoint( point ); double distance = intersectionPoint->distance( *cursorPoint ); if ( distance < toleranceA && distance < toleranceB ) { iSegIt->snappedVertex = intersectionPoint->asPoint(); myResults.append( *iSegIt ); } } } } if ( myResults.length() > 0 ) { results.clear(); results = myResults; } return 0; }
void CanvasItem::handleDamages(const QList<Damage*>& damages) { QRegion paintRegion; enum { Nothing, Everything, Clipped } paintMode = Nothing; QList<Damage*>::ConstIterator end(damages.end()); for (QList<Damage*>::ConstIterator it = damages.begin(); it != end; ++it) { Damage* damage = *it; if (!damage) continue; if (damage->type() == Damage::Cell) { CellDamage* cellDamage = static_cast<CellDamage*>(damage); kDebug(36007) << "Processing\t" << *cellDamage; Sheet* const damagedSheet = cellDamage->sheet(); if (cellDamage->changes() & CellDamage::Appearance) { const Region& region = cellDamage->region(); sheetView(damagedSheet)->invalidateRegion(region); paintMode = Everything; } continue; } if (damage->type() == Damage::Sheet) { SheetDamage* sheetDamage = static_cast<SheetDamage*>(damage); kDebug(36007) << *sheetDamage; const SheetDamage::Changes changes = sheetDamage->changes(); if (changes & (SheetDamage::Name | SheetDamage::Shown)) { // d->tabBar->setTabs(doc()->map()->visibleSheets()); paintMode = Everything; } if (changes & (SheetDamage::Shown | SheetDamage::Hidden)) { // updateShowSheetMenu(); paintMode = Everything; } // The following changes only affect the active sheet. if (sheetDamage->sheet() != d->activeSheet) { continue; } if (changes.testFlag(SheetDamage::ContentChanged)) { update(); paintMode = Everything; } if (changes.testFlag(SheetDamage::PropertiesChanged)) { sheetView(d->activeSheet)->invalidate(); paintMode = Everything; } if (sheetDamage->changes() & SheetDamage::ColumnsChanged) columnHeader()->update(); if (sheetDamage->changes() & SheetDamage::RowsChanged) rowHeader()->update(); continue; } if (damage->type() == Damage::Selection) { SelectionDamage* selectionDamage = static_cast<SelectionDamage*>(damage); kDebug(36007) << "Processing\t" << *selectionDamage; const Region region = selectionDamage->region(); if (paintMode == Clipped) { const QRectF rect = cellCoordinatesToView(region.boundingRect()); paintRegion += rect.toRect().adjusted(-3, -3, 4, 4); } else { paintMode = Everything; } continue; } kDebug(36007) << "Unhandled\t" << *damage; } // At last repaint the dirty cells. if (paintMode == Clipped) { update(paintRegion.boundingRect()); } else if (paintMode == Everything) { update(); } }
/* 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; }
void QgsStatisticalSummary::finalize() { if ( mCount == 0 ) { mFirst = std::numeric_limits<double>::quiet_NaN(); mLast = std::numeric_limits<double>::quiet_NaN(); mMin = std::numeric_limits<double>::quiet_NaN(); mMax = std::numeric_limits<double>::quiet_NaN(); mMean = std::numeric_limits<double>::quiet_NaN(); mMedian = std::numeric_limits<double>::quiet_NaN(); mStdev = std::numeric_limits<double>::quiet_NaN(); mSampleStdev = std::numeric_limits<double>::quiet_NaN(); mMinority = std::numeric_limits<double>::quiet_NaN(); mMajority = std::numeric_limits<double>::quiet_NaN(); mFirstQuartile = std::numeric_limits<double>::quiet_NaN(); mThirdQuartile = std::numeric_limits<double>::quiet_NaN(); return; } mMean = mSum / mCount; if ( mStatistics & QgsStatisticalSummary::StDev || mStatistics & QgsStatisticalSummary::StDevSample ) { double sumSquared = 0; const auto constMValues = mValues; for ( double value : constMValues ) { double diff = value - mMean; sumSquared += diff * diff; } mStdev = std::pow( sumSquared / mValues.count(), 0.5 ); mSampleStdev = std::pow( sumSquared / ( mValues.count() - 1 ), 0.5 ); } if ( mStatistics & QgsStatisticalSummary::Median || mStatistics & QgsStatisticalSummary::FirstQuartile || mStatistics & QgsStatisticalSummary::ThirdQuartile || mStatistics & QgsStatisticalSummary::InterQuartileRange ) { std::sort( mValues.begin(), mValues.end() ); bool even = ( mCount % 2 ) < 1; if ( even ) { mMedian = ( mValues[mCount / 2 - 1] + mValues[mCount / 2] ) / 2.0; } else //odd { mMedian = mValues[( mCount + 1 ) / 2 - 1]; } } if ( mStatistics & QgsStatisticalSummary::FirstQuartile || mStatistics & QgsStatisticalSummary::InterQuartileRange ) { if ( ( mCount % 2 ) < 1 ) { int halfCount = mCount / 2; bool even = ( halfCount % 2 ) < 1; if ( even ) { mFirstQuartile = ( mValues[halfCount / 2 - 1] + mValues[halfCount / 2] ) / 2.0; } else //odd { mFirstQuartile = mValues[( halfCount + 1 ) / 2 - 1]; } } else { int halfCount = mCount / 2 + 1; bool even = ( halfCount % 2 ) < 1; if ( even ) { mFirstQuartile = ( mValues[halfCount / 2 - 1] + mValues[halfCount / 2] ) / 2.0; } else //odd { mFirstQuartile = mValues[( halfCount + 1 ) / 2 - 1]; } } } if ( mStatistics & QgsStatisticalSummary::ThirdQuartile || mStatistics & QgsStatisticalSummary::InterQuartileRange ) { if ( ( mCount % 2 ) < 1 ) { int halfCount = mCount / 2; bool even = ( halfCount % 2 ) < 1; if ( even ) { mThirdQuartile = ( mValues[ halfCount + halfCount / 2 - 1] + mValues[ halfCount + halfCount / 2] ) / 2.0; } else //odd { mThirdQuartile = mValues[( halfCount + 1 ) / 2 - 1 + halfCount ]; } } else { int halfCount = mCount / 2 + 1; bool even = ( halfCount % 2 ) < 1; if ( even ) { mThirdQuartile = ( mValues[ halfCount + halfCount / 2 - 2 ] + mValues[ halfCount + halfCount / 2 - 1 ] ) / 2.0; } else //odd { mThirdQuartile = mValues[( halfCount + 1 ) / 2 - 2 + halfCount ]; } } } if ( mStatistics & QgsStatisticalSummary::Minority || mStatistics & QgsStatisticalSummary::Majority ) { QList<int> valueCounts = mValueCount.values(); std::sort( valueCounts.begin(), valueCounts.end() ); if ( mStatistics & QgsStatisticalSummary::Minority ) { mMinority = mValueCount.key( valueCounts.first() ); } if ( mStatistics & QgsStatisticalSummary::Majority ) { mMajority = mValueCount.key( valueCounts.last() ); } } }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void AlignSections::execute() { setErrorCondition(0); dataCheck(); if(getErrorCondition() < 0) { return; } DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getDataContainerName()); size_t udims[3] = { 0, 0, 0 }; m->getGeometryAs<ImageGeom>()->getDimensions(udims); #if (CMP_SIZEOF_SIZE_T == 4) typedef int32_t DimType; #else typedef int64_t DimType; #endif DimType dims[3] = { static_cast<DimType>(udims[0]), static_cast<DimType>(udims[1]), static_cast<DimType>(udims[2]), }; DimType slice = 0; DimType xspot = 0, yspot = 0; DimType newPosition = 0; DimType currentPosition = 0; std::vector<int64_t> xshifts(dims[2], 0); std::vector<int64_t> yshifts(dims[2], 0); find_shifts(xshifts, yshifts); if (getSubtractBackground()) { /**fit x and y shifts to lines * * y = mx + b * * m = (n*sum(x_i * y_i) - sum(x_i) * sum(y_i)) / (n*sum(x_i^2)-sum(x_i)^2 * * b = (sum(y_i)-m*sum(x_i))/n * */ // same for both double sumX = 0.0; // sum(x_i) double sumX_2 = 0.0; // sum(x_i^2) // x shift line double x_sumY = 0.0; // sum(y_i) double x_sumXY = 0.0; // sum(x_i * y_i) // y shift line double y_sumY = 0.0; // sum(y_i) double y_sumXY = 0.0; // sum(x_i * y_i) for (DimType iter = 0; iter < dims[2]; iter++) { slice = static_cast<DimType>( (dims[2] - 1) - iter ); sumX = static_cast<double>(sumX + iter); sumX_2 = static_cast<double>(sumX_2 + iter * iter); x_sumY = static_cast<double>(x_sumY + xshifts[iter]); x_sumXY = static_cast<double>(x_sumXY + iter * xshifts[iter]); y_sumY = static_cast<double>(y_sumY + yshifts[iter]); y_sumXY = static_cast<double>(y_sumXY + iter * yshifts[iter]); } double mx = static_cast<double>((dims[2] * x_sumXY - x_sumXY) / (dims[2] * sumX_2 - sumX)); double my = static_cast<double>((dims[2] * y_sumXY - y_sumXY) / (dims[2] * sumX_2 - sumX)); // adjust shifts so that fit line has 0 slope (~ends of the sample are fixed) for (DimType iter = 1; iter < dims[2]; iter++) { slice = (dims[2] - 1) - iter; xshifts[iter] = static_cast<int64_t>(xshifts[iter] - iter * mx); yshifts[iter] = static_cast<int64_t>(yshifts[iter] - iter * my); } } QList<QString> voxelArrayNames = m->getAttributeMatrix(getCellAttributeMatrixName())->getAttributeArrayNames(); DimType progIncrement = dims[2] / 100; DimType prog = 1; DimType progressInt = 0; for (DimType i = 1; i < dims[2]; i++) { if (i > prog) { progressInt = ((float)i / dims[2]) * 100.0f; QString ss = QObject::tr("Transferring Cell Data || %1% Complete").arg(progressInt); notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss); prog = prog + progIncrement; } if (getCancel() == true) { return; } slice = (dims[2] - 1) - i; for (DimType l = 0; l < dims[1]; l++) { for (DimType n = 0; n < dims[0]; n++) { if (yshifts[i] >= 0) { yspot = l; } else if (yshifts[i] < 0) { yspot = dims[1] - 1 - l; } if (xshifts[i] >= 0) { xspot = n; } else if (xshifts[i] < 0) { xspot = dims[0] - 1 - n; } newPosition = (slice * dims[0] * dims[1]) + (yspot * dims[0]) + xspot; currentPosition = (slice * dims[0] * dims[1]) + ((yspot + yshifts[i]) * dims[0]) + (xspot + xshifts[i]); if ((yspot + yshifts[i]) >= 0 && (yspot + yshifts[i]) <= dims[1] - 1 && (xspot + xshifts[i]) >= 0 && (xspot + xshifts[i]) <= dims[0] - 1) { for (QList<QString>::iterator iter = voxelArrayNames.begin(); iter != voxelArrayNames.end(); ++iter) { IDataArray::Pointer p = m->getAttributeMatrix(getCellAttributeMatrixName())->getAttributeArray(*iter); p->copyTuple(currentPosition, newPosition); } } if ((yspot + yshifts[i]) < 0 || (yspot + yshifts[i]) > dims[1] - 1 || (xspot + xshifts[i]) < 0 || (xspot + xshifts[i]) > dims[0] - 1) { for (QList<QString>::iterator iter = voxelArrayNames.begin(); iter != voxelArrayNames.end(); ++iter) { IDataArray::Pointer p = m->getAttributeMatrix(getCellAttributeMatrixName())->getAttributeArray(*iter); p->initializeTuple(newPosition, 0); } } } } } // If there is an error set this to something negative and also set a message notifyStatusMessage(getHumanLabel(), "Complete"); }
/** Read map layers from project file @returns \code QPair< bool, QList<QDomNode> > \endcode bool is true if function worked; else is false. list contains nodes corresponding to layers that couldn't be loaded @note XML of form: \verbatim <maplayer type="vector"> <layername>Hydrop</layername> <datasource>/data/usgs/city_shp/hydrop.shp</datasource> <zorder>0</zorder> <provider>ogr</provider> <singlesymbol> <renderitem> <value>blabla</value> <symbol> <outlinecolor red="85" green="0" blue="255" /> <outlinestyle>SolidLine</outlinestyle> <outlinewidth>1</outlinewidth> <fillcolor red="0" green="170" blue="255" /> <fillpattern>SolidPattern</fillpattern> </symbol> <label>blabla</label> </renderitem> </singlesymbol> <label>0</label> <labelattributes> <label text="Label" field="" /> <family name="Sans Serif" field="" /> <size value="12" units="pt" field="" /> <bold on="0" field="" /> <italic on="0" field="" /> <underline on="0" field="" /> <color red="0" green="0" blue="0" field="" /> <x field="" /> <y field="" /> <offset units="pt" x="0" xfield="" y="0" yfield="" /> <angle value="0" field="" /> <alignment value="center" field="" /> </labelattributes> </maplayer> \endverbatim */ QPair< bool, QList<QDomNode> > QgsProject::_getMapLayers( QDomDocument const &doc ) { // Layer order is set by the restoring the legend settings from project file. // This is done on the 'readProject( ... )' signal QDomNodeList nl = doc.elementsByTagName( "maplayer" ); // XXX what is this used for? QString layerCount( QString::number(nl.count()) ); QString wk; QList<QDomNode> brokenNodes; // a list of Dom nodes corresponding to layers // that we were unable to load; this could be // because the layers were removed or // re-located after the project was last saved // process the map layer nodes if ( 0 == nl.count() ) // if we have no layers to process, bail { return qMakePair( true, brokenNodes ); // Decided to return "true" since it's // possible for there to be a project with no // layers; but also, more imporantly, this // would cause the tests/qgsproject to fail // since the test suite doesn't currently // support test layers } bool returnStatus = true; emit layerLoaded( 0, nl.count() ); //Collect vector layers with joins. //They need to refresh join caches and symbology infos after all layers are loaded QList< QPair< QgsVectorLayer*, QDomElement > > vLayerList; for ( int i = 0; i < nl.count(); i++ ) { QDomNode node = nl.item( i ); QDomElement element = node.toElement(); if ( element.attribute( "embedded" ) == "1" ) { createEmbeddedLayer( element.attribute( "id" ), readPath( element.attribute( "project" ) ), brokenNodes, vLayerList ); continue; } else { if ( !addLayer( element, brokenNodes, vLayerList ) ) { returnStatus = false; } } emit layerLoaded( i + 1, nl.count() ); } //Update field map of layers with joins and create join caches if necessary //Needs to be done here once all dependent layers are loaded QString errorMessage; QList< QPair< QgsVectorLayer*, QDomElement > >::iterator vIt = vLayerList.begin(); for ( ; vIt != vLayerList.end(); ++vIt ) { vIt->first->createJoinCaches(); vIt->first->updateFieldMap(); //for old symbology, it is necessary to read the symbology again after having the complete field map if ( !vIt->first->isUsingRendererV2() ) { vIt->first->readSymbology( vIt->second, errorMessage ); } } return qMakePair( returnStatus, brokenNodes ); } // _getMapLayers
void DkUpnpControlPoint::rootDeviceOnline(Herqq::Upnp::HClientDevice* clientDevice) { qDebug() << "rootDeviceOnline:" << clientDevice->info().deviceType().toString(); qDebug() << "manufacturer:" << clientDevice->info().manufacturer(); if(clientDevice->info().manufacturer()=="nomacs") { qDebug() << "nomacs found!!!"; //qDebug() << "description:" << clientDevice->description(); QList<QUrl> locations = clientDevice->locations(Herqq::Upnp::AbsoluteUrl); QUrl url; for (QList<QUrl>::iterator itr = locations.begin(); itr != locations.end(); itr++) { url = *itr; } if(url.isEmpty()) { qDebug() << "url is empty, aborting"; return; } QHostAddress host = QHostAddress(url.host()); if(isLocalHostAddress(host)) { qDebug() << "is local address ... aborting"; return; } Herqq::Upnp::HClientService* service = clientDevice->serviceById(Herqq::Upnp::HServiceId("urn:nomacs-org:service:nomacsService")); if (!service) { qDebug() << "nomacs service is empty ... aborting"; return; } Herqq::Upnp::HClientActions actions = service->actions(); qDebug() << "service:" << service->description(); Herqq::Upnp::HActionArguments aas; Herqq::Upnp::HClientActionOp cao; // ask for LAN server if (!actions.value("getTCPServerURL")) { qDebug() << "action.value(getTCPServerURL) is null ... aborting"; return; } connect(actions.value("getTCPServerURL"), SIGNAL(invokeComplete(Herqq::Upnp::HClientAction*, const Herqq::Upnp::HClientActionOp&)), this, SLOT(invokeComplete(Herqq::Upnp::HClientAction*, const Herqq::Upnp::HClientActionOp&))); cao = actions.value("getTCPServerURL")->beginInvoke(aas); // ask for RC server if (!actions.value("getWhiteListServerURL")) { qDebug() << "action.value(getWhiteListServerURL) is null ... aborting"; return; } connect(actions.value("getWhiteListServerURL"), SIGNAL(invokeComplete(Herqq::Upnp::HClientAction*, const Herqq::Upnp::HClientActionOp&)), this, SLOT(invokeComplete(Herqq::Upnp::HClientAction*, const Herqq::Upnp::HClientActionOp&))); cao = actions.value("getWhiteListServerURL")->beginInvoke(aas); connect(service->stateVariables().value("tcpServerPort"), SIGNAL(valueChanged(const Herqq::Upnp::HClientStateVariable*, const Herqq::Upnp::HStateVariableEvent&)), this, SLOT(tcpValueChanged(const Herqq::Upnp::HClientStateVariable*, const Herqq::Upnp::HStateVariableEvent&))); connect(service->stateVariables().value("whiteListServerPort"), SIGNAL(valueChanged(const Herqq::Upnp::HClientStateVariable*, const Herqq::Upnp::HStateVariableEvent&)), this, SLOT(wlValueChanged(const Herqq::Upnp::HClientStateVariable*, const Herqq::Upnp::HStateVariableEvent&))); //Herqq::Upnp::HClientServices services = clientDevice->services(); //for(int i = 0; i < (int) services.size(); i++) { // Herqq::Upnp::HClientService* service = services.at(i); // qDebug() << "service " << i << ":" << service->description() ; // Herqq::Upnp::HClientActions actions = service->actions(); // QList<QString> keys = actions.keys(); // for (int j = 0; j < (int) keys.size(); j++) { // qDebug() << "action " << j << ": " << keys.at(j); // } // Herqq::Upnp::HActionArgument aa("newTargetValue", Herqq::Upnp::HStateVariableInfo("Target", Herqq::Upnp::HUpnpDataTypes::boolean, Herqq::Upnp::HInclusionRequirement::InclusionOptional)); // aa.setValue(true); // Herqq::Upnp::HActionArguments aas; // aas.append(aa); // actions.value("SetTarget")->beginInvoke(aas); //} }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ErodeDilateCoordinationNumber::execute() { setErrorCondition(0); dataCheck(); if(getErrorCondition() < 0) { return; } DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getFeatureIdsArrayPath().getDataContainerName()); size_t totalPoints = m_FeatureIdsPtr.lock()->getNumberOfTuples(); Int32ArrayType::Pointer neighborsPtr = Int32ArrayType::CreateArray(totalPoints, "Neighbors"); m_Neighbors = neighborsPtr->getPointer(0); neighborsPtr->initializeWithValue(-1); size_t udims[3] = {0, 0, 0}; m->getGeometryAs<ImageGeom>()->getDimensions(udims); #if (CMP_SIZEOF_SIZE_T == 4) typedef int32_t DimType; #else typedef int64_t DimType; #endif DimType dims[3] = { static_cast<DimType>(udims[0]), static_cast<DimType>(udims[1]), static_cast<DimType>(udims[2]), }; int32_t good = 1; int64_t point = 0; int64_t kstride = 0, jstride = 0; int32_t featurename = 0, feature = 0; int32_t coordination = 0; int32_t current = 0; int32_t most = 0; int64_t neighpoint = 0; size_t numfeatures = 0; for(size_t i = 0; i < totalPoints; i++) { featurename = m_FeatureIds[i]; if (featurename > numfeatures) { numfeatures = featurename; } } DimType neighpoints[6] = { 0, 0, 0, 0, 0, 0 }; neighpoints[0] = -dims[0] * dims[1]; neighpoints[1] = -dims[0]; neighpoints[2] = -1; neighpoints[3] = 1; neighpoints[4] = dims[0]; neighpoints[5] = dims[0] * dims[1]; QString attrMatName = m_FeatureIdsArrayPath.getAttributeMatrixName(); QList<QString> voxelArrayNames = m->getAttributeMatrix(attrMatName)->getAttributeArrayNames(); QVector<int32_t> n(numfeatures + 1, 0); QVector<int32_t> coordinationNumber(totalPoints, 0); bool keepgoing = true; int32_t counter = 1; while (counter > 0 && keepgoing == true) { counter = 0; if (m_Loop == false) { keepgoing = false; } for (DimType k = 0; k < dims[2]; k++) { kstride = dims[0] * dims[1] * k; for (DimType j = 0; j < dims[1]; j++) { jstride = dims[0] * j; for (DimType i = 0; i < dims[0]; i++) { point = kstride + jstride + i; featurename = m_FeatureIds[point]; coordination = 0; current = 0; most = 0; for (int32_t l = 0; l < 6; l++) { good = 1; neighpoint = point + neighpoints[l]; if (l == 0 && k == 0) { good = 0; } if (l == 5 && k == (dims[2] - 1)) { good = 0; } if (l == 1 && j == 0) { good = 0; } if (l == 4 && j == (dims[1] - 1)) { good = 0; } if (l == 2 && i == 0) { good = 0; } if (l == 3 && i == (dims[0] - 1)) { good = 0; } if (good == 1) { feature = m_FeatureIds[neighpoint]; if ((featurename > 0 && feature == 0) || (featurename == 0 && feature > 0)) { coordination = coordination + 1; n[feature]++; current = n[feature]; if (current > most) { most = current; m_Neighbors[point] = neighpoint; } } } } coordinationNumber[point] = coordination; int32_t neighbor = m_Neighbors[point]; if (coordinationNumber[point] >= m_CoordinationNumber && coordinationNumber[point] > 0) { for (QList<QString>::iterator iter = voxelArrayNames.begin(); iter != voxelArrayNames.end(); ++iter) { IDataArray::Pointer p = m->getAttributeMatrix(attrMatName)->getAttributeArray(*iter); p->copyTuple(neighbor, point); } } for (int32_t l = 0; l < 6; l++) { good = 1; neighpoint = point + neighpoints[l]; if (l == 0 && k == 0) { good = 0; } if (l == 5 && k == (dims[2] - 1)) { good = 0; } if (l == 1 && j == 0) { good = 0; } if (l == 4 && j == (dims[1] - 1)) { good = 0; } if (l == 2 && i == 0) { good = 0; } if (l == 3 && i == (dims[0] - 1)) { good = 0; } if (good == 1) { feature = m_FeatureIds[neighpoint]; if (feature > 0) { n[feature] = 0; } } } } } } for (DimType k = 0; k < dims[2]; k++) { kstride = static_cast<int64_t>(dims[0] * dims[1] * k); for (DimType j = 0; j < dims[1]; j++) { jstride = static_cast<int64_t>(dims[0] * j); for (DimType i = 0; i < dims[0]; i++) { point = kstride + jstride + i; if (coordinationNumber[point] >= m_CoordinationNumber) { counter++; } } } } } // If there is an error set this to something negative and also set a message notifyStatusMessage(getHumanLabel(), "Complete"); }
void QgsComposerView::keyPressEvent( QKeyEvent * e ) { if ( !composition() ) { return; } if ( mKeyPanning || mMousePanning || mToolPanning || mMovingItemContent || composition()->selectionHandles()->isDragging() || composition()->selectionHandles()->isResizing() ) { return; } if ( mTemporaryZoomStatus != QgsComposerView::Inactive ) { //temporary keyboard based zoom is active if ( e->isAutoRepeat() ) { return; } //respond to changes in ctrl key status if ( !( e->modifiers() & Qt::ControlModifier ) && !mMarqueeZoom ) { //space pressed, but control key was released, end of temporary zoom tool mTemporaryZoomStatus = QgsComposerView::Inactive; setCurrentTool( mPreviousTool ); } else if ( !( e->modifiers() & Qt::ControlModifier ) && mMarqueeZoom ) { //control key released, but user is mid-way through a marquee zoom //so end temporary zoom when user releases the mouse button mTemporaryZoomStatus = QgsComposerView::ActiveUntilMouseRelease; } else { //both control and space pressed //set cursor to zoom in/out depending on shift key status QPixmap myZoomQPixmap = QPixmap(( const char ** )( e->modifiers() & Qt::ShiftModifier ? zoom_out : zoom_in ) ); QCursor zoomCursor = QCursor( myZoomQPixmap, 7, 7 ); viewport()->setCursor( zoomCursor ); } return; } if ( mCurrentTool != QgsComposerView::Zoom && ( mRubberBandItem || mRubberBandLineItem ) ) { //disable keystrokes while drawing a box return; } if ( e->key() == Qt::Key_Space && ! e->isAutoRepeat() ) { if ( !( e->modifiers() & Qt::ControlModifier ) ) { // Pan composer with space bar mKeyPanning = true; mMouseLastXY = mMouseCurrentXY; if ( composition() ) { //prevent cursor changes while panning composition()->setPreventCursorChange( true ); } viewport()->setCursor( Qt::ClosedHandCursor ); return; } else { //ctrl+space pressed, so switch to temporary keyboard based zoom tool mTemporaryZoomStatus = QgsComposerView::Active; mPreviousTool = mCurrentTool; setCurrentTool( Zoom ); //set cursor to zoom in/out depending on shift key status QPixmap myZoomQPixmap = QPixmap(( const char ** )( e->modifiers() & Qt::ShiftModifier ? zoom_out : zoom_in ) ); QCursor zoomCursor = QCursor( myZoomQPixmap, 7, 7 ); viewport()->setCursor( zoomCursor ); return; } } if ( mCurrentTool == QgsComposerView::Zoom ) { //using the zoom tool, respond to changes in shift key status and update mouse cursor accordingly if ( ! e->isAutoRepeat() ) { QPixmap myZoomQPixmap = QPixmap(( const char ** )( e->modifiers() & Qt::ShiftModifier ? zoom_out : zoom_in ) ); QCursor zoomCursor = QCursor( myZoomQPixmap, 7, 7 ); viewport()->setCursor( zoomCursor ); } return; } QList<QgsComposerItem*> composerItemList = composition()->selectedComposerItems(); QList<QgsComposerItem*>::iterator itemIt = composerItemList.begin(); // increment used for cursor key item movement double increment = 1.0; if ( e->modifiers() & Qt::ShiftModifier ) { //holding shift while pressing cursor keys results in a big step increment = 10.0; } if ( e->key() == Qt::Key_Left ) { for ( ; itemIt != composerItemList.end(); ++itemIt ) { ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove ); ( *itemIt )->move( -1 * increment, 0.0 ); ( *itemIt )->endCommand(); } } else if ( e->key() == Qt::Key_Right ) { for ( ; itemIt != composerItemList.end(); ++itemIt ) { ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove ); ( *itemIt )->move( increment, 0.0 ); ( *itemIt )->endCommand(); } } else if ( e->key() == Qt::Key_Down ) { for ( ; itemIt != composerItemList.end(); ++itemIt ) { ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove ); ( *itemIt )->move( 0.0, increment ); ( *itemIt )->endCommand(); } } else if ( e->key() == Qt::Key_Up ) { for ( ; itemIt != composerItemList.end(); ++itemIt ) { ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove ); ( *itemIt )->move( 0.0, -1 * increment ); ( *itemIt )->endCommand(); } } }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int StatsDataArray::readH5Data(hid_t parentId) { bool ok = false; int err = 0; QString statsType; hid_t gid = QH5Utilities::openHDF5Object(parentId, m_Name); if(gid < 0) { return err; } QList<QString> names; err = QH5Utilities::getGroupObjects(gid, H5Utilities::H5Support_GROUP, names); if(err < 0) { err |= QH5Utilities::closeHDF5Object(gid); return err; } for (QList<QString>::iterator iter = names.begin(); iter != names.end(); ++iter) { int index = 0; statsType = ""; index = QString(*iter).toInt(&ok, 10); QH5Lite::readStringAttribute(gid, *iter, DREAM3D::StringConstants::StatsType, statsType); hid_t statId = QH5Utilities::openHDF5Object(gid, *iter); if(statId < 0) { continue; err |= -1; } if(statsType.compare(DREAM3D::StringConstants::PrimaryStatsData) == 0) { PrimaryStatsData::Pointer data = PrimaryStatsData::New(); data->readHDF5Data(statId); setStatsData(index, data); } else if(statsType.compare(DREAM3D::StringConstants::PrecipitateStatsData) == 0) { PrecipitateStatsData::Pointer data = PrecipitateStatsData::New(); data->readHDF5Data(statId); setStatsData(index, data); } else if(statsType.compare(DREAM3D::StringConstants::TransformationStatsData) == 0) { TransformationStatsData::Pointer data = TransformationStatsData::New(); data->readHDF5Data(statId); setStatsData(index, data); } else if(statsType.compare(DREAM3D::StringConstants::MatrixStatsData) == 0) { MatrixStatsData::Pointer data = MatrixStatsData::New(); data->readHDF5Data(statId); setStatsData(index, data); } else if(statsType.compare(DREAM3D::StringConstants::BoundaryStatsData) == 0) { BoundaryStatsData::Pointer data = BoundaryStatsData::New(); data->readHDF5Data(statId); setStatsData(index, data); } else { qDebug() << "The Type of the stats data could not be read." ; return -1100; } err |= QH5Utilities::closeHDF5Object(statId); } // Do not forget to close the object err |= QH5Utilities::closeHDF5Object(gid); return err; }
void QgsComposerView::wheelZoom( QWheelEvent * event ) { //get mouse wheel zoom behaviour settings QSettings mySettings; int wheelAction = mySettings.value( "/qgis/wheel_action", 2 ).toInt(); double zoomFactor = mySettings.value( "/qgis/zoom_factor", 2 ).toDouble(); if (( QgsMapCanvas::WheelAction )wheelAction == QgsMapCanvas::WheelNothing ) { return; } if ( event->modifiers() & Qt::ControlModifier ) { //holding ctrl while wheel zooming results in a finer zoom zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 10.0; } //caculate zoom scale factor bool zoomIn = event->delta() > 0; double scaleFactor = ( zoomIn ? 1 / zoomFactor : zoomFactor ); //get current visible part of scene QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() ); QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() ); //transform the mouse pos to scene coordinates QPointF scenePoint = mapToScene( event->pos() ); //adjust view center according to wheel action setting switch (( QgsMapCanvas::WheelAction )wheelAction ) { case QgsMapCanvas::WheelZoomAndRecenter: { centerOn( scenePoint.x(), scenePoint.y() ); break; } case QgsMapCanvas::WheelZoomToMouseCursor: { QgsPoint oldCenter( visibleRect.center() ); QgsPoint newCenter( scenePoint.x() + (( oldCenter.x() - scenePoint.x() ) * scaleFactor ), scenePoint.y() + (( oldCenter.y() - scenePoint.y() ) * scaleFactor ) ); centerOn( newCenter.x(), newCenter.y() ); break; } default: break; } //zoom composition if ( zoomIn ) { scale( zoomFactor, zoomFactor ); } else { scale( 1 / zoomFactor, 1 / zoomFactor ); } //update composition for new zoom emit zoomLevelChanged(); updateRulers(); update(); //redraw cached map items QList<QGraphicsItem *> itemList = composition()->items(); QList<QGraphicsItem *>::iterator itemIt = itemList.begin(); for ( ; itemIt != itemList.end(); ++itemIt ) { QgsComposerMap* mypItem = dynamic_cast<QgsComposerMap *>( *itemIt ); if (( mypItem ) && ( mypItem->previewMode() == QgsComposerMap::Render ) ) { mypItem->updateCachedImage(); } } }
void KisCurveMagnetic::calculateCurve(KisCurve::iterator p1, KisCurve::iterator p2, KisCurve::iterator it) { if (p1 == m_curve.end() || p2 == m_curve.end()) // It happens sometimes, for example on the first click return; if (m_parent->editingMode()) return; QPoint start = (*p1).point().toPoint(); QPoint end = (*p2).point().toPoint(); QRect rc = QRect(start, end).normalize(); rc.setTopLeft(rc.topLeft() + QPoint(-8, -8)); // Enlarge the view, so problems with gaussian blur can be removed rc.setBottomRight(rc.bottomRight() + QPoint(8, 8)); // and we are able to find paths that go beyond the rect. KisPaintDeviceSP src = m_parent->currentNode()->paintDevice(); GrayMatrix dst = GrayMatrix(rc.width(), GrayCol(rc.height())); detectEdges(rc, src, dst); reduceMatrix(rc, dst, 3, 3, 3, 3); Node startNode, endNode; multiset<Node> openSet; NodeMatrix openMatrix = NodeMatrix(rc.width(), NodeCol(rc.height())); NodeMatrix closedMatrix = NodeMatrix(rc.width(), NodeCol(rc.height())); QPoint tl(rc.topLeft().x(), rc.topLeft().y()); start -= tl; // Relative to the matrix end -= tl; // Relative to the matrix findEdge(start.x(), start.y(), dst, startNode); openMatrix[startNode.col()][startNode.row()] = *openSet.insert(startNode); endNode.setPos(end); while (!openSet.empty()) { Node current = *openSet.begin(); openSet.erase(openSet.begin()); openMatrix[current.col()][current.row()].clear(); QList<Node> successors = current.getNeighbor(dst, endNode); for (QList<Node>::iterator i = successors.begin(); i != successors.end(); i++) { int col = (*i).col(); int row = (*i).row(); if ((*i) == endNode) { while (current.parent() != QPoint(-1, -1)) { it = addPoint(it, tl + current.pos(), false, false, LINEHINT); current = closedMatrix[current.parent().x()][current.parent().y()]; } return; } Node *openNode = &openMatrix[col][row]; if (*openNode != QPoint(-1, -1)) { if (*i > *openNode) continue; else { openSet.erase(qFind(openSet.begin(), openSet.end(), *openNode)); openNode->clear(); // Clear the Node } } Node *closedNode = &closedMatrix[col][row]; if (*closedNode != QPoint(-1, -1)) { if ((*i) > (*closedNode)) continue; else { openMatrix[col][row] = *openSet.insert(*closedNode); closedNode->clear(); // Clear the Node continue; } } openMatrix[col][row] = *openSet.insert(*i); } closedMatrix[current.col()][current.row()] = current; } }