void AnnotationDialog::ListSelect::showContextMenu(const QPoint& pos) { QMenu* menu = new QMenu( this ); QTreeWidgetItem* item = m_treeWidget->itemAt(pos); // click on any item QString title = i18n("No Item Selected"); if ( item ) title = item->text(0); QLabel* label = new QLabel( i18n("<b>%1</b>",title), menu ); label->setAlignment( Qt::AlignCenter ); QWidgetAction* action = new QWidgetAction(menu); action->setDefaultWidget( label ); menu->addAction(action); QAction* deleteAction = menu->addAction( SmallIcon(QString::fromLatin1("edit-delete")), i18n("Delete") ); QAction* renameAction = menu->addAction( i18n("Rename...") ); QLabel* categoryTitle = new QLabel( i18n("<b>Tag Groups</b>"), menu ); categoryTitle->setAlignment( Qt::AlignCenter ); action = new QWidgetAction( menu ); action->setDefaultWidget( categoryTitle ); menu->addAction( action ); // -------------------------------------------------- Add/Remove member group DB::MemberMap& memberMap = DB::ImageDB::instance()->memberMap(); QMenu* members = new QMenu( i18n( "Tag groups" ) ); menu->addMenu( members ); QAction* newCategoryAction = nullptr; if ( item ) { QStringList grps = memberMap.groups( m_category->name() ); for( QStringList::ConstIterator it = grps.constBegin(); it != grps.constEnd(); ++it ) { if (!memberMap.canAddMemberToGroup(m_category->name(), *it, item->text(0))) continue; QAction* action = members->addAction( *it ); action->setCheckable(true); action->setChecked( (bool) memberMap.members( m_category->name(), *it, false ).contains( item->text(0) ) ); action->setData( *it ); } if ( !grps.isEmpty() ) members->addSeparator(); newCategoryAction = members->addAction( i18n("Add this tag to a new tag group..." ) ); } QAction* newSubcategoryAction = menu->addAction( i18n( "Make this tag a tag group and add a tag..." ) ); // -------------------------------------------------- Take item out of category QTreeWidgetItem* parent = item ? item->parent() : nullptr; QAction* takeAction = nullptr; if ( parent ) takeAction = menu->addAction( i18n( "Remove from tag group %1", parent->text(0) ) ); // -------------------------------------------------- sort QLabel* sortTitle = new QLabel( i18n("<b>Sorting</b>") ); sortTitle->setAlignment( Qt::AlignCenter ); action = new QWidgetAction( menu ); action->setDefaultWidget( sortTitle ); menu->addAction( action ); QAction* usageAction = menu->addAction( i18n("Usage") ); QAction* alphaFlatAction = menu->addAction( i18n("Alphabetical (Flat)") ); QAction* alphaTreeAction = menu->addAction( i18n("Alphabetical (Tree)") ); usageAction->setCheckable(true); usageAction->setChecked( Settings::SettingsData::instance()->viewSortType() == Settings::SortLastUse); alphaFlatAction->setCheckable(true); alphaFlatAction->setChecked( Settings::SettingsData::instance()->viewSortType() == Settings::SortAlphaFlat); alphaTreeAction->setCheckable(true); alphaTreeAction->setChecked( Settings::SettingsData::instance()->viewSortType() == Settings::SortAlphaTree); if ( !item ) { deleteAction->setEnabled( false ); renameAction->setEnabled( false ); members->setEnabled( false ); newSubcategoryAction->setEnabled( false ); } // -------------------------------------------------- exec QAction* which = menu->exec( m_treeWidget->mapToGlobal(pos)); if ( which == nullptr ) return; else if ( which == deleteAction ) { Q_ASSERT( item ); int code = KMessageBox::warningContinueCancel( this, i18n("<p>Do you really want to delete \"%1\"?<br/>" "Deleting the item will remove any information " "about it from any image containing the item.</p>" ,title), i18n("Really Delete %1?",item->text(0)), KGuiItem(i18n("&Delete"),QString::fromLatin1("editdelete")) ); if ( code == KMessageBox::Continue ) { if (item->checkState(0) == Qt::Checked and m_positionable) { // An area could be linked against this. We can use positionableTagDeselected // here, as the procedure is the same as if the tag had been deselected. emit positionableTagDeselected(m_category->name(), item->text(0)); } #ifdef HAVE_KFACE // Also delete this tag from the recognition database (if it's there) if (m_positionable) { m_recognizer = FaceManagement::Recognizer::instance(); m_recognizer->deleteTag(m_category->name(), item->text(0)); } #endif m_category->removeItem( item->text(0) ); rePopulate(); } } else if ( which == renameAction ) { Q_ASSERT( item ); bool ok; QString newStr = QInputDialog::getText( this, i18n("Rename Item"), i18n("Enter new name:"), QLineEdit::Normal, item->text(0), &ok ); if ( ok && !newStr.isEmpty() && newStr != item->text(0) ) { int code = KMessageBox::questionYesNo( this, i18n("<p>Do you really want to rename \"%1\" to \"%2\"?<br/>" "Doing so will rename \"%3\" " "on any image containing it.</p>" ,item->text(0),newStr,item->text(0)), i18n("Really Rename %1?",item->text(0)) ); if ( code == KMessageBox::Yes ) { QString oldStr = item->text(0); m_category->renameItem( oldStr, newStr ); bool checked = item->checkState(0) == Qt::Checked; rePopulate(); // rePopuldate doesn't ask the backend if the item should be checked, so we need to do that. checkItem( newStr, checked ); // rename the category image too QString oldFile = m_category->fileForCategoryImage( category(), oldStr ); QString newFile = m_category->fileForCategoryImage( category(), newStr ); KIO::move( QUrl(oldFile), QUrl(newFile) ); if (m_positionable) { #ifdef HAVE_KFACE // Handle the identity name that we probably have in the recognition database m_recognizer = FaceManagement::Recognizer::instance(); m_recognizer->changeIdentityName(m_category->name(), oldStr, newStr); #endif // Also take care of areas that could be linked against this emit positionableTagRenamed(m_category->name(), oldStr, newStr); } } } } else if ( which == usageAction ) { Settings::SettingsData::instance()->setViewSortType( Settings::SortLastUse ); } else if ( which == alphaTreeAction ) { Settings::SettingsData::instance()->setViewSortType( Settings::SortAlphaTree ); } else if ( which == alphaFlatAction ) { Settings::SettingsData::instance()->setViewSortType( Settings::SortAlphaFlat ); } else if ( which == newCategoryAction ) { Q_ASSERT( item ); QString superCategory = QInputDialog::getText( this, i18n("New tag group"), i18n("Name for the new tag group the tag will be added to:") ); if ( superCategory.isEmpty() ) return; memberMap.addGroup( m_category->name(), superCategory ); memberMap.addMemberToGroup( m_category->name(), superCategory, item->text(0) ); //DB::ImageDB::instance()->setMemberMap( memberMap ); rePopulate(); } else if ( which == newSubcategoryAction ) { Q_ASSERT( item ); QString subCategory = QInputDialog::getText( this, i18n("Add a tag"), i18n("Name for the tag to be added to this tag group:") ); if ( subCategory.isEmpty() ) return; m_category->addItem( subCategory ); memberMap.addGroup( m_category->name(), item->text(0) ); memberMap.addMemberToGroup( m_category->name(), item->text(0), subCategory ); //DB::ImageDB::instance()->setMemberMap( memberMap ); if ( isInputMode() ) m_category->addItem( subCategory ); rePopulate(); if ( isInputMode() ) checkItem( subCategory, true ); } else if ( which == takeAction ) { Q_ASSERT( item ); memberMap.removeMemberFromGroup( m_category->name(), parent->text(0), item->text(0) ); rePopulate(); } else { Q_ASSERT( item ); QString checkedItem = which->data().value<QString>(); if ( which->isChecked() ) // choosing the item doesn't check it, so this is the value before. memberMap.addMemberToGroup( m_category->name(), checkedItem, item->text(0) ); else memberMap.removeMemberFromGroup( m_category->name(), checkedItem, item->text(0) ); rePopulate(); } delete menu; }
void ScribusQApp::installTranslators(const QStringList & langs) { static QTranslator *transQt = 0; static QTranslator *trans = 0; if (transQt) { removeTranslator( transQt ); delete transQt; transQt=0; } if (trans) { removeTranslator( trans ); delete trans; trans=0; } transQt = new QTranslator(0); trans = new QTranslator(0); QString path(ScPaths::instance().translationDir()); bool loadedQt = false; bool loadedScribus = false; QString lang; for (QStringList::const_iterator it = langs.constBegin(); it != langs.constEnd() && !loadedScribus; ++it) { lang=(*it); if (lang == "en") { m_GUILang=lang; break; } else { //CB: This might need adjusting for qm files distribution locations if (transQt->load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) loadedQt = true; if (trans->load(QString("scribus." + lang), path)) loadedScribus = true; if (!loadedScribus) { QString altLang(LanguageManager::instance()->getAlternativeAbbrevfromAbbrev(lang)); if (!altLang.isEmpty()) if (trans->load(QString("scribus." + altLang), path)) loadedScribus = true; } } } if (loadedQt) installTranslator(transQt); if (loadedScribus) { installTranslator(trans); m_GUILang=lang; } else if (lang == "en") m_GUILang=lang; /* CB TODO, currently disabled, because its broken broken broken path = ScPaths::instance().pluginDir(); QDir dir(path , "*.*", QDir::Name, QDir::Files | QDir::NoSymLinks); if (dir.exists() && (dir.count() != 0)) { for (uint i = 0; i < dir.count(); ++i) { QFileInfo file(path + dir[i]); if ((file.extension(false).toLower() == "qm") && (file.extension(true).toLower().left(5) == lang)) { trans = new QTranslator(0); trans->load(QString(path + dir[i]), "."); installTranslator(trans); } } }*/ }
void QgsMapToolAddFeature::canvasReleaseEvent( QMouseEvent * e ) { QgsDebugMsg( "entered." ); QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() ); if ( !vlayer ) { notifyNotVectorLayer(); return; } QGis::WkbType layerWKBType = vlayer->wkbType(); QgsVectorDataProvider* provider = vlayer->dataProvider(); if ( !( provider->capabilities() & QgsVectorDataProvider::AddFeatures ) ) { QMessageBox::information( 0, tr( "Layer cannot be added to" ), tr( "The data provider for this layer does not support the addition of features." ) ); return; } if ( !vlayer->isEditable() ) { notifyNotEditableLayer(); return; } // POINT CAPTURING if ( mode() == CapturePoint ) { //check we only use this tool for point/multipoint layers if ( vlayer->geometryType() != QGis::Point ) { QMessageBox::information( 0, tr( "Wrong editing tool" ), tr( "Cannot apply the 'capture point' tool on this vector layer" ) ); return; } QgsPoint idPoint; //point in map coordinates QList<QgsSnappingResult> snapResults; QgsPoint savePoint; //point in layer coordinates if ( mSnapper.snapToBackgroundLayers( e->pos(), snapResults ) == 0 ) { idPoint = snapPointFromResults( snapResults, e->pos() ); try { savePoint = toLayerCoordinates( vlayer, idPoint ); QgsDebugMsg( "savePoint = " + savePoint.toString() ); } catch ( QgsCsException &cse ) { Q_UNUSED( cse ); QMessageBox::information( 0, tr( "Coordinate transform error" ), tr( "Cannot transform the point to the layers coordinate system" ) ); return; } } //only do the rest for provider with feature addition support //note that for the grass provider, this will return false since //grass provider has its own mechanism of feature addition if ( provider->capabilities() & QgsVectorDataProvider::AddFeatures ) { QgsFeature* f = new QgsFeature( 0 ); QgsGeometry *g = 0; if ( layerWKBType == QGis::WKBPoint || layerWKBType == QGis::WKBPoint25D ) { g = QgsGeometry::fromPoint( savePoint ); } else if ( layerWKBType == QGis::WKBMultiPoint || layerWKBType == QGis::WKBMultiPoint25D ) { g = QgsGeometry::fromMultiPoint( QgsMultiPoint() << savePoint ); } f->setGeometry( g ); vlayer->beginEditCommand( tr( "Feature added" ) ); if ( addFeature( vlayer, f ) ) { vlayer->endEditCommand(); } else { delete f; vlayer->destroyEditCommand(); } mCanvas->refresh(); } } else if ( mode() == CaptureLine || mode() == CapturePolygon ) { //check we only use the line tool for line/multiline layers if ( mode() == CaptureLine && vlayer->geometryType() != QGis::Line ) { QMessageBox::information( 0, tr( "Wrong editing tool" ), tr( "Cannot apply the 'capture line' tool on this vector layer" ) ); return; } //check we only use the polygon tool for polygon/multipolygon layers if ( mode() == CapturePolygon && vlayer->geometryType() != QGis::Polygon ) { QMessageBox::information( 0, tr( "Wrong editing tool" ), tr( "Cannot apply the 'capture polygon' tool on this vector layer" ) ); return; } //add point to list and to rubber band int error = addVertex( e->pos() ); if ( error == 1 ) { //current layer is not a vector layer return; } else if ( error == 2 ) { //problem with coordinate transformation QMessageBox::information( 0, tr( "Coordinate transform error" ), tr( "Cannot transform the point to the layers coordinate system" ) ); return; } if ( e->button() == Qt::LeftButton ) { startCapturing(); } else if ( e->button() == Qt::RightButton ) { // End of string //lines: bail out if there are not at least two vertices if ( mode() == CaptureLine && size() < 2 ) { stopCapturing(); return; } //polygons: bail out if there are not at least two vertices if ( mode() == CapturePolygon && size() < 3 ) { stopCapturing(); return; } //create QgsFeature with wkb representation QgsFeature* f = new QgsFeature( 0 ); QgsGeometry *g; if ( mode() == CaptureLine ) { if ( layerWKBType == QGis::WKBLineString || layerWKBType == QGis::WKBLineString25D ) { g = QgsGeometry::fromPolyline( points().toVector() ); } else if ( layerWKBType == QGis::WKBMultiLineString || layerWKBType == QGis::WKBMultiLineString25D ) { g = QgsGeometry::fromMultiPolyline( QgsMultiPolyline() << points().toVector() ); } else { QMessageBox::critical( 0, tr( "Error" ), tr( "Cannot add feature. Unknown WKB type" ) ); stopCapturing(); return; //unknown wkbtype } f->setGeometry( g ); } else // polygon { if ( layerWKBType == QGis::WKBPolygon || layerWKBType == QGis::WKBPolygon25D ) { g = QgsGeometry::fromPolygon( QgsPolygon() << points().toVector() ); } else if ( layerWKBType == QGis::WKBMultiPolygon || layerWKBType == QGis::WKBMultiPolygon25D ) { g = QgsGeometry::fromMultiPolygon( QgsMultiPolygon() << ( QgsPolygon() << points().toVector() ) ); } else { QMessageBox::critical( 0, tr( "Error" ), tr( "Cannot add feature. Unknown WKB type" ) ); stopCapturing(); return; //unknown wkbtype } if ( !g ) { stopCapturing(); delete f; return; // invalid geometry; one possibility is from duplicate points } f->setGeometry( g ); int avoidIntersectionsReturn = f->geometry()->avoidIntersections(); if ( avoidIntersectionsReturn == 1 ) { //not a polygon type. Impossible to get there } #if 0 else if ( avoidIntersectionsReturn == 2 ) //MH120131: disable this error message until there is a better way to cope with the single type / multi type problem { //bail out... QMessageBox::critical( 0, tr( "Error" ), tr( "The feature could not be added because removing the polygon intersections would change the geometry type" ) ); delete f; stopCapturing(); return; } #endif else if ( avoidIntersectionsReturn == 3 ) { QMessageBox::critical( 0, tr( "Error" ), tr( "An error was reported during intersection removal" ) ); } if ( !f->geometry()->asWkb() ) //avoid intersection might have removed the whole geometry { QString reason; if ( avoidIntersectionsReturn != 2 ) { reason = tr( "The feature cannot be added because it's geometry is empty" ); } else { reason = tr( "The feature cannot be added because it's geometry collapsed due to intersection avoidance" ); } QMessageBox::critical( 0, tr( "Error" ), reason ); delete f; stopCapturing(); return; } } vlayer->beginEditCommand( tr( "Feature added" ) ); if ( addFeature( vlayer, f ) ) { //add points to other features to keep topology up-to-date int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); //use always topological editing for avoidIntersection. //Otherwise, no way to guarantee the geometries don't have a small gap in between. QStringList intersectionLayers = QgsProject::instance()->readListEntry( "Digitizing", "/AvoidIntersectionsList" ); bool avoidIntersection = !intersectionLayers.isEmpty(); if ( avoidIntersection ) //try to add topological points also to background layers { QStringList::const_iterator lIt = intersectionLayers.constBegin(); for ( ; lIt != intersectionLayers.constEnd(); ++lIt ) { QgsMapLayer* ml = QgsMapLayerRegistry::instance()->mapLayer( *lIt ); QgsVectorLayer* vl = qobject_cast<QgsVectorLayer*>( ml ); //can only add topological points if background layer is editable... if ( vl && vl->geometryType() == QGis::Polygon && vl->isEditable() ) { vl->addTopologicalPoints( f->geometry() ); } } } else if ( topologicalEditing ) { vlayer->addTopologicalPoints( f->geometry() ); } vlayer->endEditCommand(); } else { delete f; vlayer->destroyEditCommand(); } stopCapturing(); } } }
/** * \class QgsOptions - Set user options and preferences * Constructor */ QgsOptions::QgsOptions( QWidget *parent, Qt::WFlags fl ) : QDialog( parent, fl ) { setupUi( this ); connect( cmbTheme, SIGNAL( activated( const QString& ) ), this, SLOT( themeChanged( const QString& ) ) ); connect( cmbTheme, SIGNAL( highlighted( const QString& ) ), this, SLOT( themeChanged( const QString& ) ) ); connect( cmbTheme, SIGNAL( textChanged( const QString& ) ), this, SLOT( themeChanged( const QString& ) ) ); connect( this, SIGNAL( accepted() ), this, SLOT( saveOptions() ) ); cmbIdentifyMode->addItem( tr( "Current layer" ), 0 ); cmbIdentifyMode->addItem( tr( "Top down, stop at first" ), 1 ); cmbIdentifyMode->addItem( tr( "Top down" ), 2 ); // read the current browser and set it QSettings settings; int identifyMode = settings.value( "/Map/identifyMode", 0 ).toInt(); cmbIdentifyMode->setCurrentIndex( cmbIdentifyMode->findData( identifyMode ) ); cbxAutoFeatureForm->setChecked( settings.value( "/Map/identifyAutoFeatureForm", false ).toBool() ); double identifyValue = settings.value( "/Map/identifyRadius", QGis::DEFAULT_IDENTIFY_RADIUS ).toDouble(); QgsDebugMsg( QString( "Standard Identify radius setting read from settings file: %1" ).arg( identifyValue ) ); if ( identifyValue <= 0.0 ) identifyValue = QGis::DEFAULT_IDENTIFY_RADIUS; spinBoxIdentifyValue->setMinimum( 0.01 ); spinBoxIdentifyValue->setValue( identifyValue ); //local directories to search when looking for an SVG with a given basename QString myPaths = settings.value( "svg/searchPathsForSVG", "" ).toString(); if ( !myPaths.isEmpty() ) { QStringList myPathList = myPaths.split( "|" ); QStringList::const_iterator pathIt = myPathList.constBegin(); for ( ; pathIt != myPathList.constEnd(); ++pathIt ) { QListWidgetItem* newItem = new QListWidgetItem( mListSVGPaths ); newItem->setText( *pathIt ); newItem->setFlags( Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable ); mListSVGPaths->addItem( newItem ); } } //Network timeout mNetworkTimeoutSpinBox->setValue( settings.value( "/qgis/networkAndProxy/networkTimeout", "60000" ).toInt() ); //Web proxy settings grpProxy->setChecked( settings.value( "proxy/proxyEnabled", "0" ).toBool() ); leProxyHost->setText( settings.value( "proxy/proxyHost", "" ).toString() ); leProxyPort->setText( settings.value( "proxy/proxyPort", "" ).toString() ); leProxyUser->setText( settings.value( "proxy/proxyUser", "" ).toString() ); leProxyPassword->setText( settings.value( "proxy/proxyPassword", "" ).toString() ); //available proxy types mProxyTypeComboBox->insertItem( 0, "DefaultProxy" ); mProxyTypeComboBox->insertItem( 1, "Socks5Proxy" ); mProxyTypeComboBox->insertItem( 2, "HttpProxy" ); mProxyTypeComboBox->insertItem( 3, "HttpCachingProxy" ); mProxyTypeComboBox->insertItem( 4, "FtpCachingProxy" ); QString settingProxyType = settings.value( "proxy/proxyType", "DefaultProxy" ).toString(); mProxyTypeComboBox->setCurrentIndex( mProxyTypeComboBox->findText( settingProxyType ) ); //URLs excluded not going through proxies QString proxyExcludedURLs = settings.value( "proxy/proxyExcludedUrls", "" ).toString(); if ( !proxyExcludedURLs.isEmpty() ) { QStringList splittedUrls = proxyExcludedURLs.split( "|" ); QStringList::const_iterator urlIt = splittedUrls.constBegin(); for ( ; urlIt != splittedUrls.constEnd(); ++urlIt ) { QListWidgetItem* newItem = new QListWidgetItem( mExcludeUrlListWidget ); newItem->setText( *urlIt ); newItem->setFlags( Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable ); mExcludeUrlListWidget->addItem( newItem ); } } #if QT_VERSION >= 0x40500 // cache settings QNetworkDiskCache *cache = qobject_cast<QNetworkDiskCache*>( QgsNetworkAccessManager::instance()->cache() ); if ( cache ) { mCacheDirectory->setText( cache->cacheDirectory() ); mCacheSize->setMinimum( 0 ); mCacheSize->setMaximum( std::numeric_limits<int>::max() ); mCacheSize->setSingleStep( 1024 ); QgsDebugMsg( QString( "set cacheSize: %1" ).arg( cache->maximumCacheSize() ) ); mCacheSize->setValue( cache->maximumCacheSize() / 1024 ); } #else grpUrlExclude->setHidden( true ); grpCache->setHidden( true ); #endif //wms search server leWmsSearch->setText( settings.value( "/qgis/WMSSearchUrl", "http://geopole.org/wms/search?search=%1&type=rss" ).toString() ); // set the current theme cmbTheme->setItemText( cmbTheme->currentIndex(), settings.value( "/Themes" ).toString() ); // set the attribute table behaviour cmbAttrTableBehaviour->clear(); cmbAttrTableBehaviour->addItem( tr( "Show all features" ) ); cmbAttrTableBehaviour->addItem( tr( "Show selected features" ) ); cmbAttrTableBehaviour->addItem( tr( "Show features in current canvas" ) ); cmbAttrTableBehaviour->setCurrentIndex( settings.value( "/qgis/attributeTableBehaviour", 0 ).toInt() ); // set the display update threshold spinBoxUpdateThreshold->setValue( settings.value( "/Map/updateThreshold" ).toInt() ); //set the default projection behaviour radio buttongs if ( settings.value( "/Projections/defaultBehaviour" ).toString() == "prompt" ) { radPromptForProjection->setChecked( true ); } else if ( settings.value( "/Projections/defaultBehaviour" ).toString() == "useProject" ) { radUseProjectProjection->setChecked( true ); } else //useGlobal { radUseGlobalProjection->setChecked( true ); } txtGlobalWkt->setText( settings.value( "/Projections/defaultProjectionString", GEOPROJ4 ).toString() ); // populate combo box with ellipsoids getEllipsoidList(); QString myEllipsoidId = settings.value( "/qgis/measure/ellipsoid", "WGS84" ).toString(); cmbEllipsoid->setItemText( cmbEllipsoid->currentIndex(), getEllipsoidName( myEllipsoidId ) ); // Set the units for measuring QString myUnitsTxt = settings.value( "/qgis/measure/displayunits", "meters" ).toString(); if ( myUnitsTxt == "feet" ) { radFeet->setChecked( true ); } else { radMeters->setChecked( true ); } QButtonGroup* angleButtonGroup = new QButtonGroup( this ); angleButtonGroup->addButton( mDegreesRadioButton ); angleButtonGroup->addButton( mRadiansRadioButton ); angleButtonGroup->addButton( mGonRadioButton ); QString myAngleUnitsTxt = settings.value( "/qgis/measure/angleunits", "degrees" ).toString(); if ( myAngleUnitsTxt == "gon" ) { mGonRadioButton->setChecked( true ); } else if ( myAngleUnitsTxt == "radians" ) { mRadiansRadioButton->setChecked( true ); } else //degrees { mDegreesRadioButton->setChecked( true ); } // set decimal places of the measure tool int decimalPlaces = settings.value( "/qgis/measure/decimalplaces", "3" ).toInt(); mDecimalPlacesSpinBox->setRange( 0, 12 ); mDecimalPlacesSpinBox->setValue( decimalPlaces ); // set if base unit of measure tool should be changed bool baseUnit = settings.value( "qgis/measure/keepbaseunit", false ).toBool(); if ( baseUnit == true ) { mKeepBaseUnitCheckBox->setChecked( true ); } else { mKeepBaseUnitCheckBox->setChecked( false ); } // add the themes to the combo box on the option dialog QDir myThemeDir( ":/images/themes/" ); myThemeDir.setFilter( QDir::Dirs ); QStringList myDirList = myThemeDir.entryList( QStringList( "*" ) ); cmbTheme->clear(); for ( int i = 0; i < myDirList.count(); i++ ) { if ( myDirList[i] != "." && myDirList[i] != ".." ) { cmbTheme->addItem( myDirList[i] ); } } // set the theme combo cmbTheme->setCurrentIndex( cmbTheme->findText( settings.value( "/Themes", "default" ).toString() ) ); //set the state of the checkboxes chkAntiAliasing->setChecked( settings.value( "/qgis/enable_anti_aliasing", false ).toBool() ); chkUseRenderCaching->setChecked( settings.value( "/qgis/enable_render_caching", false ).toBool() ); chkUseSymbologyNG->setChecked( settings.value( "/qgis/use_symbology_ng", false ).toBool() ); // Slightly awkard here at the settings value is true to use QImage, // but the checkbox is true to use QPixmap chkUseQPixmap->setChecked( !( settings.value( "/qgis/use_qimage_to_render", true ).toBool() ) ); chkAddedVisibility->setChecked( settings.value( "/qgis/new_layers_visible", true ).toBool() ); cbxLegendClassifiers->setChecked( settings.value( "/qgis/showLegendClassifiers", false ).toBool() ); cbxHideSplash->setChecked( settings.value( "/qgis/hideSplash", false ).toBool() ); cbxAttributeTableDocked->setChecked( settings.value( "/qgis/dockAttributeTable", false ).toBool() ); cbxIdentifyResultsDocked->setChecked( settings.value( "/qgis/dockIdentifyResults", false ).toBool() ); cbxSnappingOptionsDocked->setChecked( settings.value( "/qgis/dockSnapping", false ).toBool() ); cbxAddPostgisDC->setChecked( settings.value( "/qgis/addPostgisDC", false ).toBool() ); cbxAddNewLayersToCurrentGroup->setChecked( settings.value( "/qgis/addNewLayersToCurrentGroup", false ).toBool() ); cbxCreateRasterLegendIcons->setChecked( settings.value( "/qgis/createRasterLegendIcons", true ).toBool() ); //set the color for selections int myRed = settings.value( "/qgis/default_selection_color_red", 255 ).toInt(); int myGreen = settings.value( "/qgis/default_selection_color_green", 255 ).toInt(); int myBlue = settings.value( "/qgis/default_selection_color_blue", 0 ).toInt(); int myAlpha = settings.value( "/qgis/default_selection_color_alpha", 255 ).toInt(); pbnSelectionColor->setColor( QColor( myRed, myGreen, myBlue, myAlpha ) ); //set the default color for canvas background myRed = settings.value( "/qgis/default_canvas_color_red", 255 ).toInt(); myGreen = settings.value( "/qgis/default_canvas_color_green", 255 ).toInt(); myBlue = settings.value( "/qgis/default_canvas_color_blue", 255 ).toInt(); pbnCanvasColor->setColor( QColor( myRed, myGreen, myBlue ) ); // set the default color for the measure tool myRed = settings.value( "/qgis/default_measure_color_red", 180 ).toInt(); myGreen = settings.value( "/qgis/default_measure_color_green", 180 ).toInt(); myBlue = settings.value( "/qgis/default_measure_color_blue", 180 ).toInt(); pbnMeasureColor->setColor( QColor( myRed, myGreen, myBlue ) ); capitaliseCheckBox->setChecked( settings.value( "qgis/capitaliseLayerName", QVariant( false ) ).toBool() ); chbAskToSaveProjectChanges->setChecked( settings.value( "qgis/askToSaveProjectChanges", QVariant( true ) ).toBool() ); chbWarnOldProjectVersion->setChecked( settings.value( "/qgis/warnOldProjectVersion", QVariant( true ) ).toBool() ); cmbWheelAction->setCurrentIndex( settings.value( "/qgis/wheel_action", 0 ).toInt() ); spinZoomFactor->setValue( settings.value( "/qgis/zoom_factor", 2 ).toDouble() ); // // Locale settings // QString mySystemLocale = QLocale::system().name(); lblSystemLocale->setText( tr( "Detected active locale on your system: %1" ).arg( mySystemLocale ) ); QString myUserLocale = settings.value( "locale/userLocale", "" ).toString(); QStringList myI18nList = i18nList(); cboLocale->addItems( myI18nList ); if ( myI18nList.contains( myUserLocale ) ) { cboLocale->setCurrentIndex( myI18nList.indexOf( myUserLocale ) ); } bool myLocaleOverrideFlag = settings.value( "locale/overrideFlag", false ).toBool(); grpLocale->setChecked( myLocaleOverrideFlag ); //set elements in digitizing tab mLineWidthSpinBox->setValue( settings.value( "/qgis/digitizing/line_width", 1 ).toInt() ); QColor digitizingColor; myRed = settings.value( "/qgis/digitizing/line_color_red", 255 ).toInt(); myGreen = settings.value( "/qgis/digitizing/line_color_green", 0 ).toInt(); myBlue = settings.value( "/qgis/digitizing/line_color_blue", 0 ).toInt(); mLineColorToolButton->setColor( QColor( myRed, myGreen, myBlue ) ); //default snap mode mDefaultSnapModeComboBox->insertItem( 0, tr( "To vertex" ), "to vertex" ); mDefaultSnapModeComboBox->insertItem( 1, tr( "To segment" ), "to segment" ); mDefaultSnapModeComboBox->insertItem( 2, tr( "To vertex and segment" ), "to vertex and segment" ); QString defaultSnapString = settings.value( "/qgis/digitizing/default_snap_mode", "to vertex" ).toString(); mDefaultSnapModeComboBox->setCurrentIndex( mDefaultSnapModeComboBox->findData( defaultSnapString ) ); mDefaultSnappingToleranceSpinBox->setValue( settings.value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble() ); mSearchRadiusVertexEditSpinBox->setValue( settings.value( "/qgis/digitizing/search_radius_vertex_edit", 10 ).toDouble() ); int index; if ( settings.value( "/qgis/digitizing/default_snapping_tolerance_unit", 0 ).toInt() == QgsTolerance::MapUnits ) { index = mDefaultSnappingToleranceComboBox->findText( tr( "map units" ) ); } else { index = mDefaultSnappingToleranceComboBox->findText( tr( "pixels" ) ); } mDefaultSnappingToleranceComboBox->setCurrentIndex( index ); if ( settings.value( "/qgis/digitizing/search_radius_vertex_edit_unit", QgsTolerance::Pixels ).toInt() == QgsTolerance::MapUnits ) { index = mSearchRadiusVertexEditComboBox->findText( tr( "map units" ) ); } else { index = mSearchRadiusVertexEditComboBox->findText( tr( "pixels" ) ); } mSearchRadiusVertexEditComboBox->setCurrentIndex( index ); //vertex marker mMarkersOnlyForSelectedCheckBox->setChecked( settings.value( "/qgis/digitizing/marker_only_for_selected", false ).toBool() ); mMarkerStyleComboBox->addItem( tr( "Semi transparent circle" ) ); mMarkerStyleComboBox->addItem( tr( "Cross" ) ); mMarkerStyleComboBox->addItem( tr( "None" ) ); QString markerStyle = settings.value( "/qgis/digitizing/marker_style", "Cross" ).toString(); if ( markerStyle == "SemiTransparentCircle" ) { mMarkerStyleComboBox->setCurrentIndex( mMarkerStyleComboBox->findText( tr( "Semi transparent circle" ) ) ); } else if ( markerStyle == "Cross" ) { mMarkerStyleComboBox->setCurrentIndex( mMarkerStyleComboBox->findText( tr( "Cross" ) ) ); } else if ( markerStyle == "None" ) { mMarkerStyleComboBox->setCurrentIndex( mMarkerStyleComboBox->findText( tr( "None" ) ) ); } mMarkerSizeSpinBox->setValue( settings.value( "/qgis/digitizing/marker_size", 3 ).toInt() ); chkReuseLastValues->setChecked( settings.value( "/qgis/digitizing/reuseLastValues", false ).toBool() ); chkDisableAttributeValuesDlg->setChecked( settings.value( "/qgis/digitizing/disable_enter_attribute_values_dialog", false ).toBool() ); #ifdef Q_WS_MAC //MH: disable incremental update on Mac for now to avoid problems with resizing groupBox_5->setEnabled( false ); #endif //Q_WS_MAC //overlay placement algorithm mOverlayAlgorithmComboBox->insertItem( 0, tr( "Central point (fastest)" ) ); mOverlayAlgorithmComboBox->insertItem( 1, tr( "Chain (fast)" ) ); mOverlayAlgorithmComboBox->insertItem( 2, tr( "Popmusic tabu chain (slow)" ) ); mOverlayAlgorithmComboBox->insertItem( 3, tr( "Popmusic tabu (slow)" ) ); mOverlayAlgorithmComboBox->insertItem( 4, tr( "Popmusic chain (very slow)" ) ); QString overlayAlgorithmString = settings.value( "qgis/overlayPlacementAlgorithm", "Central point" ).toString(); if ( overlayAlgorithmString == "Chain" ) { mOverlayAlgorithmComboBox->setCurrentIndex( 1 ); } else if ( overlayAlgorithmString == "Popmusic tabu chain" ) { mOverlayAlgorithmComboBox->setCurrentIndex( 2 ); } else if ( overlayAlgorithmString == "Popmusic tabu" ) { mOverlayAlgorithmComboBox->setCurrentIndex( 3 ); } else if ( overlayAlgorithmString == "Popmusic chain" ) { mOverlayAlgorithmComboBox->setCurrentIndex( 4 ); } else { mOverlayAlgorithmComboBox->setCurrentIndex( 0 ); } //default is central point restoreGeometry( settings.value( "/Windows/Options/geometry" ).toByteArray() ); tabWidget->setCurrentIndex( settings.value( "/Windows/Options/row" ).toInt() ); }
QByteArray VCardParser::createVCards( const VCard::List &list ) { QByteArray text; QByteArray textLine; QString encodingType; QStringList idents; QStringList params; QStringList values; QStringList::ConstIterator identIt; QStringList::Iterator paramIt; QStringList::ConstIterator valueIt; VCardLine::List lines; VCardLine::List::ConstIterator lineIt; VCard::List::ConstIterator cardIt; bool hasEncoding; text.reserve( list.size() * 300 ); // reserve memory to be more efficient // iterate over the cards VCard::List::ConstIterator listEnd( list.end() ); for ( cardIt = list.begin(); cardIt != listEnd; ++cardIt ) { text.append( "BEGIN:VCARD\r\n" ); idents = ( *cardIt ).identifiers(); for ( identIt = idents.constBegin(); identIt != idents.constEnd(); ++identIt ) { lines = ( *cardIt ).lines( ( *identIt ) ); // iterate over the lines for ( lineIt = lines.constBegin(); lineIt != lines.constEnd(); ++lineIt ) { QVariant val = ( *lineIt ).value(); if ( val.isValid() ) { if ( ( *lineIt ).hasGroup() ) { textLine = ( *lineIt ).group().toLatin1() + '.' + ( *lineIt ).identifier().toLatin1(); } else { textLine = ( *lineIt ).identifier().toLatin1(); } params = ( *lineIt ).parameterList(); hasEncoding = false; if ( !params.isEmpty() ) { // we have parameters for ( paramIt = params.begin(); paramIt != params.end(); ++paramIt ) { if ( ( *paramIt ) == QLatin1String( "encoding" ) ) { hasEncoding = true; encodingType = ( *lineIt ).parameter( QLatin1String( "encoding" ) ).toLower(); } values = ( *lineIt ).parameters( *paramIt ); for ( valueIt = values.constBegin(); valueIt != values.constEnd(); ++valueIt ) { textLine.append( ';' + ( *paramIt ).toLatin1().toUpper() ); if ( !( *valueIt ).isEmpty() ) { textLine.append( '=' + ( *valueIt ).toLatin1() ); } } } } QByteArray input, output; // handle charset if ( ( *lineIt ).parameterList().contains( QLatin1String( "charset" ) ) ) { // have to convert the data const QString value = ( *lineIt ).value().toString(); QTextCodec *codec = QTextCodec::codecForName( ( *lineIt ).parameter( QLatin1String( "charset" ) ).toLatin1() ); if ( codec ) { input = codec->fromUnicode( value ); } else { input = value.toUtf8(); } } else if ( ( *lineIt ).value().type() == QVariant::ByteArray ) { input = ( *lineIt ).value().toByteArray(); } else { input = ( *lineIt ).value().toString().toUtf8(); } // handle encoding if ( hasEncoding ) { // have to encode the data if ( encodingType == QLatin1String( "b" ) ) { output = input.toBase64(); } else if ( encodingType == QLatin1String( "quoted-printable" ) ) { KCodecs::quotedPrintableEncode( input, output, false ); } } else { output = input; } addEscapes( output, ( *lineIt ).identifier() == QLatin1String( "CATEGORIES" ) ); if ( !output.isEmpty() ) { textLine.append( ':' + output ); if ( textLine.length() > FOLD_WIDTH ) { // we have to fold the line for ( int i = 0; i <= ( textLine.length() / FOLD_WIDTH ); ++i ) { text.append( ( i == 0 ? "" : " " ) + textLine.mid( i * FOLD_WIDTH, FOLD_WIDTH ) + "\r\n" ); } } else { text.append( textLine + "\r\n" ); } } } } } text.append( "END:VCARD\r\n" ); text.append( "\r\n" ); } return text; }
void VPiano::readSettings() { QSettings settings; settings.beginGroup(QSTR_WINDOW); restoreGeometry(settings.value(QSTR_GEOMETRY).toByteArray()); restoreState(settings.value(QSTR_STATE).toByteArray()); settings.endGroup(); settings.beginGroup(QSTR_PREFERENCES); int in_channel = settings.value(QSTR_INCHANNEL, 0).toInt(); int out_channel = settings.value(QSTR_OUTCHANNEL, 0).toInt(); int velocity = settings.value(QSTR_VELOCITY, 100).toInt(); int base_octave = settings.value(QSTR_BASEOCTAVE, 3).toInt(); int num_octaves = settings.value(QSTR_NUMOCTAVES, 5).toInt(); QString insFileName = settings.value(QSTR_INSTRUMENTSDEFINITION).toString(); QString insName = settings.value(QSTR_INSTRUMENTNAME).toString(); QColor defColor = QApplication::palette().highlight().color(); QColor keyColor = settings.value(QSTR_KEYPRESSEDCOLOR, defColor).value<QColor>(); bool grabKb = settings.value(QSTR_GRABKB, false).toBool(); settings.endGroup(); dlgPreferences.setInChannel(in_channel); dlgPreferences.setOutChannel(out_channel); dlgPreferences.setVelocity(velocity); dlgPreferences.setBaseOctave(base_octave); dlgPreferences.setNumOctaves(num_octaves); dlgPreferences.setKeyPressedColor(keyColor); dlgPreferences.setGrabKeyboard(grabKb); if (!insFileName.isEmpty()) { dlgPreferences.setInstrumentsFileName(insFileName); if (!insName.isEmpty()) { dlgPreferences.setInstrumentName(insName); } } settings.beginGroup(QSTR_CONNECTIONS); bool inEnabled = settings.value(QSTR_INENABLED, true).toBool(); bool thruEnabled = settings.value(QSTR_THRUENABLED, false).toBool(); QString in_port = settings.value(QSTR_INPORT).toString(); QString out_port = settings.value(QSTR_OUTPORT).toString(); settings.endGroup(); if (m_midiin == NULL) { dlgMidiSetup.inputNotAvailable(); } else { dlgMidiSetup.setInputEnabled(inEnabled); dlgMidiSetup.setThruEnabled(thruEnabled); dlgMidiSetup.setCurrentInput(in_port); } dlgMidiSetup.setCurrentOutput(out_port); settings.beginGroup(QSTR_KEYBOARD); QString mapFile = settings.value(QSTR_MAPFILE, QSTR_DEFAULT).toString(); settings.endGroup(); settings.beginGroup(QSTR_INSTRUMENT); m_lastBank = settings.value(QSTR_BANK, -1).toInt(); m_lastProg = settings.value(QSTR_PROGRAM, 0).toInt(); m_lastCtl = settings.value(QSTR_CONTROLLER, 1).toInt(); settings.endGroup(); settings.beginGroup(QSTR_CONTROLLERS); QStringList keys = settings.allKeys(); QStringList::const_iterator it; for(it = keys.constBegin(); it != keys.constEnd(); ++it) { int ctl = (*it).toInt(); int val = settings.value(*it, 0).toInt(); m_ctlSettings[ctl] = val; } settings.endGroup(); if (!mapFile.isEmpty() && (mapFile != QSTR_DEFAULT)) { QString msg = ui.pianokeybd->getKeyboardMap()->loadFromXMLFile(mapFile); ui.statusBar->showMessage(msg); } }
bool Directory::addItems(const QString & path ) { QDir thisDir( path ); if( !thisDir.isReadable() ) { return false; } treeWidget()->setUpdatesEnabled( false ); bool added_something = false; QStringList files = thisDir.entryList( QDir::Dirs, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' ) { bool orphan = true; for( int i = 0; i < childCount(); ++i ) { Directory * d = dynamic_cast<Directory *>( child( i ) ); if( d == NULL || cur_file < d->text( 0 ) ) { insertChild( i, new Directory( cur_file, path, m_filter ) ); orphan = false; m_dirCount++; //recurse for each dir addItems( path + cur_file + QDir::separator() ); break; } else if( cur_file == d->text( 0 ) ) { d->addDirectory( path ); orphan = false; break; } } if( orphan ) { addChild( new Directory( cur_file, path, m_filter ) ); m_dirCount++; } added_something = true; } } QList<QTreeWidgetItem*> items; files = thisDir.entryList( QDir::Files, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' && thisDir.match( m_filter, cur_file.toLower() ) ) { items << new FileItem( cur_file, path ); added_something = true; } } addChildren( items ); treeWidget()->setUpdatesEnabled( true ); return added_something; }
void CollectionScanner::scanFiles( const QStringList& entries ) { typedef QPair<QString, QString> CoverBundle; QStringList validImages; validImages << "jpg" << "png" << "gif" << "jpeg" << "bmp"; QStringList validPlaylists; validPlaylists << "m3u" << "pls"; QList<CoverBundle> covers; QStringList images; int itemCount = 0; for( QStringList::ConstIterator it = entries.constBegin(), end = entries.constEnd(); it != end; ++it ) { const QString path = *it; const QString ext = extension( path ); const QString dir = directory( path ); itemCount++; // Write path to logfile if( !m_logfile.isEmpty() ) { QFile log( m_logfile ); if( log.open( QIODevice::WriteOnly ) ) { QByteArray cPath = path.toUtf8(); log.write( cPath, cPath.length() ); log.close(); } } if( validImages.contains( ext ) ) images += path; else if( m_importPlaylists && validPlaylists.contains( ext ) ) { AttributeHash attributes; if( m_batch && !m_rpath.isEmpty() ) { QString rpath = path; rpath.remove( QDir::cleanPath( QDir::currentPath() ) ); rpath.prepend( QDir::cleanPath( m_rpath + '/' ) ); attributes["path"] = rpath; } else attributes["path"] = path; writeElement( "playlist", attributes ); } else { //FIXME: PORT 2.0 // QList<EmbeddedImage> images; const AttributeHash attributes = readTags( path ); if( !attributes.empty() ) { writeElement( "tags", attributes ); CoverBundle cover( attributes["artist"], attributes["album"] ); if( !covers.contains( cover ) ) covers += cover; //FIXME: PORT 2.0 // foreach( EmbeddedImage image, images ) // { // AttributeHash attributes; // if( m_batch && !m_rpath.isEmpty() ) // { // QString rpath = path; // rpath.remove( QDir::cleanPath( QDir::currentPath() ) ); // rpath.prepend( QDir::cleanPath( m_rpath + '/' ) ); // attributes["path"] = rpath; // } // else // attributes["path"] = path; // attributes["hash"] = image.hash(); // attributes["description"] = image.description(); // writeElement( "embed", attributes ); // } } } // Update Compilation-flag, when this is the last loop-run // or we're going to switch to another dir in the next run QStringList::const_iterator itTemp( it ); ++itTemp; if( path == entries.last() || dir != directory( *itTemp ) ) { // we entered the next directory foreach( const QString &imagePath, images ) { // Serialize CoverBundle list with AMAROK_MAGIC as separator QString string; for( QList<CoverBundle>::ConstIterator it2 = covers.begin(); it2 != covers.end(); ++it2 ) { string += ( string.isEmpty() ? "" : "AMAROK_MAGIC" ) + (*it2).first + "AMAROK_MAGIC" + (*it2).second; } AttributeHash attributes; if( m_batch && !m_rpath.isEmpty() ) { QString rpath = imagePath; rpath.remove( QDir::cleanPath( QDir::currentPath() ) ); rpath.prepend( QDir::cleanPath( m_rpath + '/' ) ); attributes["path"] = rpath; } else attributes["path"] = imagePath; attributes["list"] = string; writeElement( "image", attributes ); } AttributeHash attributes; if( m_batch && !m_rpath.isEmpty() ) { QString rdir = dir; rdir.remove( QDir::cleanPath( QDir::currentPath() ) ); rdir.prepend( QDir::cleanPath( m_rpath + '/' ) ); attributes["path"] = rdir; } else attributes["path"] = dir; writeElement( "compilation", attributes ); // clear now because we've processed them covers.clear(); images.clear(); }
/** * Start fitting process. */ void MuonSequentialFitDialog::startFit() { if ( m_state != Stopped ) throw std::runtime_error("Couln't start: already running"); setState(Preparing); // Explicitly run the file search. This might be needed when Start is clicked straigh after // editing the run box. In that case, lost focus event might not be processed yet and search // might not have been started yet. Otherwise, search is not done as the widget sees that it // has not been changed. Taken from LoadDialog.cpp:124. m_ui.runs->findFiles(); // Wait for file search to finish. while ( m_ui.runs->isSearching() ) { QApplication::processEvents(); } // To process events from the finished thread QApplication::processEvents(); // Validate input fields if ( ! isInputValid() ) { QMessageBox::critical(this, "Input is not valid", "One or more input fields are invalid.\n\nInvalid fields are marked with a '*'."); setState(Stopped); return; } QStringList runFilenames = m_ui.runs->getFilenames(); const std::string label = m_ui.labelInput->text().toStdString(); const std::string labelGroupName = SEQUENTIAL_PREFIX + label; AnalysisDataServiceImpl& ads = AnalysisDataService::Instance(); if ( ads.doesExist(labelGroupName) ) { QMessageBox::StandardButton answer = QMessageBox::question(this, "Label already exists", "Label you specified was used for one of the previous fits. Do you want to overwrite it?", QMessageBox::Yes | QMessageBox::Cancel); if ( answer != QMessageBox::Yes ) { setState(Stopped); return; } ads.deepRemoveGroup(labelGroupName); } // Create a group for label ads.add(labelGroupName, boost::make_shared<WorkspaceGroup>()); // Tell progress bar how many iterations we will need to make and reset it m_ui.progress->setRange( 0, runFilenames.size() ); m_ui.progress->setFormat("%p%"); m_ui.progress->setValue(0); // Clear diagnosis table for new fit m_ui.diagnosisTable->setRowCount(0); // Get fit function as specified by user in the fit browser IFunction_sptr fitFunction = FunctionFactory::Instance().createInitialized( m_fitPropBrowser->getFittingFunction()->asString() ); // Whether we should use initial function for every fit bool useInitFitFunction = (m_ui.paramTypeGroup->checkedButton() == m_ui.paramTypeInitial); setState(Running); m_stopRequested = false; for ( auto fileIt = runFilenames.constBegin(); fileIt != runFilenames.constEnd(); ++fileIt ) { // Process events (so that Stop button press is processed) QApplication::processEvents(); // Stop if requested by user if ( m_stopRequested ) break; MatrixWorkspace_sptr ws; auto load = boost::dynamic_pointer_cast<AlgorithmProxy>( AlgorithmManager::Instance().create("MuonLoad") ); load->setChild(true); load->setRethrows(true); load->copyPropertiesFrom(*m_loadAlg); try { load->initialize(); load->setPropertyValue( "Filename", fileIt->toStdString() ); load->setPropertyValue( "OutputWorkspace", "__YouDontSeeMeIAmNinja" ); // Is not used if ( m_fitPropBrowser->rawData() ) // TODO: or vice verca? load->setPropertyValue( "RebinParams", "" ); load->execute(); ws = load->getProperty("OutputWorkspace"); } catch(...) { QMessageBox::critical(this, "Loading failed", "Unable to load one of the files.\n\nCheck log for details"); break; } const std::string runTitle = getRunTitle(ws); const std::string wsBaseName = labelGroupName + "_" + runTitle; IFunction_sptr functionToFit; if ( useInitFitFunction ) // Create a copy so that the original function is not changed functionToFit = FunctionFactory::Instance().createInitialized( fitFunction->asString() ); else // Use the same function over and over, so that previous fitted params are used for the next fit functionToFit = fitFunction; IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit"); fit->setRethrows(true); try { // Set function. Gets updated when fit is done. fit->setProperty("Function", functionToFit); fit->setProperty("InputWorkspace", ws); fit->setProperty("Output", wsBaseName); // We should have one spectra only in the workspace, so use the first one. fit->setProperty("WorkspaceIndex", 0); // Various properties from the fit prop. browser fit->setProperty("StartX", m_fitPropBrowser->startX()); fit->setProperty("EndX", m_fitPropBrowser->endX()); fit->setProperty("Minimizer", m_fitPropBrowser->minimizer()); fit->setProperty("CostFunction", m_fitPropBrowser->costFunction()); fit->execute(); } catch(...) { QMessageBox::critical(this, "Fitting failed", "Unable to fit one of the files.\n\nCheck log for details"); break; } // Make sure created fit workspaces end-up in the group // TODO: this really should use loop ads.addToGroup(labelGroupName, wsBaseName + "_NormalisedCovarianceMatrix"); ads.addToGroup(labelGroupName, wsBaseName + "_Parameters"); ads.addToGroup(labelGroupName, wsBaseName + "_Workspace"); // Copy log values auto fitWs = ads.retrieveWS<MatrixWorkspace>(wsBaseName + "_Workspace"); fitWs->copyExperimentInfoFrom(ws.get()); // Add information about the fit to the diagnosis table addDiagnosisEntry(runTitle, fit->getProperty("OutputChi2OverDof"), functionToFit); // Update progress m_ui.progress->setFormat("%p% - " + QString::fromStdString(runTitle) ); m_ui.progress->setValue( m_ui.progress->value() + 1 ); } setState(Stopped); }
int main(int argc, char **argv) { QApplication app(argc, argv, true); QTranslator custranldr; QTranslator translator; QString tnapplang; QString tnappcoun; QString clangcode = ""; QStringList allappargs = app.arguments(); QList<QPair<QString, QString> > oppairs; for (QList<QString>::const_iterator i = allappargs.constBegin(); i < allappargs.constEnd(); ++i) { if (i->count('=') == 1) oppairs.append(QPair<QString, QString>(i->section('=', 0, 0).simplified(), i->section('=',1, 1).simplified())); } for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i) { if (i->first.contains("lang", Qt::CaseInsensitive)) { clangcode = i->second; tnapplang = clangcode.left(2); if (clangcode.contains('_') && clangcode.size() == 5) { tnappcoun = clangcode.section('_', -1, -1); } break; } } if (clangcode.isEmpty()) { clangcode = QLocale::system().name(); tnapplang = clangcode.left(2); if (clangcode.contains('_') && clangcode.size() == 5) { tnappcoun = clangcode.section('_', -1, -1); } } QDir applocdir(app.applicationDirPath()); QStringList applocfiles = applocdir.entryList(QStringList() << "*.qm", QDir::Files); if (!applocfiles.isEmpty()) { QString custqmfilepath = applocfiles.at(0); if (!applocfiles.filter("unetbootin").isEmpty()) { custqmfilepath = applocfiles.filter("unetbootin").at(0); if (!applocfiles.filter("unetbootin").filter(tnapplang).isEmpty()) { custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).at(0); if (!tnappcoun.isEmpty() && !applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).isEmpty()) custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).at(0); } } if (custranldr.load(custqmfilepath, app.applicationDirPath())) app.installTranslator(&custranldr); } if (!tnappcoun.isEmpty() && QFile::exists(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun)) && translator.load(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (!tnappcoun.isEmpty() && QFile::exists(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (!tnappcoun.isEmpty() && QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun))) { app.installTranslator(&translator); } else if (QFile::exists(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang)) && translator.load(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang))) { app.installTranslator(&translator); } else if (QFile::exists(QString(":/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString(":/unetbootin_%1.qm").arg(tnapplang))) { app.installTranslator(&translator); } else if (QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang))) { app.installTranslator(&translator); } else { tnapplang = "en"; tnappcoun = "US"; clangcode = "en_US"; } app.installTranslator(&translator); if (QObject::tr("LeftToRight") == "RightToLeft") app.setLayoutDirection(Qt::RightToLeft); #ifdef Q_OS_UNIX bool disabledrootcheck = false; for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i) { if (i->first.contains("rootcheck", Qt::CaseInsensitive)) { if (i->second.contains('n', Qt::CaseInsensitive)) disabledrootcheck = true; break; } } if (!disabledrootcheck) { QProcess whoamip; whoamip.start("whoami"); whoamip.waitForFinished(); if (QString(whoamip.readAll()).remove("\r").remove("\n") != "root") { QString argsconc = ""; for (int i = 1; i < allappargs.size(); ++i) { argsconc += QString("\"%1\" ").arg(allappargs.at(i)); } argsconc += "'rootcheck=no'"; #ifdef Q_OS_LINUX QString gksulocation = checkforgraphicalsu("gksu"); if (gksulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesulocation = checkforgraphicalsu("kdesu"); if (kdesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString gnomesulocation = checkforgraphicalsu("gnomesu"); if (gnomesulocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QString kdesudolocation = checkforgraphicalsu("kdesudo"); if (kdesudolocation != "REQCNOTFOUND") { QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc)); return 0; } QMessageBox rootmsgb; rootmsgb.setIcon(QMessageBox::Warning); rootmsgb.setWindowTitle(uninstaller::tr("Must run as root")); rootmsgb.setTextFormat(Qt::RichText); rootmsgb.setText(uninstaller::tr("%2 must be run as root. Close it, and re-run using either:<br/><b>sudo %1</b><br/>or:<br/><b>su - -c '%1'</b>").arg(app.applicationFilePath()).arg(UNETBOOTINB)); rootmsgb.setStandardButtons(QMessageBox::Ok); switch (rootmsgb.exec()) { case QMessageBox::Ok: break; default: break; } #endif #ifdef Q_OS_MAC QProcess osascriptProc; osascriptProc.start("osascript"); osascriptProc.write(QString("do shell script \""+app.applicationFilePath()+"\" with administrator privileges\n").toAscii().data()); osascriptProc.closeWriteChannel(); osascriptProc.waitForFinished(-1); return 0; #endif } } #endif #ifdef Q_OS_WIN32 QSettings chkinst("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\UNetbootin", QSettings::NativeFormat); #endif #ifdef Q_OS_LINUX QSettings chkinst(QSettings::SystemScope, "UNetbootin"); #endif #ifndef Q_OS_MAC if (chkinst.contains("Location")) { QMessageBox uninstmsgb; uninstmsgb.setIcon(QMessageBox::Information); uninstmsgb.setWindowTitle(uninstaller::tr("%1 Uninstaller").arg(UNETBOOTINB)); uninstmsgb.setText(uninstaller::tr("%1 is currently installed. Remove the existing version?").arg(UNETBOOTINB)); uninstmsgb.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); switch (uninstmsgb.exec()) { case QMessageBox::Ok: { ubnUninst(); } case QMessageBox::Cancel: break; default: break; } return 0; } #endif unetbootin unetbootin; unetbootin.appNlang = tnapplang; unetbootin.appDir = QDir::toNativeSeparators(QString("%1/").arg(app.applicationDirPath())); unetbootin.appLoc = app.applicationFilePath(); QIcon icon; icon.addFile(":/unetbootin_16.png", QSize(16,16)); icon.addFile(":/unetbootin_22.png", QSize(22,22)); icon.addFile(":/unetbootin_24.png", QSize(24,24)); icon.addFile(":/unetbootin_32.png", QSize(32,32)); icon.addFile(":/unetbootin_48.png", QSize(48,48)); #ifdef Q_OS_LINUX icon.addFile("/usr/share/pixmaps/unetbootin.png"); #endif unetbootin.setWindowIcon(icon); QObject::connect(&app, SIGNAL(lastWindowClosed()), &unetbootin, SLOT(killApplication())); bool automate = unetbootin.ubninitialize(oppairs); unetbootin.show(); if (automate) QTimer::singleShot(0, &unetbootin, SLOT(on_okbutton_clicked())); return app.exec(); }
int main(int argc, char *argv[]) { FillData fill_data; int fromfile_id = 1; int fromfile_offset = 0; QString fromfile_name; bool from_file = false; bool mark_repeats = true; bool usingDataDirect = false; bool grab_data = true; bool export_iconmap = false; bool import_iconmap = false; bool reset_iconmap = false; bool reset_iconmap_icons = false; QString import_icon_data_filename("iconmap.xml"); QString export_icon_data_filename("iconmap.xml"); bool update_icon_data = false; bool from_dd_file = false; int sourceid = -1; QString fromddfile_lineupid; MythFillDatabaseCommandLineParser cmdline; if (!cmdline.Parse(argc, argv)) { cmdline.PrintHelp(); return GENERIC_EXIT_INVALID_CMDLINE; } if (cmdline.toBool("showhelp")) { cmdline.PrintHelp(); return GENERIC_EXIT_OK; } if (cmdline.toBool("showversion")) { cmdline.PrintVersion(); return GENERIC_EXIT_OK; } QCoreApplication a(argc, argv); QCoreApplication::setApplicationName(MYTH_APPNAME_MYTHFILLDATABASE); myth_nice(19); int retval; if ((retval = cmdline.ConfigureLogging()) != GENERIC_EXIT_OK) return retval; if (cmdline.toBool("manual")) { cout << "###\n"; cout << "### Running in manual channel configuration mode.\n"; cout << "### This will ask you questions about every channel.\n"; cout << "###\n"; fill_data.chan_data.m_interactive = true; } if (cmdline.toBool("update")) { if (cmdline.toBool("manual")) { cerr << "--update and --manual cannot be used simultaneously" << endl; return GENERIC_EXIT_INVALID_CMDLINE; } fill_data.chan_data.m_nonUSUpdating = true; } if (cmdline.toBool("preset")) { cout << "###\n"; cout << "### Running in preset channel configuration mode.\n"; cout << "### This will assign channel "; cout << "preset numbers to every channel.\n"; cout << "###\n"; fill_data.chan_data.m_channelPreset = true; } if (cmdline.toBool("file")) { // manual file mode if (!cmdline.toBool("sourceid") || !cmdline.toBool("xmlfile")) { cerr << "The --file option must be used in combination" << endl << "with both --sourceid and --xmlfile." << endl; return GENERIC_EXIT_INVALID_CMDLINE; } fromfile_id = cmdline.toInt("sourceid"); fromfile_name = cmdline.toString("xmlfile"); LOG(VB_GENERAL, LOG_INFO, "Bypassing grabbers, reading directly from file"); from_file = true; } if (cmdline.toBool("ddfile")) { // datadirect file mode if (!cmdline.toBool("sourceid") || !cmdline.toBool("offset") || !cmdline.toBool("lineupid") || !cmdline.toBool("xmlfile")) { cerr << "The --dd-file option must be used in combination" << endl << "with each of --sourceid, --offset, --lineupid," << endl << "and --xmlfile." << endl; return GENERIC_EXIT_INVALID_CMDLINE; } fromfile_id = cmdline.toInt("sourceid"); fromfile_offset = cmdline.toInt("offset"); fromddfile_lineupid = cmdline.toString("lineupid"); fromfile_name = cmdline.toString("xmlfile"); LOG(VB_GENERAL, LOG_INFO, "Bypassing grabbers, reading directly from file"); from_dd_file = true; } if (cmdline.toBool("dochannelupdates")) fill_data.chan_data.m_channelUpdates = true; if (cmdline.toBool("removechannels")) fill_data.chan_data.m_removeNewChannels = true; if (cmdline.toBool("nofilterchannels")) fill_data.chan_data.m_filterNewChannels = false; if (!cmdline.GetPassthrough().isEmpty()) fill_data.graboptions = " " + cmdline.GetPassthrough(); if (cmdline.toBool("sourceid")) sourceid = cmdline.toInt("sourceid"); if (cmdline.toBool("cardtype")) { if (!cmdline.toBool("sourceid")) { cerr << "The --cardtype option must be used in combination" << endl << "with a --sourceid option." << endl; return GENERIC_EXIT_INVALID_CMDLINE; } fill_data.chan_data.m_cardType = cmdline.toString("cardtype") .trimmed().toUpper(); } if (cmdline.toBool("maxdays") && cmdline.toInt("maxdays") > 0) { fill_data.maxDays = cmdline.toInt("maxdays"); if (fill_data.maxDays == 1) fill_data.SetRefresh(0, true); } if (cmdline.toBool("refreshtoday")) cmdline.SetValue("refresh", cmdline.toStringList("refresh") << "today"); if (cmdline.toBool("dontrefreshtomorrow")) cmdline.SetValue("refresh", cmdline.toStringList("refresh") << "nottomorrow"); if (cmdline.toBool("refreshsecond")) cmdline.SetValue("refresh", cmdline.toStringList("refresh") << "second"); if (cmdline.toBool("refreshall")) cmdline.SetValue("refresh", cmdline.toStringList("refresh") << "all"); if (cmdline.toBool("refreshday")) cmdline.SetValue("refresh", cmdline.toStringList("refresh") << cmdline.toStringList("refreshday")); QStringList sl = cmdline.toStringList("refresh"); if (!sl.isEmpty()) { QStringList::const_iterator i = sl.constBegin(); for (; i != sl.constEnd(); ++i) { QString warn = QString("Invalid entry in --refresh list: %1") .arg(*i); bool enable = (*i).contains("not") ? false : true; if ((*i).contains("today")) fill_data.SetRefresh(0, enable); else if ((*i).contains("tomorrow")) fill_data.SetRefresh(1, enable); else if ((*i).contains("second")) fill_data.SetRefresh(2, enable); else if ((*i).contains("all")) fill_data.SetRefresh(FillData::kRefreshAll, enable); else if ((*i).contains("-")) { bool ok; QStringList r = (*i).split("-"); uint lower = r[0].toUInt(&ok); if (!ok) { cerr << warn.toLocal8Bit().constData() << endl; return false; } uint upper = r[1].toUInt(&ok); if (!ok) { cerr << warn.toLocal8Bit().constData() << endl; return false; } if (lower > upper) { cerr << warn.toLocal8Bit().constData() << endl; return false; } for (uint j = lower; j <= upper; ++j) fill_data.SetRefresh(j, true); } else { bool ok; uint day = (*i).toUInt(&ok); if (!ok) { cerr << warn.toLocal8Bit().constData() << endl; return false; } fill_data.SetRefresh(day, true); } } } if (cmdline.toBool("dontrefreshtba")) fill_data.refresh_tba = false; if (cmdline.toBool("ddgraball")) { fill_data.SetRefresh(FillData::kRefreshClear, false); fill_data.dd_grab_all = true; } if (cmdline.toBool("onlychannels")) fill_data.only_update_channels = true; mark_repeats = cmdline.toBool("markrepeats"); if (cmdline.toBool("exporticonmap")) export_icon_data_filename = cmdline.toString("exporticonmap"); if (cmdline.toBool("importiconmap")) import_icon_data_filename = cmdline.toString("importiconmap"); if (cmdline.toBool("updateiconmap")) { update_icon_data = true; grab_data = false; } if (cmdline.toBool("reseticonmap")) { reset_iconmap = true; grab_data = false; if (cmdline.toString("reseticonmap") == "all") reset_iconmap_icons = true; } CleanupGuard callCleanup(cleanup); #ifndef _WIN32 QList<int> signallist; signallist << SIGINT << SIGTERM << SIGSEGV << SIGABRT << SIGBUS << SIGFPE << SIGILL; #if ! CONFIG_DARWIN signallist << SIGRTMIN; #endif SignalHandler::Init(signallist); signal(SIGHUP, SIG_IGN); #endif gContext = new MythContext(MYTH_BINARY_VERSION); if (!gContext->Init(false)) { LOG(VB_GENERAL, LOG_ERR, "Failed to init MythContext, exiting."); return GENERIC_EXIT_NO_MYTHCONTEXT; } setHttpProxy(); MythTranslation::load("mythfrontend"); if (!UpgradeTVDatabaseSchema(false)) { LOG(VB_GENERAL, LOG_ERR, "Incorrect database schema"); return GENERIC_EXIT_DB_OUTOFDATE; } if (!grab_data) { } else if (from_file) { QString status = QObject::tr("currently running."); QDateTime GuideDataBefore, GuideDataAfter; MSqlQuery query(MSqlQuery::InitCon()); updateLastRunStart(query); updateLastRunStatus(query, status); query.prepare("SELECT MAX(endtime) FROM program p LEFT JOIN channel c " "ON p.chanid=c.chanid WHERE c.sourceid= :SRCID " "AND manualid = 0 AND c.xmltvid != '';"); query.bindValue(":SRCID", fromfile_id); if (query.exec() && query.next()) { if (!query.isNull(0)) GuideDataBefore = MythDate::fromString(query.value(0).toString()); } if (!fill_data.GrabDataFromFile(fromfile_id, fromfile_name)) { return GENERIC_EXIT_NOT_OK; } updateLastRunEnd(query); query.prepare("SELECT MAX(endtime) FROM program p LEFT JOIN channel c " "ON p.chanid=c.chanid WHERE c.sourceid= :SRCID " "AND manualid = 0 AND c.xmltvid != '';"); query.bindValue(":SRCID", fromfile_id); if (query.exec() && query.next()) { if (!query.isNull(0)) GuideDataAfter = MythDate::fromString(query.value(0).toString()); } if (GuideDataAfter == GuideDataBefore) status = QObject::tr("mythfilldatabase ran, but did not insert " "any new data into the Guide. This can indicate a " "potential problem with the XML file used for the update."); else status = QObject::tr("Successful."); updateLastRunStatus(query, status); } else if (from_dd_file) { fill_data.GrabDataFromDDFile( fromfile_id, fromfile_offset, fromfile_name, fromddfile_lineupid); } else { SourceList sourcelist; MSqlQuery sourcequery(MSqlQuery::InitCon()); QString where = ""; if (sourceid != -1) { LOG(VB_GENERAL, LOG_INFO, QString("Running for sourceid %1 ONLY because --sourceid " "was given on command-line").arg(sourceid)); where = QString("WHERE sourceid = %1").arg(sourceid); } QString querystr = QString("SELECT sourceid,name,xmltvgrabber,userid," "password,lineupid " "FROM videosource ") + where + QString(" ORDER BY sourceid;"); if (sourcequery.exec(querystr)) { if (sourcequery.size() > 0) { while (sourcequery.next()) { Source newsource; newsource.id = sourcequery.value(0).toInt(); newsource.name = sourcequery.value(1).toString(); newsource.xmltvgrabber = sourcequery.value(2).toString(); newsource.userid = sourcequery.value(3).toString(); newsource.password = sourcequery.value(4).toString(); newsource.lineupid = sourcequery.value(5).toString(); newsource.xmltvgrabber_baseline = false; newsource.xmltvgrabber_manualconfig = false; newsource.xmltvgrabber_cache = false; newsource.xmltvgrabber_prefmethod = ""; sourcelist.push_back(newsource); usingDataDirect |= is_grabber_datadirect(newsource.xmltvgrabber); } } else { LOG(VB_GENERAL, LOG_ERR, "There are no channel sources defined, did you run " "the setup program?"); return GENERIC_EXIT_SETUP_ERROR; } } else { MythDB::DBError("loading channel sources", sourcequery); return GENERIC_EXIT_DB_ERROR; } if (!fill_data.Run(sourcelist)) LOG(VB_GENERAL, LOG_ERR, "Failed to fetch some program info"); else LOG(VB_GENERAL, LOG_NOTICE, "Data fetching complete."); } if (fill_data.only_update_channels && !fill_data.need_post_grab_proc) { return GENERIC_EXIT_OK; } if (reset_iconmap) { fill_data.icon_data.ResetIconMap(reset_iconmap_icons); } if (import_iconmap) { fill_data.icon_data.ImportIconMap(import_icon_data_filename); } if (export_iconmap) { fill_data.icon_data.ExportIconMap(export_icon_data_filename); } if (update_icon_data) { MSqlQuery query(MSqlQuery::InitCon()); query.prepare("SELECT sourceid FROM videosource ORDER BY sourceid"); if (!query.exec()) { MythDB::DBError("Querying sources", query); return GENERIC_EXIT_DB_ERROR; } while (query.next()) fill_data.icon_data.UpdateSourceIcons(query.value(0).toInt()); } if (grab_data) { LOG(VB_GENERAL, LOG_INFO, "Adjusting program database end times."); int update_count = ProgramData::fix_end_times(); if (update_count == -1) LOG(VB_GENERAL, LOG_ERR, "fix_end_times failed!"); else LOG(VB_GENERAL, LOG_INFO, QString(" %1 replacements made").arg(update_count)); } if (grab_data) { LOG(VB_GENERAL, LOG_INFO, "Marking generic episodes."); MSqlQuery query(MSqlQuery::InitCon()); query.prepare("UPDATE program SET generic = 1 WHERE " "((programid = '' AND subtitle = '' AND description = '') OR " " (programid <> '' AND category_type = 'series' AND " " program.programid LIKE '%0000'));"); if (!query.exec()) MythDB::DBError("mark generic", query); else LOG(VB_GENERAL, LOG_INFO, QString(" Found %1").arg(query.numRowsAffected())); } if (grab_data) { LOG(VB_GENERAL, LOG_INFO, "Extending non-unique programids " "with multiple parts."); int found = 0; MSqlQuery sel(MSqlQuery::InitCon()); sel.prepare("SELECT DISTINCT programid, partnumber, parttotal " "FROM program WHERE partnumber > 0 AND parttotal > 0 AND " "programid LIKE '%0000'"); if (sel.exec()) { MSqlQuery repl(MSqlQuery::InitCon()); repl.prepare("UPDATE program SET programid = :NEWID " "WHERE programid = :OLDID AND " "partnumber = :PARTNUM AND " "parttotal = :PARTTOTAL"); while (sel.next()) { QString orig_programid = sel.value(0).toString(); QString new_programid = orig_programid.left(10); int partnum, parttotal; QString part; partnum = sel.value(1).toInt(); parttotal = sel.value(2).toInt(); part.setNum(parttotal); new_programid.append(part.rightJustified(2, '0')); part.setNum(partnum); new_programid.append(part.rightJustified(2, '0')); LOG(VB_GENERAL, LOG_INFO, QString(" %1 -> %2 (part %3 of %4)") .arg(orig_programid).arg(new_programid) .arg(partnum).arg(parttotal)); repl.bindValue(":NEWID", new_programid); repl.bindValue(":OLDID", orig_programid); repl.bindValue(":PARTNUM", partnum); repl.bindValue(":PARTTOTAL", parttotal); if (!repl.exec()) { LOG(VB_GENERAL, LOG_INFO, QString("Fudging programid from '%1' to '%2'") .arg(orig_programid) .arg(new_programid)); } else found += repl.numRowsAffected(); } } LOG(VB_GENERAL, LOG_INFO, QString(" Found %1").arg(found)); } if (grab_data) { LOG(VB_GENERAL, LOG_INFO, "Fixing missing original airdates."); MSqlQuery query(MSqlQuery::InitCon()); query.prepare("UPDATE program p " "JOIN ( " " SELECT programid, MAX(originalairdate) maxoad " " FROM program " " WHERE programid <> '' AND " " originalairdate IS NOT NULL " " GROUP BY programid ) oad " " ON p.programid = oad.programid " "SET p.originalairdate = oad.maxoad " "WHERE p.originalairdate IS NULL"); if (query.exec()) LOG(VB_GENERAL, LOG_INFO, QString(" Found %1 with programids") .arg(query.numRowsAffected())); query.prepare("UPDATE program p " "JOIN ( " " SELECT title, subtitle, description, " " MAX(originalairdate) maxoad " " FROM program " " WHERE programid = '' AND " " originalairdate IS NOT NULL " " GROUP BY title, subtitle, description ) oad " " ON p.programid = '' AND " " p.title = oad.title AND " " p.subtitle = oad.subtitle AND " " p.description = oad.description " "SET p.originalairdate = oad.maxoad " "WHERE p.originalairdate IS NULL"); if (query.exec()) LOG(VB_GENERAL, LOG_INFO, QString(" Found %1 without programids") .arg(query.numRowsAffected())); } if (mark_repeats) { LOG(VB_GENERAL, LOG_INFO, "Marking repeats."); int newEpiWindow = gCoreContext->GetNumSetting( "NewEpisodeWindow", 14); MSqlQuery query(MSqlQuery::InitCon()); query.prepare("UPDATE program SET previouslyshown = 1 " "WHERE previouslyshown = 0 " "AND originalairdate is not null " "AND (to_days(starttime) - to_days(originalairdate)) " " > :NEWWINDOW;"); query.bindValue(":NEWWINDOW", newEpiWindow); if (query.exec()) LOG(VB_GENERAL, LOG_INFO, QString(" Found %1").arg(query.numRowsAffected())); LOG(VB_GENERAL, LOG_INFO, "Unmarking new episode rebroadcast repeats."); query.prepare("UPDATE program SET previouslyshown = 0 " "WHERE previouslyshown = 1 " "AND originalairdate is not null " "AND (to_days(starttime) - to_days(originalairdate)) " " <= :NEWWINDOW;"); query.bindValue(":NEWWINDOW", newEpiWindow); if (query.exec()) LOG(VB_GENERAL, LOG_INFO, QString(" Found %1").arg(query.numRowsAffected())); } // Mark first and last showings if (grab_data) { MSqlQuery updt(MSqlQuery::InitCon()); updt.prepare("UPDATE program SET first = 0, last = 0;"); if (!updt.exec()) MythDB::DBError("Clearing first and last showings", updt); LOG(VB_GENERAL, LOG_INFO, "Marking episode first showings."); updt.prepare("UPDATE program " "JOIN (SELECT MIN(starttime) AS starttime, programid " " FROM program " " WHERE programid <> '' " " GROUP BY programid " " ) AS firsts " "ON program.programid = firsts.programid " " AND program.starttime = firsts.starttime " "SET program.first=1;"); if (!updt.exec()) MythDB::DBError("Marking first showings by id", updt); int found = updt.numRowsAffected(); updt.prepare("UPDATE program " "JOIN (SELECT MIN(starttime) AS starttime, title, subtitle," " LEFT(description, 1024) AS partdesc " " FROM program " " WHERE programid = '' " " GROUP BY title, subtitle, partdesc " " ) AS firsts " "ON program.starttime = firsts.starttime " " AND program.title = firsts.title " " AND program.subtitle = firsts.subtitle " " AND LEFT(program.description, 1024) = firsts.partdesc " "SET program.first = 1 " "WHERE program.programid = '';"); if (!updt.exec()) MythDB::DBError("Marking first showings", updt); found += updt.numRowsAffected(); LOG(VB_GENERAL, LOG_INFO, QString(" Found %1").arg(found)); LOG(VB_GENERAL, LOG_INFO, "Marking episode last showings."); updt.prepare("UPDATE program " "JOIN (SELECT MAX(starttime) AS starttime, programid " " FROM program " " WHERE programid <> '' " " GROUP BY programid " " ) AS lasts " "ON program.programid = lasts.programid " " AND program.starttime = lasts.starttime " "SET program.last=1;"); if (!updt.exec()) MythDB::DBError("Marking last showings by id", updt); found = updt.numRowsAffected(); updt.prepare("UPDATE program " "JOIN (SELECT MAX(starttime) AS starttime, title, subtitle," " LEFT(description, 1024) AS partdesc " " FROM program " " WHERE programid = '' " " GROUP BY title, subtitle, partdesc " " ) AS lasts " "ON program.starttime = lasts.starttime " " AND program.title = lasts.title " " AND program.subtitle = lasts.subtitle " " AND LEFT(program.description, 1024) = lasts.partdesc " "SET program.last = 1 " "WHERE program.programid = '';"); if (!updt.exec()) MythDB::DBError("Marking last showings", updt); found += updt.numRowsAffected(); LOG(VB_GENERAL, LOG_INFO, QString(" Found %1").arg(found)); } if (1) // limit MSqlQuery's lifetime { MSqlQuery query(MSqlQuery::InitCon()); query.prepare("SELECT count(previouslyshown) " "FROM program WHERE previouslyshown = 1;"); if (query.exec() && query.next()) { if (query.value(0).toInt() != 0) gCoreContext->SaveSettingOnHost("HaveRepeats", "1", NULL); else gCoreContext->SaveSettingOnHost("HaveRepeats", "0", NULL); } } if ((usingDataDirect) && (gCoreContext->GetNumSetting("MythFillGrabberSuggestsTime", 1))) { fill_data.ddprocessor.GrabNextSuggestedTime(); } LOG(VB_GENERAL, LOG_INFO, "\n" "===============================================================\n" "| Attempting to contact the master backend for rescheduling. |\n" "| If the master is not running, rescheduling will happen when |\n" "| the master backend is restarted. |\n" "==============================================================="); if (grab_data || mark_repeats) ScheduledRecording::RescheduleMatch(0, 0, 0, QDateTime(), "MythFillDatabase"); gCoreContext->SendMessage("CLEAR_SETTINGS_CACHE"); gCoreContext->SendSystemEvent("MYTHFILLDATABASE_RAN"); LOG(VB_GENERAL, LOG_NOTICE, "mythfilldatabase run complete."); return GENERIC_EXIT_OK; }
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, toleranceB; 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; }
bool CalFilter::filterIncidence( Incidence::Ptr incidence ) const { if ( !d->mEnabled ) { return true; } Todo::Ptr todo = incidence.dynamicCast<Todo>(); if ( todo ) { if ( ( d->mCriteria & HideCompletedTodos ) && todo->isCompleted() ) { // Check if completion date is suffently long ago: if ( todo->completed().addDays( d->mCompletedTimeSpan ) < KDateTime::currentUtcDateTime() ) { return false; } } if ( ( d->mCriteria & HideInactiveTodos ) && ( ( todo->hasStartDate() && KDateTime::currentUtcDateTime() < todo->dtStart() ) || todo->isCompleted() ) ) { return false; } if ( d->mCriteria & HideNoMatchingAttendeeTodos ) { bool iAmOneOfTheAttendees = false; const Attendee::List &attendees = todo->attendees(); if ( !todo->attendees().isEmpty() ) { Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if ( d->mEmailList.contains( ( *it )->email() ) ) { iAmOneOfTheAttendees = true; break; } } } else { // no attendees, must be me only iAmOneOfTheAttendees = true; } if ( !iAmOneOfTheAttendees ) { return false; } } } if ( d->mCriteria & HideRecurring ) { if ( incidence->recurs() ) { return false; } } if ( d->mCriteria & ShowCategories ) { for ( QStringList::ConstIterator it = d->mCategoryList.constBegin(); it != d->mCategoryList.constEnd(); ++it ) { QStringList incidenceCategories = incidence->categories(); for ( QStringList::ConstIterator it2 = incidenceCategories.constBegin(); it2 != incidenceCategories.constEnd(); ++it2 ) { if ( ( *it ) == ( *it2 ) ) { return true; } } } return false; } else { for ( QStringList::ConstIterator it = d->mCategoryList.constBegin(); it != d->mCategoryList.constEnd(); ++it ) { QStringList incidenceCategories = incidence->categories(); for ( QStringList::ConstIterator it2 = incidenceCategories.constBegin(); it2 != incidenceCategories.constEnd(); ++it2 ) { if ( ( *it ) == ( *it2 ) ) { return false; } } } return true; } return true; }
void ProjectManager::loadHistoryProject() { // 配置文件的每个group 都是项目根目录的绝对路径, 这样可以保持treeview中的每个group都是唯一的 QStringList projectList = historySettings->childGroups(); QStringList::const_iterator constIterator = projectList.constBegin(); QStringList::const_iterator endIterator = projectList.constEnd(); // 初始化 allProjectMap while (constIterator != endIterator) { if (!allProjectMap.contains(*constIterator)) allProjectMap[*constIterator] = QString(); ++constIterator; } qDebug() << "导入历史项目中 ..."; constIterator = projectList.constBegin(); while (constIterator != endIterator) { qDebug() << "开始导入项目" << *constIterator << "..."; historySettings->beginGroup(*constIterator); QString rootPath = historySettings->value("RootPath").toString(); if (rootPath.contains(QRegExp("/\\s*$"))) { rootPath.remove(QRegExp("/\\s*$")); historySettings->setValue("RootPath", rootPath); } // 如果 pathList 中含有rootPath, 则说明该位置的项目已经导入了, 不需要重新导入它 // 从 historySettings 和 allProjectMap 中删除它, 并继续下一个项目 if (pathList.contains(rootPath)) { historySettings->endGroup(); qDebug() << "目录" << rootPath << "中的项目已经导入, 不需要重新导入"; historySettings->remove(*constIterator); allProjectMap.remove(*constIterator); ++constIterator; continue; } // 如果rootPath 为空 或者 不存在该目录, 则从historySettings和allProjectMap中删除该项目 if (rootPath.isEmpty() || !QFile::exists(rootPath)) { historySettings->endGroup(); qDebug() << "目录" << rootPath + "不存在, 放弃该项目" << *constIterator; allProjectMap.remove(*constIterator); historySettings->remove(*constIterator); ++constIterator; continue; } // 查看是否存在project.small文件, 如果不存在, 则拷贝一份模板, 如果拷贝失败, 则从historySettings和allProjectMap中删除该项目 // 之所以在不存在的情况加拷贝一份模板, 是因为用户可能误删了配置文件, 所以重新建立它 bool isNew = false; QFileInfo fileInfo(rootPath + "/project.small"); if (!fileInfo.exists()) { if (!QFile::copy(Global::projectConfigTemplate(), fileInfo.absoluteFilePath())) { QString errorInfo = "拷贝项目配置文件失败 \ncopy from:" + Global::projectConfigTemplate() + "\n copy to:" + fileInfo.absoluteFilePath() + "\n没有导入该项目\"" + *constIterator + "\""; qDebug() << errorInfo; hintInfoList << errorInfo; emit hint(errorInfo); historySettings->endGroup(); allProjectMap.remove(*constIterator); historySettings->remove(*constIterator); ++constIterator; continue; } isNew = true; } else if (!fileInfo.isFile() || !fileInfo.isWritable() || !fileInfo.isReadable()) { // 如果project.small不是普通文件或者没有读写权限, 则从historySettings和allProjectMap中删除该项目 QString errorInfo = "文件\"" + fileInfo.absoluteFilePath() + "\"不是普通文件, 或者您没有它读写权限" + "\n没有导入该项目\"" + *constIterator + "\""; qDebug() << errorInfo; hintInfoList << errorInfo; emit hint(errorInfo); historySettings->endGroup(); allProjectMap.remove(*constIterator); historySettings->remove(*constIterator); ++constIterator; continue; } QSettings *projectSettings = new QSettings(fileInfo.absoluteFilePath(), QSettings::IniFormat); // 如果配置文件是复制得到的, 设置 Name = *constIterator if (isNew || projectSettings->value("Name").toString().isEmpty()) { projectSettings->setValue("Name", *constIterator); projectSettings->sync(); } QString projectName = projectSettings->value("Name").toString(); // 如果project.small文件中的Name 与 历史配置文件的项目名称变量不一致, 则使之尽可能与项目配置文件一致 if (projectName != *constIterator) { projectName = validProjectName(projectName); qDebug() << "项目名称" << *constIterator << "与project.small配置文件中的Name不一致, 修改项目名称"; qDebug() << "修改后的名称为" << projectName; // 暂存historySettings中项目oldName配置 QString status = historySettings->value("Status", "On").toString(); QString isCurrent = historySettings->value("IsCurrent", "False").toString(); QString path = historySettings->value("RootPath").toString(); historySettings->endGroup(); // 移除 historySettings中的oldName配置, 加入newName的配置 historySettings->remove(*constIterator); historySettings->setValue(projectName + "/Status", status); historySettings->setValue(projectName + "/IsCurrent", isCurrent); historySettings->setValue(projectName + "/RootPath", path); historySettings->sync(); historySettings->beginGroup(projectName); // 更新项目配置文件 QSettings *projectSettings = new QSettings(rootPath + "/project.small", QSettings::IniFormat); projectSettings->setValue("Name", projectName); projectSettings->sync(); delete projectSettings; } allProjectMap[projectName] = rootPath; pathList << rootPath; // 如果Status = On/on/oN if (historySettings->value("Status", "On").toString().toLower() == "on") { openedProjectList << projectName; QString isCurrent = historySettings->value("IsCurrent", "False").toString().toLower(); // 如果currentProject为空, 且IsCurrent = True, 则设置currentProject = projectName if (isCurrent == "true" && currentProject.isEmpty()) currentProject = projectName; } else { closedProjectList << projectName; } historySettings->endGroup(); qDebug() << "导入项目" << projectName << "成功."; ++constIterator; } historySettings->sync(); qDebug() << "所有项目导入完成."; }
/*! Creates a declaration (header file) for the form given in \a e \sa createFormImpl() */ void Ui3Reader::createFormDecl(const QDomElement &e, bool implicitIncludes) { QDomElement body = e; QDomElement n; QDomNodeList nl; int i; QString objClass = getClassName(e); if (objClass.isEmpty()) return; QString objName = getObjectName(e); QStringList typeDefs; QMap<QString, CustomInclude> customWidgetIncludes; /* We are generating a few QImage members that are not strictly necessary in some cases. Ideally, we would use requiredImage, which is computed elsewhere, to keep the generated .h and .cpp files synchronized. */ // at first the images QMap<QString, int> customWidgets; QStringList forwardDecl; QStringList forwardDecl2; for (n = e; !n.isNull(); n = n.nextSibling().toElement()) { if (n.tagName().toLower() == QLatin1String("customwidgets")) { QDomElement n2 = n.firstChild().toElement(); while (!n2.isNull()) { if (n2.tagName().toLower() == QLatin1String("customwidget")) { QDomElement n3 = n2.firstChild().toElement(); QString cl; while (!n3.isNull()) { QString tagName = n3.tagName().toLower(); if (tagName == QLatin1String("class")) { cl = n3.firstChild().toText().data(); if (!nofwd) forwardDecl << cl; customWidgets.insert(cl, 0); } else if (tagName == QLatin1String("header")) { CustomInclude ci; ci.header = n3.firstChild().toText().data(); ci.location = n3.attribute(QLatin1String("location"), QLatin1String("global")); if (!ci.header.isEmpty()) forwardDecl.removeAll(cl); customWidgetIncludes.insert(cl, ci); } n3 = n3.nextSibling().toElement(); } } n2 = n2.nextSibling().toElement(); } } } // register the object and unify its name objName = registerObject(objName); QString protector = objName.toUpper() + QLatin1String("_H"); protector.replace(QLatin1String("::"), QLatin1String("_")); out << "#ifndef " << protector << endl; out << "#define " << protector << endl; out << endl; out << "#include <qvariant.h>" << endl; // for broken HP-UX compilers QStringList globalIncludes, localIncludes; { QMap<QString, CustomInclude>::Iterator it = customWidgetIncludes.find(objClass); if (it != customWidgetIncludes.end()) { if ((*it).location == QLatin1String("global")) globalIncludes += (*it).header; else localIncludes += (*it).header; } } QStringList::ConstIterator it; globalIncludes = unique(globalIncludes); for (it = globalIncludes.constBegin(); it != globalIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include <" << header << ">" << endl; } } localIncludes = unique(localIncludes); for (it = localIncludes.constBegin(); it != localIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include \"" << header << "\"" << endl; } } out << endl; bool dbForm = false; registerDatabases(e); dbConnections = unique(dbConnections); if (dbForms[QLatin1String("(default)")].count()) dbForm = true; bool subDbForms = false; for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) { if (dbForms[(*it)].count()) { subDbForms = true; break; } } } // some typedefs, maybe typeDefs = unique(typeDefs); for (it = typeDefs.constBegin(); it != typeDefs.constEnd(); ++it) { if (!(*it).isEmpty()) out << "typedef " << *it << ";" << endl; } nl = e.parentNode().toElement().elementsByTagName(QLatin1String("forward")); for (i = 0; i < (int) nl.length(); i++) forwardDecl2 << fixDeclaration(nl.item(i).toElement().firstChild().toText().data()); forwardDecl = unique(forwardDecl); for (it = forwardDecl.constBegin(); it != forwardDecl.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != objClass) { QString forwardName = *it; QStringList forwardNamespaces = forwardName.split(QLatin1String("::")); forwardName = forwardNamespaces.last(); forwardNamespaces.removeAt(forwardNamespaces.size()-1); QStringList::ConstIterator ns = forwardNamespaces.constBegin(); while (ns != forwardNamespaces.constEnd()) { out << "namespace " << *ns << " {" << endl; ++ns; } out << "class " << forwardName << ";" << endl; for (int i = 0; i < (int) forwardNamespaces.count(); i++) out << "}" << endl; } } for (it = forwardDecl2.constBegin(); it != forwardDecl2.constEnd(); ++it) { QString fd = *it; fd = fd.trimmed(); if (!fd.endsWith(QLatin1String(";"))) fd += QLatin1String(";"); out << fd << endl; } out << endl; Driver d; d.option().headerProtection = false; d.option().copyrightHeader = false; d.option().extractImages = m_extractImages; d.option().qrcOutputFile = m_qrcOutputFile; d.option().implicitIncludes = implicitIncludes; if (trmacro.size()) d.option().translateFunction = trmacro; DomUI *ui = generateUi4(e, implicitIncludes); d.uic(fileName, ui, &out); delete ui; createWrapperDeclContents(e); out << "#endif // " << protector << endl; }
void QgsSvgCache::replaceElemParams( QDomElement &elem, const QColor &fill, const QColor &stroke, double strokeWidth ) { if ( elem.isNull() ) { return; } //go through attributes QDomNamedNodeMap attributes = elem.attributes(); int nAttributes = attributes.count(); for ( int i = 0; i < nAttributes; ++i ) { QDomAttr attribute = attributes.item( i ).toAttr(); //e.g. style="fill:param(fill);param(stroke)" if ( attribute.name().compare( QLatin1String( "style" ), Qt::CaseInsensitive ) == 0 ) { //entries separated by ';' QString newAttributeString; QStringList entryList = attribute.value().split( ';' ); QStringList::const_iterator entryIt = entryList.constBegin(); for ( ; entryIt != entryList.constEnd(); ++entryIt ) { QStringList keyValueSplit = entryIt->split( ':' ); if ( keyValueSplit.size() < 2 ) { continue; } QString key = keyValueSplit.at( 0 ); QString value = keyValueSplit.at( 1 ); if ( value.startsWith( QLatin1String( "param(fill)" ) ) ) { value = fill.name(); } else if ( value.startsWith( QLatin1String( "param(fill-opacity)" ) ) ) { value = fill.alphaF(); } else if ( value.startsWith( QLatin1String( "param(outline)" ) ) ) { value = stroke.name(); } else if ( value.startsWith( QLatin1String( "param(outline-opacity)" ) ) ) { value = stroke.alphaF(); } else if ( value.startsWith( QLatin1String( "param(outline-width)" ) ) ) { value = QString::number( strokeWidth ); } if ( entryIt != entryList.constBegin() ) { newAttributeString.append( ';' ); } newAttributeString.append( key + ':' + value ); } elem.setAttribute( attribute.name(), newAttributeString ); } else { QString value = attribute.value(); if ( value.startsWith( QLatin1String( "param(fill)" ) ) ) { elem.setAttribute( attribute.name(), fill.name() ); } else if ( value.startsWith( QLatin1String( "param(fill-opacity)" ) ) ) { elem.setAttribute( attribute.name(), fill.alphaF() ); } else if ( value.startsWith( QLatin1String( "param(outline)" ) ) ) { elem.setAttribute( attribute.name(), stroke.name() ); } else if ( value.startsWith( QLatin1String( "param(outline-opacity)" ) ) ) { elem.setAttribute( attribute.name(), stroke.alphaF() ); } else if ( value.startsWith( QLatin1String( "param(outline-width)" ) ) ) { elem.setAttribute( attribute.name(), QString::number( strokeWidth ) ); } } } QDomNodeList childList = elem.childNodes(); int nChildren = childList.count(); for ( int i = 0; i < nChildren; ++i ) { QDomElement childElem = childList.at( i ).toElement(); replaceElemParams( childElem, fill, stroke, strokeWidth ); } }
void Ui3Reader::createWrapperDeclContents(const QDomElement &e) { QString objClass = getClassName(e); if (objClass.isEmpty()) return; QDomNodeList nl; QString exportMacro; int i; QDomElement n; QStringList::ConstIterator it; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("exportmacro")); if (nl.length() == 1) exportMacro = nl.item(0).firstChild().toText().data(); QStringList::ConstIterator ns = namespaces.constBegin(); while (ns != namespaces.constEnd()) { out << "namespace " << *ns << " {" << endl; ++ns; } out << "class "; if (!exportMacro.isEmpty()) out << exportMacro << " "; out << bareNameOfClass << " : public " << objClass << ", public Ui::" << bareNameOfClass << endl << "{" << endl; /* qmake ignore Q_OBJECT */ out << " Q_OBJECT" << endl; out << endl; out << "public:" << endl; // constructor if (objClass == QLatin1String("QDialog") || objClass == QLatin1String("QWizard")) { out << " " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, bool modal = false, Qt::WindowFlags fl = 0);" << endl; } else if (objClass == QLatin1String("QWidget")) { out << " " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = 0);" << endl; } else if (objClass == QLatin1String("QMainWindow") || objClass == QLatin1String("Q3MainWindow")) { out << " " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = Qt::WType_TopLevel);" << endl; isMainWindow = true; } else { out << " " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0);" << endl; } // destructor out << " ~" << bareNameOfClass << "();" << endl; out << endl; // database connections dbConnections = unique(dbConnections); bool hadOutput = false; for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) { if (!(*it).isEmpty()) { // only need pointers to non-default connections if ((*it) != QLatin1String("(default)") && !(*it).isEmpty()) { out << indent << "QSqlDatabase* " << *it << "Connection;" << endl; hadOutput = true; } } } if (hadOutput) out << endl; QStringList publicSlots, protectedSlots, privateSlots; QStringList publicSlotTypes, protectedSlotTypes, privateSlotTypes; QStringList publicSlotSpecifier, protectedSlotSpecifier, privateSlotSpecifier; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("slot")); for (i = 0; i < (int) nl.length(); i++) { n = nl.item(i).toElement(); if (n.parentNode().toElement().tagName() != QLatin1String("slots") && n.parentNode().toElement().tagName() != QLatin1String("connections")) continue; if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); if (functionName.endsWith(QLatin1String(";"))) functionName = functionName.left(functionName.length() - 1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if (access == QLatin1String(QLatin1String("protected"))) { protectedSlots += functionName; protectedSlotTypes += returnType; protectedSlotSpecifier += specifier; } else if (access == QLatin1String("private")) { privateSlots += functionName; privateSlotTypes += returnType; privateSlotSpecifier += specifier; } else { publicSlots += functionName; publicSlotTypes += returnType; publicSlotSpecifier += specifier; } } QStringList publicFuncts, protectedFuncts, privateFuncts; QStringList publicFunctRetTyp, protectedFunctRetTyp, privateFunctRetTyp; QStringList publicFunctSpec, protectedFunctSpec, privateFunctSpec; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("function")); for (i = 0; i < (int) nl.length(); i++) { n = nl.item(i).toElement(); if (n.parentNode().toElement().tagName() != QLatin1String("functions")) continue; if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); if (functionName.endsWith(QLatin1String(";"))) functionName = functionName.left(functionName.length() - 1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if (access == QLatin1String("protected")) { protectedFuncts += functionName; protectedFunctRetTyp += returnType; protectedFunctSpec += specifier; } else if (access == QLatin1String("private")) { privateFuncts += functionName; privateFunctRetTyp += returnType; privateFunctSpec += specifier; } else { publicFuncts += functionName; publicFunctRetTyp += returnType; publicFunctSpec += specifier; } } QStringList publicVars, protectedVars, privateVars; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("variable")); for (i = 0; i < (int)nl.length(); i++) { n = nl.item(i).toElement(); // Because of compatibility the next lines have to be commented out. // Someday it should be uncommented. //if (n.parentNode().toElement().tagName() != QLatin1String("variables")) // continue; QString access = n.attribute(QLatin1String("access"), QLatin1String("protected")); QString var = fixDeclaration(n.firstChild().toText().data().trimmed()); if (!var.endsWith(QLatin1String(";"))) var += QLatin1String(";"); if (access == QLatin1String("public")) publicVars += var; else if (access == QLatin1String("private")) privateVars += var; else protectedVars += var; } if (!publicVars.isEmpty()) { for (it = publicVars.constBegin(); it != publicVars.constEnd(); ++it) out << indent << *it << endl; out << endl; } if (!publicFuncts.isEmpty()) writeFunctionsDecl(publicFuncts, publicFunctRetTyp, publicFunctSpec); if (!publicSlots.isEmpty()) { out << "public slots:" << endl; if (!publicSlots.isEmpty()) writeFunctionsDecl(publicSlots, publicSlotTypes, publicSlotSpecifier); } // find signals QStringList extraSignals; nl = e.parentNode().toElement().elementsByTagName(QLatin1String("signal")); for (i = 0; i < (int) nl.length(); i++) { n = nl.item(i).toElement(); if (n.parentNode().toElement().tagName() != QLatin1String("signals") && n.parentNode().toElement().tagName() != QLatin1String("connections")) continue; if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString sigName = n.firstChild().toText().data().trimmed(); if (sigName.endsWith(QLatin1String(";"))) sigName = sigName.left(sigName.length() - 1); extraSignals += fixDeclaration(sigName); } // create signals if (!extraSignals.isEmpty()) { out << "signals:" << endl; for (it = extraSignals.constBegin(); it != extraSignals.constEnd(); ++it) out << " void " << (*it) << ";" << endl; out << endl; } if (!protectedVars.isEmpty()) { out << "protected:" << endl; for (it = protectedVars.constBegin(); it != protectedVars.constEnd(); ++it) out << indent << *it << endl; out << endl; } if (!protectedFuncts.isEmpty()) { if (protectedVars.isEmpty()) out << "protected:" << endl; writeFunctionsDecl(protectedFuncts, protectedFunctRetTyp, protectedFunctSpec); } out << "protected slots:" << endl; out << " virtual void languageChange();" << endl; if (!protectedSlots.isEmpty()) { out << endl; writeFunctionsDecl(protectedSlots, protectedSlotTypes, protectedSlotSpecifier); } out << endl; // create all private stuff if (!privateFuncts.isEmpty() || !privateVars.isEmpty()) { out << "private:" << endl; if (!privateVars.isEmpty()) { for (it = privateVars.constBegin(); it != privateVars.constEnd(); ++it) out << indent << *it << endl; out << endl; } if (!privateFuncts.isEmpty()) writeFunctionsDecl(privateFuncts, privateFunctRetTyp, privateFunctSpec); } if (!privateSlots.isEmpty()) { out << "private slots:" << endl; writeFunctionsDecl(privateSlots, privateSlotTypes, privateSlotSpecifier); } out << "};" << endl; for (i = 0; i < (int) namespaces.count(); i++) out << "}" << endl; out << endl; }
void QgsSvgCache::containsElemParams( const QDomElement &elem, bool &hasFillParam, bool &hasDefaultFill, QColor &defaultFill, bool &hasFillOpacityParam, bool &hasDefaultFillOpacity, double &defaultFillOpacity, bool &hasStrokeParam, bool &hasDefaultStroke, QColor &defaultStroke, bool &hasStrokeWidthParam, bool &hasDefaultStrokeWidth, double &defaultStrokeWidth, bool &hasStrokeOpacityParam, bool &hasDefaultStrokeOpacity, double &defaultStrokeOpacity ) const { if ( elem.isNull() ) { return; } //we already have all the information, no need to go deeper if ( hasFillParam && hasStrokeParam && hasStrokeWidthParam && hasFillOpacityParam && hasStrokeOpacityParam ) { return; } //check this elements attribute QDomNamedNodeMap attributes = elem.attributes(); int nAttributes = attributes.count(); QStringList valueSplit; for ( int i = 0; i < nAttributes; ++i ) { QDomAttr attribute = attributes.item( i ).toAttr(); if ( attribute.name().compare( QLatin1String( "style" ), Qt::CaseInsensitive ) == 0 ) { //entries separated by ';' QStringList entryList = attribute.value().split( ';' ); QStringList::const_iterator entryIt = entryList.constBegin(); for ( ; entryIt != entryList.constEnd(); ++entryIt ) { QStringList keyValueSplit = entryIt->split( ':' ); if ( keyValueSplit.size() < 2 ) { continue; } QString value = keyValueSplit.at( 1 ); valueSplit = value.split( ' ' ); if ( !hasFillParam && value.startsWith( QLatin1String( "param(fill)" ) ) ) { hasFillParam = true; if ( valueSplit.size() > 1 ) { defaultFill = QColor( valueSplit.at( 1 ) ); hasDefaultFill = true; } } else if ( !hasFillOpacityParam && value.startsWith( QLatin1String( "param(fill-opacity)" ) ) ) { hasFillOpacityParam = true; if ( valueSplit.size() > 1 ) { bool ok; double opacity = valueSplit.at( 1 ).toDouble( &ok ); if ( ok ) { defaultFillOpacity = opacity; hasDefaultFillOpacity = true; } } } else if ( !hasStrokeParam && value.startsWith( QLatin1String( "param(outline)" ) ) ) { hasStrokeParam = true; if ( valueSplit.size() > 1 ) { defaultStroke = QColor( valueSplit.at( 1 ) ); hasDefaultStroke = true; } } else if ( !hasStrokeWidthParam && value.startsWith( QLatin1String( "param(outline-width)" ) ) ) { hasStrokeWidthParam = true; if ( valueSplit.size() > 1 ) { defaultStrokeWidth = valueSplit.at( 1 ).toDouble(); hasDefaultStrokeWidth = true; } } else if ( !hasStrokeOpacityParam && value.startsWith( QLatin1String( "param(outline-opacity)" ) ) ) { hasStrokeOpacityParam = true; if ( valueSplit.size() > 1 ) { bool ok; double opacity = valueSplit.at( 1 ).toDouble( &ok ); if ( ok ) { defaultStrokeOpacity = opacity; hasDefaultStrokeOpacity = true; } } } } } else { QString value = attribute.value(); valueSplit = value.split( ' ' ); if ( !hasFillParam && value.startsWith( QLatin1String( "param(fill)" ) ) ) { hasFillParam = true; if ( valueSplit.size() > 1 ) { defaultFill = QColor( valueSplit.at( 1 ) ); hasDefaultFill = true; } } else if ( !hasFillOpacityParam && value.startsWith( QLatin1String( "param(fill-opacity)" ) ) ) { hasFillOpacityParam = true; if ( valueSplit.size() > 1 ) { bool ok; double opacity = valueSplit.at( 1 ).toDouble( &ok ); if ( ok ) { defaultFillOpacity = opacity; hasDefaultFillOpacity = true; } } } else if ( !hasStrokeParam && value.startsWith( QLatin1String( "param(outline)" ) ) ) { hasStrokeParam = true; if ( valueSplit.size() > 1 ) { defaultStroke = QColor( valueSplit.at( 1 ) ); hasDefaultStroke = true; } } else if ( !hasStrokeWidthParam && value.startsWith( QLatin1String( "param(outline-width)" ) ) ) { hasStrokeWidthParam = true; if ( valueSplit.size() > 1 ) { defaultStrokeWidth = valueSplit.at( 1 ).toDouble(); hasDefaultStrokeWidth = true; } } else if ( !hasStrokeOpacityParam && value.startsWith( QLatin1String( "param(outline-opacity)" ) ) ) { hasStrokeOpacityParam = true; if ( valueSplit.size() > 1 ) { bool ok; double opacity = valueSplit.at( 1 ).toDouble( &ok ); if ( ok ) { defaultStrokeOpacity = opacity; hasDefaultStrokeOpacity = true; } } } } } //pass it further to child items QDomNodeList childList = elem.childNodes(); int nChildren = childList.count(); for ( int i = 0; i < nChildren; ++i ) { QDomElement childElem = childList.at( i ).toElement(); containsElemParams( childElem, hasFillParam, hasDefaultFill, defaultFill, hasFillOpacityParam, hasDefaultFillOpacity, defaultFillOpacity, hasStrokeParam, hasDefaultStroke, defaultStroke, hasStrokeWidthParam, hasDefaultStrokeWidth, defaultStrokeWidth, hasStrokeOpacityParam, hasDefaultStrokeOpacity, defaultStrokeOpacity ); } }
void FileBrowser::addItems(const QString & path ) { if( m_dirsAsItems ) { m_l->addTopLevelItem( new Directory( path, QString::null, m_filter ) ); return; } QDir cdir( path ); QStringList files = cdir.entryList( QDir::Dirs, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' ) { bool orphan = true; for( int i = 0; i < m_l->topLevelItemCount(); ++i ) { Directory * d = dynamic_cast<Directory *>( m_l->topLevelItem( i ) ); if( d == NULL || cur_file < d->text( 0 ) ) { Directory *dd = new Directory( cur_file, path, m_filter ); m_l->insertTopLevelItem( i,dd ); dd->update(); orphan = false; break; } else if( cur_file == d->text( 0 ) ) { d->addDirectory( path ); d->update(); orphan = false; break; } } if( orphan ) { Directory *d = new Directory( cur_file, path, m_filter ); d->update(); m_l->addTopLevelItem( d ); } } } files = cdir.entryList( QDir::Files, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' ) { // TODO: don't insert instead of removing, order changed // remove existing file-items QList<QTreeWidgetItem *> existing = m_l->findItems( cur_file, Qt::MatchFixedString ); if( !existing.empty() ) { delete existing.front(); } (void) new FileItem( m_l, cur_file, path ); } } }
QgsPointDisplacementRendererWidget::QgsPointDisplacementRendererWidget( QgsVectorLayer* layer, QgsStyleV2* style, QgsFeatureRendererV2* renderer ): \ QgsRendererV2Widget( layer, style ), mEmbeddedRendererWidget( 0 ) { if ( !layer ) { return; } //the renderer only applies to point vector layers if ( layer->wkbType() != QGis::WKBPoint && layer->wkbType() != QGis::WKBPoint25D ) { //setup blank dialog mRenderer = 0; setupBlankUi( layer->name() ); return; } setupUi( this ); if ( renderer && renderer->type() == "pointDisplacement" ) { mRenderer = dynamic_cast<QgsPointDisplacementRenderer*>( renderer->clone() ); } else { mRenderer = new QgsPointDisplacementRenderer(); } blockAllSignals( true ); //insert attributes into combo box if ( layer ) { const QgsFieldMap layerAttributes = layer->pendingFields(); QgsFieldMap::const_iterator it = layerAttributes.constBegin(); for ( ; it != layerAttributes.constEnd(); ++it ) { mLabelFieldComboBox->addItem( it.value().name() ); } mLabelFieldComboBox->addItem( tr( "None" ) ); QString currentLabelAttribute = mRenderer->labelAttributeName(); if ( !currentLabelAttribute.isEmpty() ) { mLabelFieldComboBox->setCurrentIndex( mLabelFieldComboBox->findText( currentLabelAttribute ) ); } else { mLabelFieldComboBox->setCurrentIndex( mLabelFieldComboBox->findText( tr( "None" ) ) ); } } //insert possible renderer types QStringList rendererList = QgsRendererV2Registry::instance()->renderersList(); QStringList::const_iterator it = rendererList.constBegin(); for ( ; it != rendererList.constEnd(); ++it ) { if ( *it != "pointDisplacement" ) { QgsRendererV2AbstractMetadata* m = QgsRendererV2Registry::instance()->rendererMetadata( *it ); mRendererComboBox->addItem( m->icon(), m->visibleName(), *it ); } } mCircleWidthSpinBox->setValue( mRenderer->circleWidth() ); mCircleColorButton->setColor( mRenderer->circleColor() ); mLabelColorButton->setColor( mRenderer->labelColor() ); mCircleModificationSpinBox->setValue( mRenderer->circleRadiusAddition() ); mDistanceSpinBox->setValue( mRenderer->tolerance() ); //scale dependent labelling mMaxScaleDenominatorEdit->setText( QString::number( mRenderer->maxLabelScaleDenominator() ) ); mMaxScaleDenominatorEdit->setValidator( new QDoubleValidator( mMaxScaleDenominatorEdit ) ); if ( mRenderer->maxLabelScaleDenominator() > 0 ) { mScaleDependentLabelsCheckBox->setCheckState( Qt::Checked ); } else { mScaleDependentLabelsCheckBox->setCheckState( Qt::Unchecked ); mMaxScaleDenominatorEdit->setEnabled( false ); } blockAllSignals( false ); //set the appropriate renderer dialog if ( mRenderer && mRenderer->embeddedRenderer() ) { QString rendererName = mRenderer->embeddedRenderer()->type(); int rendererIndex = mRendererComboBox->findData( rendererName ); if ( rendererIndex != -1 ) { mRendererComboBox->setCurrentIndex( rendererIndex ); on_mRendererComboBox_currentIndexChanged( rendererIndex ); } } updateCenterIcon(); }
void IngredientParserDialog::parseText() { previewIngView->clear(); Q3ListViewItem *last_item = 0; int line_num = 0; QStringList ingredients; if (ingredientTextEdit->document()->isEmpty()) ingredients = QStringList(); else ingredients = ingredientTextEdit->toPlainText().split( '\n', QString::SkipEmptyParts); for ( QStringList::const_iterator it = ingredients.constBegin(); it != ingredients.constEnd(); ++it ) { QString line = (*it).simplified(); ++line_num; int format_at = 0; Ingredient ing; //======amount======// int first_space = line.indexOf( " ", format_at+1 ); if ( first_space == -1 ) first_space = line.length(); int second_space = line.indexOf( " ", first_space+1 ); if ( second_space == -1 ) second_space = line.length(); Ingredient i; bool ok; i.setAmount(line.mid(format_at,second_space-format_at),&ok); if ( !ok ) { i.setAmount(line.mid(format_at,first_space-format_at),&ok); if ( ok ) format_at = first_space+1; } else format_at = second_space+1; if ( ok ) { ing.amount = i.amount; ing.amount_offset = i.amount_offset; } else kDebug()<<"no amount on line "<<line_num; //======unit======// first_space = line.indexOf( " ", format_at+1 ); if ( first_space == -1 ) first_space = line.length(); bool isUnit = false; QString unitCheck = line.mid(format_at,first_space-format_at); for ( UnitList::const_iterator unit_it = m_unitList.constBegin(); unit_it != m_unitList.constEnd(); ++unit_it ) { if ( (*unit_it).name() == unitCheck || (*unit_it).plural() == unitCheck || (*unit_it).nameAbbrev() == unitCheck || (*unit_it).pluralAbbrev() == unitCheck ) { isUnit = true; format_at = first_space+1; break; } } if ( isUnit ) { ing.units.setName(unitCheck); ing.units.setPlural(unitCheck); } else kDebug()<<"no unit on line "<<line_num; //======ingredient======// int ing_end = line.indexOf( QRegExp("(,|;)"), format_at+1 ); if ( ing_end == -1 ) ing_end = line.length(); ing.name = line.mid(format_at,ing_end-format_at); format_at = ing_end+2; //======prep method======// int end = line.length(); ing.prepMethodList = ElementList::split(",",line.mid(format_at,end-format_at)); last_item = new IngListViewItem(previewIngView,last_item,ing); enableButtonOk( true ); } }
LinkDialog::LinkDialog(QWidget* parent, Selection* selection) : KPageDialog(parent) , d(new Private) { setCaption(i18n("Insert Link")); setButtons(Ok | Cancel); setFaceType(List); // link for web or ftp d->internetPage = new QWidget(); d->p1 = addPage(d->internetPage, i18n("Internet")); d->p1->setHeader(i18n("Link to Internet Address")); d->p1->setIcon(KIcon("internet-web-browser")); QVBoxLayout* iLayout = new QVBoxLayout(d->internetPage); iLayout->addWidget(new QLabel(i18n("Text to display:"), d->internetPage)); d->internetText = new KLineEdit(d->internetPage); iLayout->addWidget(d->internetText); iLayout->addWidget(new QLabel(i18n("Internet address:"), d->internetPage)); d->internetLink = new KLineEdit(d->internetPage); iLayout->addWidget(d->internetLink); iLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); connect(d->internetText, SIGNAL(textChanged(const QString&)), this, SLOT(setText(const QString&))); // link for e-mail d->mailPage = new QWidget(); d->p2 = addPage(d->mailPage, i18n("Mail")); d->p2->setHeader(i18n("Link to Mail Address")); d->p2->setIcon(KIcon("mail-message")); QVBoxLayout* mLayout = new QVBoxLayout(d->mailPage); mLayout->addWidget(new QLabel(i18n("Text to display:"), d->mailPage)); d->mailText = new KLineEdit(d->mailPage); mLayout->addWidget(d->mailText); mLayout->addWidget(new QLabel(i18n("Email:"), d->mailPage)); d->mailLink = new KLineEdit(d->mailPage); mLayout->addWidget(d->mailLink); connect(d->mailText, SIGNAL(textChanged(const QString&)), this, SLOT(setText(const QString&))); mLayout->addWidget(new QLabel(i18n("Subject:"), d->mailPage)); d->mailSubject = new KLineEdit(d->mailPage); mLayout->addWidget(d->mailSubject); mLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); // link for external file d->filePage = new QWidget(); d->p3 = addPage(d->filePage, i18n("File")); d->p3->setHeader(i18n("Link to File")); d->p3->setIcon(KIcon("system-file-manager")); QVBoxLayout* fLayout = new QVBoxLayout(d->filePage); fLayout->addWidget(new QLabel(i18n("Text to display:"), d->filePage)); d->fileText = new KLineEdit(d->filePage); fLayout->addWidget(d->fileText); fLayout->addWidget(new QLabel(i18n("File location:"), d->filePage)); d->fileLink = new KUrlRequester(d->filePage); d->fileLink->completionObject()->setReplaceHome(true); d->fileLink->completionObject()->setReplaceEnv(true); fLayout->addWidget(d->fileLink); fLayout->addWidget(new QLabel(i18n("Recent file:"), d->filePage)); KComboBox* recentFile = new KComboBox(d->filePage); recentFile->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); recentFile->setMinimumContentsLength(40); fLayout->addWidget(recentFile); fLayout->addItem(new QSpacerItem(0, 40, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding)); connect(d->fileText, SIGNAL(textChanged(const QString&)), this, SLOT(setText(const QString&))); QObject::connect(recentFile, SIGNAL(highlighted(const QString &)), d->fileLink->lineEdit(), SLOT(setText(const QString &))); // populate recent files int index = 0; const QStringList fileList = KRecentDocument::recentDocuments(); for (QStringList::ConstIterator it = fileList.constBegin(); it != fileList.constEnd(); ++it) { KDesktopFile f(*it); if (!f.readUrl().isEmpty()) recentFile->insertItem(index++, f.readUrl()); } if (recentFile->count() == 0) { recentFile->insertItem(0, i18n("No Entries")); recentFile->setEnabled(false); } // link to another cell d->cellPage = new QWidget(); d->p4 = addPage(d->cellPage, i18n("Cell")); d->p4->setHeader(i18n("Link to Cell")); d->p4->setIcon(KIcon("table")); QVBoxLayout* cLayout = new QVBoxLayout(d->cellPage); cLayout->addWidget(new QLabel(i18n("Text to display:"), d->cellPage)); d->cellText = new KLineEdit(d->cellPage); cLayout->addWidget(d->cellText); cLayout->addWidget(new QLabel(i18n("Cell or Named Area:"), d->cellPage)); d->cellLink = new KComboBox(d->cellPage); d->cellLink->setEditable(true); const Sheet *sheet = selection->activeSheet(); if (sheet && selection) { Cell cell(sheet, selection->cursor()); d->cellLink->addItem(cell.fullName()); } const NamedAreaManager *manager = selection->activeSheet()->map()->namedAreaManager(); d->cellLink->addItems(manager->areaNames()); d->cellLink->setItemText(d->cellLink->currentIndex(), ""); cLayout->addWidget(d->cellLink); cLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); connect(d->cellText, SIGNAL(textChanged(const QString&)), this, SLOT(setText(const QString&))); showButtonSeparator(true); d->internetText->setFocus(); resize(400, 300); connect(this, SIGNAL(okClicked()), this, SLOT(slotOk())); }
void QgsSearchQueryBuilder::loadQuery() { QgsSettings s; QString lastQueryFileDir = s.value( QStringLiteral( "/UI/lastQueryFileDir" ), QDir::homePath() ).toString(); QString queryFileName = QFileDialog::getOpenFileName( nullptr, tr( "Load Query from File" ), lastQueryFileDir, tr( "Query files" ) + " (*.qqf);;" + tr( "All files" ) + " (*)" ); if ( queryFileName.isNull() ) { return; } QFile queryFile( queryFileName ); if ( !queryFile.open( QIODevice::ReadOnly ) ) { QMessageBox::critical( nullptr, tr( "Load Query from File" ), tr( "Could not open file for reading." ) ); return; } QDomDocument queryDoc; if ( !queryDoc.setContent( &queryFile ) ) { QMessageBox::critical( nullptr, tr( "Load Query from File" ), tr( "File is not a valid xml document." ) ); return; } QDomElement queryElem = queryDoc.firstChildElement( QStringLiteral( "Query" ) ); if ( queryElem.isNull() ) { QMessageBox::critical( nullptr, tr( "Load Query from File" ), tr( "File is not a valid query document." ) ); return; } QString query = queryElem.text(); //todo: test if all the attributes are valid QgsExpression search( query ); if ( search.hasParserError() ) { QMessageBox::critical( this, tr( "Query Result" ), search.parserErrorString() ); return; } QString newQueryText = query; #if 0 // TODO: implement with visitor pattern in QgsExpression QStringList attributes = searchTree->referencedColumns(); QMap< QString, QString> attributesToReplace; QStringList existingAttributes; //get all existing fields QMap<QString, int>::const_iterator fieldIt = mFieldMap.constBegin(); for ( ; fieldIt != mFieldMap.constEnd(); ++fieldIt ) { existingAttributes.push_back( fieldIt.key() ); } //if a field does not exist, ask what field should be used instead QStringList::const_iterator attIt = attributes.constBegin(); for ( ; attIt != attributes.constEnd(); ++attIt ) { //test if attribute is there if ( !mFieldMap.contains( attIt ) ) { bool ok; QString replaceAttribute = QInputDialog::getItem( 0, tr( "Select Attribute" ), tr( "There is no attribute '%1' in the current vector layer. Please select an existing attribute." ).arg( *attIt ), existingAttributes, 0, false, &ok ); if ( !ok || replaceAttribute.isEmpty() ) { return; } attributesToReplace.insert( *attIt, replaceAttribute ); } } //Now replace all the string in the query QList<QgsSearchTreeNode *> columnRefList = searchTree->columnRefNodes(); QList<QgsSearchTreeNode *>::iterator columnIt = columnRefList.begin(); for ( ; columnIt != columnRefList.end(); ++columnIt ) { QMap< QString, QString>::const_iterator replaceIt = attributesToReplace.find( ( *columnIt )->columnRef() ); if ( replaceIt != attributesToReplace.constEnd() ) { ( *columnIt )->setColumnRef( replaceIt.value() ); } } if ( attributesToReplace.size() > 0 ) { newQueryText = query; } #endif txtSQL->clear(); txtSQL->insertText( newQueryText ); }
bool QgsVectorLayerDiagramProvider::prepare( const QgsRenderContext& context, QStringList& attributeNames ) { QgsDiagramLayerSettings& s2 = mSettings; const QgsMapSettings& mapSettings = mEngine->mapSettings(); s2.ct = nullptr; if ( mapSettings.hasCrsTransformEnabled() ) { if ( context.coordinateTransform() ) // this is context for layer rendering - use its CT as it includes correct datum transform s2.ct = context.coordinateTransform()->clone(); else // otherwise fall back to creating our own CT - this one may not have the correct datum transform! s2.ct = new QgsCoordinateTransform( mLayerCrs, mapSettings.destinationCrs() ); } s2.xform = &mapSettings.mapToPixel(); s2.fields = mFields; s2.renderer = mDiagRenderer; const QgsDiagramRendererV2* diagRenderer = s2.renderer; //add attributes needed by the diagram renderer QList<QString> att = diagRenderer->diagramAttributes(); QList<QString>::const_iterator attIt = att.constBegin(); for ( ; attIt != att.constEnd(); ++attIt ) { QgsExpression* expression = diagRenderer->diagram()->getExpression( *attIt, context.expressionContext() ); QStringList columns = expression->referencedColumns(); QStringList::const_iterator columnsIterator = columns.constBegin(); for ( ; columnsIterator != columns.constEnd(); ++columnsIterator ) { if ( !attributeNames.contains( *columnsIterator ) ) attributeNames << *columnsIterator; } } const QgsLinearlyInterpolatedDiagramRenderer* linearlyInterpolatedDiagramRenderer = dynamic_cast<const QgsLinearlyInterpolatedDiagramRenderer*>( diagRenderer ); if ( linearlyInterpolatedDiagramRenderer ) { if ( linearlyInterpolatedDiagramRenderer->classificationAttributeIsExpression() ) { QgsExpression* expression = diagRenderer->diagram()->getExpression( linearlyInterpolatedDiagramRenderer->classificationAttributeExpression(), context.expressionContext() ); QStringList columns = expression->referencedColumns(); QStringList::const_iterator columnsIterator = columns.constBegin(); for ( ; columnsIterator != columns.constEnd(); ++columnsIterator ) { if ( !attributeNames.contains( *columnsIterator ) ) attributeNames << *columnsIterator; } } else { QString name = mFields.at( linearlyInterpolatedDiagramRenderer->classificationAttribute() ).name(); if ( !attributeNames.contains( name ) ) attributeNames << name; } } //and the ones needed for data defined diagram positions if ( mSettings.xPosColumn != -1 ) attributeNames << mFields.at( mSettings.xPosColumn ).name(); if ( mSettings.yPosColumn != -1 ) attributeNames << mFields.at( mSettings.yPosColumn ).name(); return true; }
QgsInvertedPolygonRendererWidget::QgsInvertedPolygonRendererWidget( QgsVectorLayer* layer, QgsStyleV2* style, QgsFeatureRendererV2* renderer ) : QgsRendererV2Widget( layer, style ) { if ( !layer ) { return; } // the renderer only applies to polygon vector layers if ( layer->wkbType() != QGis::WKBPolygon && layer->wkbType() != QGis::WKBPolygon25D && layer->wkbType() != QGis::WKBMultiPolygon && layer->wkbType() != QGis::WKBMultiPolygon25D ) { //setup blank dialog mRenderer.reset( 0 ); QGridLayout* layout = new QGridLayout( this ); QLabel* label = new QLabel( tr( "The inverted polygon renderer only applies to polygon and multipolygon layers. \n" "'%1' is not a polygon layer and then cannot be displayed" ) .arg( layer->name() ), this ); layout->addWidget( label ); return; } setupUi( this ); // try to recognize the previous renderer // (null renderer means "no previous renderer") if ( renderer ) { mRenderer.reset( QgsInvertedPolygonRenderer::convertFromRenderer( renderer ) ); } if ( ! mRenderer ) { mRenderer.reset( new QgsInvertedPolygonRenderer() ); } mMergePolygonsCheckBox->blockSignals( true ); mMergePolygonsCheckBox->setCheckState( mRenderer->preprocessingEnabled() ? Qt::Checked : Qt::Unchecked ); mMergePolygonsCheckBox->blockSignals( false ); int currentEmbeddedIdx = 0; //insert possible renderer types QStringList rendererList = QgsRendererV2Registry::instance()->renderersList(); QStringList::const_iterator it = rendererList.constBegin(); int idx = 0; mRendererComboBox->blockSignals( true ); for ( ; it != rendererList.constEnd(); ++it, ++idx ) { if (( *it != "invertedPolygonRenderer" ) && //< an inverted renderer cannot contain another inverted renderer ( *it != "pointDisplacement" ) ) //< an inverted renderer can only contain a polygon renderer { QgsRendererV2AbstractMetadata* m = QgsRendererV2Registry::instance()->rendererMetadata( *it ); mRendererComboBox->addItem( m->icon(), m->visibleName(), /* data */ *it ); const QgsFeatureRendererV2* embeddedRenderer = mRenderer->embeddedRenderer(); if ( embeddedRenderer && embeddedRenderer->type() == m->name() ) { // store the combo box index of the current renderer currentEmbeddedIdx = idx; } } } mRendererComboBox->blockSignals( false ); int oldIdx = mRendererComboBox->currentIndex(); mRendererComboBox->setCurrentIndex( currentEmbeddedIdx ); if ( oldIdx == currentEmbeddedIdx ) { // force update on_mRendererComboBox_currentIndexChanged( currentEmbeddedIdx ); } }
static void mergeKeySets(NameSet *dest, const QStringList &src) { QStringList::const_iterator it = src.constBegin(); for (; it != src.constEnd(); ++it) dest->insert(unescapedKey(*it), QString()); }
QString CppToolsPlugin::correspondingHeaderOrSourceI(const QString &fileName) const { const Core::ICore *core = Core::ICore::instance(); const Core::MimeDatabase *mimeDatase = core->mimeDatabase(); ProjectExplorer::ProjectExplorerPlugin *explorer = ProjectExplorer::ProjectExplorerPlugin::instance(); ProjectExplorer::Project *project = (explorer ? explorer->currentProject() : 0); const QFileInfo fi(fileName); const FileType type = fileType(mimeDatase, fi); if (debug) qDebug() << Q_FUNC_INFO << fileName << type; if (type == UnknownType) return QString(); const QDir absoluteDir = fi.absoluteDir(); const QString baseName = fi.completeBaseName(); const QStringList suffixes = matchingCandidateSuffixes(mimeDatase, type); const QString privateHeaderSuffix = QLatin1String("_p"); const QChar dot = QLatin1Char('.'); // Check base matches 'source.h'-> 'source.cpp' and vice versa const QStringList::const_iterator scend = suffixes.constEnd(); for (QStringList::const_iterator it = suffixes.constBegin(); it != scend; ++it) { QString candidate = baseName; candidate += dot; candidate += *it; const QFileInfo candidateFi = findFile(absoluteDir, candidate, project); if (candidateFi.isFile()) return candidateFi.absoluteFilePath(); } if (type == HeaderFile) { // 'source_p.h': try 'source.cpp' if (baseName.endsWith(privateHeaderSuffix)) { QString sourceBaseName = baseName; sourceBaseName.truncate(sourceBaseName.size() - privateHeaderSuffix.size()); for (QStringList::const_iterator it = suffixes.constBegin(); it != scend; ++it) { QString candidate = sourceBaseName; candidate += dot; candidate += *it; const QFileInfo candidateFi = findFile(absoluteDir, candidate, project); if (candidateFi.isFile()) return candidateFi.absoluteFilePath(); } } } else { // 'source.cpp': try 'source_p.h' const QStringList::const_iterator scend = suffixes.constEnd(); for (QStringList::const_iterator it = suffixes.constBegin(); it != scend; ++it) { QString candidate = baseName; candidate += privateHeaderSuffix; candidate += dot; candidate += *it; const QFileInfo candidateFi = findFile(absoluteDir, candidate, project); if (candidateFi.isFile()) return candidateFi.absoluteFilePath(); } } return QString(); }
void QWinSettingsPrivate::set(const QString &uKey, const QVariant &value) { if (writeHandle() == 0) { setStatus(QSettings::AccessError); return; } QString rKey = escapedKey(uKey); HKEY handle = createOrOpenKey(writeHandle(), registryPermissions, keyPath(rKey)); if (handle == 0) { setStatus(QSettings::AccessError); return; } DWORD type; QByteArray regValueBuff; // Determine the type switch (value.type()) { case QVariant::List: case QVariant::StringList: { // If none of the elements contains '\0', we can use REG_MULTI_SZ, the // native registry string list type. Otherwise we use REG_BINARY. type = REG_MULTI_SZ; QStringList l = variantListToStringList(value.toList()); QStringList::const_iterator it = l.constBegin(); for (; it != l.constEnd(); ++it) { if ((*it).length() == 0 || stringContainsNullChar(*it)) { type = REG_BINARY; break; } } if (type == REG_BINARY) { QString s = variantToString(value); regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2); } else { QStringList::const_iterator it = l.constBegin(); for (; it != l.constEnd(); ++it) { const QString &s = *it; regValueBuff += QByteArray((const char*)s.utf16(), (s.length() + 1) * 2); } regValueBuff.append((char)0); regValueBuff.append((char)0); } break; } case QVariant::Int: case QVariant::UInt: { type = REG_DWORD; qint32 i = value.toInt(); regValueBuff = QByteArray((const char*)&i, sizeof(qint32)); break; } case QVariant::LongLong: case QVariant::ULongLong: { type = REG_QWORD; qint64 i = value.toLongLong(); regValueBuff = QByteArray((const char*)&i, sizeof(qint64)); break; } case QVariant::ByteArray: // fallthrough intended default: { // If the string does not contain '\0', we can use REG_SZ, the native registry // string type. Otherwise we use REG_BINARY. QString s = variantToString(value); type = stringContainsNullChar(s) ? REG_BINARY : REG_SZ; if (type == REG_BINARY) { regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2); } else { regValueBuff = QByteArray((const char*)s.utf16(), (s.length() + 1) * 2); } break; } } // set the value LONG res = RegSetValueEx(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()), 0, type, reinterpret_cast<const unsigned char*>(regValueBuff.constData()), regValueBuff.size()); if (res == ERROR_SUCCESS) { deleteWriteHandleOnExit = false; } else { qWarning("QSettings: failed to set subkey \"%s\": %s", rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data()); setStatus(QSettings::AccessError); } RegCloseKey(handle); }
void QgsSimpleLineSymbolLayerV2::applyDataDefinedSymbology( QgsSymbolV2RenderContext& context, QPen& pen, QPen& selPen, double& offset ) { //data defined properties double scaledWidth = 0; QgsExpression* strokeWidthExpression = expression( "width" ); if ( strokeWidthExpression ) { scaledWidth = strokeWidthExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble() * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit, mWidthMapUnitScale ); pen.setWidthF( scaledWidth ); selPen.setWidthF( scaledWidth ); } else if ( context.renderHints() & QgsSymbolV2::DataDefinedSizeScale ) { scaledWidth = mWidth * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit, mWidthMapUnitScale ); pen.setWidthF( scaledWidth ); selPen.setWidthF( scaledWidth ); } //color QgsExpression* strokeColorExpression = expression( "color" ); if ( strokeColorExpression ) { pen.setColor( QgsSymbolLayerV2Utils::decodeColor( strokeColorExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() ) ); } //offset offset = mOffset; QgsExpression* lineOffsetExpression = expression( "offset" ); if ( lineOffsetExpression ) { offset = lineOffsetExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble(); } //dash dot vector QgsExpression* dashPatternExpression = expression( "customdash" ); if ( dashPatternExpression ) { double scaledWidth = mWidth * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit, mWidthMapUnitScale ); double dashWidthDiv = mPen.widthF(); if ( strokeWidthExpression ) { dashWidthDiv = pen.widthF(); scaledWidth = pen.widthF(); } //fix dash pattern width in Qt 4.8 QStringList versionSplit = QString( qVersion() ).split( "." ); if ( versionSplit.size() > 1 && versionSplit.at( 1 ).toInt() >= 8 && ( scaledWidth * context.renderContext().rasterScaleFactor() ) < 1.0 ) { dashWidthDiv = 1.0; } QVector<qreal> dashVector; QStringList dashList = dashPatternExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString().split( ";" ); QStringList::const_iterator dashIt = dashList.constBegin(); for ( ; dashIt != dashList.constEnd(); ++dashIt ) { dashVector.push_back( dashIt->toDouble() * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mCustomDashPatternUnit, mCustomDashPatternMapUnitScale ) / dashWidthDiv ); } pen.setDashPattern( dashVector ); } //join style QgsExpression* joinStyleExpression = expression( "joinstyle" ); if ( joinStyleExpression ) { QString joinStyleString = joinStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString(); pen.setJoinStyle( QgsSymbolLayerV2Utils::decodePenJoinStyle( joinStyleString ) ); } //cap style QgsExpression* capStyleExpression = expression( "capstyle" ); if ( capStyleExpression ) { QString capStyleString = capStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString(); pen.setCapStyle( QgsSymbolLayerV2Utils::decodePenCapStyle( capStyleString ) ); } }
int main(int argc, char * argv[]) { KComponentData componentData("newapi"); KexiDB::DriverManager manager; QStringList names = manager.driverNames(); kDebug() << "DRIVERS: "; for (QStringList::ConstIterator it = names.constBegin(); it != names.constEnd() ; ++it) kDebug() << *it; if (manager.error()) { kDebug() << manager.errorMsg(); return 1; } //get driver KexiDB::Driver *driver = manager.driver("mySQL"); if (manager.error()) { kDebug() << manager.errorMsg(); return 1; } //connection data that can be later reused KexiDB::ConnectionData conn_data; conn_data.userName = "******"; if (argc > 1) conn_data.password = argv[1]; else conn_data.password = "******"; conn_data.hostName = "localhost"; KexiDB::Connection *conn = driver->createConnection(conn_data); if (driver->error()) { kDebug() << driver->errorMsg(); return 1; } if (!conn->connect()) { kDebug() << conn->errorMsg(); return 1; } if (!conn->useDatabase("test")) { kDebug() << "use db:" << conn->errorMsg(); return 1; } kDebug() << "Creating first cursor"; KexiDB::Cursor *c = conn->executeQuery("select * from Applications"); if (!c) kDebug() << conn->errorMsg(); kDebug() << "Creating second cursor"; KexiDB::Cursor *c2 = conn->executeQuery("select * from Applications"); if (!c2) kDebug() << conn->errorMsg(); QStringList l = conn->databaseNames(); if (l.isEmpty()) kDebug() << conn->errorMsg(); kDebug() << "Databases:"; for (QStringList::ConstIterator it = l.constBegin(); it != l.constEnd() ; ++it) kDebug() << *it; if (c) { while (c->moveNext()) { kDebug() << "Cursor: Value(0)" << c->value(0).toString(); kDebug() << "Cursor: Value(1)" << c->value(1).toString(); } kDebug() << "Cursor error:" << c->errorMsg(); } if (c2) { while (c2->moveNext()) { kDebug() << "Cursor2: Value(0)" << c2->value(0).toString(); kDebug() << "Cursor2: Value(1)" << c2->value(1).toString(); } } if (c) { kDebug() << "Cursor::prev"; while (c->movePrev()) { kDebug() << "Cursor: Value(0)" << c->value(0).toString(); kDebug() << "Cursor: Value(1)" << c->value(1).toString(); } kDebug() << "up/down"; c->moveNext(); kDebug() << "Cursor: Value(0)" << c->value(0).toString(); kDebug() << "Cursor: Value(1)" << c->value(1).toString(); c->moveNext(); kDebug() << "Cursor: Value(0)" << c->value(0).toString(); kDebug() << "Cursor: Value(1)" << c->value(1).toString(); c->movePrev(); kDebug() << "Cursor: Value(0)" << c->value(0).toString(); kDebug() << "Cursor: Value(1)" << c->value(1).toString(); c->movePrev(); kDebug() << "Cursor: Value(0)" << c->value(0).toString(); kDebug() << "Cursor: Value(1)" << c->value(1).toString(); } #if 0 KexiDB::Table *t = conn->tableSchema("persons"); if (t) t->debug(); t = conn->tableSchema("cars"); if (t) t->debug(); // conn->tableNames(); if (!conn->disconnect()) { kDebug() << conn->errorMsg(); return 1; } debug("before del"); delete conn; debug("after del"); #endif return 0; }