Ejemplo n.º 1
0
void CProject::updateMainSourceDepend()
{
	// mainSourceDependMap
	QString mainSourceDependValue = settings->value("MainSourceDepend").toString();
	if (mainSourceDependValue.isEmpty())
		return;

	// 将分组保存在dependList中
	QStringList dependList = mainSourceDependValue.split(QRegExp("\\s*:\\s*"), QString::SkipEmptyParts);
	QStringList::const_iterator constIterator = dependList.constBegin();
	QStringList::const_iterator endIterator = dependList.constEnd();
	// 分析组内的依赖关系, 保存在dependMap中
	while (constIterator != endIterator) {
		// 将组内文件名保存在childList中
		QStringList childList = (*constIterator).split(QRegExp("\\s+"), QString::SkipEmptyParts);
		// 如果组内的单词个数小于2, 则无效, 放弃它处理下一个.
		if (childList.count() < 2) {
			++constIterator;
			continue;
		}

		// 主内第一个名称是main文件的依赖方式标志, "all"表示所有, "only"表示不依赖其它源文件, "part"标示依赖指定的源文件
		QString mode = childList.at(0);
		// 组内的第二个文件名是含main() 的源文件, 保存在mainSource中
		QString mainSource = childList.at(1);
		mainSource.remove(QRegExp("^./"));
		// 如果mainSourceList 中没有该mainSource, 则放弃该mainSource处理下一个.
		if (!mainSourceList.contains(mainSource)) {
			++constIterator;
			continue;
		}

		// 若mode = "only", 则它不依赖于任何其它源文件, dependSources为"only";
		// 若mode = "part", 则它依赖于指定的源文件, dependSources, 为 "part" 和 mainSource后面的文件
		// 若mode 不是上面两种情况, 则保持mainSourceDependMap中原来的值"all"
		QFileInfo fileInfo(mainSource);
		QString executeFile = fileInfo.path() + "/" + fileInfo.completeBaseName();
		executeFile.remove(QRegExp("^./"));
		if (mode == "only") {
			mainSourceDependMap[mainSource] = QStringList() << "only";
			executeFileDependMap[executeFile].removeAt(0);
			executeFileDependMap[executeFile].insert(0, "only");
		} else if (mode == "part") {
			QStringList dependSources;
			QStringList objects;
			dependSources << "part";
			objects << "part" << executeFile + ".o";
			QString source = QString();
			QString object = QString();
			int count = childList.count();
			int i = 2;
			while (i < count) {
				source = childList.at(i);
				source.remove(QRegExp("^./"));
				dependSources << source;
				fileInfo.setFile(source);
				object = fileInfo.path() + "/" + fileInfo.completeBaseName() + ".o";
				object.remove(QRegExp("^./"));
				objects << object;
				++i;
			}
			mainSourceDependMap[mainSource] = dependSources;
			executeFileDependMap[executeFile] = objects;
		}
		++constIterator;
	}
}
Ejemplo n.º 2
0
void QgsSimpleLineSymbolLayerV2::applyDataDefinedSymbology( QgsSymbolV2RenderContext& context, QPen& pen, QPen& selPen, double& offset )
{
  if ( mDataDefinedProperties.isEmpty() )
    return; // shortcut

  //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
  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 ) );
  }
}
Ejemplo n.º 3
0
QgsAbstractGeometryV2* QgsGeometryEditUtils::avoidIntersections( const QgsAbstractGeometryV2& geom, QMap<QgsVectorLayer*, QSet<QgsFeatureId> > ignoreFeatures )
{
  QScopedPointer<QgsGeometryEngine> geomEngine( QgsGeometry::createGeometryEngine( &geom ) );
  if ( geomEngine.isNull() )
  {
    return nullptr;
  }
  QgsWKBTypes::Type geomTypeBeforeModification = geom.wkbType();


  //check if g has polygon type
  if ( QgsWKBTypes::geometryType( geomTypeBeforeModification ) != QgsWKBTypes::PolygonGeometry )
  {
    return nullptr;
  }

  //read avoid intersections list from project properties
  bool listReadOk;
  QStringList avoidIntersectionsList = QgsProject::instance()->readListEntry( "Digitizing", "/AvoidIntersectionsList", QStringList(), &listReadOk );
  if ( !listReadOk )
    return nullptr; //no intersections stored in project does not mean error

  QList< QgsAbstractGeometryV2* > nearGeometries;

  //go through list, convert each layer to vector layer and call QgsVectorLayer::removePolygonIntersections for each
  QgsVectorLayer* currentLayer = nullptr;
  QStringList::const_iterator aIt = avoidIntersectionsList.constBegin();
  for ( ; aIt != avoidIntersectionsList.constEnd(); ++aIt )
  {
    currentLayer = dynamic_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( *aIt ) );
    if ( currentLayer )
    {
      QgsFeatureIds ignoreIds;
      QMap<QgsVectorLayer*, QSet<qint64> >::const_iterator ignoreIt = ignoreFeatures.find( currentLayer );
      if ( ignoreIt != ignoreFeatures.constEnd() )
        ignoreIds = ignoreIt.value();

      QgsFeatureIterator fi = currentLayer->getFeatures( QgsFeatureRequest( geom.boundingBox() )
                              .setFlags( QgsFeatureRequest::ExactIntersect )
                              .setSubsetOfAttributes( QgsAttributeList() ) );
      QgsFeature f;
      while ( fi.nextFeature( f ) )
      {
        if ( ignoreIds.contains( f.id() ) )
          continue;

        if ( !f.hasGeometry() )
          continue;

        nearGeometries << f.geometry().geometry()->clone();
      }
    }
  }

  if ( nearGeometries.isEmpty() )
  {
    return nullptr;
  }


  QgsAbstractGeometryV2* combinedGeometries = geomEngine.data()->combine( nearGeometries );
  qDeleteAll( nearGeometries );
  if ( !combinedGeometries )
  {
    return nullptr;
  }

  QgsAbstractGeometryV2* diffGeom = geomEngine.data()->difference( *combinedGeometries );

  delete combinedGeometries;
  return diffGeom;
}
Ejemplo n.º 4
0
static void mergeKeySets(NameSet *dest, const QStringList &src)
{
    QStringList::const_iterator it = src.constBegin();
    for (; it != src.constEnd(); ++it)
        dest->insert(unescapedKey(*it), QString());
}
Ejemplo n.º 5
0
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 );
		}
	}
}
Ejemplo n.º 6
0
///////////////////////////
//                       //
//  PACKING OPERATIONS   //
//                       //
///////////////////////////
void
ProjectPackager::runPack()
{

RG_DEBUG << "ProjectPackager::runPack()";

    m_info->setText(tr("Packing project..."));

    // go into spinner mode
    m_progress->setMaximum(0);

    QStringList audioFiles = getAudioFiles();

    // the base tmp directory where we'll assemble all the files
    m_packTmpDirName = QString("%1/rosegarden-project-packager-tmp").arg(QDir::homePath());

    // the data directory where audio and other files will go
    QFileInfo fi(m_filename);
    m_packDataDirName = fi.baseName();

RG_DEBUG << "using tmp data directory: " << m_packTmpDirName << "/" << 
    m_packDataDirName;

    QDir tmpDir(m_packTmpDirName);

    // get the original filename saved by RosegardenMainWindow and the name of
    // the new one we'll be including in the bundle (name isn't changing, path
    // component changes from one to the other)
    // QFileInfo::baseName() given /tmp/foo/bar/rat.rgp returns rat
    //
    // m_filename comes in already having an .rgp extension, but the file
    // was saved .rg
    QString oldName = QString("%1/%2.rg").arg(fi.path()).arg(fi.baseName());
    QString newName = QString("%1/%2.rg").arg(m_packTmpDirName).arg(fi.baseName());

    // if the tmp directory already exists, just hose it
    rmdirRecursive(m_packTmpDirName);

    // make the temporary working directory
    if (tmpDir.mkdir(m_packTmpDirName)) {

    } else {
        puke(tr("<qt><p>Could not create temporary working directory.</p>%1</qt>").arg(m_abortText));
        return;
    }

    m_info->setText(tr("Copying audio files..."));

    // leave spinner mode
    m_progress->setMaximum(100);
    m_progress->setValue(0);

    // count total audio files
    int af = 0;
    QStringList::const_iterator si;
    for (si = audioFiles.constBegin(); si != audioFiles.constEnd(); ++si)
        af++;
    int afStep = ((af == 0) ? 1 : (100 / af));

    // make the data subdir
    tmpDir.mkdir(m_packDataDirName);    

    // copy the audio files (do not remove the originals!)
    af = 0;
    for (si = audioFiles.constBegin(); si != audioFiles.constEnd(); ++si) {

        // comes in with full path and filename
        QString srcFile = (*si);
        QString srcFilePk = QString("%1.pk").arg(srcFile);

        // needs the filename split away from the path, so we can replace the
        // path with the new one
        QFileInfo fi(*si);
        QString filename = QString("%1.%2").arg(fi.baseName()).arg(fi.completeSuffix());

        QString dstFile = QString("%1/%2/%3").arg(m_packTmpDirName).arg(m_packDataDirName).arg(filename);
        QString dstFilePk = QString("%1.pk").arg(dstFile);

RG_DEBUG << "cp " << srcFile << " " << dstFile;
RG_DEBUG << "cp " << srcFilePk << " " << dstFilePk;

        if (!QFile::copy(srcFile, dstFile)) {
            puke(tr("<qt>Could not copy<br>%1<br>  to<br>%2<br><br>Processing aborted.</qt>").arg(srcFile).arg(dstFile));
            return;
        }

        // Try to copy the .wav.pk file derived from transforming the name of
        // the .wav file.  We don't trap the fail condition for this one and
        // allow it to fail silently without complaining or aborting.  If the
        // .wav.pk files are missing, they will be generated again as needed.
        //
        // Legacy .rgp files ship with improperly named .wav.pk files, from
        // a bug in the original rosegarden-project-package script.  You'd wind
        // up with an .rgp that contained, for example:
        //
        //   emergence-rg-0014.wav.pk
        //   RG-AUDIO-0014.wav.pk
        //
        // That is why this version of the project packager doesn't screw around
        // with the original filenames!
        QFile::copy(srcFilePk, dstFilePk);

        m_progress->setValue(afStep * ++af);
    }

    // deal with adding any extra files
    QStringList extraFiles;

    // first, if the composition includes synth plugins, there may be assorted
    // random audio files, soundfonts, and who knows what else in use by these
    // plugins
    //
    // obtain a list of these files, and rewrite the XML to update the referring
    // path from its original source to point to our bundled copy instead
    QString newPath = QString("%1/%2").arg(m_packTmpDirName).arg(m_packDataDirName);
    extraFiles = getPluginFilesAndRewriteXML(oldName, newPath);

    // If we do the above here and add it to extraFiles then if the user has any
    // other extra files to add by hand, it all processes out the same way with
    // no extra bundling code required (unless we want to flac any random extra
    // .wav files, and I say no, let's not get that complicated)

    // Copy the modified .rg file to the working tmp dir

RG_DEBUG << "cp " << oldName << " " << newName;

    // copy m_filename(.rgp) as $tmp/m_filename.rg
    if (!QFile::copy(oldName, newName)) {
        puke(tr("<qt>Could not copy<br>%1<br>  to<br>%2<br><br>Processing aborted.</qt>").arg(oldName).arg(newName));
        return;
    }

    QMessageBox::StandardButton reply = QMessageBox::information(this,
            tr("Rosegarden"),
            tr("<qt><p>Rosegarden can add any number of extra files you may desire to a project package.  For example, you may wish to include an explanatory text file, a soundfont, a bank definition for ZynAddSubFX, or perhaps some cover art.</p><p>Would you like to include any additional files?</p></qt>"),
            QMessageBox::Yes | QMessageBox::No, QMessageBox::No);

    while (reply == QMessageBox::Yes) {

        // it would take some trouble to make the last used paths thing work
        // here, where we're building a list of files from potentially anywhere,
        // so we'll just use the open_file path as it was last set elsewhere,
        // and leave it at that until somebody complains
        QSettings settings;
        settings.beginGroup(LastUsedPathsConfigGroup);
        QString directory = settings.value("open_file", QDir::homePath()).toString();
        settings.endGroup();

        // must iterate over a copy of the QStringList returned by
        // (Q)FileDialog::getOpenFileNames for some reason
        //
        // NOTE: This still doesn't work.  I can only add one filename.
        // Something broken in the subclass of QFileDialog?  Bad code?  I'm just
        // leaving it unresolved for now. One file at a time at least satisfies
        // the bare minimum requirements
        QStringList files =  FileDialog::getOpenFileNames(this, "Open File", directory, tr("All files") + " (*)", 0, 0);
        extraFiles << files;
       
        //!!!  It would be nice to show the list of files already chosen and
        // added, in some nice little accumulator list widget, but this would
        // require doing something more complicated than using QMessageBox
        // static convenience functions, and it's probably just not worth it
        reply =  QMessageBox::information(this,
                tr("Rosegarden"),
                tr("<qt><p>Would you like to include any additional files?</p></qt>"),
                QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
    }

    m_info->setText(tr("Copying plugin data and extra files..."));

    // reset progress bar
    m_progress->setValue(0);

    // count total audio files
    int ef = 0;
    for (si = extraFiles.constBegin(); si != extraFiles.constEnd(); ++si)
        ef++;
    int efStep = ((ef == 0) ? 1 : (100 / ef));

    // copy the extra files (do not remove the originals!)
    // (iterator previously declared)
    ef = 0;
    for (si = extraFiles.constBegin(); si != extraFiles.constEnd(); ++si) {
    
        // each QStringList item from the FileDialog will include the full path
        QString srcFile = (*si);

        // so we cut it up to swap the source dir for the dest dir while leaving
        // the complete filename stuck on the end
        QFileInfo efi(*si);
        QString basename = QString("%1.%2").arg(efi.baseName()).arg(efi.completeSuffix());
        QString dstFile = QString("%1/%2/%3").arg(m_packTmpDirName).arg(m_packDataDirName).arg(basename);

RG_DEBUG << "cp " << srcFile << " " << dstFile;

        if (!QFile::copy(srcFile, dstFile)) {
            puke(tr("<qt>Could not copy<br>%1<br>  to<br>%2<br><br>Processing aborted.</qt>").arg(srcFile).arg(dstFile));
            return;
        }

        m_progress->setValue(efStep * ++ef);
    }

    // and now we have everything discovered, uncovered, added, smothered,
    // scattered and splattered, and we're ready to pack the files and
    // get the hell out of here!
    startAudioEncoder(audioFiles);
}
Ejemplo n.º 7
0
bool QgsWFSProvider::addFeatures( QgsFeatureList &flist )
{
  //create <Transaction> xml
  QDomDocument transactionDoc;
  QDomElement transactionElem = createTransactionElement( transactionDoc );
  transactionDoc.appendChild( transactionElem );

  //find out typename from uri and strip namespace prefix
  QString tname = mShared->mURI.typeName();
  if ( tname.isNull() )
  {
    return false;
  }
  removeNamespacePrefix( tname );

  //Add the features
  QgsFeatureList::iterator featureIt = flist.begin();
  for ( ; featureIt != flist.end(); ++featureIt )
  {
    //Insert element
    QDomElement insertElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Insert" );
    transactionElem.appendChild( insertElem );

    QDomElement featureElem = transactionDoc.createElementNS( mApplicationNamespace, tname );

    QgsAttributes featureAttributes = featureIt->attributes();
    int nAttrs = featureAttributes.size();
    for ( int i = 0; i < nAttrs; ++i )
    {
      const QVariant& value = featureAttributes.at( i );
      if ( value.isValid() && !value.isNull() )
      {
        QDomElement fieldElem = transactionDoc.createElementNS( mApplicationNamespace, mShared->mFields.at( i ).name() );
        QDomText fieldText = transactionDoc.createTextNode( value.toString() );
        fieldElem.appendChild( fieldText );
        featureElem.appendChild( fieldElem );
      }
    }

    //add geometry column (as gml)
    const QgsGeometry* geometry = featureIt->constGeometry();
    if ( geometry != nullptr )
    {
      QDomElement geomElem = transactionDoc.createElementNS( mApplicationNamespace, mShared->mGeometryAttribute );
      QgsGeometry the_geom( *geometry );
      // convert to multi if the layer geom type is multi and the geom is not
      if ( QGis::isMultiType( this->geometryType( ) ) && ! the_geom.isMultipart( ) )
      {
        the_geom.convertToMultiType();
      }
      QDomElement gmlElem = QgsOgcUtils::geometryToGML( &the_geom, transactionDoc );
      if ( !gmlElem.isNull() )
      {
        gmlElem.setAttribute( "srsName", crs().authid() );
        geomElem.appendChild( gmlElem );
        featureElem.appendChild( geomElem );
      }
    }

    insertElem.appendChild( featureElem );
  }

  QDomDocument serverResponse;
  bool success = sendTransactionDocument( transactionDoc, serverResponse );
  if ( !success )
  {
    return false;
  }

  if ( transactionSuccess( serverResponse ) )
  {
    //transaction successful. Add the features to the cache
    QStringList idList = insertedFeatureIds( serverResponse );
    QStringList::const_iterator idIt = idList.constBegin();
    featureIt = flist.begin();

    QVector<QgsWFSFeatureGmlIdPair> serializedFeatureList;
    for ( ; idIt != idList.constEnd() && featureIt != flist.end(); ++idIt, ++featureIt )
    {
      serializedFeatureList.push_back( QgsWFSFeatureGmlIdPair( *featureIt, *idIt ) );
    }
    mShared->serializeFeatures( serializedFeatureList );

    // And now set the feature id from the one got from the database
    QMap< QString, QgsFeatureId > map;
    for ( int idx = 0; idx < serializedFeatureList.size(); idx++ )
      map[ serializedFeatureList[idx].second ] = serializedFeatureList[idx].first.id();

    idIt = idList.constBegin();
    featureIt = flist.begin();
    for ( ; idIt != idList.constEnd() && featureIt != flist.end(); ++idIt, ++featureIt )
    {
      if ( map.find( *idIt ) != map.end() )
        featureIt->setFeatureId( map[*idIt] );
    }

    return true;
  }
  else
  {
    handleException( serverResponse );
    return false;
  }
}
Ejemplo n.º 8
0
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::LayerUnits;

    snapLayers.append( snapLayer );
  }

  mSnapper->setSnapLayers( snapLayers );

  if ( mSnapper->snapMapPoint( 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 );
      delete lineB;

      if ( intersectionPoint && intersectionPoint->type() == QGis::Point )
      {
        //We have to check the intersection point is inside the tolerance distance for both layers
        double toleranceA = 0;
        double toleranceB = 0;
        for ( int i = 0 ;i < snapLayers.size();++i )
        {
          if ( snapLayers[i].mLayer == oSegIt->layer )
          {
            toleranceA = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType );
          }
          if ( snapLayers[i].mLayer == iSegIt->layer )
          {
            toleranceB = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType );
          }
        }
        QgsGeometry* cursorPoint = QgsGeometry::fromPoint( point );
        double distance = intersectionPoint->distance( *cursorPoint );
        if ( distance < toleranceA && distance < toleranceB )
        {
          iSegIt->snappedVertex = intersectionPoint->asPoint();
          myResults.append( *iSegIt );
        }
        delete cursorPoint;
      }
      delete intersectionPoint;

    }

    delete lineA;
  }

  if ( myResults.length() > 0 )
  {
    results.clear();
    results = myResults;
  }

  return 0;
}
Ejemplo n.º 9
0
bool FileSystemInfo::FromStringList(const QStringList &slist)
{
    QStringList::const_iterator it = slist.constBegin();
    return FromStringList(it, slist.constEnd());
}
Ejemplo n.º 10
0
void TestRegressionWindow::directoryListingFinished(KJob *)
{
	QTreeWidgetItem *topLevelItem = m_ui.treeWidget->topLevelItem(0);

	// Gather a lot of statistics...
	unsigned long availableDomFiles = 0;
	unsigned long availableDumpFiles = 0;
	unsigned long availableRenderFiles = 0;

	unsigned long ignoredJSTests = 0;
	unsigned long availableJSTests = 0;

	unsigned long ignoredXMLTests = 0;
	unsigned long availableXMLTests = 0;

	unsigned long ignoredHTMLTests = 0;
	unsigned long availableHTMLTests = 0;

	unsigned long ignoredDOMTSTests = 0;
	unsigned long availableDOMTSTests = 0;

	// Start the actual data processing...
	QMap<QString, QStringList>::const_iterator it = m_directoryMap.constBegin();
	const QMap<QString, QStringList>::const_iterator end = m_directoryMap.constEnd();

	for(; it != end; ++it)
	{
		QString directory = it.key();
		QStringList filenames = it.value();

		if(filenames.isEmpty()) // Do not add empty directories at all...
			continue;

		bool hasIgnores = (m_ignoreMap.constFind(directory) != m_directoryMap.constEnd());
		bool hasFailures = (m_failureMap.constFind(directory) != m_failureMap.constEnd());

		// Extract parent directory...
		int position = directory.lastIndexOf('/');

		QString parentDirectory = directory.mid(0, (position == -1 ? 0 : position));
		QString parentDirectoryItem = directory.mid(position + 1);

		bool hasParentIgnores = (m_ignoreMap.constFind(parentDirectory) != m_directoryMap.constEnd());
		bool hasParentFailures = (m_failureMap.constFind(parentDirectory) != m_failureMap.constEnd());

		// Sort in ascending order...
		filenames.sort();

		QStringList::const_iterator it2 = filenames.constBegin();
		const QStringList::const_iterator end2 = filenames.constEnd();

		// Create new tree widget item for the active directory...
		QTreeWidgetItem *parent = topLevelItem;

		if(!directory.isEmpty())
		{
			parent = new QTreeWidgetItem(topLevelItem, QStringList(directory));

			// Directory is completely ignored, mark it 'yellow'...
			if(hasParentIgnores && m_ignoreMap[parentDirectory].contains(parentDirectoryItem))
				parent->setIcon(0, m_ignorePixmap);

			// Directory is completely known to fail, mark it 'red'...
			if(hasParentFailures && m_failureMap[parentDirectory].contains(parentDirectoryItem))
				parent->setIcon(0, m_failKnownPixmap);
		}

		// Add all contained files as new items below 'parent'...
		for(; it2 != end2; ++it2)
		{
			QString test = (*it2);
			QString cacheName = directory + "/" + test;	//krazy:exclude=duoblequote_chars DOM demands chars

			QTreeWidgetItem *testItem = new QTreeWidgetItem(parent, QStringList(KUrl(test).path()));

			// Remember name <-> item pair...
			assert(m_itemMap.contains(cacheName));
			m_itemMap.insert(cacheName, testItem);

			bool ignore = (hasIgnores && m_ignoreMap[directory].contains(test));
			bool ignoreParent = (hasParentIgnores && m_ignoreMap[parentDirectory].contains(parentDirectoryItem));

			bool failure = (hasFailures && m_failureMap[directory].contains(test));

			// Check baseline directory for this test...
			QString baseLinePath = m_testsUrl.path() + "/baseline/" + cacheName;

			bool dom[9], render[9];
			for(unsigned int i = 0; i < 9; ++i)
			{
				if(i == 0)
				{
					dom[i] = (QFileInfo(baseLinePath + "-dom").exists());
					render[i] = (QFileInfo(baseLinePath + "-render").exists());
				}
				else
				{
					dom[i] = (QFileInfo(baseLinePath + "-" + QString::number(i) + "-dom").exists());	//krazy:exclude=duoblequote_chars DOM demands chars
					render[i] = (QFileInfo(baseLinePath + "-" + QString::number(i) + "-render").exists());	//krazy:exclude=duoblequote_chars DOM demands chars
				}
			}

			bool dump = (QFileInfo(baseLinePath + "-dump.png").exists());

			// Ignored tests are marked 'yellow'...
			if(ignore)
				testItem->setIcon(0, m_ignorePixmap);

			// Tests, known to fail, are marked 'red'...
			if(failure)
				testItem->setIcon(0, m_failKnownPixmap);

			// Detect whether the tests has no corresponding baseline items...
			if(!ignore && !failure)
			{
				if(!dom[0] && !dump && !render && !cacheName.endsWith(".js") && !cacheName.startsWith("domts"))
				{
					// See if parent directory is completely ignored...
					if(!ignoreParent)
						testItem->setIcon(0, m_noBaselinePixmap);
				}
			}

			// Update statistics...
			if(dump)
				availableDumpFiles++;

			for(unsigned i = 0; i < 9; ++i)
			{
				if(dom[i])
					availableDomFiles++;

				if(render[i])
					availableRenderFiles++;
			}

			// Count DOM Testsuite files separated... (these have no baseline items!)
			if(cacheName.startsWith("domts"))
			{
				// See if parent directory is completely ignored...
				if(ignore || ignoreParent)
					ignoredDOMTSTests++;
				else
					availableDOMTSTests++;
			}

			if(cacheName.endsWith(".html") || cacheName.endsWith(".htm") || cacheName.endsWith(".xhtml"))
			{
				if(ignore || ignoreParent)
					ignoredHTMLTests++;
				else
					availableHTMLTests++;
			}
			else if(cacheName.endsWith(".xml"))
			{
				if(ignore || ignoreParent)
					ignoredXMLTests++;
				else
					availableXMLTests++;
			}
			else if(cacheName.endsWith(".js"))
			{
				unsigned long containedTests = 0;

				// Try hard to _ESTIMATE_ the number of tests...
				// I really meant estimate, no way to calculate it perfectly.

				QString jsFilePath = m_testsUrl.path() + "/tests/" + cacheName;
				assert(QFileInfo(jsFilePath).exists() == true);

				QStringList fileList = readListFile(jsFilePath);
				QString fileContent = fileList.join("");

				// #1 -> Check js file for the 'reportResult' calls...
				containedTests = fileContent.count("reportResult");

				// #2 -> Check js file for 'openPage' calls...
				containedTests += fileContent.count("openPage");

				// #3 -> Check js file for 'checkOutput' calls...
				containedTests += fileContent.count("checkOutput");

				// #4 -> Fallback for ie. mozilla/ecma files...
				if(containedTests == 0) // Doesn't use 'reportResult' scheme...
					containedTests++;

				if(ignore || ignoreParent)
					ignoredJSTests += containedTests;
				else
					availableJSTests += containedTests;
			}
		}
	}

	// Now we can calculate all ignored/available tests...
	unsigned long ignoredTests = ignoredJSTests + ignoredXMLTests + ignoredHTMLTests;
	unsigned long availableTests = availableJSTests + availableXMLTests + availableHTMLTests;

	// This estimates the number of total tests, depending on the mode...
	m_totalTests = availableDomFiles + availableDumpFiles + availableRenderFiles +
				   availableDOMTSTests + availableJSTests;

	m_totalTestsJS = availableJSTests;
	m_totalTestsDOMTS = availableDOMTSTests;

	// Update progress bar range...
	updateProgressBarRange();

	QString statistics = QString("<body><table border='0' align='center' cellspacing='15'>") +
						 QString("<tr valign='top'><td colspan='3'><center><b>Statistics</b></center></td></tr>") +
						 QString("<tr valign='middle'><td>JS Tests</td><td>" + QString::number(availableJSTests) + "</td><td>(" + QString::number(ignoredJSTests) + " ignored)</td></tr>") +
						 QString("<tr valign='middle'><td>XML Tests</td><td>" + QString::number(availableXMLTests) + "</td><td>(" + QString::number(ignoredXMLTests) + " ignored)</td></tr>") +
						 QString("<tr valign='middle'><td>HTML Tests</td><td>" + QString::number(availableHTMLTests) + "</td><td>(" + QString::number(ignoredHTMLTests) + " ignored)</td></tr>") +
						 QString("</table></body>");

	// Go to end...
	QTextCursor cursor = m_ui.textEdit->textCursor();
	cursor.movePosition(QTextCursor::End);
	m_ui.textEdit->setTextCursor(cursor);

	// Insert statistics...
	m_ui.textEdit->insertHtml(statistics);

	// Update treeview...
	m_ui.treeWidget->headerItem()->setText(0, i18n("Available Tests: %1 (ignored: %2)", availableTests, ignoredTests));
}
Ejemplo n.º 11
0
    KTRMRequestHandler()
    {
        m_pimp = tp_New("KTRM", "0.1");
        //tp_SetDebug(m_pimp, true);
        tp_SetTRMCollisionThreshold(m_pimp, 100);
        tp_SetAutoSaveThreshold(m_pimp, -1);
        tp_SetMoveFiles(m_pimp, false);
        tp_SetRenameFiles(m_pimp, false);
#if HAVE_MUSICBRAINZ >= 4
        tp_SetFileNameEncoding(m_pimp, "UTF-8");
#else
        tp_SetUseUTF8(m_pimp, true);
#endif
        tp_SetNotifyCallback(m_pimp, TRMNotifyCallback, 0);

        // Re-read proxy config.
        KProtocolManager::reparseConfiguration();

        if(KProtocolManager::useProxy()) {
            // split code copied from kcm_kio.
            QString noProxiesFor = KProtocolManager::noProxyFor();
            QStringList noProxies = QStringList::split(QRegExp("[',''\t'' ']"), noProxiesFor);
            bool useProxy = true;

            // Host that libtunepimp will contact.
            QString tunepimpHost = "www.musicbrainz.org";
            QString tunepimpHostWithPort = "www.musicbrainz.org:80";

            // Check what hosts are allowed to proceed without being proxied,
            // or is using reversed proxy, what hosts must be proxied.
            for(QStringList::ConstIterator it = noProxies.constBegin(); it != noProxies.constEnd(); ++it) {
                QString normalizedHost = KNetwork::KResolver::normalizeDomain(*it);

                if(normalizedHost == tunepimpHost ||
                   tunepimpHost.endsWith("." + normalizedHost))
                {
                    useProxy = false;
                    break;
                }

                // KDE's proxy mechanism also supports exempting a specific
                // host/port combo, check that also.
                if(normalizedHost == tunepimpHostWithPort ||
                   tunepimpHostWithPort.endsWith("." + normalizedHost))
                {
                    useProxy = false;
                    break;
                }
            }

            // KDE supports a reverse proxy mechanism.  Uh, yay.
            if(KProtocolManager::useReverseProxy())
                useProxy = !useProxy;

            if(useProxy) {
                KURL proxy = KProtocolManager::proxyFor("http");
                QString proxyHost = proxy.host();

                kdDebug(65432) << "Using proxy server " << proxyHost << " for www.musicbrainz.org.\n";
                tp_SetProxy(m_pimp, proxyHost.latin1(), short(proxy.port()));
            }
        }
    }
Ejemplo n.º 12
0
void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillParam, QColor& defaultFill, bool& hasOutlineParam, QColor& defaultOutline,
                                      bool& hasOutlineWidthParam, double& defaultOutlineWidth ) const
{
  if ( elem.isNull() )
  {
    return;
  }

  //we already have all the information, no need to go deeper
  if ( hasFillParam && hasOutlineParam && hasOutlineWidthParam )
  {
    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( "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 key = keyValueSplit.at( 0 );
        QString value = keyValueSplit.at( 1 );
        valueSplit = value.split( " " );
        if ( !hasFillParam && value.startsWith( "param(fill)" ) )
        {
          hasFillParam = true;
          if ( valueSplit.size() > 1 )
          {
            defaultFill = QColor( valueSplit.at( 1 ) );
          }
        }
        else if ( !hasOutlineParam && value.startsWith( "param(outline)" ) )
        {
          hasOutlineParam = true;
          if ( valueSplit.size() > 1 )
          {
            defaultOutline = QColor( valueSplit.at( 1 ) );
          }
        }
        else if ( !hasOutlineWidthParam && value.startsWith( "param(outline-width)" ) )
        {
          hasOutlineWidthParam = true;
          if ( valueSplit.size() > 1 )
          {
            defaultOutlineWidth = valueSplit.at( 1 ).toDouble();
          }
        }
      }
    }
    else
    {
      QString value = attribute.value();
      valueSplit = value.split( " " );
      if ( !hasFillParam && value.startsWith( "param(fill)" ) )
      {
        hasFillParam = true;
        if ( valueSplit.size() > 1 )
        {
          defaultFill = QColor( valueSplit.at( 1 ) );
        }
      }
      else if ( !hasOutlineParam && value.startsWith( "param(outline)" ) )
      {
        hasOutlineParam = true;
        if ( valueSplit.size() > 1 )
        {
          defaultOutline = QColor( valueSplit.at( 1 ) );
        }
      }
      else if ( !hasOutlineWidthParam && value.startsWith( "param(outline-width)" ) )
      {
        hasOutlineWidthParam = true;
        if ( valueSplit.size() > 1 )
        {
          defaultOutlineWidth = valueSplit.at( 1 ).toDouble();
        }
      }
    }
  }

  //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, defaultFill, hasOutlineParam, defaultOutline, hasOutlineWidthParam, defaultOutlineWidth );
  }
}
Ejemplo n.º 13
0
void QgsSvgCache::replaceElemParams( QDomElement& elem, const QColor& fill, const QColor& outline, double outlineWidth )
{
  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( "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( "param(fill" ) )
        {
          value = fill.name();
        }
        else if ( value.startsWith( "param(outline)" ) )
        {
          value = outline.name();
        }
        else if ( value.startsWith( "param(outline-width)" ) )
        {
          value = QString::number( outlineWidth );
        }

        if ( entryIt != entryList.constBegin() )
        {
          newAttributeString.append( ";" );
        }
        newAttributeString.append( key + ":" + value );
      }
      elem.setAttribute( attribute.name(), newAttributeString );
    }
    else
    {
      QString value = attribute.value();
      if ( value.startsWith( "param(fill)" ) )
      {
        elem.setAttribute( attribute.name(), fill.name() );
      }
      else if ( value.startsWith( "param(outline)" ) )
      {
        elem.setAttribute( attribute.name(), outline.name() );
      }
      else if ( value.startsWith( "param(outline-width)" ) )
      {
        elem.setAttribute( attribute.name(), QString::number( outlineWidth ) );
      }
    }
  }

  QDomNodeList childList = elem.childNodes();
  int nChildren = childList.count();
  for ( int i = 0; i < nChildren; ++i )
  {
    QDomElement childElem = childList.at( i ).toElement();
    replaceElemParams( childElem, fill, outline, outlineWidth );
  }
}
Ejemplo n.º 14
0
void QgsDiagramSettings::readXml( const QDomElement& elem, const QgsVectorLayer* layer )
{
  Q_UNUSED( layer );

  enabled = ( elem.attribute( "enabled", "1" ) != "0" );
  if ( !QgsFontUtils::setFromXmlChildNode( font, elem, "fontProperties" ) )
  {
    font.fromString( elem.attribute( "font" ) );
  }
  backgroundColor.setNamedColor( elem.attribute( "backgroundColor" ) );
  backgroundColor.setAlpha( elem.attribute( "backgroundAlpha" ).toInt() );
  size.setWidth( elem.attribute( "width" ).toDouble() );
  size.setHeight( elem.attribute( "height" ).toDouble() );
  transparency = elem.attribute( "transparency", "0" ).toInt();
  penColor.setNamedColor( elem.attribute( "penColor" ) );
  int penAlpha = elem.attribute( "penAlpha", "255" ).toInt();
  penColor.setAlpha( penAlpha );
  penWidth = elem.attribute( "penWidth" ).toDouble();

  minScaleDenominator = elem.attribute( "minScaleDenominator", "-1" ).toDouble();
  maxScaleDenominator = elem.attribute( "maxScaleDenominator", "-1" ).toDouble();
  if ( elem.hasAttribute( "scaleBasedVisibility" ) )
  {
    scaleBasedVisibility = ( elem.attribute( "scaleBasedVisibility", "1" ) != "0" );
  }
  else
  {
    scaleBasedVisibility = minScaleDenominator >= 0 && maxScaleDenominator >= 0;
  }

  //diagram size unit type and scale
  if ( elem.attribute( "sizeType" ) == "MapUnits" )
  {
    //compatibility with pre-2.16 project files
    sizeType = QgsUnitTypes::RenderMapUnits;
  }
  else
  {
    sizeType = QgsUnitTypes::decodeRenderUnit( elem.attribute( "sizeType" ) );
  }
  sizeScale = QgsSymbolLayerUtils::decodeMapUnitScale( elem.attribute( "sizeScale" ) );

  //line width unit type and scale
  lineSizeUnit = QgsUnitTypes::decodeRenderUnit( elem.attribute( "lineSizeType" ) );
  lineSizeScale = QgsSymbolLayerUtils::decodeMapUnitScale( elem.attribute( "lineSizeScale" ) );

  //label placement method
  if ( elem.attribute( "labelPlacementMethod" ) == "Height" )
  {
    labelPlacementMethod = Height;
  }
  else
  {
    labelPlacementMethod = XHeight;
  }

  // orientation
  if ( elem.attribute( "diagramOrientation" ) == "Left" )
  {
    diagramOrientation = Left;
  }
  else if ( elem.attribute( "diagramOrientation" ) == "Right" )
  {
    diagramOrientation = Right;
  }
  else if ( elem.attribute( "diagramOrientation" ) == "Down" )
  {
    diagramOrientation = Down;
  }
  else
  {
    diagramOrientation = Up;
  }

  // scale dependency
  if ( elem.attribute( "scaleDependency" ) == "Diameter" )
  {
    scaleByArea = false;
  }
  else
  {
    scaleByArea = true;
  }

  barWidth = elem.attribute( "barWidth" ).toDouble();

  angleOffset = elem.attribute( "angleOffset" ).toInt();

  minimumSize = elem.attribute( "minimumSize" ).toDouble();

  //colors
  categoryColors.clear();
  QDomNodeList attributes = elem.elementsByTagName( "attribute" );

  if ( attributes.length() > 0 )
  {
    for ( int i = 0; i < attributes.size(); i++ )
    {
      QDomElement attrElem = attributes.at( i ).toElement();
      QColor newColor( attrElem.attribute( "color" ) );
      newColor.setAlpha( 255 - transparency );
      categoryColors.append( newColor );
      categoryAttributes.append( attrElem.attribute( "field" ) );
      categoryLabels.append( attrElem.attribute( "label" ) );
      if ( categoryLabels.back().isEmpty() )
      {
        categoryLabels.back() = categoryAttributes.back();
      }
    }
  }
  else
  {
    // Restore old format attributes and colors

    QStringList colorList = elem.attribute( "colors" ).split( '/' );
    QStringList::const_iterator colorIt = colorList.constBegin();
    for ( ; colorIt != colorList.constEnd(); ++colorIt )
    {
      QColor newColor( *colorIt );
      newColor.setAlpha( 255 - transparency );
      categoryColors.append( QColor( newColor ) );
    }

    //attribute indices
    categoryAttributes.clear();
    QStringList catList = elem.attribute( "categories" ).split( '/' );
    QStringList::const_iterator catIt = catList.constBegin();
    for ( ; catIt != catList.constEnd(); ++catIt )
    {
      categoryAttributes.append( *catIt );
      categoryLabels.append( *catIt );
    }
  }
}
Ejemplo n.º 15
0
void
ProjectPackager::startAudioDecoder(QStringList flacFiles, QStringList wavpackFiles)
{
    // we can't do a oneliner bash script straight out of a QProcess command
    // line, so we'll have to create a purpose built script and run that
    QString scriptName("/tmp/rosegarden-audio-decoder-backend");
    m_script.setFileName(scriptName);

    // remove any lingering copy from a previous run
    if (m_script.exists()) m_script.remove();

    if (!m_script.open(QIODevice::WriteOnly | QIODevice::Text)) {
        puke(tr("<qt><p>Unable to write to temporary backend processing script %1.</p>%2</qt>").arg(scriptName).arg(m_abortText));
        return;
    }

    QTextStream out(&m_script);
    out << "# This script was generated by Rosegarden to combine multiple external processing"      << endl
        << "# operations so they could be managed by a single QProcess.  If you find this script"   << endl
        << "# it is likely that something has gone terribly wrong. See http://rosegardenmusic.com" << endl;

    int errorPoint = 1;

    // The working directory must be the key to why tar is not failing, but
    // failing to do anything detectable.  Let's cut apart m_filename...
    QFileInfo fi(m_filename);
    QString dirname = fi.path();
    QString basename = QString("%1.%2").arg(fi.baseName()).arg(fi.completeSuffix());

    // There were mysterious stupid problems running tar xf in a separate
    // QProcess step, so screw it, let's just throw it into this script!
    out << "tar xzf \"" << basename << "\" || exit " << errorPoint++ << endl;

    // Decode FLAC files
    QStringList::const_iterator si;
    for (si = flacFiles.constBegin(); si != flacFiles.constEnd(); ++si) {
        QString o1 = (*si);

        // the file strings are things like xxx.wav.rgp.flac
        // without specifying the output file they will turn into xxx.wav.rgp.wav
        // thus it is best to specify the output as xxx.wav
        //
        // files from new project packages have rg-23324234.flac files, files
        // from old project packages have rg-2343242.wav.rgp.flac files, so we
        // want a robust solution to this one... QFileInfo::baseName() should
        // get it
        QFileInfo fi(o1);
        QString o2 = QString("%1/%2.wav").arg(fi.path()).arg(fi.baseName());

        // we'll eschew anything fancy or pretty in this disposable script and
        // just write a command on each line, terminating with an || exit n
        // which can be used to figure out at which point processing broke, for
        // cheap and easy error reporting without a lot of fancy stream wiring
        //
        // (let's just try escaping spaces &c. with surrounding " and see if
        // that is good enough)

RG_DEBUG << "flad -d " << o1 << " -o " << o2;

        out << "flac -d \"" <<  o1 << "\" -o \"" << o2 << "\" && rm \"" << o1 <<  "\" || exit " << errorPoint << endl;
        errorPoint++;
    }

    // Decode WavPack files
    for (si = wavpackFiles.constBegin(); si != wavpackFiles.constEnd(); ++si) {
        QString o = (*si);

        // NOTE: wvunpack -d means "delete the file if successful" not "decode"
        out << "wvunpack -d \"" <<  o << "\" || exit " << errorPoint << endl;
        errorPoint++;
    }

    m_script.close();

    // run the assembled script
    m_process = new QProcess;

    // set to the working directory extracted from m_filename above, as this is
    // was apparently the reason why tar always failed to do anything
    m_process->setWorkingDirectory(dirname);
    m_process->start("bash", QStringList() << scriptName);
    connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)),
            this, SLOT(finishUnpack(int, QProcess::ExitStatus)));

    // wait up to 30 seconds for process to start
    m_info->setText(tr("Decoding audio files..."));
    if (!m_process->waitForStarted()) {
        puke(tr("<qt>Could not start backend processing script %1.</qt>").arg(scriptName));
        return;
    }
}
Ejemplo n.º 16
0
void BackendGoogleMaps::slotHTMLEvents(const QStringList& events)
{
    // for some events, we just note that they appeared and then process them later on:
    bool centerProbablyChanged    = false;
    bool mapTypeChanged           = false;
    bool zoomProbablyChanged      = false;
    bool mapBoundsProbablyChanged = false;
    QIntList movedClusters;
    QList<QPersistentModelIndex> movedMarkers;
    QIntList clickedClusters;

    // TODO: verify that the order of the events is still okay
    //       or that the order does not matter
    for (QStringList::const_iterator it = events.constBegin(); it != events.constEnd(); ++it)
    {
        const QString eventCode           = it->left(2);
        const QString eventParameter      = it->mid(2);
        const QStringList eventParameters = eventParameter.split(QLatin1Char( '/' ));

        if (eventCode == QLatin1String("MT"))
        {
            // map type changed
            mapTypeChanged  = true;
            d->cacheMapType = eventParameter;
        }
        else if (eventCode == QLatin1String("MB"))
        {   // NOTE: event currently disabled in javascript part
            // map bounds changed
            centerProbablyChanged    = true;
            zoomProbablyChanged      = true;
            mapBoundsProbablyChanged = true;
        }
        else if (eventCode == QLatin1String("ZC"))
        {   // NOTE: event currently disabled in javascript part
            // zoom changed
            zoomProbablyChanged      = true;
            mapBoundsProbablyChanged = true;
        }
        else if (eventCode == QLatin1String("id"))
        {
            // idle after drastic map changes
            centerProbablyChanged    = true;
            zoomProbablyChanged      = true;
            mapBoundsProbablyChanged = true;
        }
        else if (eventCode == QLatin1String("cm"))
        {
            /// @todo buffer this event type!
            // cluster moved
            bool okay              = false;
            const int clusterIndex = eventParameter.toInt(&okay);
            KGEOMAP_ASSERT(okay);

            if (!okay)
                continue;

            KGEOMAP_ASSERT(clusterIndex >= 0);
            KGEOMAP_ASSERT(clusterIndex<s->clusterList.size());

            if ((clusterIndex<0)||(clusterIndex>s->clusterList.size()))
                continue;

            // re-read the marker position:
            GeoCoordinates clusterCoordinates;
            const bool isValid = d->htmlWidget->runScript2Coordinates(
                    QString::fromLatin1("kgeomapGetClusterPosition(%1);").arg(clusterIndex),
                    &clusterCoordinates
                );

            KGEOMAP_ASSERT(isValid);

            if (!isValid)
                continue;

            /// @todo this discards the altitude!
            /// @todo is this really necessary? clusters should be regenerated anyway...
            s->clusterList[clusterIndex].coordinates = clusterCoordinates;

            movedClusters << clusterIndex;
        }
        else if (eventCode == QLatin1String("cs"))
        {
            /// @todo buffer this event type!
            // cluster snapped
            bool okay = false;
            const int clusterIndex = eventParameters.first().toInt(&okay);
            KGEOMAP_ASSERT(okay);

            if (!okay)
                continue;

            KGEOMAP_ASSERT(clusterIndex >= 0);
            KGEOMAP_ASSERT(clusterIndex<s->clusterList.size());

            if ((clusterIndex<0)||(clusterIndex>s->clusterList.size()))
                continue;

            // determine to which marker we snapped:
            okay                  = false;
            const int snapModelId = eventParameters.at(1).toInt(&okay);
            KGEOMAP_ASSERT(okay);

            if (!okay)
                continue;

            okay                   = false;
            const int snapMarkerId = eventParameters.at(2).toInt(&okay);
            KGEOMAP_ASSERT(okay);

            if (!okay)
                continue;

            /// @todo emit signal here or later?
            ModelHelper* const modelHelper  = s->ungroupedModels.at(snapModelId);
            QAbstractItemModel* const model = modelHelper->model();
            QPair<int, QModelIndex> snapTargetIndex(snapModelId, model->index(snapMarkerId, 0));
            emit(signalClustersMoved(QIntList()<<clusterIndex, snapTargetIndex));
        }
        else if (eventCode == QLatin1String("cc"))
        {
            /// @todo buffer this event type!
            // cluster clicked
            bool okay              = false;
            const int clusterIndex = eventParameter.toInt(&okay);
            KGEOMAP_ASSERT(okay);

            if (!okay)
                continue;

            KGEOMAP_ASSERT(clusterIndex>=0);
            KGEOMAP_ASSERT(clusterIndex<s->clusterList.size());

            if ((clusterIndex<0)||(clusterIndex>s->clusterList.size()))
                continue;

            clickedClusters << clusterIndex;
        }
        else if (eventCode == QLatin1String("mm"))
        {
//             // TODO: buffer this event type!
//             // marker moved
//             bool okay           = false;
//             const int markerRow = eventParameter.toInt(&okay);
//             KGEOMAP_ASSERT(okay);
//
//             if (!okay)
//                 continue;
//
//             KGEOMAP_ASSERT(markerRow >= 0);
//             KGEOMAP_ASSERT(markerRow<s->specialMarkersModel->rowCount());
//
//             if ((markerRow<0)||(markerRow>=s->specialMarkersModel->rowCount()))
//                 continue;
//
//             // re-read the marker position:
//             GeoCoordinates markerCoordinates;
//             const bool isValid = d->htmlWidget->runScript2Coordinates(
//                     QString::fromLatin1("kgeomapGetMarkerPosition(%1);").arg(markerRow),
//                     &markerCoordinates
//                 );
//
//             KGEOMAP_ASSERT(isValid);
//
//             if (!isValid)
//                 continue;
//
//             // TODO: this discards the altitude!
//             const QModelIndex markerIndex = s->specialMarkersModel->index(markerRow, 0);
//             s->specialMarkersModel->setData(markerIndex, QVariant::fromValue(markerCoordinates), s->specialMarkersCoordinatesRole);
//
//             movedMarkers << QPersistentModelIndex(markerIndex);
        }
        else if (eventCode == QLatin1String("do"))
        {
            // debug output:
            kDebug() << QString::fromLatin1("javascript:%1").arg(eventParameter);
        }
    }

    if (!movedClusters.isEmpty())
    {
        kDebug()<<movedClusters;
        emit(signalClustersMoved(movedClusters, QPair<int, QModelIndex>(-1, QModelIndex())));
    }

    if (!movedMarkers.isEmpty())
    {
        kDebug()<<movedMarkers;
//         emit(signalSpecialMarkersMoved(movedMarkers));
    }

    if (!clickedClusters.isEmpty())
    {
        kDebug()<<clickedClusters;
        emit(signalClustersClicked(clickedClusters));
    }

    // now process the buffered events:
    if (mapTypeChanged)
    {
        updateZoomMinMaxCache();
    }

    if (zoomProbablyChanged)
    {
        d->cacheZoom = d->htmlWidget->runScript(QLatin1String("kgeomapGetZoom();")).toInt();
        emit(signalZoomChanged(QString::fromLatin1("googlemaps:%1").arg(d->cacheZoom)));
    }

    if (centerProbablyChanged)
    {
        // there is nothing we can do if the coordinates are invalid
        /*const bool isValid = */d->htmlWidget->runScript2Coordinates(QLatin1String("kgeomapGetCenter();"), &(d->cacheCenter));
    }

    // update the actions if necessary:
    if (zoomProbablyChanged || mapTypeChanged || centerProbablyChanged)
    {
        updateActionAvailability();
    }

    if (mapBoundsProbablyChanged)
    {
        const QString mapBoundsString = d->htmlWidget->runScript(QLatin1String("kgeomapGetBounds();")).toString();
        KGeoMapHelperParseBoundsString(mapBoundsString, &d->cacheBounds);
    }

    if (mapBoundsProbablyChanged||!movedClusters.isEmpty())
    {
        s->worldMapWidget->markClustersAsDirty();
        s->worldMapWidget->updateClusters();
    }
}
Ejemplo n.º 17
0
QStringList
ProjectPackager::getPluginFilesAndRewriteXML(const QString fileToModify, const QString newPath)
{
    // yet another miserable wrinkle in this whole wretched thing: we
    // automatically ignore audio files not actually used by segments, but
    // Rosegarden wants to hunt for the missing (but useless) files when we load
    // the result, so we have to strip them out of the XML too
    //
    // ARGH!!!
    QStringList usedAudioFiles;
    if (m_mode == ProjectPackager::Pack) usedAudioFiles = getAudioFiles();

    QStringList list;

    // read the input file
    QString inText;

    bool readOK = GzipFile::readFromFile(fileToModify, inText);
    if (!readOK) {
        puke(tr("<qt><p>Unable to read %1.</p>%2</qt>").arg(fileToModify).arg(m_abortText));
        return QStringList();
    }

    // the pre-process input stream
    QString preText = inText;
    QTextStream preIn(&preText, QIODevice::ReadOnly);

    // the pre-process output steram
    QString postText;
    QTextStream preOut(&postText, QIODevice::WriteOnly);

    // insert \n between tags
    do {
        QString l = preIn.readLine();
        l.replace(QRegExp("><"), ">\n<");
        preOut << l << endl;
    } while (!preIn.atEnd());

    // the input stream
    QTextStream inStream(&postText, QIODevice::ReadOnly);

    // the output stream
    QString outText;
    QTextStream outStream(&outText, QIODevice::WriteOnly);
    outStream.setCodec("UTF-8");

    // synth plugin XML:
    //
    //  <synth identifier="dssi:/usr/lib/dssi/fluidsynth-dssi.so:FluidSynth-DSSI" bypassed="false" >
    //       <configure key="__ROSEGARDEN__:__RESERVED__:ProjectDirectoryKey" value="/home/michael/rosegarden/"/>
    //       <configure key="load" value="/home/michael/data/soundfonts/PC51f.sf2"/>
    //  </synth>    
    QString pluginAudioPathKey("<configure key=\"__ROSEGARDEN__:__RESERVED__:ProjectDirectoryKey\" value=\"");
    QString pluginAudioDataKey("<configure key=\"load\" value=\"");

    // audio path XML:
    //
    //  <audiofiles>
    //       <audioPath value="~/rosegarden/"/>
    //  </audiofiles>
    QString audioPathKey("<audioPath value=\"");

    // audio file XML:
    //  <audio id="4" file="rg-20071210-214212-5.wav" label="rg-20071210-214212-5.wav"/>
    //  -or-
    //  <audio file="asdfasdf" id="0" label="asdfasdf"/>
    //
    //  only common thread is "audio "
    QString audioFileKey("<audio ");

    QString valueTagEndKey("\"/>");

    // process the input line by line and stream it all back out, making any
    // necessary modifications along the way
    QString line;

    int c = 0;

    do {

        line = inStream.readLine();
        // don't flood the console
        if (c < 10) {
            RG_DEBUG << "LINE: " << ++c << " BUFFER SIZE: " << line.size();
        }

        if (line.contains(pluginAudioPathKey)) {

RG_DEBUG << "rewriting plugin audio path tag...";

            // we don't care what the old path was at all, this was the bug;
            // just write the new path straight up
            QString extract = newPath;
            extract.prepend(pluginAudioPathKey);
            extract.append(valueTagEndKey);

RG_DEBUG << "old line: " << line;

            line = extract;

RG_DEBUG << "new line: " << line;

        } else if (line.contains(pluginAudioDataKey)) {

            // note that "plugin audio data" is a bit of a misnomer, as this
            // could contain a soundfont or who knows what else; they're handled
            // the same way regardless, as "extra files" to add to the package

RG_DEBUG << "rewriting the path for a plugin data item...";

            int s = line.indexOf(pluginAudioDataKey) + pluginAudioDataKey.length();
            int e = line.indexOf(valueTagEndKey);

            QString extract = line.mid(s, e - s);
            
RG_DEBUG << "extracted value string:  value=\"" << extract << "\"";

            // save the extracted path to the list of extra files (and this is
            // the one part of these three block copied implementations that
            // differs significantly--really should refactor this into some
            // function, but I decided just not to bother)
            list << extract;

            // alter the path component (note that we added extract to files
            // BEFORE changing its path)
            QFileInfo fi(extract);
            extract = QString("%1/%2.%3").arg(newPath).arg(fi.baseName()).arg(fi.completeSuffix());

            // construct a new line around the altered substring
            extract.prepend(pluginAudioDataKey);
            extract.append(valueTagEndKey);

RG_DEBUG << "old line: " << line;

            line = extract;

RG_DEBUG << "new line: " << line;

        } else if (line.contains(audioPathKey)) {

RG_DEBUG << "rewriting document audio path...";

            // we don't care what the old path was at all, this was the bug;
            // just write the new path straight up
            //
            QString extract = newPath;
            extract.prepend(audioPathKey);
            extract.append(valueTagEndKey);

RG_DEBUG << "old line: " << line;

            line = extract;

RG_DEBUG << "new line: " << line;

        } else if (line.contains(audioFileKey) && 
                   m_mode == ProjectPackager::Pack) {

            // sigh... more and more brittle, on the pack, but only the PACK
            // step, we have to strip the unused audio files out of the XML,
            // since we're not including them
            //
            // RG doesn't write the tags in the same order (I have files with
            // the tags in different orders) so all we can do is iterate through
            // the list of used files and see if this line contains that string
            // somewhere, and if so, keep it, else ditch it

            QStringList::const_iterator si;
            bool keep = false;
            QFileInfo fileInfo;
                    
            for (si = usedAudioFiles.constBegin(); 
                 si != usedAudioFiles.constEnd(); 
                 ++si) {

                fileInfo.setFile(*si);

RG_DEBUG << "\"" << line << "\" contains? \"" << (fileInfo.baseName()) << "\"";
RG_DEBUG << "Qt says " << (line.contains(fileInfo.baseName()) ? "yes" : "no");
RG_DEBUG;

                if (line.contains(fileInfo.baseName())) {
                    keep = true;
                    break;
                }
            }

            if (!keep) {

RG_DEBUG << "Removed the following line referring to unused audio file: ";
RG_DEBUG << "  " << line;

                continue;
            }
        }

        outStream << line << endl;

    } while (!inStream.atEnd());


    // write the modified data to the output file
    QString ofileName = QString("%1.tmp").arg(fileToModify);
    bool writeOK = GzipFile::writeToFile(ofileName, outText);
    if (!writeOK) {
        puke(tr("<qt><p>Could not write<br>%1.</p>%2</qt>").arg(ofileName).arg(m_abortText));
        return QStringList();
    }

    // swap the .tmp modified copy back to the original filename
    if (!QFile::remove(fileToModify)) {
        puke(tr("<qt>Could not remove<br>%1<br><br>%2</qt>").arg(fileToModify).arg(m_abortText));
        return QStringList();
    }

    if (!QFile::copy(ofileName, fileToModify)) {
        puke(tr("<qt>Could not copy<br>%1<br>  to<br>%2<br><br>%3</qt>").arg(ofileName).arg(fileToModify).arg(m_abortText));
        return QStringList();
    }
    if (!QFile::remove(ofileName)) {
        puke(tr("<qt><p>Could not remove<br>%1.</p>%2</qt>").arg(ofileName).arg(m_abortText));
        return QStringList();
    }

    return list;
}
Ejemplo n.º 18
0
//==================================================================================
//Use this as our connection instead of connect
bool pqxxSqlConnection::drv_useDatabase( const QString &dbName, bool *cancelled, 
	MessageHandler* msgHandler )
{
	Q_UNUSED(cancelled);
	Q_UNUSED(msgHandler);
	KexiDBDrvDbg << "pqxxSqlConnection::drv_useDatabase: " << dbName << endl;

	QString conninfo;
	QString socket;
	QStringList sockets;

	if (data()->hostName.isEmpty() || data()->hostName == "localhost")
	{
		if (data()->localSocketFileName.isEmpty())
		{
			sockets.append("/tmp/.s.PGSQL.5432");

			for(QStringList::ConstIterator it = sockets.constBegin(); it != sockets.constEnd(); it++)
			{
				if(QFile(*it).exists())
				{
					socket = (*it);
					break;
				}
			}
		}
		else
		{
			socket=data()->localSocketFileName; //data()->fileName();
		}
	}
	else
	{
		conninfo = "host='" + data()->hostName + "'";
	}

	//Build up the connection string
	if (data()->port == 0)
		data()->port = 5432;

	conninfo += QString::fromLatin1(" port='%1'").arg(data()->port);

	conninfo += QString::fromLatin1(" dbname='%1'").arg(dbName);

	if (!data()->userName.isNull())
		conninfo += QString::fromLatin1(" user='******'").arg(data()->userName);

	if (!data()->password.isNull())
		conninfo += QString::fromLatin1(" password='******'").arg(data()->password);

	try
	{
		d->pqxxsql = new pqxx::connection( conninfo.latin1() );
		drv_executeSQL( "SET DEFAULT_WITH_OIDS TO ON" ); //Postgres 8.1 changed the default to no oids but we need them

		if (d->version) {
//! @todo set version using the connection pointer when we drop libpqxx for libpq
		}
		return true;
	}
	catch(const std::exception &e)
	{
		KexiDBDrvDbg << "pqxxSqlConnection::drv_useDatabase:exception - " << e.what() << endl;
		d->errmsg = QString::fromUtf8( e.what() );

	}
	catch(...)
	{
		d->errmsg = i18n("Unknown error.");
	}
	return false;
}
Ejemplo n.º 19
0
void
ProjectPackager::startAudioEncoder(QStringList files)
{
    m_info->setText(tr("Packing project..."));

    // (we could do some kind of QProcess monitoring, but I'm feeling lazy at
    // the moment and this will at least make us look busy while we chew)
    // go into spinner mode
    m_progress->setMaximum(0);

    // we can't do a oneliner bash script straight out of a QProcess command
    // line, so we'll have to create a purpose built script and run that
    QString scriptName("/tmp/rosegarden-audio-encoder-backend");
    m_script.setFileName(scriptName);

    // remove any lingering copy from a previous run
    if (m_script.exists()) m_script.remove();

    if (!m_script.open(QIODevice::WriteOnly | QIODevice::Text)) {
        puke(tr("<qt><p>Unable to write to temporary backend processing script %1.</p>%2</qt>").arg(m_abortText));
        return;
    }
    
    // build the script
    QTextStream out(&m_script);
    out << "# This script was generated by Rosegarden to combine multiple external processing"      << endl
        << "# operations so they could be managed by a single QProcess.  If you find this script"   << endl
        << "# it is likely that something has gone terribly wrong. See http://rosegardenmusic.com" << endl;

    QStringList::const_iterator si;
    int errorPoint = 1;
    for (si = files.constBegin(); si != files.constEnd(); ++si) {
        QFileInfo fi(*si);
        QString filename = QString("%1.%2").arg(fi.baseName()).arg(fi.completeSuffix());
        QString o = QString("%1/%2").arg(m_packDataDirName).arg(filename);

        // we'll eschew anything fancy or pretty in this disposable script and
        // just write a command on each line, terminating with an || exit n
        // which can be used to figure out at which point processing broke, for
        // cheap and easy error reporting without a lot of fancy stream wiring
        out << "wavpack -d \"" << o << "\" || exit " << errorPoint << endl;
        errorPoint++;
    }

    // Throw tar on the ass end of this script and save an extra processing step
    //
    // first cheap trick, m_packDataDirName.rg is our boy and we know it
    QString rgFile = QString("%1.rg").arg(m_packDataDirName);

    // second cheap trick, don't make a tarball in tmpdir and move it, just
    // write it at m_filename and shazam, nuke the tmpdir behind us and peace out
    out << "tar czf \"" << m_filename << "\" " << rgFile.toLocal8Bit() << " " <<  m_packDataDirName.toLocal8Bit() <<  "/ || exit " << errorPoint++ << endl;

    m_script.close();

    // run the assembled script
    m_process = new QProcess;
    m_process->setWorkingDirectory(m_packTmpDirName);
    m_process->start("bash", QStringList() << scriptName);
    connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)),
            this, SLOT(finishPack(int, QProcess::ExitStatus)));
}
Ejemplo n.º 20
0
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( "Error" ), tr( "Could not open file for reading" ) );
    return;
  }
  QDomDocument queryDoc;
  if ( !queryDoc.setContent( &queryFile ) )
  {
    QMessageBox::critical( nullptr, tr( "Error" ), tr( "File is not a valid xml document" ) );
    return;
  }

  QDomElement queryElem = queryDoc.firstChildElement( QStringLiteral( "Query" ) );
  if ( queryElem.isNull() )
  {
    QMessageBox::critical( nullptr, tr( "Error" ), 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( "Search string parsing error" ), 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 );
}
Ejemplo n.º 21
0
KisImportExportFilter::ConversionStatus KisImportExportManager::exportDocument(const QString& url, QByteArray& mimeType)
{
    bool userCancelled = false;

    // The import url should already be set correctly (null if we have a KisDocument
    // file manager and to the correct URL if we have an embedded manager)
    m_direction = Export; // vital information!
    m_exportUrl = url;

    KisFilterChain::Ptr chain;
    if (m_document) {
        // We have to pick the right native mimetype as source.
        QStringList nativeMimeTypes;
        nativeMimeTypes.append(m_document->nativeFormatMimeType());
        nativeMimeTypes += m_document->extraNativeMimeTypes();
        QStringList::ConstIterator it = nativeMimeTypes.constBegin();
        const QStringList::ConstIterator end = nativeMimeTypes.constEnd();
        for (; !chain && it != end; ++it) {
            m_graph.setSourceMimeType((*it).toLatin1());
            if (m_graph.isValid())
                chain = m_graph.chain(this, mimeType);
        }
    } else if (!m_importUrlMimetypeHint.isEmpty()) {
        dbgFile << "Using the mimetype hint:" << m_importUrlMimetypeHint;
        m_graph.setSourceMimeType(m_importUrlMimetypeHint);
    } else {
        QUrl u;
        u.setPath(m_importUrl);
        QMimeDatabase db;
        QMimeType t = db.mimeTypeForFile(u.path(), QMimeDatabase::MatchExtension);
        if (!t.isValid() || t.isDefault()) {
            errFile << "No mimetype found for" << m_importUrl;
            return KisImportExportFilter::BadMimeType;
        }
        m_graph.setSourceMimeType(t.name().toLatin1());

        if (!m_graph.isValid()) {
            warnFile << "Can't open" << t.name() << ", trying filter chooser";

            QApplication::setOverrideCursor(Qt::ArrowCursor);
            KisFilterChooser chooser(0, KisImportExportManager::mimeFilter(), QString(), u);
            if (chooser.exec())
                m_graph.setSourceMimeType(chooser.filterSelected().toLatin1());
            else
                userCancelled = true;

            QApplication::restoreOverrideCursor();
        }
    }

    if (!m_graph.isValid()) {
        errFile << "Couldn't create a valid graph for this source mimetype.";
        if (!d->batch && !userCancelled) {
            QMessageBox::critical(0, i18nc("@title:window", "Krita"), i18n("Could not export file: the export filter is missing."));
        }
        return KisImportExportFilter::BadConversionGraph;
    }

    if (!chain)   // already set when coming from the m_document case
        chain = m_graph.chain(this, mimeType);

    if (!chain) {
        errFile << "Couldn't create a valid filter chain to " << mimeType << " !" << endl;
        if (!d->batch) {
            QMessageBox::critical(0, i18nc("@title:window", "Krita"), i18n("Could not export file: the export filter is missing."));
        }
        return KisImportExportFilter::BadConversionGraph;
    }

    return chain->invokeChain();
}
Ejemplo n.º 22
0
//moved from KFormDesigner::FormManager
void KexiFormManager::createActions(KActionCollection* collection)
{
    d->collection = collection;
//    KXMLGUIClient* client = (KXMLGUIClient*)d->collection->parentGUIClient();

    d->lib->createWidgetActions(d->widgetActionGroup);
//! @todo insertWidget() slot?
//2.0    d->lib->createWidgetActions(client, d->collection,
//2.0                                this, SLOT(insertWidget(const QByteArray &)));

#ifdef KFD_SIGSLOTS
    if (d->features & KFormDesigner::Form::EnableConnections) {
        // nothing
    }
    else {
        d->dragConnectionAction = new KToggleAction(
            KIcon("signalslot"), i18n("Connect Signals/Slots"), d->collection);
        d->dragConnectionAction->setObjectName("drag_connection");
//        d->widgetActionGroup->addAction(d->dragConnectionAction);
        connect(d->dragConnectionAction, SIGNAL(triggered()),
                this, SLOT(startCreatingConnection()));
        d->dragConnectionAction->setChecked(false);
    }
#endif

    d->pointerAction = new KToggleAction(
        KIcon("mouse_pointer"), i18n("Pointer"), d->collection);
    d->pointerAction->setObjectName("edit_pointer");
    d->widgetActionGroup->addAction(d->pointerAction);
    connect(d->pointerAction, SIGNAL(triggered()),
            this, SLOT(slotPointerClicked()));
    d->pointerAction->setChecked(true);

    d->snapToGridAction = new KToggleAction(
        i18n("Snap to Grid"), d->collection);
    d->snapToGridAction->setObjectName("snap_to_grid");
//    d->widgetActionGroup->addAction(d->snapToGridAction);
//    d->snapToGridAction->setChecked(true);

#if 0 // 2.0: todo
    // Create the Style selection action (with a combo box in toolbar and submenu items)
    KSelectAction *styleAction = new KSelectAction(
        i18n("Style"), d->collection);
    styleAction->setObjectName("change_style");
    connect(styleAction, SIGNAL(triggered()),
            this, SLOT(slotStyle()));
    styleAction->setEditable(false);

//js: unused? KGlobalGroup cg = KGlobal::config()->group("General");
    QString currentStyle(kapp->style()->objectName().toLower());
    const QStringList styles = QStyleFactory::keys();
    styleAction->setItems(styles);
    styleAction->setCurrentItem(0);

    QStringList::ConstIterator endIt = styles.constEnd();
    int idx = 0;
    for (QStringList::ConstIterator it = styles.constBegin(); it != endIt; ++it, ++idx) {
        if ((*it).toLower() == currentStyle) {
            styleAction->setCurrentItem(idx);
            break;
        }
    }
    styleAction->setToolTip(i18n("Set the current view style."));
    styleAction->setMenuAccelsEnabled(true);
#endif

    d->lib->addCustomWidgetActions(d->collection);

#ifdef KEXI_DEBUG_GUI
    KConfigGroup generalGroup(KGlobal::config()->group("General"));
    if (generalGroup.readEntry("ShowInternalDebugger", false)) {
        KAction *a = new KAction(KIcon("run-build-file"), i18n("Show Form UI Code"), this);
        d->collection->addAction("show_form_ui", a);
        a->setShortcut(Qt::CTRL + Qt::Key_U);
        connect(a, SIGNAL(triggered()), this, SLOT(showFormUICode()));
    }
#endif

//! @todo move elsewhere
    {
        // (from obsolete kexiformpartinstui.rc)
        QStringList formActions;
        formActions
            << "edit_pointer"
            << QString() //sep
#ifndef KEXI_NO_AUTOFIELD_WIDGET
            << ":library_widget_KexiDBAutoField"
#endif
            << ":library_widget_KexiDBLabel"
            << ":library_widget_KexiDBImageBox"
            << ":library_widget_KexiDBLineEdit"
            << ":library_widget_KexiDBTextEdit"
            << ":library_widget_KPushButton"
            << ":library_widget_KexiDBComboBox"
            << ":library_widget_KexiDBCheckBox"
#ifndef KEXI_NO_FORM_LAYOUTS
            << ":library_widget_Spacer"
#endif
            << ":library_widget_Line"
            << ":library_widget_KexiFrame"
            << ":library_widget_QGroupBox"
            << ":library_widget_KFDTabWidget"
#ifndef KEXI_NO_FORM_SPRING_ELEMENT
            << ":library_widget_Spring"
#endif
            << QString() //sep
            ;
        KexiMainWindowIface *win = KexiMainWindowIface::global();
        foreach( const QString& actionName_, formActions ) {
            QAction *a;
            const QString actionName(actionName_.startsWith(':') ? actionName_.mid(1) : actionName_);
            if (actionName.isEmpty()) {
                a = new QAction(this);
                a->setSeparator(true);
            }
            else {
                a = d->widgetActionGroup->action(actionName);
            }
            if (actionName_.startsWith(':')) {  // icon only
                KexiSmallToolButton *btn = new KexiSmallToolButton(a, win->toolBar("form"));
                btn->setToolButtonStyle(Qt::ToolButtonIconOnly);
                win->appendWidgetToToolbar("form", btn);
            }
            else {
                win->addToolBarAction("form", a);
            }
        }

        QSet<QString> iconOnlyActions;
        iconOnlyActions << "widget_assign_action" << "show_form_ui";
        const QList<QAction*> actions( d->collection->actions() );
        foreach( QAction *a, actions ) {
            if (iconOnlyActions.contains(a->objectName())) { // icon only
                KexiSmallToolButton *btn = new KexiSmallToolButton(a, win->toolBar("form"));
                btn->setToolButtonStyle(Qt::ToolButtonIconOnly);
                win->appendWidgetToToolbar("form", btn);
            }
            else {
                win->addToolBarAction("form", a);
            }
        }
    }
Ejemplo n.º 23
0
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);
}
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 );
  }
}
Ejemplo n.º 25
0
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++;
					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;
}
Ejemplo n.º 26
0
KNMusicPlaylistModel *KNMusicPlaylistiTunesXMLParser::read(
        const QString &filePath)
{
    //Get the plist file.
    QFile plistFile(filePath);
    //Open the playlist file first.
    if(!plistFile.open(QIODevice::ReadOnly))
    {
        return nullptr;
    }
    //Generate a dom document to parse the file.
    QDomDocument plistDocument;
    //Use QDomDocument to parse the file.
    if(!plistDocument.setContent(&plistFile, true))
    {
        //If there's any error, return nullptr.
        return nullptr;
    }
    //Close the playlist file.
    plistFile.close();
    //Get the 'plist' element from the document.
    QDomElement plistRoot=plistDocument.documentElement();
    //Check the 'plist' element.
    if(plistRoot.nodeName()!="plist" ||
                !plistRoot.hasAttribute("version") ||
                plistRoot.attribute("version")!="1.0")
    {
        return nullptr;
    }
    //Get the dict elements from the 'plist'.
    QDomNodeList root=plistRoot.elementsByTagName("dict");
    //Check the list data.
    if(root.isEmpty())
    {
        return nullptr;
    }
    //Pick out the 'dict' element.
    QDomNodeList dictElement=root.at(0).toElement().childNodes();
    //Check 'dict' childe nodes size.
    if(dictElement.isEmpty())
    {
        return nullptr;
    }
    //Initial the track info hash.
    QHash<QString, QString> musicLocateHash;
    QStringList playlistIndexList;
    //Prepare the playlist.
    KNMusicPlaylistModel *model=new KNMusicPlaylistModel(thread());
    //Get the first node.
    QDomElement keyNode=dictElement.at(0).toElement(),
                valueNode=keyNode.nextSiblingElement();
    //Check the current key node.
    while(!keyNode.isNull() && !keyNode.isNull())
    {
        //Check the name of the node.
        //For 'tracks':
        if(keyNode.text()=="Tracks")
        {
            //Check whether the child nodes is empty.
            if(!valueNode.childNodes().isEmpty())
            {
                //Get all the tracks information.
                QDomElement trackKeyNode=
                                valueNode.childNodes().at(0).toElement(),
                            trackValueNode=
                                trackKeyNode.nextSiblingElement();
                //Pick out all the tracks.
                while(!trackKeyNode.isNull() && !trackValueNode.isNull())
                {
                    //Parse the track dict information.
                    QDomElement songKeyNode=
                                  trackValueNode.childNodes().at(0).toElement(),
                                songValueNode=
                                  songKeyNode.nextSiblingElement();
                    //If all the information is valid.
                    while(!songKeyNode.isNull() && !songValueNode.isNull())
                    {
                        //Get the location of the song.
                        if(songKeyNode.text()=="Location")
                        {
                            //Get the url from the file.
                            //Use QUrl to translate it to a readable string.
                            QString rawUrlText=
                                    QUrl::fromPercentEncoding(
                                        songValueNode.text().toUtf8());
                            //Remove the protocol name.
                            if(rawUrlText.length()>17 &&
                                    rawUrlText.left(17)=="file://localhost/")
                            {
                                rawUrlText.remove(0, 17);
                            }
                            else
                            {
                                rawUrlText=QUrl(rawUrlText).path();
                            }
                            //Set the hash.
                            musicLocateHash.insert(
                                        trackKeyNode.text(),
                                        QFileInfo(rawUrlText).absoluteFilePath()
                                        );
                            break;
                        }
                        //Switch to the next song elements.
                        songKeyNode=songValueNode.nextSiblingElement();
                        songValueNode=songKeyNode.nextSiblingElement();
                    }
                    //Switch to the track elements.
                    trackKeyNode=trackValueNode.nextSiblingElement();
                    trackValueNode=trackKeyNode.nextSiblingElement();
                }
            }
        }
        //For 'Playlists'.
        else if(keyNode.text()=="Playlists")
        {
            //Check the node size.
            if(valueNode.childNodes().size()!=0)
            {
                //Get the dict of the playlist.
                QDomElement playlistDict=
                        valueNode.childNodes().at(0).toElement();
                //Check the size of playlist dict.
                if(playlistDict.childNodes().size()!=0)
                {
                    //Get the playlist keys.
                    QDomElement playlistKey=
                            playlistDict.childNodes().at(0).toElement(),
                                playlistValue=
                            playlistKey.nextSiblingElement();
                    //Read the playlist information.
                    while(!playlistKey.isNull() && !playlistValue.isNull())
                    {
                        //For 'Name' element, it stored the name of the
                        //playlist.
                        if(playlistKey.text()=="Name")
                        {
                            //Set the title to model.
                            model->setTitle(playlistValue.text());
                        }
                        //For 'Playlist Items' element, it stored the file path
                        //information of the songs.
                        else if(playlistKey.text()=="Playlist Items")
                        {
                            //Check the array is empty or not.
                            QDomNodeList itemsArray=playlistValue.childNodes();
                            if(!itemsArray.isEmpty())
                            {
                                //Get all the information from the items array.
                                for(int i=0; i<itemsArray.size(); i++)
                                {
                                    QDomElement currentTrack=
                                            itemsArray.at(i).toElement();
                                    if(currentTrack.childNodes().size()==2)
                                    {
                                        QDomElement trackElement=
                                                        currentTrack.
                                                        childNodes().
                                                        at(0).toElement(),
                                                    trackIndex=
                                                        trackElement.
                                                        nextSiblingElement();
                                        //Check if the track element is
                                        //'Track ID' we will save track info.
                                        if(trackElement.text()=="Track ID")
                                        {
                                            //Insert the track.
                                            playlistIndexList.append(
                                                        trackIndex.text());
                                        }
                                    }
                                }
                            }
                        }
                        //Switch to the next playlist key.
                        playlistKey=playlistValue.nextSiblingElement();
                        playlistValue=playlistKey.nextSiblingElement();
                    }
                }
            }
        }
        //Switch to the next elements.
        keyNode=valueNode.nextSiblingElement();
        valueNode=keyNode.nextSiblingElement();
    }
    //Prepare the file list.
    QStringList fileList;
    //Translate the index list to file list.
    for(auto i=playlistIndexList.constBegin();
        i!=playlistIndexList.constEnd();
        ++i)
    {
        //Get the file path according to the hash table.
        QString filePath=musicLocateHash.value((*i), QString());
        //If the file is not empty,
        if(!filePath.isEmpty())
        {
            //Add to file list.
            fileList.append(filePath);
        }
    }
    //Add the file list to model.
    model->appendFiles(fileList);
    //Set the changed flag.
    model->setChanged(true);
    //Give back the model.
    return model;
}
Ejemplo n.º 27
0
int ScanDir::scan(ScanItem* si, ScanItemList& list, int data)
{
  clear();
  _dirsFinished = 0;
  _fileSize = 0;
  _dirty = true;

  if (isForbiddenDir(si->absPath)) {
      if (_parent)
          _parent->subScanFinished();
      return 0;
  }

  KUrl u;
  u.setPath(si->absPath);
  if (!KAuthorized::authorizeUrlAction("list", KUrl(), u)) {
    if (_parent)
      _parent->subScanFinished();

    return 0;
  }

  QDir d(si->absPath);
  const QStringList fileList = d.entryList( QDir::Files |
				      QDir::Hidden | QDir::NoSymLinks );

  if (fileList.count()>0) {
    KDE_struct_stat buff;

    _files.reserve(fileList.count());

    QStringList::ConstIterator it;
    for (it = fileList.constBegin(); it != fileList.constEnd(); ++it ) {
      if (KDE::lstat( si->absPath + QLatin1Char('/') + (*it), &buff ) != 0)
        continue;
      _files.append( ScanFile(*it, buff.st_size) );
      _fileSize += buff.st_size;
    }
  }

  const QStringList dirList = d.entryList( QDir::Dirs | 
				     QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot );

  if (dirList.count()>0) {
    _dirs.reserve(dirList.count());

    QStringList::ConstIterator it;
    for (it = dirList.constBegin(); it != dirList.constEnd(); ++it ) {
      _dirs.append( ScanDir(*it, _manager, this, data) );
      QString newpath = si->absPath;
      if (!newpath.endsWith(QChar('/'))) newpath.append("/");
      newpath.append(*it);
      list.append( new ScanItem( newpath, &(_dirs.last()) ));
    }
    _dirCount += _dirs.count();
  }

  callScanStarted();
  callSizeChanged();

  if (_dirs.count() == 0) {
    callScanFinished();

    if (_parent)
      _parent->subScanFinished();
  }

  return _dirs.count();
}
CodaClientApplication::ParseArgsResult CodaClientApplication::parseArguments(QString *errorMessage)
{
    int argNumber = 1;
    const QStringList args = QCoreApplication::arguments();
    const QStringList::const_iterator cend = args.constEnd();
    QStringList::const_iterator it = args.constBegin();
    bool optionsEnd = false;
    for (++it; it != cend; ++it) {
        if (!optionsEnd  && *it == QLatin1String("--")) {
            optionsEnd = true;
            continue;
        }
        if (!optionsEnd &&  it->startsWith(QLatin1Char('-')) && it->size() == 2) {
            switch (it->at(1).toAscii()) {
            case 'v':
                m_verbose++;
                break;
            case 'd':
                m_launchDebug = true;
                break;
            case 's':
                m_installSilently = true;
                break;
            case 'c':
                if (++it == cend) {
                    *errorMessage = QString::fromLatin1("Parameter missing for -c");
                    return ParseArgsError;
                }
                m_putChunkSize = it->toULongLong() * 1024;
                if (!m_putChunkSize) {
                    *errorMessage = QString::fromLatin1("Invalid chunk size.");
                    return ParseArgsError;
                }
                break;
            default:
                *errorMessage = QString::fromLatin1("Invalid option %1").arg(*it);
                return ParseArgsError;
            }
        } else {
            if (!parseArgument(*it, argNumber++, errorMessage))
                return ParseArgsError;
        }
    } //for loop
    // Basic Check & init
    switch (m_mode) {
    case Invalid:
        return ParseArgsError;
    case Launch:
        if (m_address.isEmpty() || !m_launchUID || m_launchBinary.isEmpty()) {
            *errorMessage = QString::fromLatin1("Not enough parameters for launch.");
            return ParseInitError;
        }
        break;
    case Ping:
        if (m_address.isEmpty()) {
            *errorMessage = QString::fromLatin1("Not enough parameters for ping.");
            return ParseInitError;
        }
        if (!isSerialPort(m_address)) {
            *errorMessage = QString::fromLatin1("'ping' not supported for TCP/IP.");
            return ParseInitError;
        }
        break;
    case Install:
        if (m_address.isEmpty() || m_installSisFile.isEmpty()) {
            *errorMessage = QString::fromLatin1("Not enough parameters for install.");
            return ParseInitError;
        }
        break;
    case Uninstall:
        if (!m_uninstallPackage) {
            *errorMessage = QString::fromLatin1("Not enough parameters for uninstall.");
            return ParseInitError;
        }
        break;
    case Put: {
        if (m_address.isEmpty() || m_putLocalFile.isEmpty() || m_putRemoteFile.isEmpty()) {
            *errorMessage = QString::fromLatin1("Not enough parameters for put.");
            return ParseInitError;
        }
        const QFileInfo fi(m_putLocalFile);
        if (!fi.isFile() || !fi.isReadable()) {
            *errorMessage = QString::fromLatin1("Local file '%1' not readable.").arg(m_putLocalFile);
            return ParseInitError;
        }
    }
        break;
    default:
        break;
    }
    return ParseArgsOk;
}
Ejemplo n.º 29
0
static QFontEngine::FaceId fontFile(const QByteArray &_xname, QFreetypeFace **freetype, int *synth)
{
    *freetype = 0;
    *synth = 0;

    QByteArray xname = _xname.toLower();

    int pos = 0;
    int minus = 0;
    while (minus < 5 && (pos = xname.indexOf('-', pos + 1)))
        ++minus;
    QByteArray searchname = xname.left(pos);
    while (minus < 12 && (pos = xname.indexOf('-', pos + 1)))
        ++minus;
    QByteArray encoding = xname.mid(pos + 1);
    //qDebug("xname='%s', searchname='%s', encoding='%s'", xname.data(), searchname.data(), encoding.data());
    QStringList fontpath = fontPath();
    QFontEngine::FaceId face_id;
    face_id.index = 0;

    QByteArray best_mapping;

    for (QStringList::ConstIterator it = fontpath.constBegin(); it != fontpath.constEnd(); ++it) {
        if (!(*it).startsWith(QLatin1Char('/')))
            continue; // not a path name, a font server
        QString fontmapname;
        int num = 0;
        // search font.dir and font.scale for the right file
        while (num < 2) {
            if (num == 0)
                fontmapname = (*it) + QLatin1String("/fonts.scale");
            else
                fontmapname = (*it) + QLatin1String("/fonts.dir");
            ++num;
            //qWarning(fontmapname);
            QFile fontmap(fontmapname);
            if (!fontmap.open(QIODevice::ReadOnly))
                continue;
            while (!fontmap.atEnd()) {
                QByteArray mapping = fontmap.readLine();
                QByteArray lmapping = mapping.toLower();

                //qWarning(xfontname);
                //qWarning(mapping);
                if (!lmapping.contains(searchname))
                    continue;
                int index = mapping.indexOf(' ');
                QByteArray ffn = mapping.mid(0,index);
                // remove bitmap formats freetype can't handle
                if (ffn.contains(".spd") || ffn.contains(".phont"))
                    continue;
                bool best_match = false;
                if (!best_mapping.isEmpty()) {
                    if (lmapping.contains("-0-0-0-0-")) { // scalable font
                        best_match = true;
                        goto found;
                    }
                    if (lmapping.contains(encoding) && !best_mapping.toLower().contains(encoding))
                        goto found;
                    continue;
                }

            found:
                int colon = ffn.lastIndexOf(':');
                if (colon != -1) {
                    QByteArray s = ffn.left(colon);
                    ffn = ffn.mid(colon + 1);
                    if (s.contains("ds="))
                        *synth |= QFontEngine::SynthesizedBold;
                    if (s.contains("ai="))
                        *synth |= QFontEngine::SynthesizedItalic;
                }
                face_id.filename = (*it).toLocal8Bit() + '/' + ffn;
                best_mapping = mapping;
                if (best_match)
                    goto end;
            }
        }
    }
end:
//     qDebug("fontfile for %s is from '%s'\n    got %s synth=%d", xname.data(),
//            best_mapping.data(), face_id.filename.data(), *synth);
    *freetype = QFreetypeFace::getFace(face_id);
    if (!*freetype) {
        face_id.index = 0;
        face_id.filename = QByteArray();
    }
    return face_id;
}
Ejemplo n.º 30
0
void CProject::setMainSourceDepend(const QStringList &list)
{
	update();
	// 首先根据list中依赖关系修改原来的依赖关系, 然后将list中没有包含的mainSource的依赖关系重置为all
	QStringList resetedDepend;
	
	// 根据list中依赖关系修改原来的依赖关系
	QStringList dependList = list;
	QStringList::const_iterator constIterator = dependList.constBegin();
	QStringList::const_iterator endIterator = dependList.constEnd();
	// 分析组内的依赖关系, 保存在dependMap中
	while (constIterator != endIterator) {
		// 将组内文件名保存在childList中
		QStringList childList = (*constIterator).split(QRegExp("\\s+"), QString::SkipEmptyParts);
		// 如果组内的单词个数小于2, 则无效, 放弃它处理下一个.
		if (childList.count() < 2) {
			++constIterator;
			continue;
		}

		// 主内第一个名称是main文件的依赖方式标志, "all"表示所有, "only"表示不依赖其它源文件, "part"标示依赖指定的源文件
		QString mode = childList.at(0).toLower();
		if (!(mode == "all" || mode == "part" || mode == "only")) {
			++constIterator;
			continue;
		}
		
		// 组内的第二个文件名是含main() 的源文件, 保存在mainSource中
		QString mainSource = childList.at(1);
		mainSource.remove(QRegExp("^./"));
		// 如果mainSourceList 中没有该mainSource, 则放弃该mainSource处理下一个.
		if (!mainSourceList.contains(mainSource)) {
			++constIterator;
			continue;
		}

		resetedDepend << mainSource; // 标记不需要重置为依赖"all"
		
		// 若mode = "part", 则它依赖于指定的源文件, dependSources, 为 "part" 和 mainSource后面的文件
		// 若mode = "only", 则它不依赖于任何其它源文件, dependSources为"only";
		// 若mode 不是上面两种情况, 则保持mainSourceDependMap中原来的值"all"
		QFileInfo fileInfo(mainSource);
		QString executeFile = fileInfo.path() + "/" + fileInfo.completeBaseName();
		executeFile.remove(QRegExp("^./"));
		if (mode == "part") {
			QStringList dependSources;
			QStringList objects;
			dependSources << "part";
			objects << "part" << executeFile + ".o";
			QString source = QString();
			QString object = QString();
			int count = childList.count();
			int i = 2;
			while (i < count) {
				source = childList.at(i);
				source.remove(QRegExp("^./"));
				dependSources << source;
				fileInfo.setFile(source);
				object = fileInfo.path() + "/" + fileInfo.completeBaseName() + ".o";
				object.remove(QRegExp("^./"));
				objects << object;
				++i;
			}
			mainSourceDependMap[mainSource] = dependSources;
			executeFileDependMap[executeFile] = objects;
		} else if (mode == "only") {
			mainSourceDependMap[mainSource] = QStringList() << "only";
			executeFileDependMap[executeFile] = QStringList() << "only" << executeFile + ".o";
		} else {
			mainSourceDependMap[mainSource] = QStringList() << "all";
			executeFileDependMap[executeFile] = QStringList() << "all" << executeFile + ".o";
		}
		++constIterator;
	}

	// 将list中没有包含的mainSource的依赖关系重置为all
	constIterator = mainSourceList.constBegin();
	endIterator = mainSourceList.constEnd();
	while (constIterator != endIterator) {
		if (!resetedDepend.contains(*constIterator)) {
			mainSourceDependMap[*constIterator] = QStringList() << "all";
			QFileInfo fileInfo(*constIterator);
			QString executeFile = fileInfo.path() + "/" + fileInfo.completeBaseName();
			executeFile.remove(QRegExp("./"));
			executeFileDependMap[executeFile] = QStringList() << "all" << executeFile + ".o";
		}
		++constIterator;
	}

	// 将新的设置转化为字符串, 并写入settings中
	QString mainSourceDependValue = QString();
	constIterator = mainSourceList.constBegin();
	endIterator = mainSourceList.constEnd();
	while (constIterator != endIterator) {
		QStringList list = mainSourceDependMap[*constIterator];
		mainSourceDependValue += list.at(0);
		mainSourceDependValue += " " + *constIterator + " ";
		list.removeAt(0);
		mainSourceDependValue += list.join(" ") + ":";
		++constIterator;
	}
	mainSourceDependValue.remove(QRegExp(":$"));
	settings->setValue("MainSourceDepend", mainSourceDependValue);
	settings->sync();
	settingsFileInfo.refresh();
	lastUpdateTime = settingsFileInfo.lastModified();
	emit updated(nameStr);
}