示例#1
0
ErrorList topolTest::checkDuplicates( QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  Q_UNUSED( layer2 );
  //TODO: multilines - check all separate pieces
  int i = 0;
  ErrorList errorList;

  QList<QgsFeatureId> duplicateIds;

  QgsSpatialIndex *index = mLayerIndexes[layer1->id()];

  QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( qgsInterface->mapCanvas()->extent().asWktPolygon() );

  QMap<QgsFeatureId, FeatureLayer>::const_iterator it;
  for ( it = mFeatureMap2.constBegin(); it != mFeatureMap2.constEnd(); ++it )
  {
    if ( !( ++i % 100 ) )
      emit progress( i );

    QgsFeatureId currentId = it->feature.id();

    if ( duplicateIds.contains( currentId ) )
    {
      //is already a duplicate geometry..skip..
      continue;
    }

    if ( testCanceled() )
      break;

    QgsGeometry g1 = it->feature.geometry();
    QgsRectangle bb = g1.boundingBox();

    QList<QgsFeatureId> crossingIds;
    crossingIds = index->intersects( bb );

    QList<QgsFeatureId>::ConstIterator cit = crossingIds.constBegin();
    QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.constEnd();

    bool duplicate = false;

    for ( ; cit != crossingIdsEnd; ++cit )
    {
      duplicate = false;
      // skip itself
      if ( mFeatureMap2[*cit].feature.id() == it->feature.id() )
        continue;

      QgsGeometry g2 = mFeatureMap2[*cit].feature.geometry();
      if ( g2.isNull() )
      {
        QgsMessageLog::logMessage( tr( "Invalid second geometry in duplicate geometry test." ), tr( "Topology plugin" ) );
        continue;
      }

      if ( !_canExportToGeos( g2 ) )
      {
        QgsMessageLog::logMessage( tr( "Failed to import second geometry into GEOS in duplicate geometry test." ), tr( "Topology plugin" ) );
        continue;
      }

      if ( g1.isGeosEqual( g2 ) )
      {
        duplicate = true;
        duplicateIds.append( mFeatureMap2[*cit].feature.id() );
      }

      if ( duplicate )
      {


        QList<FeatureLayer> fls;
        fls << *it << *it;
        QgsGeometry conflict( g1 );

        if ( isExtent )
        {
          if ( canvasExtentPoly.disjoint( conflict ) )
          {
            continue;
          }
          if ( canvasExtentPoly.crosses( conflict ) )
          {
            conflict = conflict.intersection( canvasExtentPoly );
          }
        }

        TopolErrorDuplicates *err = new TopolErrorDuplicates( bb, conflict, fls );

        errorList << err;
      }

    }

  }
  return errorList;
}
SimpleRichTextEdit::SimpleRichTextEdit(QWidget *parent)
	: KTextEdit(parent)
{
	enableFindReplace(false);
	setCheckSpellingEnabled(true);

	setAutoFormatting(KTextEdit::AutoNone);
	setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);

	QTextDocument *textDocument = document();

	QTextOption textOption;
	textOption.setAlignment(Qt::AlignCenter);
	textOption.setWrapMode(QTextOption::NoWrap);
	textDocument->setDefaultTextOption(textOption);

	QFont defaultFont = font();
	defaultFont.setPointSize(defaultFont.pointSize() + 2);
	textDocument->setDefaultFont(defaultFont);

	QString styleSheet("p {" "   display: block;" "   white-space: pre;" "   margin-top: 0px;" "   margin-bottom: 0px;" "}");
	textDocument->setDefaultStyleSheet(styleSheet);

	setTextInteractionFlags(Qt::TextEditorInteraction);

	m_actions[Undo] = new QAction(this);
	m_actions[Undo]->setIcon(QIcon::fromTheme("edit-undo"));
	m_actions[Undo]->setText(i18n("Undo"));
	m_actions[Undo]->setShortcuts(KStandardShortcut::undo());
	connect(m_actions[Undo], SIGNAL(triggered()), this, SLOT(undo()));

	m_actions[Redo] = new QAction(this);
	m_actions[Redo]->setIcon(QIcon::fromTheme("edit-redo"));
	m_actions[Redo]->setText(i18n("Redo"));
	m_actions[Redo]->setShortcuts(KStandardShortcut::redo());
	connect(m_actions[Redo], SIGNAL(triggered()), this, SLOT(redo()));

	m_actions[Cut] = new QAction(this);
	m_actions[Cut]->setIcon(QIcon::fromTheme("edit-cut"));
	m_actions[Cut]->setText(i18n("Cut"));
	m_actions[Cut]->setShortcuts(KStandardShortcut::cut());
	connect(m_actions[Cut], SIGNAL(triggered()), this, SLOT(cut()));

	m_actions[Copy] = new QAction(this);
	m_actions[Copy]->setIcon(QIcon::fromTheme("edit-copy"));
	m_actions[Copy]->setText(i18n("Copy"));
	m_actions[Copy]->setShortcuts(KStandardShortcut::copy());
	connect(m_actions[Copy], SIGNAL(triggered()), this, SLOT(copy()));

#if !defined(QT_NO_CLIPBOARD)
	m_actions[Paste] = new QAction(this);
	m_actions[Paste]->setIcon(QIcon::fromTheme("edit-paste"));
	m_actions[Paste]->setText(i18n("Paste"));
	m_actions[Paste]->setShortcuts(KStandardShortcut::paste());
	connect(m_actions[Paste], SIGNAL(triggered()), this, SLOT(paste()));
#endif

	m_actions[Delete] = new QAction(this);
	m_actions[Delete]->setIcon(QIcon::fromTheme("edit-delete"));
	m_actions[Delete]->setText(i18n("Delete"));
	m_actions[Delete]->setShortcut(QKeySequence::Delete);
	connect(m_actions[Delete], SIGNAL(triggered()), this, SLOT(deleteText()));

	m_actions[Clear] = new QAction(this);
	m_actions[Clear]->setIcon(QIcon::fromTheme("edit-clear"));
	m_actions[Clear]->setText(i18nc("@action:inmenu Clear all text", "Clear"));
	connect(m_actions[Clear], SIGNAL(triggered()), this, SLOT(undoableClear()));

	m_actions[SelectAll] = new QAction(this);
	m_actions[SelectAll]->setIcon(QIcon::fromTheme("edit-select-all"));
	m_actions[SelectAll]->setText(i18n("Select All"));
	m_actions[SelectAll]->setShortcut(QKeySequence::SelectAll);
	connect(m_actions[SelectAll], SIGNAL(triggered()), this, SLOT(selectAll()));

	m_actions[ToggleBold] = new QAction(this);
	m_actions[ToggleBold]->setIcon(QIcon::fromTheme("format-text-bold"));
	m_actions[ToggleBold]->setText(i18nc("@action:inmenu Toggle bold style", "Bold"));
	m_actions[ToggleBold]->setShortcut(QKeySequence("Ctrl+B"));
	connect(m_actions[ToggleBold], SIGNAL(triggered()), this, SLOT(toggleFontBold()));

	m_actions[ToggleItalic] = new QAction(this);
	m_actions[ToggleItalic]->setIcon(QIcon::fromTheme("format-text-italic"));
	m_actions[ToggleItalic]->setText(i18nc("@action:inmenu Toggle italic style", "Italic"));
	m_actions[ToggleItalic]->setShortcut(QKeySequence("Ctrl+I"));
	connect(m_actions[ToggleItalic], SIGNAL(triggered()), this, SLOT(toggleFontItalic()));

	m_actions[ToggleUnderline] = new QAction(this);
	m_actions[ToggleUnderline]->setIcon(QIcon::fromTheme("format-text-underline"));
	m_actions[ToggleUnderline]->setText(i18nc("@action:inmenu Toggle underline style", "Underline"));
	m_actions[ToggleUnderline]->setShortcut(QKeySequence("Ctrl+U"));
	connect(m_actions[ToggleUnderline], SIGNAL(triggered()), this, SLOT(toggleFontUnderline()));

	m_actions[ToggleStrikeOut] = new QAction(this);
	m_actions[ToggleStrikeOut]->setIcon(QIcon::fromTheme("format-text-strikethrough"));
	m_actions[ToggleStrikeOut]->setText(i18nc("@action:inmenu Toggle strike through style", "Strike Through"));
	m_actions[ToggleStrikeOut]->setShortcut(QKeySequence("Ctrl+T"));
	connect(m_actions[ToggleStrikeOut], SIGNAL(triggered()), this, SLOT(toggleFontStrikeOut()));

	m_actions[ChangeTextColor] = new QAction(this);
	m_actions[ChangeTextColor]->setIcon(QIcon::fromTheme("format-text-color"));
	m_actions[ChangeTextColor]->setText(i18nc("@action:inmenu Change Text Color", "Text Color"));
	m_actions[ChangeTextColor]->setShortcut(QKeySequence("Ctrl+Shift+C"));
	connect(m_actions[ChangeTextColor], SIGNAL(triggered()), this, SLOT(changeTextColor()));

	m_actions[CheckSpelling] = new QAction(this);
	m_actions[CheckSpelling]->setIcon(QIcon::fromTheme("tools-check-spelling"));
	m_actions[CheckSpelling]->setText(i18n("Check Spelling..."));
	connect(m_actions[CheckSpelling], SIGNAL(triggered()), this, SLOT(checkSpelling()));

	m_actions[ToggleAutoSpellChecking] = new QAction(this);
	m_actions[ToggleAutoSpellChecking]->setText(i18n("Auto Spell Check"));
	m_actions[ToggleAutoSpellChecking]->setCheckable(true);
	connect(m_actions[ToggleAutoSpellChecking], SIGNAL(triggered()), this, SLOT(toggleAutoSpellChecking()));

	m_actions[AllowTabulations] = new QAction(this);
	m_actions[AllowTabulations]->setText(i18n("Allow Tabulations"));
	connect(m_actions[AllowTabulations], SIGNAL(triggered()), this, SLOT(toggleTabChangesFocus()));

	QMenu *menu = createStandardContextMenu();
	menu->setParent(this);
	QList<QAction *> actions = menu->actions();
	m_insertUnicodeControlCharMenu = 0;
	for(QList<QAction *>::ConstIterator it = actions.constBegin(), end = actions.constEnd(); it != end; ++it) {
		if((*it)->menu()) {
			// this depends on Qt private implementation but at least is guaranteed
			// to behave reasonably if that implementation changes in the future.
			if(!strcmp((*it)->menu()->metaObject()->className(), "QUnicodeControlCharacterMenu")) {
				m_insertUnicodeControlCharMenu = (*it)->menu();
				break;
			}
		}
	}
}
bool NetworkCookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
{
#if defined(NETWORKCOOKIEJAR_DEBUG)
    qDebug() << "NetworkCookieJar::" << __FUNCTION__ << url;
    qDebug() << cookieList;
#endif
    QDateTime now = QDateTime::currentDateTime().toTimeSpec(Qt::UTC);
    bool changed = false;
    QString fullUrlPath = url.path();
    QString defaultPath = fullUrlPath.mid(0, fullUrlPath.lastIndexOf(QLatin1Char('/')) + 1);
    if (defaultPath.isEmpty())
        defaultPath = QLatin1Char('/');

    QString urlPath = d->urlPath(url);
    foreach (QNetworkCookie cookie, cookieList) {
        if (cookie.path().length() > maxCookiePathLength)
            continue;

        bool alreadyDead = !cookie.isSessionCookie() && cookie.expirationDate() < now;

        if (cookie.path().isEmpty()) {
            cookie.setPath(defaultPath);
        }
        // Matching the behavior of Firefox, no path checking is done when setting cookies
        // Safari does something even odder, when that paths don't match it keeps
        // the cookie, but changes the paths to the default path
#if 0
        else if (!d->matchingPath(cookie, urlPath)) {
#ifdef NETWORKCOOKIEJAR_LOGREJECTEDCOOKIES
            qDebug() << "NetworkCookieJar::" << __FUNCTION__
                     << "Blocked cookie because: path doesn't match: " << cookie << url;
#endif
            continue;
        }
#endif

        if (cookie.domain().isEmpty()) {
            QString host = url.host().toLower();
            if (host.isEmpty())
                continue;
            cookie.setDomain(host);
        } else if (!d->matchingDomain(cookie, url)) {
#ifdef NETWORKCOOKIEJAR_LOGREJECTEDCOOKIES
            qDebug() << "NetworkCookieJar::" << __FUNCTION__
                     << "Blocked cookie because: domain doesn't match: " << cookie << url;
#endif
            continue;
        }

        // replace/remove existing cookies
        QString domain = cookie.domain();
        Q_ASSERT(!domain.isEmpty());
        QStringList urlHost = splitHost(domain);

        QList<QNetworkCookie> cookies = d->tree.find(urlHost);
        QList<QNetworkCookie>::const_iterator it = cookies.constBegin();
        for (; it != cookies.constEnd(); ++it) {
            if (cookie.name() == it->name() &&
                cookie.domain() == it->domain() &&
                cookie.path() == it->path()) {
                d->tree.remove(urlHost, *it);
                break;
            }
        }

        if (alreadyDead)
            continue;

        changed = true;
        d->tree.insert(urlHost, cookie);
    }

    return changed;
}
示例#4
0
void ICQFullInfo::fill( Buffer* buffer )
{
	Buffer tlvListBuffer( buffer->getBSTR() );
	QList<TLV> tlvList = tlvListBuffer.getTLVList();

	QList<TLV>::const_iterator it;
	for ( it = tlvList.constBegin(); it != tlvList.constEnd(); ++it )
	{
		switch ( (*it).type )
		{
		case 0x0032:
			uin = (*it).data;
			break;
		case 0x0046:
			break;
		case 0x0050:
			break;
		case 0x0055:
			break;
		case 0x0064:
			firstName = (*it).data;
			break;
		case 0x006e:
			lastName = (*it).data;
			break;
		case 0x0078:
			nickName = (*it).data;
			break;
		case 0x0082:
			{
			Buffer b( (*it).data );
			gender = b.getByte();
			}
			break;
		case 0x008c:
			break;
		case 0x0096:
			homeList = parseAddressItemList( (*it).data );
			break;
		case 0x00A0:
			originList = parseAddressItemList( (*it).data );
			break;
		case 0x00AA:
			{
				Buffer b( (*it).data );
				language1 = b.getWord();
			}
			break;
		case 0x00B4:
			{
				Buffer b( (*it).data );
				language2 = b.getWord();
			}
			break;
		case 0x00BE:
			{
				Buffer b( (*it).data );
				language3 = b.getWord();
			}
			break;
		case 0x00C8:
			phoneList = parseInfoItemList( (*it).data );
			break;
		case 0x00FA:
			homepage = (*it).data;
			break;
		case 0x0104:
			break;
		case 0x010e:
			break;
		case 0x0118:
			workList = parseWorkItemList( (*it).data );
			break;
		case 0x0122:
			interestList = parseInfoItemList( (*it).data );
			break;
		case 0x0123:
			organizationList = parseInfoItemList( (*it).data );
			break;
		case 0x0124:
			pastAffliationList = parseInfoItemList( (*it).data );
			break;
		case 0x012C:
			break;
		case 0x0136:
			break;
		case 0x0140:
			break;
		case 0x014A:
			break;
		case 0x0154:
			break;
		case 0x015E:
			break;
		case 0x0168:
			break;
		case 0x0172:
			break;
		case 0x017C:
			timezone = Buffer( (*it).data ).getWord();
			break;
		case 0x0186:
			notes = (*it).data;
			break;
		case 0x0190:
			break;
		case 0x019A:
			{
				Buffer b( (*it).data );
				webAware = (b.getWord() == 0x0001);
			}
			break;
		case 0x01A4:
			break;
		case 0x01AE:
			break;
		case 0x01B8:
			break;
		case 0x01C2:
			break;
		case 0x01CC:
			break;
		case 0x01D6:
			break;
		case 0x01E0:
			break;
		case 0x01EA:
			break;
		case 0x01F4:
			break;
		case 0x01F9:
			{
				Buffer b( (*it).data );
				privacyProfile = b.getWord();
			}
			break;
		case 0x01FE:
			break;
		case 0x0208:
			break;
		case 0x0212:
			break;
		case 0x021C:
			break;
		case 0x0226:
			statusDescription = (*it).data;
			break;
		case 0x0230:
			break;
		case 0x003C:
			break;
		default:
			kDebug(OSCAR_RAW_DEBUG) << "Unhandled tlv: " << hex << (*it).type << " data: " << hex << (*it).data;
			break;
		}
	}
}
示例#5
0
QgsGeometry QgsGeometryAnalyzer::createOffsetGeometry( const QgsGeometry& geom, const QgsGeometry& lineGeom, double offset )
{
  if ( !geom || lineGeom.isEmpty() )
  {
    return QgsGeometry();
  }

  QList<QgsGeometry> inputGeomList;

  if ( geom.isMultipart() )
  {
    inputGeomList = geom.asGeometryCollection();
  }
  else
  {
    inputGeomList.push_back( geom );
  }

  QList<GEOSGeometry*> outputGeomList;
  QList<QgsGeometry>::const_iterator inputGeomIt = inputGeomList.constBegin();
  GEOSContextHandle_t geosctxt = QgsGeometry::getGEOSHandler();
  for ( ; inputGeomIt != inputGeomList.constEnd(); ++inputGeomIt )
  {
    if ( geom.type() == QgsWkbTypes::LineGeometry )
    {
      GEOSGeometry* offsetGeom = GEOSOffsetCurve_r( geosctxt, ( *inputGeomIt ).asGeos(), -offset, 8 /*quadSegments*/, 0 /*joinStyle*/, 5.0 /*mitreLimit*/ );
      if ( !offsetGeom || !GEOSisValid_r( geosctxt, offsetGeom ) )
      {
        return QgsGeometry();
      }
      if ( !GEOSisValid_r( geosctxt, offsetGeom ) || GEOSGeomTypeId_r( geosctxt, offsetGeom ) != GEOS_LINESTRING || GEOSGeomGetNumPoints_r( geosctxt, offsetGeom ) < 1 )
      {
        GEOSGeom_destroy_r( geosctxt, offsetGeom );
        return QgsGeometry();
      }
      outputGeomList.push_back( offsetGeom );
    }
    else if ( geom.type() == QgsWkbTypes::PointGeometry )
    {
      QgsPoint p = ( *inputGeomIt ).asPoint();
      p = createPointOffset( p.x(), p.y(), offset, lineGeom );
      GEOSCoordSequence* ptSeq = GEOSCoordSeq_create_r( geosctxt, 1, 2 );
      GEOSCoordSeq_setX_r( geosctxt, ptSeq, 0, p.x() );
      GEOSCoordSeq_setY_r( geosctxt, ptSeq, 0, p.y() );
      GEOSGeometry* geosPt = GEOSGeom_createPoint_r( geosctxt, ptSeq );
      outputGeomList.push_back( geosPt );
    }
  }

  QgsGeometry outGeometry;
  if ( !geom.isMultipart() )
  {
    GEOSGeometry* outputGeom = outputGeomList.at( 0 );
    if ( outputGeom )
    {
      outGeometry.fromGeos( outputGeom );
    }
  }
  else
  {
    GEOSGeometry** geomArray = new GEOSGeometry*[outputGeomList.size()];
    for ( int i = 0; i < outputGeomList.size(); ++i )
    {
      geomArray[i] = outputGeomList.at( i );
    }
    GEOSGeometry* collection = nullptr;
    if ( geom.type() == QgsWkbTypes::PointGeometry )
    {
      collection = GEOSGeom_createCollection_r( geosctxt, GEOS_MULTIPOINT, geomArray, outputGeomList.size() );
    }
    else if ( geom.type() == QgsWkbTypes::LineGeometry )
    {
      collection = GEOSGeom_createCollection_r( geosctxt, GEOS_MULTILINESTRING, geomArray, outputGeomList.size() );
    }
    outGeometry.fromGeos( collection );
    delete[] geomArray;
  }
  return outGeometry;
}
void KCalResourceSlox::slotLoadEventsResult( KJob *job )
{
  kDebug() << long( this );

  if ( job->error() ) {
    loadError( job->errorString() );
  } else {
    kDebug() << "success";

    QDomDocument doc = mLoadEventsJob->response();

    mWebdavHandler.log( doc.toString( 2 ) );

    QList<SloxItem> items = WebdavHandler::getSloxItems( this, doc );

    bool changed = false;

    disableChangeNotification();

    QList<SloxItem>::ConstIterator it;
    for( it = items.constBegin(); it != items.constEnd(); ++it ) {
      SloxItem item = *it;
      QString uid = sloxIdToEventUid( item.sloxId );
      if ( item.status == SloxItem::Delete ) {
        Event *event = calendar()->event( uid );
        if ( event ) {
          calendar()->deleteEvent( event );
          changed = true;
        }
      } else if ( item.status == SloxItem::Create ) {
        Event *newEvent = 0;
        Event *event = calendar()->event( uid );
        if ( !event ) {
          newEvent = new Event;
          event = newEvent;
          event->setUid( uid );
          event->setSecrecy( Incidence::SecrecyPrivate );
        }

        event->setCustomProperty( "SLOX", "ID", item.sloxId );

        QDomNode n = item.domNode.namedItem( fieldName( FullTime ) );
        event->setAllDay( n.toElement().text() == boolToStr( true ) );

        bool doesRecur = false;

        mWebdavHandler.clearSloxAttributeStatus();

        for( n = item.domNode.firstChild(); !n.isNull(); n = n.nextSibling() ) {
          QDomElement e = n.toElement();
          mWebdavHandler.parseSloxAttribute( e );
          parseIncidenceAttribute( e, event );
          parseEventAttribute( e, event );
          if ( e.tagName() == fieldName( RecurrenceType ) && e.text() != "no" ) {
            doesRecur = true;
          }
        }

        if ( doesRecur )
          parseRecurrence( item.domNode, event );
        else
          event->recurrence()->unsetRecurs();

        mWebdavHandler.setSloxAttributes( event );

//        kDebug() << "EVENT" << item.uid << event->summary();

        if ( newEvent ) calendar()->addEvent( event );

        changed = true;
      }
    }

    enableChangeNotification();

    saveToCache();

    clearChanges();

    if ( changed ) emit resourceChanged( this );

    emit resourceLoaded( this );
  }

  mLoadEventsJob = 0;

  if ( mLoadEventsProgress ) mLoadEventsProgress->setComplete();
  mLoadEventsProgress = 0;
}
void QgsPointDisplacementRenderer::drawGroup( const DisplacementGroup& group, QgsRenderContext& context )
{
  const QgsFeature& feature = group.begin().value().first;
  bool selected = mSelectedFeatures.contains( feature.id() ); // maybe we should highlight individual features instead of the whole group?

  QPointF pt;
  _getPoint( pt, context, feature.constGeometry()->asWkb() );

  //get list of labels and symbols
  QStringList labelAttributeList;
  QList<QgsMarkerSymbolV2*> symbolList;

  for ( DisplacementGroup::const_iterator attIt = group.constBegin(); attIt != group.constEnd(); ++attIt )
  {
    labelAttributeList << ( mDrawLabels ? getLabel( attIt.value().first ) : QString() );
    symbolList << dynamic_cast<QgsMarkerSymbolV2*>( attIt.value().second );
  }

  //draw symbol
  double diagonal = 0;
  double currentWidthFactor; //scale symbol size to map unit and output resolution

  QList<QgsMarkerSymbolV2*>::const_iterator it = symbolList.constBegin();
  for ( ; it != symbolList.constEnd(); ++it )
  {
    if ( *it )
    {
      currentWidthFactor = QgsSymbolLayerV2Utils::lineWidthScaleFactor( context, ( *it )->outputUnit(), ( *it )->mapUnitScale() );
      double currentDiagonal = sqrt( 2 * (( *it )->size() * ( *it )->size() ) ) * currentWidthFactor;
      if ( currentDiagonal > diagonal )
      {
        diagonal = currentDiagonal;
      }
    }
  }


  QgsSymbolV2RenderContext symbolContext( context, QgsSymbolV2::MM, 1.0, selected );
  double circleAdditionPainterUnits = symbolContext.outputLineWidth( mCircleRadiusAddition );
  double radius = qMax(( diagonal / 2 ), labelAttributeList.size() * diagonal / 2 / M_PI ) + circleAdditionPainterUnits;

  //draw Circle
  drawCircle( radius, symbolContext, pt, symbolList.size() );

  QList<QPointF> symbolPositions;
  QList<QPointF> labelPositions;
  calculateSymbolAndLabelPositions( pt, labelAttributeList.size(), radius, diagonal, symbolPositions, labelPositions );

  //draw mid point
  if ( labelAttributeList.size() > 1 )
  {
    if ( mCenterSymbol )
    {
      mCenterSymbol->renderPoint( pt, &feature, context, -1, selected );
    }
    else
    {
      context.painter()->drawRect( QRectF( pt.x() - symbolContext.outputLineWidth( 1 ), pt.y() - symbolContext.outputLineWidth( 1 ), symbolContext.outputLineWidth( 2 ), symbolContext.outputLineWidth( 2 ) ) );
    }
  }

  //draw symbols on the circle
  drawSymbols( feature, context, symbolList, symbolPositions, selected );
  //and also the labels
  drawLabels( pt, symbolContext, labelPositions, labelAttributeList );
}
QgsRasterRenderer* QgsRasterRendererRegistry::defaultRendererForDrawingStyle( QgsRaster::DrawingStyle theDrawingStyle, QgsRasterDataProvider* provider ) const
{
  if ( !provider || provider->bandCount() < 1 )
  {
    return nullptr;
  }


  QgsRasterRenderer* renderer = nullptr;
  switch ( theDrawingStyle )
  {
    case QgsRaster::PalettedColor:
    {
      int grayBand = 1; //reasonable default
      QList<QgsColorRampShader::ColorRampItem> colorEntries = provider->colorTable( grayBand );

      //go through list and take maximum value (it could be that entries don't start at 0 or indices are not contiguous)
      int colorArraySize = 0;
      QList<QgsColorRampShader::ColorRampItem>::const_iterator colorIt = colorEntries.constBegin();
      for ( ; colorIt != colorEntries.constEnd(); ++colorIt )
      {
        if ( colorIt->value > colorArraySize )
        {
          colorArraySize = ( int )( colorIt->value );
        }
      }

      colorArraySize += 1; //usually starts at 0
      QColor* colorArray = new QColor[ colorArraySize ];
      colorIt = colorEntries.constBegin();
      QVector<QString> labels;
      for ( ; colorIt != colorEntries.constEnd(); ++colorIt )
      {
        int idx = ( int )( colorIt->value );
        colorArray[idx] = colorIt->color;
        if ( !colorIt->label.isEmpty() )
        {
          if ( labels.size() <= idx ) labels.resize( idx + 1 );
          labels[idx] = colorIt->label;
        }
      }

      renderer = new QgsPalettedRasterRenderer( provider,
          grayBand,
          colorArray,
          colorArraySize,
          labels );
    }
    break;
    case QgsRaster::MultiBandSingleBandGray:
    case QgsRaster::SingleBandGray:
    {
      int grayBand = 1;
      renderer = new QgsSingleBandGrayRenderer( provider, grayBand );

      QgsContrastEnhancement* ce = new QgsContrastEnhancement(( QGis::DataType )(
            provider->dataType( grayBand ) ) );

// Default contrast enhancement is set from QgsRasterLayer, it has already setContrastEnhancementAlgorithm(). Default enhancement must only be set if default style was not loaded (to avoid stats calculation).
      (( QgsSingleBandGrayRenderer* )renderer )->setContrastEnhancement( ce );
      break;
    }
    case QgsRaster::SingleBandPseudoColor:
    {
      int bandNo = 1;
      double minValue = 0;
      double maxValue = 0;
      // TODO: avoid calculating statistics if not necessary (default style loaded)
      minMaxValuesForBand( bandNo, provider, minValue, maxValue );
      QgsRasterShader* shader = new QgsRasterShader( minValue, maxValue );
      renderer = new QgsSingleBandPseudoColorRenderer( provider, bandNo, shader );
      break;
    }
    case QgsRaster::MultiBandColor:
    {
      QSettings s;

      int redBand = s.value( "/Raster/defaultRedBand", 1 ).toInt();
      if ( redBand < 0 || redBand > provider->bandCount() )
      {
        redBand = -1;
      }
      int greenBand = s.value( "/Raster/defaultGreenBand", 2 ).toInt();
      if ( greenBand < 0 || greenBand > provider->bandCount() )
      {
        greenBand = -1;
      }
      int blueBand = s.value( "/Raster/defaultBlueBand", 3 ).toInt();
      if ( blueBand < 0 || blueBand > provider->bandCount() )
      {
        blueBand = -1;
      }

      renderer = new QgsMultiBandColorRenderer( provider, redBand, greenBand, blueBand );
      break;
    }
    case QgsRaster::SingleBandColorDataStyle:
    {
      renderer = new QgsSingleBandColorDataRenderer( provider, 1 );
      break;
    }
    default:
      return nullptr;
  }

  QgsRasterTransparency* tr = new QgsRasterTransparency(); //renderer takes ownership
  int bandCount = renderer->usesBands().size();
  if ( bandCount == 1 )
  {
    QList<QgsRasterTransparency::TransparentSingleValuePixel> transparentSingleList;
    tr->setTransparentSingleValuePixelList( transparentSingleList );
  }
  else if ( bandCount == 3 )
  {
    QList<QgsRasterTransparency::TransparentThreeValuePixel> transparentThreeValueList;
    tr->setTransparentThreeValuePixelList( transparentThreeValueList );
  }
  renderer->setRasterTransparency( tr );
  return renderer;
}
QImage* QgsPieDiagramFactory::createDiagram( int size, const QgsFeature& f, const QgsRenderContext& renderContext ) const
{
  QgsAttributeMap dataValues = f.attributeMap();
  double sizeScaleFactor = diagramSizeScaleFactor( renderContext );

  //create transparent QImage
  int imageSideLength = size * sizeScaleFactor * renderContext.rasterScaleFactor() + 2 * mMaximumPenWidth + 2 * mMaximumGap;
  QImage* diagramImage = new QImage( QSize( imageSideLength, imageSideLength ), QImage::Format_ARGB32_Premultiplied );
  diagramImage->fill( qRgba( 0, 0, 0, 0 ) ); //transparent background
  QPainter p;
  p.begin( diagramImage );
  p.setRenderHint( QPainter::Antialiasing );
  p.setPen( Qt::NoPen );

  //calculate sum of data values
  double sum = 0;
  QList<double> valueList; //cash the values to use them in drawing later

  QgsAttributeMap::const_iterator value_it;
  QList<QgsDiagramCategory>::const_iterator it = mCategories.constBegin();
  for ( ; it != mCategories.constEnd(); ++it )
  {
    value_it = dataValues.find( it->propertyIndex() );
    valueList.push_back( value_it->toDouble() );
    if ( value_it != dataValues.constEnd() )
    {
      sum += value_it->toDouble();
    }
  }

  if ( doubleNear( sum, 0.0 ) )
  {
    p.end();
    delete diagramImage;
    return 0;
  }

  //draw pies

  int totalAngle = 0;
  int currentAngle, currentGap;
  int xGapOffset = 0;
  int yGapOffset = 0;

  QList<QgsDiagramCategory>::const_iterator category_it = mCategories.constBegin();
  QList<double>::const_iterator valueList_it = valueList.constBegin();

  for ( ; category_it != mCategories.constEnd() && valueList_it != valueList.constEnd(); ++category_it, ++valueList_it )
  {
    p.setPen( category_it->pen() );
    currentAngle = ( int )(( *valueList_it ) / sum * 360 * 16 );
    p.setBrush( category_it->brush() );

    xGapOffset = 0;
    yGapOffset = 0;
    currentGap = category_it->gap();
    if ( currentGap != 0 )
    {
      //qt angles are degrees*16
      gapOffsetsForPieSlice( currentGap, totalAngle + currentAngle / 2, xGapOffset, yGapOffset );
    }

    p.drawPie( mMaximumPenWidth * renderContext.rasterScaleFactor() + mMaximumGap + xGapOffset, mMaximumPenWidth * renderContext.rasterScaleFactor() + mMaximumGap - yGapOffset, sizeScaleFactor * renderContext.rasterScaleFactor() * size, sizeScaleFactor * renderContext.rasterScaleFactor() * size, totalAngle, currentAngle );
    totalAngle += currentAngle;
  }
  p.end();

  return diagramImage;
}
示例#10
0
QString qt_mac_get_save_file_name(const QFileDialogArgs &args, QString *pwd,
                                  QString *selectedFilter)
{
    QWidget *parent = args.parent;
    OSErr err;
    QString retstr;
    NavDialogCreationOptions options;
    NavGetDefaultDialogCreationOptions(&options);
    static const int w = 450, h = 350;
    if (args.options & QFileDialog::DontConfirmOverwrite)
        options.optionFlags |= kNavDontConfirmReplacement;
    options.modality = kWindowModalityAppModal;
    options.location.h = options.location.v = -1;
    if (!args.directory.isEmpty())
        options.saveFileName = QCFString::toCFStringRef(args.selection);
    if (!args.caption.isEmpty())
        options.windowTitle = QCFString::toCFStringRef(args.caption);
    if (parent && parent->isVisible()) {
        WindowClass wclass;
        GetWindowClass(qt_mac_window_for(parent), &wclass);
        if (!(args.options & QFileDialog::DontUseSheet) && (wclass == kDocumentWindowClass ||
                                                            wclass == kFloatingWindowClass || wclass == kMovableModalWindowClass)) {
            options.modality = kWindowModalityWindowModal;
            options.parentWindow = qt_mac_window_for(parent);

            // The parent needs to be active for the sheet to get keyboard focus.
            if (!parent->isActiveWindow())
                parent->activateWindow();
        } else {
            parent = parent->window();
            QString s = parent->windowTitle();
            options.clientName = CFStringCreateWithCharacters(0, (UniChar *)s.unicode(), s.length());
            options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2);
            options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2);

            QRect r = QApplication::desktop()->screenGeometry(
                QApplication::desktop()->screenNumber(parent));
            if (options.location.h + w > r.right())
                options.location.h -= (options.location.h + w) - r.right() + 10;
            if (options.location.v + h > r.bottom())
                options.location.v -= (options.location.v + h) - r.bottom() + 10;
        }
#if 0
    } else if (QWidget *p = qApp->mainWidget()) {
        static int last_screen = -1;
        int scr = QApplication::desktop()->screenNumber(p);
        if (last_screen != scr) {
            QRect r = QApplication::desktop()->screenGeometry(scr);
            options.location.h = (r.x() + (r.width() / 2)) - (w / 2);
            options.location.v = (r.y() + (r.height() / 2)) - (h / 2);
        }
#endif
    }

    QList<qt_mac_filter_name*> filts = qt_mac_make_filters_list(args.filter);
    qt_mac_nav_filter_type t;
    t.saveDialog = true;
    t.index = 0;
    t.filts = &filts;
    if (filts.count() > 1) {
        int i = 0;
        CFStringRef *arr = static_cast<CFStringRef *>(malloc(sizeof(CFStringRef) * filts.count()));
        for (QList<qt_mac_filter_name*>::const_iterator it = filts.constBegin();
             it != filts.constEnd(); ++it)
            arr[i++] = QCFString::toCFStringRef((*it)->description);
        options.popupExtension = CFArrayCreate(0, reinterpret_cast<const void **>(arr), filts.count(), 0);
    }

    NavDialogRef dlg;
    if (NavCreatePutFileDialog(&options, 'cute', kNavGenericSignature, make_navProcUPP(),
                               static_cast<void *>(filts.isEmpty() ? 0 : &t), &dlg)) {
        qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
        return retstr;
    }
    if (pwd && !pwd->isEmpty()) {
        FSRef fsref;
        if (qt_mac_create_fsref(*pwd, &fsref) == noErr) {
            AEDesc desc;
            if (AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr)
                NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc);
        }
    }
    NavDialogRun(dlg);
    if (selectedFilter) {
        NavMenuItemSpec navSpec;
        bzero(&navSpec, sizeof(NavMenuItemSpec));
        qt_mac_filter_name *sel_filt_name = qt_mac_make_filters_list(*selectedFilter).at(0);
        for (int i = 0; i < filts.count(); ++i) {
            const qt_mac_filter_name *filter = filts.at(i);
            if (sel_filt_name->description == filter->description
                    && sel_filt_name->regxp == filter->regxp
                    && sel_filt_name->filter == filter->filter) {
                navSpec.menuType = i;
                break;
            }
        }
        NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec);
    }
    if (options.modality == kWindowModalityWindowModal) { //simulate modality
        QWidget modal_widg(parent, Qt::Sheet);
        modal_widg.createWinId();
        QApplicationPrivate::enterModal(&modal_widg);
        while (g_nav_blocking)
            qApp->processEvents(QEventLoop::WaitForMoreEvents);
        QApplicationPrivate::leaveModal(&modal_widg);
    }

    if (NavDialogGetUserAction(dlg) != kNavUserActionSaveAs) {
        NavDialogDispose(dlg);
        return retstr;
    }
    NavReplyRecord ret;
    NavDialogGetReply(dlg, &ret);
    NavDialogDispose(dlg);

    long count;
    err = AECountItems(&(ret.selection), &count);
    if (!ret.validRecord || err != noErr || !count) {
        NavDisposeReply(&ret);
        return retstr;
    }

    AEKeyword        keyword;
    DescType    type;
    Size        size;
    FSRef ref;
    err = AEGetNthPtr(&(ret.selection), 1, typeFSRef, &keyword,
                      &type, &ref, sizeof(ref), &size);
    if (err == noErr) {
        if (!str_buffer) {
            qAddPostRoutine(cleanup_str_buffer);
            str_buffer = (UInt8 *)malloc(1024);
        }
        FSRefMakePath(&ref, str_buffer, 1024);
        retstr = QString::fromUtf8((const char *)str_buffer);
        //now filename
        CFStringGetCString(ret.saveFileName, (char *)str_buffer, 1024, kCFStringEncodingUTF8);
        retstr += QLatin1String("/") + QString::fromUtf8((const char *)str_buffer);
    }
    NavDisposeReply(&ret);
    if (selectedFilter)
        *selectedFilter = filts.at(t.index)->filter;
    while (!filts.isEmpty())
        delete filts.takeFirst();
    return retstr;
}
示例#11
0
void QgsHistogramDiagram::renderDiagram( const QgsFeature& feature, QgsRenderContext& c, const QgsDiagramSettings& s, QPointF position )
{
  QPainter* p = c.painter();
  if ( !p )
  {
    return;
  }

  QList<double> values;
  double maxValue = 0;

  QgsExpressionContext expressionContext = c.expressionContext();
  expressionContext.setFeature( feature );
  if ( feature.fields() )
    expressionContext.setFields( *feature.fields() );

  Q_FOREACH ( const QString& cat, s.categoryAttributes )
  {
    QgsExpression* expression = getExpression( cat, expressionContext );
    double currentVal = expression->evaluate( &expressionContext ).toDouble();
    values.push_back( currentVal );
    maxValue = qMax( currentVal, maxValue );
  }

  double scaledMaxVal = sizePainterUnits( maxValue * mScaleFactor, s, c );

  double currentOffset = 0;
  double scaledWidth = sizePainterUnits( s.barWidth, s, c );

  double baseX = position.x();
  double baseY = position.y();

  mPen.setColor( s.penColor );
  setPenWidth( mPen, s, c );
  p->setPen( mPen );

  QList<double>::const_iterator valIt = values.constBegin();
  QList< QColor >::const_iterator colIt = s.categoryColors.constBegin();
  for ( ; valIt != values.constEnd(); ++valIt, ++colIt )
  {
    double length = sizePainterUnits( *valIt * mScaleFactor, s, c );

    mCategoryBrush.setColor( *colIt );
    p->setBrush( mCategoryBrush );

    switch ( s.diagramOrientation )
    {
      case QgsDiagramSettings::Up:
        p->drawRect( baseX + currentOffset, baseY, scaledWidth, length * -1 );
        break;

      case QgsDiagramSettings::Down:
        p->drawRect( baseX + currentOffset, baseY - scaledMaxVal, scaledWidth, length );
        break;

      case QgsDiagramSettings::Right:
        p->drawRect( baseX, baseY - currentOffset, length, scaledWidth * -1 );
        break;

      case QgsDiagramSettings::Left:
        p->drawRect( baseX + scaledMaxVal, baseY - currentOffset, 0 - length, scaledWidth * -1 );
        break;
    }

    currentOffset += scaledWidth;
  }
}
示例#12
0
QStringList qt_mac_get_open_file_names(const QFileDialogArgs &args, QString *pwd,
                                       QString *selectedFilter)
{
    QWidget *parent = args.parent;
    OSErr err;
    QStringList retstrl;

    NavDialogCreationOptions options;
    NavGetDefaultDialogCreationOptions(&options);
    options.modality = kWindowModalityAppModal;
    options.optionFlags |= kNavSupportPackages;
    if (args.options & QFileDialog::DontConfirmOverwrite)
        options.optionFlags |= kNavDontConfirmReplacement;
    if (args.mode != QFileDialog::ExistingFiles)
        options.optionFlags &= ~kNavAllowMultipleFiles;

    if (!args.caption.isEmpty())
        options.windowTitle = QCFString::toCFStringRef(args.caption);

    static const int w = 450, h = 350;
    options.location.h = options.location.v = -1;
    if (parent && parent->isVisible()) {
        WindowClass wclass;
        GetWindowClass(qt_mac_window_for(parent), &wclass);
        if (!(args.options & QFileDialog::DontUseSheet) && (wclass == kDocumentWindowClass ||
                                                            wclass == kFloatingWindowClass || wclass == kMovableModalWindowClass)) {
            options.modality = kWindowModalityWindowModal;
            options.parentWindow = qt_mac_window_for(parent);
        } else {
            parent = parent->window();
            QString s = parent->windowTitle();
            options.clientName = QCFString::toCFStringRef(s);
            options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2);
            options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2);

            QRect r = QApplication::desktop()->screenGeometry(
                QApplication::desktop()->screenNumber(parent));
            const int border = 10;
            if (options.location.h + w > r.right())
                options.location.h -= (options.location.h + w) - r.right() + border;
            if (options.location.v + h > r.bottom())
                options.location.v -= (options.location.v + h) - r.bottom() + border;
            if (options.location.h < r.left())
                options.location.h = r.left() + border;
            if (options.location.v < r.top())
                options.location.v = r.top() + border;
        }
#if 0
    } else if (QWidget *p = qApp->mainWidget()) {
        static int last_screen = -1;
        int scr = QApplication::desktop()->screenNumber(p);
        if (last_screen != scr) {
            QRect r = QApplication::desktop()->screenGeometry(scr);
            options.location.h = (r.x() + (r.width() / 2)) - (w / 2);
            options.location.v = (r.y() + (r.height() / 2)) - (h / 2);
        }
#endif
    }

    QList<qt_mac_filter_name*> filts = qt_mac_make_filters_list(args.filter);
    qt_mac_nav_filter_type t;
    t.saveDialog = false;
    t.index = 0;
    t.filts = &filts;
    if (filts.count() > 1) {
        int i = 0;
        CFStringRef *arr = static_cast<CFStringRef *>(malloc(sizeof(CFStringRef) * filts.count()));
        for (QList<qt_mac_filter_name*>::const_iterator it = filts.constBegin();
             it != filts.constEnd(); ++it)
            arr[i++] = QCFString::toCFStringRef((*it)->description);
        options.popupExtension = CFArrayCreate(0, reinterpret_cast<const void **>(arr), filts.count(), 0);
    }

    NavDialogRef dlg;
    if (args.mode == QFileDialog::DirectoryOnly ||
        args.mode == QFileDialog::Directory) {
        if (NavCreateChooseFolderDialog(&options, make_navProcUPP(), 0, 0, &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    } else {
        if (NavCreateGetFileDialog(&options, 0, make_navProcUPP(), 0,
                                  make_navFilterUPP(), (void *) (filts.isEmpty() ? 0 : &t),
                                  &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    }
    if (pwd && !pwd->isEmpty()) {
        FSRef fsref;
        if (qt_mac_create_fsref(*pwd, &fsref) == noErr) {
            AEDesc desc;
            if (AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr)
                NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc);
        }
    }

    NavDialogRun(dlg);

    if (selectedFilter) {
        NavMenuItemSpec navSpec;
        bzero(&navSpec, sizeof(NavMenuItemSpec));
        qt_mac_filter_name *sel_filt_name = qt_mac_make_filters_list(*selectedFilter).at(0);
        for (int i = 0; i < filts.count(); ++i) {
            const qt_mac_filter_name *filter = filts.at(i);
            if (sel_filt_name->description == filter->description
                    && sel_filt_name->regxp == filter->regxp
                    && sel_filt_name->filter == filter->filter) {
                navSpec.menuType = i;
                break;
            }
        }
        NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec);
    }

    if (options.modality == kWindowModalityWindowModal) { //simulate modality
        QWidget modal_widg(parent, Qt::Sheet);
        modal_widg.createWinId();
        QApplicationPrivate::enterModal(&modal_widg);
        while (g_nav_blocking)
            qApp->processEvents(QEventLoop::WaitForMoreEvents);
        QApplicationPrivate::leaveModal(&modal_widg);
    }

    if (!(NavDialogGetUserAction(dlg) &
          (kNavUserActionOpen | kNavUserActionChoose | kNavUserActionNewFolder))) {
        NavDialogDispose(dlg);
        return retstrl;
    }
    NavReplyRecord ret;
    NavDialogGetReply(dlg, &ret);
    NavDialogDispose(dlg);

    long count;
    err = AECountItems(&(ret.selection), &count);
    if (!ret.validRecord || err != noErr || !count) {
        NavDisposeReply(&ret);
        return retstrl;
    }

    for (long index = 1; index <= count; index++) {
        FSRef ref;
        err = AEGetNthPtr(&(ret.selection), index, typeFSRef, 0, 0, &ref, sizeof(ref), 0);
        if (err != noErr)
            break;

        if (!str_buffer) {
            qAddPostRoutine(cleanup_str_buffer);
            str_buffer = (UInt8 *)malloc(1024);
        }
        FSRefMakePath(&ref, str_buffer, 1024);
        retstrl.append(QString::fromUtf8((const char *)str_buffer));
    }
    NavDisposeReply(&ret);
    if (selectedFilter)
        *selectedFilter = filts.at(t.index)->filter;
    while (!filts.isEmpty())
        delete filts.takeFirst();
    return retstrl;
}
示例#13
0
KEquityPriceUpdateDlg::KEquityPriceUpdateDlg(QWidget *parent, const QString& securityId) :
    KEquityPriceUpdateDlgDecl(parent),
    m_fUpdateAll(false)
{
  QStringList headerList;
  headerList << i18n("Symbol") << i18nc("Equity name", "Name")
  << i18n("Price") << i18n("Date");

  lvEquityList->header()->setSortIndicator(0, Qt::AscendingOrder);
  lvEquityList->setColumnWidth(NAME_COL, 125);

  // This is a "get it up and running" hack.  Will replace this in the future.
  headerList << i18nc("Internal identifier", "ID")
  << i18nc("Online quote source", "Source");
  lvEquityList->setColumnWidth(ID_COL, 0);

  lvEquityList->setHeaderLabels(headerList);

  lvEquityList->setSelectionMode(QAbstractItemView::MultiSelection);
  lvEquityList->setAllColumnsShowFocus(true);

  btnUpdateAll->setEnabled(false);

  btnOK->setGuiItem(KStandardGuiItem::ok());
  btnCancel->setGuiItem(KStandardGuiItem::cancel());

  MyMoneyFile* file = MyMoneyFile::instance();

  //
  // Add each price pair that we know about
  //

  // send in securityId == "XXX YYY" to get a single-shot update for XXX to YYY.
  // for consistency reasons, this accepts the same delimiters as WebPriceQuote::launch()
  QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive);
  MyMoneySecurityPair currencyIds;
  if (splitrx.indexIn(securityId) != -1) {
    currencyIds = MyMoneySecurityPair(splitrx.cap(1).toUtf8(), splitrx.cap(2).toUtf8());
  }

  MyMoneyPriceList prices = file->priceList();
  for (MyMoneyPriceList::ConstIterator it_price = prices.constBegin(); it_price != prices.constEnd(); ++it_price) {
    const MyMoneySecurityPair& pair = it_price.key();
    if (file->security(pair.first).isCurrency() && (securityId.isEmpty() || (pair == currencyIds))) {
      const MyMoneyPriceEntries& entries = (*it_price);
      if (entries.count() > 0 && entries.begin().key() <= QDate::currentDate()) {
        addPricePair(pair);
        btnUpdateAll->setEnabled(true);
      }
    }
  }

  //
  // Add each investment
  //

  QList<MyMoneySecurity> securities = file->securityList();
  for (QList<MyMoneySecurity>::const_iterator it = securities.constBegin(); it != securities.constEnd(); ++it) {
    if (!(*it).isCurrency()
        && (securityId.isEmpty() || ((*it).id() == securityId))
        && !(*it).value("kmm-online-source").isEmpty()
       ) {
      addInvestment(*it);
      btnUpdateAll->setEnabled(true);
    }
  }

  // if list is empty, add the request price pair
  if (lvEquityList->invisibleRootItem()->childCount() == 0) {
    addPricePair(currencyIds, true);
  }

  connect(btnOK, SIGNAL(clicked()), this, SLOT(accept()));
  connect(btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
  connect(btnUpdateSelected, SIGNAL(clicked()), this, SLOT(slotUpdateSelectedClicked()));
  connect(btnUpdateAll, SIGNAL(clicked()), this, SLOT(slotUpdateAllClicked()));

  connect(&m_webQuote, SIGNAL(quote(QString,QString,QDate,double)),
          this, SLOT(slotReceivedQuote(QString,QString,QDate,double)));
  connect(&m_webQuote, SIGNAL(failed(QString,QString)),
          this, SLOT(slotQuoteFailed(QString,QString)));
  connect(&m_webQuote, SIGNAL(status(QString)),
          this, SLOT(logStatusMessage(QString)));
  connect(&m_webQuote, SIGNAL(error(QString)),
          this, SLOT(logErrorMessage(QString)));

  connect(lvEquityList, SIGNAL(itemSelectionChanged()), this, SLOT(slotUpdateSelection()));

  // Not implemented yet.
  btnConfigure->hide();
  //connect(btnConfigure, SIGNAL(clicked()), this, SLOT(slotConfigureClicked()));

  if (!securityId.isEmpty()) {
    btnUpdateSelected->hide();
    btnUpdateAll->hide();
    // delete layout1;

    QTimer::singleShot(100, this, SLOT(slotUpdateAllClicked()));
  }

  // Hide OK button until we have received the first update
  btnOK->setEnabled(false);

  slotUpdateSelection();

  // previous versions of this dialog allowed to store a "Don't ask again" switch.
  // Since we don't support it anymore, we just get rid of it
  KSharedConfigPtr config = KGlobal::config();
  KConfigGroup grp = config->group("Notification Messages");
  grp.deleteEntry("KEquityPriceUpdateDlg::slotQuoteFailed::Price Update Failed");
}
示例#14
0
ErrorList topolTest::checkPointCoveredByLineEnds( QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  int i = 0;
  ErrorList errorList;


  if ( layer1->geometryType() != QgsWkbTypes::PointGeometry )
  {
    return errorList;
  }

  if ( layer2->geometryType() != QgsWkbTypes::LineGeometry )
  {
    return errorList;
  }

  QgsSpatialIndex *index = mLayerIndexes[layer2->id()];
  QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( qgsInterface->mapCanvas()->extent().asWktPolygon() );

  QList<FeatureLayer>::Iterator it;
  for ( it = mFeatureList1.begin(); it != mFeatureList1.end(); ++it )
  {
    if ( !( ++i % 100 ) )
      emit progress( i );
    if ( testCanceled() )
      break;
    QgsGeometry g1 = it->feature.geometry();
    QgsRectangle bb = g1.boundingBox();
    QList<QgsFeatureId> crossingIds;
    crossingIds = index->intersects( bb );
    QList<QgsFeatureId>::ConstIterator cit = crossingIds.constBegin();
    QList<QgsFeatureId>::ConstIterator crossingIdsEnd = crossingIds.constEnd();
    bool touched = false;
    for ( ; cit != crossingIdsEnd; ++cit )
    {
      QgsFeature &f = mFeatureMap2[*cit].feature;
      QgsGeometry g2 = f.geometry();
      if ( g2.isNull() || !_canExportToGeos( g2 ) )
      {
        QgsMessageLog::logMessage( tr( "Second geometry missing or GEOS import failed." ), tr( "Topology plugin" ) );
        continue;
      }
      QgsPolylineXY g2Line = g2.asPolyline();
      QgsGeometry startPoint = QgsGeometry::fromPointXY( g2Line.at( 0 ) );
      QgsGeometry endPoint = QgsGeometry::fromPointXY( g2Line.last() );
      touched = g1.intersects( startPoint ) || g1.intersects( endPoint );

      if ( touched )
      {
        break;
      }
    }
    if ( !touched )
    {
      QgsGeometry conflictGeom = g1;
      if ( isExtent )
      {
        if ( canvasExtentPoly.disjoint( conflictGeom ) )
        {
          continue;
        }
      }

      QList<FeatureLayer> fls;
      fls << *it << *it;
      //bb.scale(10);

      TopolErrorPointNotCoveredByLineEnds *err = new TopolErrorPointNotCoveredByLineEnds( bb, conflictGeom, fls );
      errorList << err;
    }
  }
  return errorList;
}
示例#15
0
void QgsPieDiagram::renderDiagram( const QgsAttributes& att, QgsRenderContext& c, const QgsDiagramSettings& s, const QPointF& position )
{
  QPainter* p = c.painter();
  if ( !p )
  {
    return;
  }

  //get sum of values
  QList<double> values;
  double currentVal = 0;
  double valSum = 0;
  int valCount = 0;

  QList<int>::const_iterator catIt = s.categoryIndices.constBegin();
  for ( ; catIt != s.categoryIndices.constEnd(); ++catIt )
  {
    currentVal = att[*catIt].toDouble();
    values.push_back( currentVal );
    valSum += currentVal;
    if ( currentVal ) valCount++;
  }

  //draw the slices
  double totalAngle = 0;
  double currentAngle;

  //convert from mm / map units to painter units
  QSizeF spu = sizePainterUnits( s.size, s, c );
  double w = spu.width();
  double h = spu.height();

  double baseX = position.x();
  double baseY = position.y() - h;

  mPen.setColor( s.penColor );
  setPenWidth( mPen, s, c );
  p->setPen( mPen );

  // there are some values > 0 available
  if ( valSum > 0 )
  {
    QList<double>::const_iterator valIt = values.constBegin();
    QList< QColor >::const_iterator colIt = s.categoryColors.constBegin();
    for ( ; valIt != values.constEnd(); ++valIt, ++colIt )
    {
      if ( *valIt )
      {
        currentAngle = *valIt / valSum * 360 * 16;
        mCategoryBrush.setColor( *colIt );
        p->setBrush( mCategoryBrush );
        // if only 1 value is > 0, draw a circle
        if ( valCount == 1 )
        {
          p->drawEllipse( baseX, baseY, w, h );
        }
        else
        {
          p->drawPie( baseX, baseY, w, h, totalAngle + s.angleOffset, currentAngle );
        }
        totalAngle += currentAngle;
      }
    }
  }
  else // valSum > 0
  {
    // draw empty circle if no values are defined at all
    mCategoryBrush.setColor( Qt::transparent );
    p->setBrush( mCategoryBrush );
    p->drawEllipse( baseX, baseY, w, h );
  }
}
示例#16
0
文件: qdbusmisc.cpp 项目: Afreeca/qt
// calculates the metatypes for the method
// the slot must have the parameters in the following form:
//  - zero or more value or const-ref parameters of any kind
//  - zero or one const ref of QDBusMessage
//  - zero or more non-const ref parameters
// No parameter may be a template.
// this function returns -1 if the parameters don't match the above form
// this function returns the number of *input* parameters, including the QDBusMessage one if any
// this function does not check the return type, so metaTypes[0] is always 0 and always present
// metaTypes.count() >= retval + 1 in all cases
//
// sig must be the normalised signature for the method
int qDBusParametersForMethod(const QMetaMethod &mm, QList<int>& metaTypes)
{
    QDBusMetaTypeId::init();

    QList<QByteArray> parameterTypes = mm.parameterTypes();
    metaTypes.clear();

    metaTypes.append(0);        // return type
    int inputCount = 0;
    bool seenMessage = false;
    QList<QByteArray>::ConstIterator it = parameterTypes.constBegin();
    QList<QByteArray>::ConstIterator end = parameterTypes.constEnd();
    for ( ; it != end; ++it) {
        const QByteArray &type = *it;
        if (type.endsWith('*')) {
            //qWarning("Could not parse the method '%s'", mm.signature());
            // pointer?
            return -1;
        }

        if (type.endsWith('&')) {
            QByteArray basictype = type;
            basictype.truncate(type.length() - 1);

            int id = qDBusNameToTypeId(basictype);
            if (id == 0) {
                //qWarning("Could not parse the method '%s'", mm.signature());
                // invalid type in method parameter list
                return -1;
            } else if (QDBusMetaType::typeToSignature(id) == 0)
                return -1;

            metaTypes.append( id );
            seenMessage = true; // it cannot appear anymore anyways
            continue;
        }

        if (seenMessage) {      // && !type.endsWith('&')
            //qWarning("Could not parse the method '%s'", mm.signature());
            // non-output parameters after message or after output params
            return -1;          // not allowed
        }

        int id = qDBusNameToTypeId(type);
        if (id == 0) {
            //qWarning("Could not parse the method '%s'", mm.signature());
            // invalid type in method parameter list
            return -1;
        }

        if (id == QDBusMetaTypeId::message)
            seenMessage = true;
        else if (QDBusMetaType::typeToSignature(id) == 0)
            return -1;

        metaTypes.append(id);
        ++inputCount;
    }

    return inputCount;
}
void KCalResourceSlox::slotLoadTodosResult( KJob *job )
{
  kDebug();

  if ( job->error() ) {
    loadError( job->errorString() );
  } else {
    kDebug() << "success";

    QDomDocument doc = mLoadTodosJob->response();

    mWebdavHandler.log( doc.toString( 2 ) );

    QList<SloxItem> items = WebdavHandler::getSloxItems( this, doc );

    bool changed = false;

    disableChangeNotification();

    QList<SloxItem>::ConstIterator it;
    for( it = items.constBegin(); it != items.constEnd(); ++it ) {
      SloxItem item = *it;
      QString uid = sloxIdToTodoUid( item.sloxId );
      if ( item.status == SloxItem::Delete ) {
        Todo *todo = calendar()->todo( uid );
        if ( todo ) {
          calendar()->deleteTodo( todo );
          changed = true;
        }
      } else if ( item.status == SloxItem::Create ) {
        Todo *newTodo = 0;
        Todo *todo = calendar()->todo( uid );
        if ( !todo ) {
          newTodo = new Todo;
          todo = newTodo;
          todo->setUid( uid );
          todo->setSecrecy( Incidence::SecrecyPrivate );
        }

        todo->setCustomProperty( "SLOX", "ID", item.sloxId );

        mWebdavHandler.clearSloxAttributeStatus();

        QDomNode n;
        for( n = item.domNode.firstChild(); !n.isNull(); n = n.nextSibling() ) {
          QDomElement e = n.toElement();
          mWebdavHandler.parseSloxAttribute( e );
          parseIncidenceAttribute( e, todo );
          parseTodoAttribute( e, todo );
        }

        mWebdavHandler.setSloxAttributes( todo );

        if ( newTodo ) calendar()->addTodo( todo );

        changed = true;
      }
    }

    enableChangeNotification();

    clearChanges();

    if ( changed ) emit resourceChanged( this );

    emit resourceLoaded( this );
  }

  mLoadTodosJob = 0;

  if ( mLoadTodosProgress ) mLoadTodosProgress->setComplete();
  mLoadTodosProgress = 0;
}
示例#18
0
int QgsVectorLayerEditUtils::splitFeatures( const QList<QgsPoint>& splitLine, bool topologicalEditing )
{
  if ( !L->hasGeometryType() )
    return 4;

  QgsFeatureList newFeatures; //store all the newly created features
  double xMin, yMin, xMax, yMax;
  QgsRectangle bBox; //bounding box of the split line
  int returnCode = 0;
  int splitFunctionReturn; //return code of QgsGeometry::splitGeometry
  int numberOfSplittedFeatures = 0;

  QgsFeatureIterator features;
  const QgsFeatureIds selectedIds = L->selectedFeaturesIds();

  if ( selectedIds.size() > 0 ) //consider only the selected features if there is a selection
  {
    features = L->selectedFeaturesIterator();
  }
  else //else consider all the feature that intersect the bounding box of the split line
  {
    if ( boundingBoxFromPointList( splitLine, xMin, yMin, xMax, yMax ) == 0 )
    {
      bBox.setXMinimum( xMin ); bBox.setYMinimum( yMin );
      bBox.setXMaximum( xMax ); bBox.setYMaximum( yMax );
    }
    else
    {
      return 1;
    }

    if ( bBox.isEmpty() )
    {
      //if the bbox is a line, try to make a square out of it
      if ( bBox.width() == 0.0 && bBox.height() > 0 )
      {
        bBox.setXMinimum( bBox.xMinimum() - bBox.height() / 2 );
        bBox.setXMaximum( bBox.xMaximum() + bBox.height() / 2 );
      }
      else if ( bBox.height() == 0.0 && bBox.width() > 0 )
      {
        bBox.setYMinimum( bBox.yMinimum() - bBox.width() / 2 );
        bBox.setYMaximum( bBox.yMaximum() + bBox.width() / 2 );
      }
      else
      {
        //If we have a single point, we still create a non-null box
        double bufferDistance = 0.000001;
        if ( L->crs().geographicFlag() )
          bufferDistance = 0.00000001;
        bBox.setXMinimum( bBox.xMinimum() - bufferDistance );
        bBox.setXMaximum( bBox.xMaximum() + bufferDistance );
        bBox.setYMinimum( bBox.yMinimum() - bufferDistance );
        bBox.setYMaximum( bBox.yMaximum() + bufferDistance );
      }
    }

    features = L->getFeatures( QgsFeatureRequest().setFilterRect( bBox ).setFlags( QgsFeatureRequest::ExactIntersect ) );
  }

  QgsFeature feat;
  while ( features.nextFeature( feat ) )
  {
    if ( !feat.constGeometry() )
    {
      continue;
    }
    QList<QgsGeometry*> newGeometries;
    QList<QgsPoint> topologyTestPoints;
    QgsGeometry* newGeometry = 0;
    splitFunctionReturn = feat.geometry()->splitGeometry( splitLine, newGeometries, topologicalEditing, topologyTestPoints );
    if ( splitFunctionReturn == 0 )
    {
      //change this geometry
      L->editBuffer()->changeGeometry( feat.id(), feat.geometry() );

      //insert new features
      for ( int i = 0; i < newGeometries.size(); ++i )
      {
        newGeometry = newGeometries.at( i );
        QgsFeature newFeature;
        newFeature.setGeometry( newGeometry );

        //use default value where possible for primary key (e.g. autoincrement),
        //and use the value from the original (split) feature if not primary key
        QgsAttributes newAttributes = feat.attributes();
        Q_FOREACH ( int pkIdx, L->dataProvider()->pkAttributeIndexes() )
        {
          const QVariant defaultValue = L->dataProvider()->defaultValue( pkIdx );
          if ( !defaultValue.isNull() )
          {
            newAttributes[ pkIdx ] = defaultValue;
          }
          else //try with NULL
          {
            newAttributes[ pkIdx ] = QVariant();
          }
        }

        newFeature.setAttributes( newAttributes );

        newFeatures.append( newFeature );
      }

      if ( topologicalEditing )
      {
        QList<QgsPoint>::const_iterator topol_it = topologyTestPoints.constBegin();
        for ( ; topol_it != topologyTestPoints.constEnd(); ++topol_it )
        {
          addTopologicalPoints( *topol_it );
        }
      }
      ++numberOfSplittedFeatures;
    }
    else if ( splitFunctionReturn > 1 ) //1 means no split but also no error
示例#19
0
int main(int argc, char **argv)
{
	QApplication app(argc, argv, true);
	QTranslator custranldr;
	QTranslator translator;
	QString tnapplang;
	QString tnappcoun;
	QString clangcode = "";
	QStringList allappargs = app.arguments();
	QList<QPair<QString, QString> > oppairs;
	for (QList<QString>::const_iterator i = allappargs.constBegin(); i < allappargs.constEnd(); ++i)
	{
		if (i->count('=') == 1)
			oppairs.append(QPair<QString, QString>(i->section('=', 0, 0).simplified(), i->section('=',1, 1).simplified()));
	}
	for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i)
	{
		if (i->first.contains("lang", Qt::CaseInsensitive))
		{
			clangcode = i->second;
			tnapplang = clangcode.left(2);
			if (clangcode.contains('_') && clangcode.size() == 5)
			{
				tnappcoun = clangcode.section('_', -1, -1);
			}
			break;
		}
	}
	if (clangcode.isEmpty())
	{
		clangcode = QLocale::system().name();
		tnapplang = clangcode.left(2);
		if (clangcode.contains('_') && clangcode.size() == 5)
		{
			tnappcoun = clangcode.section('_', -1, -1);
		}
	}
	QDir applocdir(app.applicationDirPath());
	QStringList applocfiles = applocdir.entryList(QStringList() << "*.qm", QDir::Files);
	if (!applocfiles.isEmpty())
	{
		QString custqmfilepath = applocfiles.at(0);
		if (!applocfiles.filter("unetbootin").isEmpty())
		{
			custqmfilepath = applocfiles.filter("unetbootin").at(0);
			if (!applocfiles.filter("unetbootin").filter(tnapplang).isEmpty())
			{
				custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).at(0);
				if (!tnappcoun.isEmpty() && !applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).isEmpty())
					custqmfilepath = applocfiles.filter("unetbootin").filter(tnapplang).filter(tnappcoun).at(0);
			}
		}
		if (custranldr.load(custqmfilepath, app.applicationDirPath()))
			app.installTranslator(&custranldr);
	}
	if (!tnappcoun.isEmpty() && QFile::exists(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun)) && translator.load(QString("%1/unetbootin_%2_%3.qm").arg(app.applicationDirPath()).arg(tnapplang).arg(tnappcoun)))
	{
		app.installTranslator(&translator);
	}
	else if (!tnappcoun.isEmpty() && QFile::exists(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString(":/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)))
	{
		app.installTranslator(&translator);
	}
	else if (!tnappcoun.isEmpty() && QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1_%2.qm").arg(tnapplang).arg(tnappcoun)))
	{
		app.installTranslator(&translator);
	}
	else if (QFile::exists(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang)) && translator.load(QString("%1/unetbootin_%2.qm").arg(app.applicationDirPath(), tnapplang)))
	{
		app.installTranslator(&translator);
	}
	else if (QFile::exists(QString(":/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString(":/unetbootin_%1.qm").arg(tnapplang)))
	{
		app.installTranslator(&translator);
	}
	else if (QFile::exists(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang)) && translator.load(QString("/usr/share/unetbootin/unetbootin_%1.qm").arg(tnapplang)))
	{
		app.installTranslator(&translator);
	}
	else
	{
		tnapplang = "en";
		tnappcoun = "US";
		clangcode = "en_US";
	}
	app.installTranslator(&translator);
	if (QObject::tr("LeftToRight") == "RightToLeft")
		app.setLayoutDirection(Qt::RightToLeft);
	#ifdef Q_OS_UNIX
	bool disabledrootcheck = false;
	for (QList<QPair<QString, QString> >::const_iterator i = oppairs.constBegin(); i < oppairs.constEnd(); ++i)
	{
		if (i->first.contains("rootcheck", Qt::CaseInsensitive))
		{
			if (i->second.contains('n', Qt::CaseInsensitive))
				disabledrootcheck = true;
			break;
		}
	}
	if (!disabledrootcheck)
	{
		QProcess whoamip;
		whoamip.start("whoami");
		whoamip.waitForFinished();
		if (QString(whoamip.readAll()).remove("\r").remove("\n") != "root")
		{
			QString argsconc = "";
            QString argsconcSingleQuote = "";
			for (int i = 1; i < allappargs.size(); ++i)
			{
				argsconc += QString("\"%1\" ").arg(allappargs.at(i));
                argsconcSingleQuote += QString("'%1' ").arg(allappargs.at(i));
			}
            argsconc += "\"rootcheck=no\"";
            argsconcSingleQuote += "'rootcheck=no'";
#ifdef Q_OS_LINUX
            QString gksuarg1;
            gksuarg1 += QString("bash -c 'QT_X11_NO_MITSHM=1 ");
            gksuarg1 += QString("%1 %2").arg(app.applicationFilePath()).arg(argsconc);
            gksuarg1 += QString("'");
            QStringList gksuargs;
            gksuargs.append(gksuarg1);
            QString gksulocation = checkforgraphicalsu("gksu");
			if (gksulocation != "REQCNOTFOUND")
			{
                //QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc));
                QProcess::startDetached(gksulocation, gksuargs);
				return 0;
			}
			QString kdesulocation = checkforgraphicalsu("kdesu");
			if (kdesulocation != "REQCNOTFOUND")
			{
                //QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc));
                QProcess::startDetached(kdesulocation, gksuargs);
				return 0;
			}
			QString gnomesulocation = checkforgraphicalsu("gnomesu");
			if (gnomesulocation != "REQCNOTFOUND")
			{
                //QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc));
                QProcess::startDetached(gnomesulocation, gksuargs);
				return 0;
			}
			QString kdesudolocation = checkforgraphicalsu("kdesudo");
			if (kdesudolocation != "REQCNOTFOUND")
			{
                //QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc));
                QProcess::startDetached(kdesudolocation, gksuargs);
				return 0;
			}
			QMessageBox rootmsgb;
			rootmsgb.setIcon(QMessageBox::Warning);
			rootmsgb.setWindowTitle(uninstaller::tr("Must run as root"));
			rootmsgb.setTextFormat(Qt::RichText);
            rootmsgb.setText(uninstaller::tr("%2 must be run as root. Run it from the command line using:<br/><b>sudo QT_X11_NO_MITSHM=1 %1</b><br/>").arg(app.applicationFilePath()).arg(UNETBOOTINB));
			rootmsgb.setStandardButtons(QMessageBox::Ok);
			switch (rootmsgb.exec())
			{
				case QMessageBox::Ok:
					break;
				default:
					break;
			}
     return 0;
     /*
     QString pkexeclocation = checkforgraphicalsu("pkexec");
     if (pkexeclocation != "REQCNOTFOUND" && app.applicationFilePath() == "/usr/bin/unetbootin" && QFile::exists("/usr/share/polkit-1/actions/org.unetbootin.pkexec.unetbootin.policy"))
     {
         QProcess::startDetached(QString("%1 %2").arg(pkexeclocation).arg(app.applicationFilePath()));
         //QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc));
         //QProcess::startDetached(QString("%1 %2 %3").arg(pkexeclocation).arg(app.applicationFilePath()).arg(argsconc));
         return 0;
     }
     */
#endif
#ifdef Q_OS_MAC
            /*
			QProcess osascriptProc;
			osascriptProc.start("osascript");
			osascriptProc.write(QString("do shell script \""+app.applicationFilePath()+"\" with administrator privileges\n").toAscii().data());
			osascriptProc.closeWriteChannel();
			osascriptProc.waitForFinished(-1);
            */
            //qDebug() << QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc);
            //QProcess::startDetached(QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc));
            QProcess::startDetached("osascript", QStringList() << "-e" << QString("do shell script \"'%1' %2\" with administrator privileges").arg(app.applicationFilePath()).arg(argsconcSingleQuote));
            return 0;
#endif
		}
	}
	#endif
	#ifdef Q_OS_WIN32
	QSettings chkinst("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\UNetbootin", QSettings::NativeFormat);
	#endif
	#ifdef Q_OS_LINUX
	QSettings chkinst(QSettings::SystemScope, "UNetbootin");
	#endif
#ifndef Q_OS_MAC
	if (chkinst.contains("Location"))
	{
		QMessageBox uninstmsgb;
		uninstmsgb.setIcon(QMessageBox::Information);
		uninstmsgb.setWindowTitle(uninstaller::tr("%1 Uninstaller").arg(UNETBOOTINB));
		uninstmsgb.setText(uninstaller::tr("%1 is currently installed. Remove the existing version?").arg(UNETBOOTINB));
 		uninstmsgb.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
 		switch (uninstmsgb.exec())
 		{
 			case QMessageBox::Ok:
 			{
 				ubnUninst();
			}
			case QMessageBox::Cancel:
				break;
	 		default:
				break;
 		}
		return 0;
	}
#endif
	unetbootin unetbootin;
	unetbootin.appNlang = tnapplang;
	unetbootin.appDir = QDir::toNativeSeparators(QString("%1/").arg(app.applicationDirPath()));
	unetbootin.appLoc = app.applicationFilePath();
	QIcon icon;
	icon.addFile(":/unetbootin_16.png", QSize(16,16));
	icon.addFile(":/unetbootin_22.png", QSize(22,22));
	icon.addFile(":/unetbootin_24.png", QSize(24,24));
	icon.addFile(":/unetbootin_32.png", QSize(32,32));
	icon.addFile(":/unetbootin_48.png", QSize(48,48));
#ifdef Q_OS_LINUX
	icon.addFile("/usr/share/pixmaps/unetbootin.png");
	icon.addFile("/usr/share/pixmaps/unetbootin.xpm");
#endif
	unetbootin.setWindowIcon(icon);
	QObject::connect(&app, SIGNAL(lastWindowClosed()), &unetbootin, SLOT(killApplication()));
	bool automate = unetbootin.ubninitialize(oppairs);
	unetbootin.show();
	if (automate)
		QTimer::singleShot(0, &unetbootin, SLOT(on_okbutton_clicked()));
	return app.exec();
}
示例#20
0
void QgsDecorationGrid::render( QPainter * p )
{
  if ( ! mEnabled )
    return;

  // p->setPen( mGridPen );

  QList< QPair< qreal, QLineF > > verticalLines;
  yGridLines( verticalLines );
  QList< QPair< qreal, QLineF > > horizontalLines;
  xGridLines( horizontalLines );
  //QgsDebugMsg( QString("grid has %1 vertical and %2 horizontal lines").arg( verticalLines.size() ).arg( horizontalLines.size() ) );

  QList< QPair< qreal, QLineF > >::const_iterator vIt = verticalLines.constBegin();
  QList< QPair< qreal, QLineF > >::const_iterator hIt = horizontalLines.constBegin();

  //simpler approach: draw vertical lines first, then horizontal ones
  if ( mGridStyle == QgsDecorationGrid::Line )
  {
    if ( ! mLineSymbol )
      return;

    QgsRenderContext context = QgsRenderContext::fromMapSettings( QgisApp::instance()->mapCanvas()->mapSettings() );
    context.setPainter( p );
    mLineSymbol->startRender( context, 0 );

    for ( ; vIt != verticalLines.constEnd(); ++vIt )
    {
      // p->drawLine( vIt->second );
      // need to convert QLineF to QPolygonF ...
      QVector<QPointF> poly;
      poly << vIt->second.p1() << vIt->second.p2();
      mLineSymbol->renderPolyline( QPolygonF( poly ), 0, context );
    }

    for ( ; hIt != horizontalLines.constEnd(); ++hIt )
    {
      // p->drawLine( hIt->second );
      // need to convert QLineF to QPolygonF ...
      QVector<QPointF> poly;
      poly << hIt->second.p1() << hIt->second.p2();
      mLineSymbol->renderPolyline( QPolygonF( poly ), 0, context );
    }

    mLineSymbol->stopRender( context );
  }
#if 0
  else if ( mGridStyle == QgsDecorationGrid::Cross )
  {
    QPointF intersectionPoint, crossEnd1, crossEnd2;
    for ( ; vIt != verticalLines.constEnd(); ++vIt )
    {
      //start mark
      crossEnd1 = QgsSymbolLayerV2Utils::pointOnLineWithDistance( vIt->second.p1(), vIt->second.p2(), mCrossLength );
      p->drawLine( vIt->second.p1(), crossEnd1 );

      //test for intersection with every horizontal line
      hIt = horizontalLines.constBegin();
      for ( ; hIt != horizontalLines.constEnd(); ++hIt )
      {
        if ( hIt->second.intersect( vIt->second, &intersectionPoint ) == QLineF::BoundedIntersection )
        {
          crossEnd1 = QgsSymbolLayerV2Utils::pointOnLineWithDistance( intersectionPoint, vIt->second.p1(), mCrossLength );
          crossEnd2 = QgsSymbolLayerV2Utils::pointOnLineWithDistance( intersectionPoint, vIt->second.p2(), mCrossLength );
          p->drawLine( crossEnd1, crossEnd2 );
        }
      }
      //end mark
      QPointF crossEnd2 = QgsSymbolLayerV2Utils::pointOnLineWithDistance( vIt->second.p2(), vIt->second.p1(), mCrossLength );
      p->drawLine( vIt->second.p2(), crossEnd2 );
    }

    hIt = horizontalLines.constBegin();
    for ( ; hIt != horizontalLines.constEnd(); ++hIt )
    {
      //start mark
      crossEnd1 = QgsSymbolLayerV2Utils::pointOnLineWithDistance( hIt->second.p1(), hIt->second.p2(), mCrossLength );
      p->drawLine( hIt->second.p1(), crossEnd1 );

      vIt = verticalLines.constBegin();
      for ( ; vIt != verticalLines.constEnd(); ++vIt )
      {
        if ( vIt->second.intersect( hIt->second, &intersectionPoint ) == QLineF::BoundedIntersection )
        {
          crossEnd1 = QgsSymbolLayerV2Utils::pointOnLineWithDistance( intersectionPoint, hIt->second.p1(), mCrossLength );
          crossEnd2 = QgsSymbolLayerV2Utils::pointOnLineWithDistance( intersectionPoint, hIt->second.p2(), mCrossLength );
          p->drawLine( crossEnd1, crossEnd2 );
        }
      }
      //end mark
      crossEnd1 = QgsSymbolLayerV2Utils::pointOnLineWithDistance( hIt->second.p2(), hIt->second.p1(), mCrossLength );
      p->drawLine( hIt->second.p2(), crossEnd1 );
    }
  }
#endif
  else //marker
  {
    if ( ! mMarkerSymbol )
      return;

    QgsRenderContext context = QgsRenderContext::fromMapSettings( QgisApp::instance()->mapCanvas()->mapSettings() );
    context.setPainter( p );
    mMarkerSymbol->startRender( context, 0 );

    QPointF intersectionPoint;
    for ( ; vIt != verticalLines.constEnd(); ++vIt )
    {
      //test for intersection with every horizontal line
      hIt = horizontalLines.constBegin();
      for ( ; hIt != horizontalLines.constEnd(); ++hIt )
      {
        if ( hIt->second.intersect( vIt->second, &intersectionPoint ) == QLineF::BoundedIntersection )
        {
          mMarkerSymbol->renderPoint( intersectionPoint, 0, context );
        }
      }
    }
    mMarkerSymbol->stopRender( context );
  }

  // p->setClipRect( thisPaintRect, Qt::NoClip );

  if ( mShowGridAnnotation )
  {
    drawCoordinateAnnotations( p, horizontalLines, verticalLines );
  }
}
示例#21
0
ICQFullInfo::WorkItemList ICQFullInfo::parseWorkItemList( const QByteArray& data ) const
{
	Buffer buffer( data );
	WorkItemList infoList;

	int count = buffer.getWord();
	while ( (count--) > 0 )
	{
		QList<TLV> tlvList = Buffer( buffer.getBSTR() ).getTLVList();

		WorkItem info;
		QList<TLV>::const_iterator it;
		for ( it = tlvList.constBegin(); it != tlvList.constEnd(); ++it )
		{
			switch ( (*it).type )
			{
			case 0x0064:
				info.position = (*it).data;
				break;
			case 0x006E:
				info.companyName = (*it).data;
				break;
			case 0x007D:
				info.department = (*it).data;
				break;
			case 0x0078:
				info.homepage = (*it).data;
				break;
			case 0x0082:
				break;
			case 0x008C:
				break;
			case 0x0096:
				break;
			case 0x00A0:
				break;
			case 0x00AA:
				info.address = (*it).data;
				break;
			case 0x00B4:
				info.city = (*it).data;
				break;
			case 0x00BE:
				info.state = (*it).data;
				break;
			case 0x00C8:
				info.zip = (*it).data;
				break;
			case 0x00D2:
				{
				Buffer b( (*it).data );
				info.country = b.getDWord();
				break;
				}
			default:
				kDebug(OSCAR_RAW_DEBUG) << "Unhandled tlv: " << hex << (*it).type << " data: " << hex << (*it).data;
				break;
			}
		}
		infoList.append( info );
	}
	return infoList;
}
示例#22
0
QgsComposition* QgsConfigParser::createPrintComposition( const QString& composerTemplate, QgsMapRenderer* mapRenderer, const QMap< QString, QString >& parameterMap ) const
{
  QList<QgsComposerMap*> composerMaps;
  QList<QgsComposerLabel*> composerLabels;

  QgsComposition* c = initComposition( composerTemplate, mapRenderer, composerMaps, composerLabels );
  if ( !c )
  {
    return 0;
  }

  QMap< QString, QString >::const_iterator dpiIt = parameterMap.find( "DPI" );
  if ( dpiIt != parameterMap.constEnd() )
  {
    c->setPrintResolution( dpiIt.value().toInt() );
  }

  //replace composer map parameters
  QList<QgsComposerMap*>::iterator mapIt = composerMaps.begin();
  QgsComposerMap* currentMap = 0;
  for ( ; mapIt != composerMaps.end(); ++mapIt )
  {
    currentMap = *mapIt;
    if ( !currentMap )
    {
      continue;
    }

    QString mapId = "MAP" + QString::number( currentMap->id() );
    QMap< QString, QString >::const_iterator extentIt = parameterMap.find( mapId + ":EXTENT" );
    if ( extentIt == parameterMap.constEnd() ) //map extent is mandatory
    {
      //remove map from composition if not referenced by the request
      c->removeItem( *mapIt ); delete( *mapIt ); continue;
    }

    QStringList coordList = extentIt.value().split( "," );
    if ( coordList.size() < 4 )
    {
      c->removeItem( *mapIt ); delete( *mapIt ); continue; //need at least four coordinates
    }

    bool xMinOk, yMinOk, xMaxOk, yMaxOk;
    double xmin = coordList.at( 0 ).toDouble( &xMinOk );
    double ymin = coordList.at( 1 ).toDouble( &yMinOk );
    double xmax = coordList.at( 2 ).toDouble( &xMaxOk );
    double ymax = coordList.at( 3 ).toDouble( &yMaxOk );
    if ( !xMinOk || !yMinOk || !xMaxOk || !yMaxOk )
    {
      c->removeItem( *mapIt ); delete( *mapIt ); continue;
    }

    //Change x- and y- of extent for WMS 1.3.0 and geographic coordinate systems
    QMap<QString, QString>::const_iterator versionIt = parameterMap.find( "VERSION" );
    if ( versionIt != parameterMap.end() )
    {
      if ( mapRenderer && versionIt.value() == "1.3.0" && mapRenderer->destinationCrs().geographicFlag() )
      {
        //switch coordinates of extent
        double tmp;
        tmp = xmin;
        xmin = ymin; ymin = tmp;
        tmp = xmax;
        xmax = ymax; ymax = tmp;
      }
    }
    currentMap->setNewExtent( QgsRectangle( xmin, ymin, xmax, ymax ) );

    //scale
    QMap< QString, QString >::const_iterator scaleIt = parameterMap.find( mapId + ":SCALE" );
    if ( scaleIt != parameterMap.constEnd() )
    {
      bool scaleOk;
      double scale = scaleIt->toDouble( &scaleOk );
      if ( scaleOk )
      {
        currentMap->setNewScale( scale );
      }
    }

    //rotation
    QMap< QString, QString >::const_iterator rotationIt = parameterMap.find( mapId + ":ROTATION" );
    if ( rotationIt != parameterMap.constEnd() )
    {
      bool rotationOk;
      double rotation = rotationIt->toDouble( &rotationOk );
      if ( rotationOk )
      {
        currentMap->setMapRotation( rotation );
      }
    }

    //layers / styles
    QMap< QString, QString >::const_iterator layersIt = parameterMap.find( mapId + ":LAYERS" );
    QMap< QString, QString >::const_iterator stylesIt = parameterMap.find( mapId + ":STYLES" );
    if ( layersIt != parameterMap.constEnd() )
    {
      QStringList layerSet;
      QStringList wmsLayerList = layersIt->split( "," );
      QStringList wmsStyleList;

      if ( stylesIt != parameterMap.constEnd() )
      {
        wmsStyleList = stylesIt->split( "," );
      }
      for ( int i = 0; i < wmsLayerList.size(); ++i )
      {
        QString styleName;
        if ( wmsStyleList.size() > i )
        {
          styleName = wmsStyleList.at( i );
        }
        QList<QgsMapLayer*> layerList = mapLayerFromStyle( wmsLayerList.at( i ), styleName );
        QList<QgsMapLayer*>::const_iterator mapIdIt = layerList.constBegin();
        for ( ; mapIdIt != layerList.constEnd(); ++mapIdIt )
        {
          if ( *mapIdIt )
          {
            layerSet.push_back(( *mapIdIt )->id() );
          }
        }
      }

      currentMap->setLayerSet( layerSet );
      currentMap->setKeepLayerSet( true );
    }

    //grid space x / y
    QMap< QString, QString >::const_iterator gridSpaceXIt = parameterMap.find( mapId + ":GRID_INTERVAL_X" );
    if ( gridSpaceXIt != parameterMap.constEnd() )
    {
      bool intervalXOk;
      double intervalX = gridSpaceXIt->toDouble( &intervalXOk );
      if ( intervalXOk )
      {
        currentMap->setGridIntervalX( intervalX );
      }
    }
    else
    {
      currentMap->setGridIntervalX( 0 );
    }

    QMap< QString, QString >::const_iterator gridSpaceYIt = parameterMap.find( mapId + ":GRID_INTERVAL_Y" );
    if ( gridSpaceYIt != parameterMap.constEnd() )
    {
      bool intervalYOk;
      double intervalY = gridSpaceYIt->toDouble( &intervalYOk );
      if ( intervalYOk )
      {
        currentMap->setGridIntervalY( intervalY );
      }
    }
    else
    {
      currentMap->setGridIntervalY( 0 );
    }
  }

  //replace label text
  QList<QgsComposerLabel*>::const_iterator labelIt = composerLabels.constBegin();
  QgsComposerLabel* currentLabel = 0;

  for ( ; labelIt != composerLabels.constEnd(); ++labelIt )
  {
    currentLabel = *labelIt;
    QMap< QString, QString >::const_iterator titleIt = parameterMap.find( currentLabel->id().toUpper() );
    if ( titleIt == parameterMap.constEnd() )
    {
      //remove exported labels not referenced in the request
      if ( !currentLabel->id().isEmpty() )
      {
        c->removeItem( currentLabel );
        delete( currentLabel );
      }
      continue;
    }

    if ( !titleIt.key().isEmpty() ) //no label text replacement with empty key
    {
      currentLabel->setText( titleIt.value() );
      currentLabel->adjustSizeToText();
    }
  }

  return c;
}
示例#23
0
void Feed::appendArticles(const Syndication::FeedPtr feed)
{
    d->setTotalCountDirty();
    bool changed = false;
    const bool notify = useNotification() || Settings::useNotifications();

    QList<ItemPtr> items = feed->items();
    QList<ItemPtr>::ConstIterator it = items.constBegin();
    QList<ItemPtr>::ConstIterator en = items.constEnd();


    int nudge=0;

    QList<Article> deletedArticles = d->deletedArticles;

    for ( ; it != en; ++it)
    {
        if ( !d->articles.contains((*it)->id()) ) // article not in list
        {
            Article mya(*it, this);
            mya.offsetPubDate(nudge);
            nudge--;
            appendArticle(mya);
            d->addedArticlesNotify.append(mya);

            if (!mya.isDeleted() && !markImmediatelyAsRead())
                mya.setStatus(New);
            else
                mya.setStatus(Read);
            if ( notify )
                NotificationManager::self()->slotNotifyArticle( mya );
            changed = true;
        }
        else // article is in list
        {
            // if the article's guid is no hash but an ID, we have to check if the article was updated. That's done by comparing the hash values.
            Article old = d->articles[(*it)->id()];
            Article mya(*it, this);
            if (!mya.guidIsHash() && mya.hash() != old.hash() && !old.isDeleted())
            {
                mya.setKeep(old.keep());
                int oldstatus = old.status();
                old.setStatus(Read);

                d->articles.remove(old.guid());
                appendArticle(mya);

                mya.setStatus(oldstatus);

                d->updatedArticlesNotify.append(mya);
                changed = true;
            }
            else if (old.isDeleted())
                deletedArticles.removeAll(mya);
        }
    }


    QList<Article>::ConstIterator dit = deletedArticles.constBegin();
    QList<Article>::ConstIterator dtmp;
    QList<Article>::ConstIterator den = deletedArticles.constEnd();

    // delete articles with delete flag set completely from archive, which aren't in the current feed source anymore
    while (dit != den)
    {
        dtmp = dit;
        ++dit;
        d->articles.remove((*dtmp).guid());
        d->archive->deleteArticle((*dtmp).guid());
        d->removedArticlesNotify.append( *dtmp );
        changed = true;
        d->deletedArticles.removeAll(*dtmp);
    }

    if (changed)
        articlesModified();
}
void QgsPointDisplacementRenderer::createDisplacementGroups( QgsVectorLayer* vlayer, const QgsRectangle& viewExtent )
{
  if ( !vlayer || ( vlayer->wkbType() != QGis::WKBPoint && vlayer->wkbType() != QGis::WKBPoint25D ) )
  {
    return;
  }

  mDisplacementGroups.clear();
  mDisplacementIds.clear();

  //use a spatial index to check if there is already a point at a position
  QgsSpatialIndex spatialIndex;

  //attributes
  QgsAttributeList attList;
  QList<QString> attributeStrings = usedAttributes();
  QList<QString>::const_iterator attStringIt = attributeStrings.constBegin();
  for ( ; attStringIt != attributeStrings.constEnd(); ++attStringIt )
  {
    attList.push_back( vlayer->fieldNameIndex( *attStringIt ) );
  }

  QgsFeature f;
  QList<QgsFeatureId> intersectList;

  QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( viewExtent ).setSubsetOfAttributes( attList ) );
  while ( fit.nextFeature( f ) )
  {
    intersectList.clear();

    //check, if there is already a point at that position
    if ( f.geometry() )
    {
      intersectList = spatialIndex.intersects( searchRect( f.geometry()->asPoint() ) );
      if ( intersectList.empty() )
      {
        spatialIndex.insertFeature( f );
      }
      else
      {
        //go through all the displacement group maps and search an entry where the id equals the result of the spatial search
        QgsFeatureId existingEntry = intersectList.at( 0 );
        bool found = false;
        QList< QMap<QgsFeatureId, QgsFeature> >::iterator it = mDisplacementGroups.begin();
        for ( ; it != mDisplacementGroups.end(); ++it )
        {
          if ( it->size() > 0 && it->contains( existingEntry ) )
          {
            found = true;
            QgsFeature feature;
            it->insert( f.id(), f );
            mDisplacementIds.insert( f.id() );
            break;
          }
        }

        if ( !found )//insert the already existing feature and the new one into a map
        {
          QMap<QgsFeatureId, QgsFeature> newMap;
          QgsFeature existingFeature;
          vlayer->getFeatures( QgsFeatureRequest().setFilterFid( existingEntry ) ).nextFeature( existingFeature );
          newMap.insert( existingEntry, existingFeature );
          mDisplacementIds.insert( existingEntry );
          newMap.insert( f.id(), f );
          mDisplacementIds.insert( f.id() );
          mDisplacementGroups.push_back( newMap );
        }
      }
    }
  }
}
示例#25
0
IntervalList IntervalList::intersect(const IntervalList& a, const IntervalList& b)
{
  IntervalList output;

  const QList<Interval> aList = a.getList();
  const QList<Interval> bList = b.getList();

  QList<Interval>::const_iterator aIt = aList.constBegin();
  QList<Interval>::const_iterator bIt = bList.constBegin();

  QList<Interval>::const_iterator aItEnd = aList.constEnd();
  QList<Interval>::const_iterator bItEnd = bList.constEnd();

  bool a_open = false;
  bool b_open = false;

  int start = 0;
  int end = 0;

  // This looks atrocious, but is probably one of the quickest available methods
  // to find the intersections of two lists of Intervals.  An easier (but much 
  // less effecient way) would be to define Interval::intersect(Interval a, Interval b)
  // for the Interval class, and then use that method to intersect two lists.  

  // Plus, this is probably overkill anyway: who is going to spend time typing 
  // in an interval list big enough to slow a computer down?
  while(aIt != aItEnd && bIt != bItEnd)
  {
    if(!a_open && !b_open)
    {
      if((*aIt).start() < (*bIt).start())
      {
        a_open = true;
      } 
      else if((*aIt).start() > (*bIt).start())
      {
        b_open = true;
      }
      else
      {
        a_open = true;
        b_open = true;
        start = (*aIt).start();
      }
    }
    else if(a_open && !b_open)
    {
      if((*aIt).end() < (*bIt).start())
      {
        a_open = false;
        ++aIt;
      } 
      else if((*aIt).end() > (*bIt).start())
      {
        b_open = true;
        start = (*bIt).start();
      }
      else
      {
        a_open = false;
        b_open = true;
        start = (*aIt).end();
        end = (*bIt).start();
        Interval interval(start, end);
        output.addInterval(interval);
        ++aIt;
      }
    }
    else if(!a_open && b_open)
    {
      if((*bIt).end() < (*aIt).start())
      {
        b_open = false;
        ++bIt;
      } 
      else if((*aIt).end() > (*bIt).start())
      {
        a_open = true;
        start = (*aIt).start();
      }
      else
      {
        b_open = false;
        a_open = true;
        start = (*bIt).end();
        end = (*aIt).start();
        Interval interval(start, end);
        output.addInterval(interval);
        ++bIt;
      }
    }
    else
    {
      if((*aIt).end() < (*bIt).end())
      {
        a_open = false;
        end = (*aIt).end();
        Interval interval(start, end);
        output.addInterval(interval);
        ++aIt;
      } 
      else if((*aIt).end() > (*bIt).end())
      {
        b_open = false;
        end = (*bIt).end();
        Interval interval(start, end);
        output.addInterval(interval);
        ++bIt;
      }
      else
      {
        a_open = false;
        b_open = false;
        end = (*aIt).end();
        Interval interval(start, end);
        output.addInterval(interval);
        ++aIt;
        ++bIt;
      }
    }
  }

  return output;
}
bool QgsPointDisplacementRenderer::renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer, bool selected, bool drawVertexMarker )
{
  Q_UNUSED( drawVertexMarker );
  //point position in screen coords
  QgsGeometry* geom = feature.geometry();
  QGis::WkbType geomType = geom->wkbType();
  if ( geomType != QGis::WKBPoint && geomType != QGis::WKBPoint25D )
  {
    //can only render point type
    return false;
  }
  QPointF pt;
  _getPoint( pt, context, geom->asWkb() );


  //get list of labels and symbols
  QStringList labelAttributeList;
  QList<QgsMarkerSymbolV2*> symbolList;

  if ( mDisplacementIds.contains( feature.id() ) )
  {
    //create the symbol for the whole display group if the id is the first entry in a display group
    QList<QMap<QgsFeatureId, QgsFeature> >::iterator it = mDisplacementGroups.begin();
    for ( ; it != mDisplacementGroups.end(); ++it )
    {
      //create the symbol for the whole display group if the id is the first entry in a display group
      if ( feature.id() == it->begin().key() )
      {
        QMap<QgsFeatureId, QgsFeature>::iterator attIt = it->begin();
        for ( ; attIt != it->end(); ++attIt )
        {
          if ( mDrawLabels )
          {
            labelAttributeList << getLabel( attIt.value() );
          }
          else
          {
            labelAttributeList << QString();
          }
          symbolList << dynamic_cast<QgsMarkerSymbolV2*>( firstSymbolForFeature( mRenderer, attIt.value() ) );
        }
      }
    }
  }
  else //only one feature
  {
    symbolList << dynamic_cast<QgsMarkerSymbolV2*>( firstSymbolForFeature( mRenderer, feature ) );
    if ( mDrawLabels )
    {
      labelAttributeList << getLabel( feature );
    }
    else
    {
      labelAttributeList << QString();
    }
  }

  if ( symbolList.isEmpty() && labelAttributeList.isEmpty() )
  {
    return true; //display all point symbols for one posi
  }


  //draw symbol
  double diagonal = 0;
  double currentWidthFactor; //scale symbol size to map unit and output resolution

  QList<QgsMarkerSymbolV2*>::const_iterator it = symbolList.constBegin();
  for ( ; it != symbolList.constEnd(); ++it )
  {
    if ( *it )
    {
      currentWidthFactor = QgsSymbolLayerV2Utils::lineWidthScaleFactor( context, ( *it )->outputUnit() );
      double currentDiagonal = sqrt( 2 * (( *it )->size() * ( *it )->size() ) ) * currentWidthFactor;
      if ( currentDiagonal > diagonal )
      {
        diagonal = currentDiagonal;
      }
    }
  }


  QgsSymbolV2RenderContext symbolContext( context, QgsSymbolV2::MM, 1.0, selected );
  double circleAdditionPainterUnits = symbolContext.outputLineWidth( mCircleRadiusAddition );
  double radius = qMax(( diagonal / 2 ), labelAttributeList.size() * diagonal / 2 / M_PI ) + circleAdditionPainterUnits;

  //draw Circle
  drawCircle( radius, symbolContext, pt, symbolList.size() );

  QList<QPointF> symbolPositions;
  QList<QPointF> labelPositions;
  calculateSymbolAndLabelPositions( pt, labelAttributeList.size(), radius, diagonal, symbolPositions, labelPositions );

  //draw mid point
  if ( labelAttributeList.size() > 1 )
  {
    if ( mCenterSymbol )
    {
      mCenterSymbol->renderPoint( pt, &feature, context, layer, selected );
    }
    else
    {
      context.painter()->drawRect( QRectF( pt.x() - symbolContext.outputLineWidth( 1 ), pt.y() - symbolContext.outputLineWidth( 1 ), symbolContext.outputLineWidth( 2 ), symbolContext.outputLineWidth( 2 ) ) );
    }
  }

  //draw symbols on the circle
  drawSymbols( feature, context, symbolList, symbolPositions, selected );
  //and also the labels
  drawLabels( pt, symbolContext, labelPositions, labelAttributeList );
  return true;
}
示例#27
0
QList< QList< int > > QgsCoordinateTransform::datumTransformations( const QgsCoordinateReferenceSystem &srcCRS, const QgsCoordinateReferenceSystem &destCRS )
{
  QList< QList< int > > transformations;

  QString srcGeoId = srcCRS.geographicCrsAuthId();
  QString destGeoId = destCRS.geographicCrsAuthId();

  if ( srcGeoId.isEmpty() || destGeoId.isEmpty() )
  {
    return transformations;
  }

  QStringList srcSplit = srcGeoId.split( ':' );
  QStringList destSplit = destGeoId.split( ':' );

  if ( srcSplit.size() < 2 || destSplit.size() < 2 )
  {
    return transformations;
  }

  int srcAuthCode = srcSplit.at( 1 ).toInt();
  int destAuthCode = destSplit.at( 1 ).toInt();

  if ( srcAuthCode == destAuthCode )
  {
    return transformations; //crs have the same datum
  }

  QList<int> directTransforms;
  searchDatumTransform( QStringLiteral( "SELECT coord_op_code FROM tbl_datum_transform WHERE source_crs_code=%1 AND target_crs_code=%2 ORDER BY deprecated ASC,preferred DESC" ).arg( srcAuthCode ).arg( destAuthCode ),
                        directTransforms );
  QList<int> reverseDirectTransforms;
  searchDatumTransform( QStringLiteral( "SELECT coord_op_code FROM tbl_datum_transform WHERE source_crs_code = %1 AND target_crs_code=%2 ORDER BY deprecated ASC,preferred DESC" ).arg( destAuthCode ).arg( srcAuthCode ),
                        reverseDirectTransforms );
  QList<int> srcToWgs84;
  searchDatumTransform( QStringLiteral( "SELECT coord_op_code FROM tbl_datum_transform WHERE (source_crs_code=%1 AND target_crs_code=%2) OR (source_crs_code=%2 AND target_crs_code=%1) ORDER BY deprecated ASC,preferred DESC" ).arg( srcAuthCode ).arg( 4326 ),
                        srcToWgs84 );
  QList<int> destToWgs84;
  searchDatumTransform( QStringLiteral( "SELECT coord_op_code FROM tbl_datum_transform WHERE (source_crs_code=%1 AND target_crs_code=%2) OR (source_crs_code=%2 AND target_crs_code=%1) ORDER BY deprecated ASC,preferred DESC" ).arg( destAuthCode ).arg( 4326 ),
                        destToWgs84 );

  //add direct datum transformations
  QList<int>::const_iterator directIt = directTransforms.constBegin();
  for ( ; directIt != directTransforms.constEnd(); ++directIt )
  {
    transformations.push_back( QList<int>() << *directIt << -1 );
  }

  //add direct datum transformations
  directIt = reverseDirectTransforms.constBegin();
  for ( ; directIt != reverseDirectTransforms.constEnd(); ++directIt )
  {
    transformations.push_back( QList<int>() << -1 << *directIt );
  }

  QList<int>::const_iterator srcWgsIt = srcToWgs84.constBegin();
  for ( ; srcWgsIt != srcToWgs84.constEnd(); ++srcWgsIt )
  {
    QList<int>::const_iterator dstWgsIt = destToWgs84.constBegin();
    for ( ; dstWgsIt != destToWgs84.constEnd(); ++dstWgsIt )
    {
      transformations.push_back( QList<int>() << *srcWgsIt << *dstWgsIt );
    }
  }

  return transformations;
}
示例#28
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 );
  }

  QgsVectorLayer* currentVectorLayer = dynamic_cast<QgsVectorLayer*>( mMapCanvas->currentLayer() );
  if ( !currentVectorLayer )
  {
    return 1;
  }

  //read snapping settings from project
  QStringList layerIdList, enabledList, toleranceList, toleranceUnitList, snapToList;

  bool ok, snappingDefinedInProject;

  QSettings settings;
  QString snappingMode = QgsProject::instance()->readEntry( "Digitizing", "/SnappingMode", "current_layer", &snappingDefinedInProject );
  QString defaultSnapToleranceUnit = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapToleranceUnit" ) : settings.value( "/qgis/digitizing/default_snapping_tolerance_unit", "0" ).toString();
  QString defaultSnapType = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapType" ) : settings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString();
  QString defaultSnapTolerance = snappingDefinedInProject ? QString::number( QgsProject::instance()->readDoubleEntry( "Digitizing", "/DefaultSnapTolerance" ) ) : settings.value( "/qgis/digitizing/default_snapping_tolerance", "0" ).toString();

  if ( !snappingDefinedInProject && defaultSnapType == "off" )
  {
    return 0;
  }

  if ( snappingMode == "current_layer" || !snappingDefinedInProject )
  {
    layerIdList.append( currentVectorLayer->id() );
    enabledList.append( "enabled" );
    toleranceList.append( defaultSnapTolerance );
    toleranceUnitList.append( defaultSnapToleranceUnit );
    snapToList.append( defaultSnapType );
  }
  else if ( snappingMode == "all_layers" )
  {
    QList<QgsMapLayer*> allLayers = mMapCanvas->layers();
    QList<QgsMapLayer*>::const_iterator layerIt = allLayers.constBegin();
    for ( ; layerIt != allLayers.constEnd(); ++layerIt )
    {
      if ( !( *layerIt ) )
      {
        continue;
      }
      layerIdList.append(( *layerIt )->id() );
      enabledList.append( "enabled" );
      toleranceList.append( defaultSnapTolerance );
      toleranceUnitList.append( defaultSnapToleranceUnit );
      snapToList.append( defaultSnapType );
    }
  }
  else //advanced
  {
    layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &ok );
    enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok );
    toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok );
    toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok );
    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;



  // 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" || *snapIt == "to_vertex" )
    {
      snapLayer.mSnapTo = QgsSnapper::SnapToVertex;
    }
    else if ( *snapIt == "to segment" || *snapIt == "to_segment" )
    {
      snapLayer.mSnapTo = QgsSnapper::SnapToSegment;
    }
    else if ( *snapIt == "to vertex and segment" || *snapIt == "to_vertex_and_segment" )
    {
      snapLayer.mSnapTo = QgsSnapper::SnapToVertexAndSegment;
    }
    else //off
    {
      continue;
    }

    snapLayers.append( snapLayer );
  }

  mSnapper->setSnapLayers( snapLayers );

  if ( mSnapper->snapMapPoint( point, results, excludePoints ) != 0 )
    return 4;

  if ( intersectionSnapping != 1 )
    return 0;

  QVector<QgsSnappingResult> segments;
  QVector<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.count() < 2 )
    return 0;

  QList<QgsSnappingResult> myResults;

  for ( QVector<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 ( QVector<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;
}
示例#29
0
void Wms::getCapabilities()
{
  QByteArray data;
  QTextStream out(&data);
  QString wmsurl = Qt::escape(m_request->url(FastCgiQt::LocationUrl).toEncoded()); 

  QString proj = renderer.map.getProjection();
  LayerList layers = renderer.map.getLayerList();

  //out << XML_HEADER << endl;
  out << "<WMT_MS_Capabilities version=\"1.1.1\">";

  // service info

  out << "<Service>"
      << "<Name>OGC:WMS</Name>"
      << "<Title>" << Qt::escape(renderer.title()) << "</Title>"
      << "<Abstract/>"
      << "<OnlineResource " << XML_XLINK_NS << " xlink:href=\"" << wmsurl << "\"/>"
      << "<ContactInformation/>"
      << "<Fees/>"
      << "<AccessConstraints/>"
      << "<KeywordList>";
  
  out << "<Keyword>" << "</Keyword>"; // TODO

  out << "</KeywordList>"
      << "</Service>";

  out << "<Capability>" 
      << "<Request>" 
      << "<GetCapabilities>" 
      << "<Format>" << MIMETYPE_GC << "</Format>" 
      << "<DCPType><HTTP><Get>"
      << "<OnlineResource " << XML_XLINK_NS
      <<   " xlink:href=\"" << wmsurl << "?Service=WMS&amp;"
      <<   "\"/></Get></HTTP></DCPType>"
      << "</GetCapabilities>" 
      << "<GetMap>";

  // image formats
  QList<QByteArray> formats = renderer.getImageFormats();
  for (QList<QByteArray>::ConstIterator fit = formats.constBegin();
    fit != formats.constEnd();
    ++fit) {
    QByteArray fb = *fit;
    QString outf;

    // ony return a few formats we want to support
    if (fb == "png") {
      outf = MIMETYPE_PNG;
    }
    else if (fb == "jpg") {
      outf = MIMETYPE_JPG;
    }
    else if (fb == "tiff") {
      outf = MIMETYPE_TIF;
    }

    if (!outf.isEmpty()) {
      out << "<Format>" << QString(outf) << "</Format>";  
    }
  }
  
  out << "<DCPType><HTTP><Get>" 
      << "<OnlineResource " << XML_XLINK_NS
      <<  " xlink:href=\"" << wmsurl << "?SERVICE=WMS&amp;\"/>"
      << "</Get></HTTP></DCPType>"
      << "</GetMap>"
      << "</Request>"; 

  out << "<Exception><Format>" << MIMETYPE_SE << "</Format></Exception>";

  out << "<Layer>" 
      << "<Title>" << Qt::escape(renderer.title()) << "</Title>" 
      << "<SRS>" << Qt::escape(proj) << "</SRS>"; 
      //<LatLonBoundingBox minx="-179.992" miny="-90.008" maxx="180.008" maxy="89.992"/> 
      //
   // layers

/*  for (LayerList::ConstIterator layer_it = layers.constBegin();
              layer_it != layers.constEnd();
              ++layer_it) {
    Layer layer = **layer_it;
*/
  for(int i = 0; i < layers.count(); ++i) {
    Layer* layer = layers[i];

    out << "<Layer queryable=\"0\">" 
        << "<Name>" << Qt::escape(layer->name) << "</Name>"
        << "<Title>" << Qt::escape(layer->title) << "</Title>"
        << "<SRS>" << Qt::escape(proj) << "</SRS>";

    out << "<LatLonBoundingBox minx=\"" << layer->bbox.left << "\" miny=\""
        << layer->bbox.bottom << "\" maxx=\"" << layer->bbox.right 
        << "\" maxy=\"" << layer->bbox.top << "\"/>" 
        << "<BoundingBox SRS=\"" << Qt::escape(proj) << "\" minx=\"" << layer->bbox.left 
        << "\" miny=\"" << layer->bbox.bottom << "\" maxx=\"" 
        << layer->bbox.right << "\" maxy=\"" << layer->bbox.top << "\"/>"; 

    out << "</Layer>";

  }

  out << "</Layer>"
      << "</Capability>"
      << "</WMT_MS_Capabilities>";

  out.flush();

  m_request->setHeader(HTTP_CONTENT_TYPE, MIMETYPE_GC);
  QByteArray content_length = QByteArray::number(data.length());
  m_request->setHeader(HTTP_CONTENT_LEN, content_length );
  m_request->write(data);
}
示例#30
0
QList<QgsMapLayer*> QgsProjectParser::mapLayerFromStyle( const QString& lName, const QString& styleName, bool allowCaching ) const
{
  Q_UNUSED( styleName );
  Q_UNUSED( allowCaching );
  QList<QgsMapLayer*> layerList;

  //first assume lName refers to a leaf layer
  QMap< QString, QDomElement > layerElemMap = projectLayerElementsByName();
  QMap< QString, QDomElement >::const_iterator layerElemIt = layerElemMap.find( lName );
  if ( layerElemIt != layerElemMap.constEnd() )
  {
    QgsMapLayer* layer = createLayerFromElement( layerElemIt.value() );
    if ( layer )
    {
      layerList.push_back( layer );
      return layerList;
    }
  }

  //Check if layer name refers to the top level group for the project.
  if ( lName == projectTitle() )
  {
    QList<QDomElement> layerElemList = projectLayerElements();
    QList<QDomElement>::const_iterator layerElemIt = layerElemList.constBegin();
    for ( ; layerElemIt != layerElemList.constEnd(); ++layerElemIt )
    {
      layerList.push_back( createLayerFromElement( *layerElemIt ) );
    }
    return layerList;
  }

  //maybe the layer is a goup. Check if lName is contained in the group list
  QMap< QString, QDomElement > idLayerMap = projectLayerElementsById();

  QList<QDomElement> legendGroups = legendGroupElements();
  QList<QDomElement>::const_iterator groupIt = legendGroups.constBegin();
  for ( ; groupIt != legendGroups.constEnd(); ++groupIt )
  {
    if ( groupIt->attribute( "name" ) == lName )
    {
      if ( groupIt->attribute( "embedded" ) == "1" ) //requested group is embedded from another project
      {
        QString project = convertToAbsolutePath( groupIt->attribute( "project" ) );
        QgsDebugMsg( QString( "Project path: %1" ).arg( project ) );
        QgsProjectParser* p = dynamic_cast<QgsProjectParser*>( QgsConfigCache::instance()->searchConfiguration( project ) );
        if ( p )
        {
          QList<QDomElement> pGroupElems = p->legendGroupElements();
          QList<QDomElement>::const_iterator pGroupIt = pGroupElems.constBegin();
          QDomElement embeddedGroupElem;

          for ( ; pGroupIt != pGroupElems.constEnd(); ++pGroupIt )
          {
            if ( pGroupIt->attribute( "name" ) == lName )
            {
              embeddedGroupElem = *pGroupIt;
              break;
            }
          }

          if ( !embeddedGroupElem.isNull() )
          {
            //add all the layers under the group
            QMap< QString, QDomElement > pLayerElems = p->projectLayerElementsById();
            QDomNodeList pLayerNodes = embeddedGroupElem.elementsByTagName( "legendlayer" );
            for ( int i = 0; i < pLayerNodes.size(); ++i )
            {
              QString pLayerId = pLayerNodes.at( i ).toElement().firstChildElement( "filegroup" ).firstChildElement( "legendlayerfile" ).attribute( "layerid" );
              QgsMapLayer* pLayer = p->createLayerFromElement( pLayerElems[pLayerId] );
              if ( pLayer )
              {
                layerList.push_back( pLayer );
              }
            }
          }
        }
      }
      else //normal (not embedded) group
      {
        QDomNodeList layerFileList = groupIt->elementsByTagName( "legendlayerfile" );
        for ( int i = 0; i < layerFileList.size(); ++i )
        {
          QMap< QString, QDomElement >::const_iterator layerEntry = idLayerMap.find( layerFileList.at( i ).toElement().attribute( "layerid" ) );
          if ( layerEntry != idLayerMap.constEnd() )
          {
            layerList.push_back( createLayerFromElement( layerEntry.value() ) );
          }
        }
      }
      return layerList;
    }
  }

  //maybe the layer is embedded from another project
  QMap< QString, QDomElement >::const_iterator layerIt = idLayerMap.constBegin();
  for ( ; layerIt != idLayerMap.constEnd(); ++layerIt )
  {
    if ( layerIt.value().attribute( "embedded" ) == "1" )
    {
      QString id = layerIt.value().attribute( "id" );
      QString project = layerIt.value().attribute( "project" );
      QgsDebugMsg( QString( "Project path: %1" ).arg( project ) );

      //get config parser from cache
      QgsProjectParser* otherParser = dynamic_cast<QgsProjectParser*>( QgsConfigCache::instance()->searchConfiguration( project ) );
      if ( otherParser )
      {
        //get element by id
        QMap< QString, QDomElement > otherLayerElems = otherParser->projectLayerElementsById();
        QMap< QString, QDomElement >::const_iterator otherLayerIt = otherLayerElems.find( id );
        if ( otherLayerIt != otherLayerElems.constEnd() )
        {
          if ( otherLayerIt.value().firstChildElement( "layername" ).text() == lName )
          {
            layerList.push_back( otherParser->createLayerFromElement( otherLayerIt.value() ) );
            return layerList;
          }
        }
      }
    }
  }

  //layer still not found. Check if it is a single layer contained in a embedded layer group
  groupIt = legendGroups.constBegin();
  for ( ; groupIt != legendGroups.constEnd(); ++groupIt )
  {
    if ( groupIt->attribute( "embedded" ) == "1" )
    {
      QString project = convertToAbsolutePath( groupIt->attribute( "project" ) );
      QgsDebugMsg( QString( "Project path: %1" ).arg( project ) );
      QgsProjectParser* p = dynamic_cast<QgsProjectParser*>( QgsConfigCache::instance()->searchConfiguration( project ) );
      if ( p )
      {
        QMap< QString, QDomElement > pLayers = p->projectLayerElementsByName();
        QMap< QString, QDomElement >::const_iterator pLayerIt = pLayers.find( lName );
        if ( pLayerIt != pLayers.constEnd() )
        {
          QgsMapLayer* layer = p->createLayerFromElement( pLayerIt.value() );
          if ( layer )
          {
            layerList.push_back( layer );
            return layerList;
          }
        }
      }
    }
  }

  //layer not found, return empty list
  return layerList;
}