QGIS API Documentation  2.14.3-Essen
qgspallabeling.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgspallabeling.cpp
3  Smart labeling for vector layers
4  -------------------
5  begin : June 2009
6  copyright : (C) Martin Dobias
7  email : wonder dot sk at gmail dot com
8 
9  ***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
18 #include "qgspallabeling.h"
19 #include "qgstextlabelfeature.h"
20 #include "qgsunittypes.h"
21 
22 #include <list>
23 
24 #include <pal/pal.h>
25 #include <pal/feature.h>
26 #include <pal/layer.h>
27 #include <pal/palexception.h>
28 #include <pal/problem.h>
29 #include <pal/labelposition.h>
30 
31 #include <cmath>
32 
33 #include <QApplication>
34 #include <QByteArray>
35 #include <QString>
36 #include <QFontMetrics>
37 #include <QTime>
38 #include <QPainter>
39 
40 #include "diagram/qgsdiagram.h"
41 #include "qgsdiagramrendererv2.h"
42 #include "qgsfontutils.h"
43 #include "qgslabelsearchtree.h"
44 #include "qgsexpression.h"
45 #include "qgsdatadefined.h"
46 #include "qgslabelingenginev2.h"
47 #include "qgsvectorlayerlabeling.h"
48 
49 #include <qgslogger.h>
50 #include <qgsvectorlayer.h>
51 #include <qgsmaplayerregistry.h>
52 #include <qgsvectordataprovider.h>
55 #include <qgsgeometry.h>
56 #include <qgsmaprenderer.h>
57 #include <qgsmarkersymbollayerv2.h>
58 #include <qgsproject.h>
59 #include "qgssymbolv2.h"
60 #include "qgssymbollayerv2utils.h"
61 #include <QMessageBox>
62 
63 
64 Q_GUI_EXPORT extern int qt_defaultDpiX();
65 Q_GUI_EXPORT extern int qt_defaultDpiY();
66 
67 static void _fixQPictureDPI( QPainter* p )
68 {
69  // QPicture makes an assumption that we drawing to it with system DPI.
70  // Then when being drawn, it scales the painter. The following call
71  // negates the effect. There is no way of setting QPicture's DPI.
72  // See QTBUG-20361
73  p->scale( static_cast< double >( qt_defaultDpiX() ) / p->device()->logicalDpiX(),
74  static_cast< double >( qt_defaultDpiY() ) / p->device()->logicalDpiY() );
75 }
76 
77 
78 using namespace pal;
79 
80 // -------------
81 
82 /* ND: Default point label position priority. These are set to match variants of the ideal placement priority described
83  in "Making Maps", Krygier & Wood (2011) (p216),
84  "Elements of Cartography", Robinson et al (1995)
85  and "Designing Better Maps", Brewer (2005) (p76)
86  Note that while they agree on positions 1-4, 5-8 are more contentious so I've selected these placements
87  based on my preferences, and to follow Krygier and Wood's placements more closer. (I'm not going to disagree
88  with Denis Wood on anything cartography related...!)
89 */
99 //debugging only - don't use these placements by default
100 /* << QgsPalLayerSettings::TopSlightlyLeft
101 << QgsPalLayerSettings::BottomSlightlyLeft;
102 << QgsPalLayerSettings::TopMiddle
103 << QgsPalLayerSettings::BottomMiddle;*/
104 
106  : upsidedownLabels( Upright )
107  , mCurFeat( nullptr )
108  , xform( nullptr )
109  , ct( nullptr )
110  , extentGeom( nullptr )
111  , mFeaturesToLabel( 0 )
112  , mFeatsSendingToPal( 0 )
113  , mFeatsRegPal( 0 )
114  , expression( nullptr )
115 {
116  enabled = false;
117  drawLabels = true;
118  isExpression = false;
119  fieldIndex = 0;
120 
121  // text style
123  fontSizeInMapUnits = false;
124  textColor = Qt::black;
125  textTransp = 0;
126  blendMode = QPainter::CompositionMode_SourceOver;
127  previewBkgrdColor = Qt::white;
128  // font processing info
129  mTextFontFound = true;
131 
132  // text formatting
133  wrapChar = "";
134  multilineHeight = 1.0;
136  addDirectionSymbol = false;
137  leftDirectionSymbol = QString( "<" );
138  rightDirectionSymbol = QString( ">" );
139  reverseDirectionSymbol = false;
141  formatNumbers = false;
142  decimals = 3;
143  plusSign = false;
144 
145  // text buffer
146  bufferDraw = false;
147  bufferSize = 1.0;
148  bufferSizeInMapUnits = false;
149  bufferColor = Qt::white;
150  bufferTransp = 0;
151  bufferNoFill = false;
152  bufferJoinStyle = Qt::BevelJoin;
153  bufferBlendMode = QPainter::CompositionMode_SourceOver;
154 
155  // shape background
156  shapeDraw = false;
158  shapeSVGFile = QString();
160  shapeSize = QPointF( 0.0, 0.0 );
161  shapeSizeUnits = MM;
163  shapeRotation = 0.0;
164  shapeOffset = QPointF( 0.0, 0.0 );
166  shapeRadii = QPointF( 0.0, 0.0 );
168  shapeFillColor = Qt::white;
169  shapeBorderColor = Qt::darkGray;
170  shapeBorderWidth = 0.0;
172  shapeJoinStyle = Qt::BevelJoin;
173  shapeTransparency = 0;
174  shapeBlendMode = QPainter::CompositionMode_SourceOver;
175 
176  // drop shadow
177  shadowDraw = false;
179  shadowOffsetAngle = 135;
180  shadowOffsetDist = 1.0;
182  shadowOffsetGlobal = true;
183  shadowRadius = 1.5;
185  shadowRadiusAlphaOnly = false;
186  shadowTransparency = 30;
187  shadowScale = 100;
188  shadowColor = Qt::black;
189  shadowBlendMode = QPainter::CompositionMode_Multiply;
190 
191  // placement
194  centroidWhole = false;
195  centroidInside = false;
196  predefinedPositionOrder = DEFAULT_PLACEMENT_ORDER;
197  fitInPolygonOnly = false;
199  xOffset = 0;
200  yOffset = 0;
201  labelOffsetInMapUnits = true;
202  dist = 0;
203  distInMapUnits = false;
205  angleOffset = 0;
206  preserveRotation = true;
207  maxCurvedCharAngleIn = 20.0;
208  maxCurvedCharAngleOut = -20.0;
209  priority = 5;
210  repeatDistance = 0;
212 
213  // rendering
214  scaleVisibility = false;
215  scaleMin = 1;
216  scaleMax = 10000000;
217  fontLimitPixelSize = false;
218  fontMinPixelSize = 0; //trigger to turn it on by default for map unit labels
219  fontMaxPixelSize = 10000;
220  displayAll = false;
222 
223  labelPerPart = false;
224  mergeLines = false;
225  minFeatureSize = 0.0;
226  limitNumLabels = false;
227  maxNumLabels = 2000;
228  obstacle = true;
229  obstacleFactor = 1.0;
231  zIndex = 0.0;
232 
233  // scale factors
234  vectorScaleFactor = 1.0;
235  rasterCompressFactor = 1.0;
236 
237  // data defined string and old-style index values
238  // NOTE: in QPair use -1 for second value (other values are for old-style layer properties migration)
239 
240  // text style
241  mDataDefinedNames.insert( Size, QPair<QString, int>( "Size", 0 ) );
242  mDataDefinedNames.insert( Bold, QPair<QString, int>( "Bold", 1 ) );
243  mDataDefinedNames.insert( Italic, QPair<QString, int>( "Italic", 2 ) );
244  mDataDefinedNames.insert( Underline, QPair<QString, int>( "Underline", 3 ) );
245  mDataDefinedNames.insert( Color, QPair<QString, int>( "Color", 4 ) );
246  mDataDefinedNames.insert( Strikeout, QPair<QString, int>( "Strikeout", 5 ) );
247  mDataDefinedNames.insert( Family, QPair<QString, int>( "Family", 6 ) );
248  mDataDefinedNames.insert( FontStyle, QPair<QString, int>( "FontStyle", -1 ) );
249  mDataDefinedNames.insert( FontSizeUnit, QPair<QString, int>( "FontSizeUnit", -1 ) );
250  mDataDefinedNames.insert( FontTransp, QPair<QString, int>( "FontTransp", 18 ) );
251  mDataDefinedNames.insert( FontCase, QPair<QString, int>( "FontCase", -1 ) );
252  mDataDefinedNames.insert( FontLetterSpacing, QPair<QString, int>( "FontLetterSpacing", -1 ) );
253  mDataDefinedNames.insert( FontWordSpacing, QPair<QString, int>( "FontWordSpacing", -1 ) );
254  mDataDefinedNames.insert( FontBlendMode, QPair<QString, int>( "FontBlendMode", -1 ) );
255 
256  // text formatting
257  mDataDefinedNames.insert( MultiLineWrapChar, QPair<QString, int>( "MultiLineWrapChar", -1 ) );
258  mDataDefinedNames.insert( MultiLineHeight, QPair<QString, int>( "MultiLineHeight", -1 ) );
259  mDataDefinedNames.insert( MultiLineAlignment, QPair<QString, int>( "MultiLineAlignment", -1 ) );
260  mDataDefinedNames.insert( DirSymbDraw, QPair<QString, int>( "DirSymbDraw", -1 ) );
261  mDataDefinedNames.insert( DirSymbLeft, QPair<QString, int>( "DirSymbLeft", -1 ) );
262  mDataDefinedNames.insert( DirSymbRight, QPair<QString, int>( "DirSymbRight", -1 ) );
263  mDataDefinedNames.insert( DirSymbPlacement, QPair<QString, int>( "DirSymbPlacement", -1 ) );
264  mDataDefinedNames.insert( DirSymbReverse, QPair<QString, int>( "DirSymbReverse", -1 ) );
265  mDataDefinedNames.insert( NumFormat, QPair<QString, int>( "NumFormat", -1 ) );
266  mDataDefinedNames.insert( NumDecimals, QPair<QString, int>( "NumDecimals", -1 ) );
267  mDataDefinedNames.insert( NumPlusSign, QPair<QString, int>( "NumPlusSign", -1 ) );
268 
269  // text buffer
270  mDataDefinedNames.insert( BufferDraw, QPair<QString, int>( "BufferDraw", -1 ) );
271  mDataDefinedNames.insert( BufferSize, QPair<QString, int>( "BufferSize", 7 ) );
272  mDataDefinedNames.insert( BufferUnit, QPair<QString, int>( "BufferUnit", -1 ) );
273  mDataDefinedNames.insert( BufferColor, QPair<QString, int>( "BufferColor", 8 ) );
274  mDataDefinedNames.insert( BufferTransp, QPair<QString, int>( "BufferTransp", 19 ) );
275  mDataDefinedNames.insert( BufferJoinStyle, QPair<QString, int>( "BufferJoinStyle", -1 ) );
276  mDataDefinedNames.insert( BufferBlendMode, QPair<QString, int>( "BufferBlendMode", -1 ) );
277 
278  // background
279  mDataDefinedNames.insert( ShapeDraw, QPair<QString, int>( "ShapeDraw", -1 ) );
280  mDataDefinedNames.insert( ShapeKind, QPair<QString, int>( "ShapeKind", -1 ) );
281  mDataDefinedNames.insert( ShapeSVGFile, QPair<QString, int>( "ShapeSVGFile", -1 ) );
282  mDataDefinedNames.insert( ShapeSizeType, QPair<QString, int>( "ShapeSizeType", -1 ) );
283  mDataDefinedNames.insert( ShapeSizeX, QPair<QString, int>( "ShapeSizeX", -1 ) );
284  mDataDefinedNames.insert( ShapeSizeY, QPair<QString, int>( "ShapeSizeY", -1 ) );
285  mDataDefinedNames.insert( ShapeSizeUnits, QPair<QString, int>( "ShapeSizeUnits", -1 ) );
286  mDataDefinedNames.insert( ShapeRotationType, QPair<QString, int>( "ShapeRotationType", -1 ) );
287  mDataDefinedNames.insert( ShapeRotation, QPair<QString, int>( "ShapeRotation", -1 ) );
288  mDataDefinedNames.insert( ShapeOffset, QPair<QString, int>( "ShapeOffset", -1 ) );
289  mDataDefinedNames.insert( ShapeOffsetUnits, QPair<QString, int>( "ShapeOffsetUnits", -1 ) );
290  mDataDefinedNames.insert( ShapeRadii, QPair<QString, int>( "ShapeRadii", -1 ) );
291  mDataDefinedNames.insert( ShapeRadiiUnits, QPair<QString, int>( "ShapeRadiiUnits", -1 ) );
292  mDataDefinedNames.insert( ShapeTransparency, QPair<QString, int>( "ShapeTransparency", -1 ) );
293  mDataDefinedNames.insert( ShapeBlendMode, QPair<QString, int>( "ShapeBlendMode", -1 ) );
294  mDataDefinedNames.insert( ShapeFillColor, QPair<QString, int>( "ShapeFillColor", -1 ) );
295  mDataDefinedNames.insert( ShapeBorderColor, QPair<QString, int>( "ShapeBorderColor", -1 ) );
296  mDataDefinedNames.insert( ShapeBorderWidth, QPair<QString, int>( "ShapeBorderWidth", -1 ) );
297  mDataDefinedNames.insert( ShapeBorderWidthUnits, QPair<QString, int>( "ShapeBorderWidthUnits", -1 ) );
298  mDataDefinedNames.insert( ShapeJoinStyle, QPair<QString, int>( "ShapeJoinStyle", -1 ) );
299 
300  // drop shadow
301  mDataDefinedNames.insert( ShadowDraw, QPair<QString, int>( "ShadowDraw", -1 ) );
302  mDataDefinedNames.insert( ShadowUnder, QPair<QString, int>( "ShadowUnder", -1 ) );
303  mDataDefinedNames.insert( ShadowOffsetAngle, QPair<QString, int>( "ShadowOffsetAngle", -1 ) );
304  mDataDefinedNames.insert( ShadowOffsetDist, QPair<QString, int>( "ShadowOffsetDist", -1 ) );
305  mDataDefinedNames.insert( ShadowOffsetUnits, QPair<QString, int>( "ShadowOffsetUnits", -1 ) );
306  mDataDefinedNames.insert( ShadowRadius, QPair<QString, int>( "ShadowRadius", -1 ) );
307  mDataDefinedNames.insert( ShadowRadiusUnits, QPair<QString, int>( "ShadowRadiusUnits", -1 ) );
308  mDataDefinedNames.insert( ShadowTransparency, QPair<QString, int>( "ShadowTransparency", -1 ) );
309  mDataDefinedNames.insert( ShadowScale, QPair<QString, int>( "ShadowScale", -1 ) );
310  mDataDefinedNames.insert( ShadowColor, QPair<QString, int>( "ShadowColor", -1 ) );
311  mDataDefinedNames.insert( ShadowBlendMode, QPair<QString, int>( "ShadowBlendMode", -1 ) );
312 
313  // placement
314  mDataDefinedNames.insert( CentroidWhole, QPair<QString, int>( "CentroidWhole", -1 ) );
315  mDataDefinedNames.insert( OffsetQuad, QPair<QString, int>( "OffsetQuad", -1 ) );
316  mDataDefinedNames.insert( OffsetXY, QPair<QString, int>( "OffsetXY", -1 ) );
317  mDataDefinedNames.insert( OffsetUnits, QPair<QString, int>( "OffsetUnits", -1 ) );
318  mDataDefinedNames.insert( LabelDistance, QPair<QString, int>( "LabelDistance", 13 ) );
319  mDataDefinedNames.insert( DistanceUnits, QPair<QString, int>( "DistanceUnits", -1 ) );
320  mDataDefinedNames.insert( OffsetRotation, QPair<QString, int>( "OffsetRotation", -1 ) );
321  mDataDefinedNames.insert( CurvedCharAngleInOut, QPair<QString, int>( "CurvedCharAngleInOut", -1 ) );
322  mDataDefinedNames.insert( RepeatDistance, QPair<QString, int>( "RepeatDistance", -1 ) );
323  mDataDefinedNames.insert( RepeatDistanceUnit, QPair<QString, int>( "RepeatDistanceUnit", -1 ) );
324  mDataDefinedNames.insert( Priority, QPair<QString, int>( "Priority", -1 ) );
325  mDataDefinedNames.insert( IsObstacle, QPair<QString, int>( "IsObstacle", -1 ) );
326  mDataDefinedNames.insert( ObstacleFactor, QPair<QString, int>( "ObstacleFactor", -1 ) );
327  mDataDefinedNames.insert( PredefinedPositionOrder, QPair<QString, int>( "PredefinedPositionOrder", -1 ) );
328 
329  // (data defined only)
330  mDataDefinedNames.insert( PositionX, QPair<QString, int>( "PositionX", 9 ) );
331  mDataDefinedNames.insert( PositionY, QPair<QString, int>( "PositionY", 10 ) );
332  mDataDefinedNames.insert( Hali, QPair<QString, int>( "Hali", 11 ) );
333  mDataDefinedNames.insert( Vali, QPair<QString, int>( "Vali", 12 ) );
334  mDataDefinedNames.insert( Rotation, QPair<QString, int>( "Rotation", 14 ) );
335 
336  //rendering
337  mDataDefinedNames.insert( ScaleVisibility, QPair<QString, int>( "ScaleVisibility", -1 ) );
338  mDataDefinedNames.insert( MinScale, QPair<QString, int>( "MinScale", 16 ) );
339  mDataDefinedNames.insert( MaxScale, QPair<QString, int>( "MaxScale", 17 ) );
340  mDataDefinedNames.insert( FontLimitPixel, QPair<QString, int>( "FontLimitPixel", -1 ) );
341  mDataDefinedNames.insert( FontMinPixel, QPair<QString, int>( "FontMinPixel", -1 ) );
342  mDataDefinedNames.insert( FontMaxPixel, QPair<QString, int>( "FontMaxPixel", -1 ) );
343  mDataDefinedNames.insert( ZIndex, QPair<QString, int>( "ZIndex", -1 ) );
344  // (data defined only)
345  mDataDefinedNames.insert( Show, QPair<QString, int>( "Show", 15 ) );
346  mDataDefinedNames.insert( AlwaysShow, QPair<QString, int>( "AlwaysShow", 20 ) );
347 
348  // temp stuff for when drawing label components (don't copy)
349  showingShadowRects = false;
350 }
351 
353  : mCurFeat( nullptr )
354  , fieldIndex( 0 )
355  , xform( nullptr )
356  , ct( nullptr )
357  , extentGeom( nullptr )
358  , mFeaturesToLabel( 0 )
359  , mFeatsSendingToPal( 0 )
360  , mFeatsRegPal( 0 )
361  , showingShadowRects( false )
362  , expression( nullptr )
363 {
364  *this = s;
365 }
366 
368 {
369  if ( this == &s )
370  return *this;
371 
372  // copy only permanent stuff
373 
374  enabled = s.enabled;
376 
377  // text style
378  fieldName = s.fieldName;
380  textFont = s.textFont;
384  textColor = s.textColor;
386  blendMode = s.blendMode;
388  // font processing info
391 
392  // text formatting
393  wrapChar = s.wrapChar;
402  decimals = s.decimals;
403  plusSign = s.plusSign;
404 
405  // text buffer
415 
416  // placement
417  placement = s.placement;
424  xOffset = s.xOffset;
425  yOffset = s.yOffset;
428  dist = s.dist;
436  priority = s.priority;
440 
441  // rendering
443  scaleMin = s.scaleMin;
444  scaleMax = s.scaleMax;
450 
456  obstacle = s.obstacle;
459  zIndex = s.zIndex;
460 
461  // shape background
462  shapeDraw = s.shapeDraw;
463  shapeType = s.shapeType;
466  shapeSize = s.shapeSize;
485 
486  // drop shadow
502 
503  // data defined
506  for ( ; it != s.dataDefinedProperties.constEnd(); ++it )
507  {
508  dataDefinedProperties.insert( it.key(), it.value() ? new QgsDataDefined( *it.value() ) : nullptr );
509  }
510  mDataDefinedNames = s.mDataDefinedNames;
511 
512  // scale factors
515  return *this;
516 }
517 
518 
520 {
521  // pal layer is deleted internally in PAL
522 
523  delete ct;
524  delete expression;
525  delete extentGeom;
526 
527  // delete all QgsDataDefined objects (which also deletes their QgsExpression object)
529 }
530 
531 
533 {
534  QgsPalLayerSettings settings;
535  settings.readFromLayer( layer );
536  return settings;
537 }
538 
539 
541 {
542  if ( !expression )
543  {
544  expression = new QgsExpression( fieldName );
545  }
546  return expression;
547 }
548 
549 static QColor _readColor( QgsVectorLayer* layer, const QString& property, const QColor& defaultColor = Qt::black, bool withAlpha = true )
550 {
551  int r = layer->customProperty( property + 'R', QVariant( defaultColor.red() ) ).toInt();
552  int g = layer->customProperty( property + 'G', QVariant( defaultColor.green() ) ).toInt();
553  int b = layer->customProperty( property + 'B', QVariant( defaultColor.blue() ) ).toInt();
554  int a = withAlpha ? layer->customProperty( property + 'A', QVariant( defaultColor.alpha() ) ).toInt() : 255;
555  return QColor( r, g, b, a );
556 }
557 
558 static void _writeColor( QgsVectorLayer* layer, const QString& property, const QColor& color, bool withAlpha = true )
559 {
560  layer->setCustomProperty( property + 'R', color.red() );
561  layer->setCustomProperty( property + 'G', color.green() );
562  layer->setCustomProperty( property + 'B', color.blue() );
563  if ( withAlpha )
564  layer->setCustomProperty( property + 'A', color.alpha() );
565 }
566 
568 {
569  if ( str.compare( "Point", Qt::CaseInsensitive ) == 0
570  || str.compare( "Points", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Points;
571  if ( str.compare( "MapUnit", Qt::CaseInsensitive ) == 0
572  || str.compare( "MapUnits", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::MapUnits;
573  if ( str.compare( "Percent", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Percent;
574  return QgsPalLayerSettings::MM; // "MM"
575 }
576 
577 static Qt::PenJoinStyle _decodePenJoinStyle( const QString& str )
578 {
579  if ( str.compare( "Miter", Qt::CaseInsensitive ) == 0 ) return Qt::MiterJoin;
580  if ( str.compare( "Round", Qt::CaseInsensitive ) == 0 ) return Qt::RoundJoin;
581  return Qt::BevelJoin; // "Bevel"
582 }
583 
584 void QgsPalLayerSettings::readDataDefinedPropertyMap( QgsVectorLayer* layer, QDomElement* parentElem,
586 {
587  if ( !layer && !parentElem )
588  {
589  return;
590  }
591 
593  while ( i.hasNext() )
594  {
595  i.next();
596  if ( layer )
597  {
598  // reading from layer's custom properties (old way)
599  readDataDefinedProperty( layer, i.key(), propertyMap );
600  }
601  else if ( parentElem )
602  {
603  // reading from XML (new way)
604  QDomElement e = parentElem->firstChildElement( i.value().first );
605  if ( !e.isNull() )
606  {
607  QgsDataDefined* dd = new QgsDataDefined();
608  if ( dd->setFromXmlElement( e ) )
609  propertyMap.insert( i.key(), dd );
610  else
611  delete dd;
612  }
613  }
614  }
615 }
616 
617 void QgsPalLayerSettings::writeDataDefinedPropertyMap( QgsVectorLayer* layer, QDomElement* parentElem,
619 {
620  if ( !layer && !parentElem )
621  {
622  return;
623  }
624 
626  while ( i.hasNext() )
627  {
628  i.next();
629  QString newPropertyName = "labeling/dataDefined/" + i.value().first;
630  QVariant propertyValue = QVariant();
631 
633  if ( it != propertyMap.constEnd() )
634  {
635  QgsDataDefined* dd = it.value();
636  if ( dd )
637  {
638  bool active = dd->isActive();
639  bool useExpr = dd->useExpression();
640  QString expr = dd->expressionString();
641  QString field = dd->field();
642 
643  bool defaultVals = ( !active && !useExpr && expr.isEmpty() && field.isEmpty() );
644 
645  if ( !defaultVals )
646  {
647  // TODO: update this when project settings for labeling are migrated to better XML layout
648  QStringList values;
649  values << ( active ? "1" : "0" );
650  values << ( useExpr ? "1" : "0" );
651  values << expr;
652  values << field;
653  if ( !values.isEmpty() )
654  {
655  propertyValue = QVariant( values.join( "~~" ) );
656  }
657  }
658 
659  if ( parentElem )
660  {
661  // writing to XML document (instead of writing to layer)
662  QDomDocument doc = parentElem->ownerDocument();
663  QDomElement e = dd->toXmlElement( doc, i.value().first );
664  parentElem->appendChild( e );
665  }
666  }
667  }
668 
669  if ( layer )
670  {
671  // writing to layer's custom properties (old method)
672 
673  if ( propertyValue.isValid() )
674  {
675  layer->setCustomProperty( newPropertyName, propertyValue );
676  }
677  else
678  {
679  // remove unused properties
680  layer->removeCustomProperty( newPropertyName );
681  }
682 
683  if ( layer->customProperty( newPropertyName, QVariant() ).isValid() && i.value().second > -1 )
684  {
685  // remove old-style field index-based property, if still present
686  layer->removeCustomProperty( QString( "labeling/dataDefinedProperty" ) + QString::number( i.value().second ) );
687  }
688  }
689  }
690 }
691 
692 void QgsPalLayerSettings::readDataDefinedProperty( QgsVectorLayer* layer,
695 {
696  QString newPropertyName = "labeling/dataDefined/" + mDataDefinedNames.value( p ).first;
697  QVariant newPropertyField = layer->customProperty( newPropertyName, QVariant() );
698 
699  QString ddString = QString();
700  if ( newPropertyField.isValid() )
701  {
702  ddString = newPropertyField.toString();
703  }
704  else // maybe working with old-style field index-based property (< QGIS 2.0)
705  {
706  int oldIndx = mDataDefinedNames.value( p ).second;
707 
708  if ( oldIndx < 0 ) // something went wrong and we are working with new-style
709  {
710  return;
711  }
712 
713  QString oldPropertyName = "labeling/dataDefinedProperty" + QString::number( oldIndx );
714  QVariant oldPropertyField = layer->customProperty( oldPropertyName, QVariant() );
715 
716  if ( !oldPropertyField.isValid() )
717  {
718  return;
719  }
720 
721  // switch from old-style field index- to name-based properties
722  bool conversionOk;
723  int indx = oldPropertyField.toInt( &conversionOk );
724 
725  if ( conversionOk )
726  {
727  // Fix to migrate from old-style vector api, where returned QMap keys possibly
728  // had 'holes' in sequence of field indices, e.g. 0,2,3
729  // QgsAttrPalIndexNameHash provides a means of access field name in sequences from
730  // providers that procuded holes (e.g. PostGIS skipped geom column), otherwise it is empty
731  QgsAttrPalIndexNameHash oldIndicesToNames = layer->dataProvider()->palAttributeIndexNames();
732 
733  if ( !oldIndicesToNames.isEmpty() )
734  {
735  ddString = oldIndicesToNames.value( indx );
736  }
737  else
738  {
739  QgsFields fields = layer->dataProvider()->fields();
740  if ( indx < fields.size() ) // in case field count has changed
741  {
742  ddString = fields.at( indx ).name();
743  }
744  }
745  }
746 
747  if ( !ddString.isEmpty() )
748  {
749  //upgrade any existing property to field name-based
750  layer->setCustomProperty( newPropertyName, QVariant( updateDataDefinedString( ddString ) ) );
751 
752  // fix for buffer drawing triggered off of just its data defined size in the past (<2.0)
753  if ( oldIndx == 7 ) // old bufferSize enum
754  {
755  bufferDraw = true;
756  layer->setCustomProperty( "labeling/bufferDraw", true );
757  }
758 
759  // fix for scale visibility limits triggered off of just its data defined values in the past (<2.0)
760  if ( oldIndx == 16 || oldIndx == 17 ) // old minScale and maxScale enums
761  {
762  scaleVisibility = true;
763  layer->setCustomProperty( "labeling/scaleVisibility", true );
764  }
765  }
766 
767  // remove old-style field index-based property
768  layer->removeCustomProperty( oldPropertyName );
769  }
770 
771  if ( !ddString.isEmpty() && ddString != QLatin1String( "0~~0~~~~" ) )
772  {
773  // TODO: update this when project settings for labeling are migrated to better XML layout
774  QString newStyleString = updateDataDefinedString( ddString );
775  QStringList ddv = newStyleString.split( "~~" );
776 
777  QgsDataDefined* dd = new QgsDataDefined( ddv.at( 0 ).toInt(), ddv.at( 1 ).toInt(), ddv.at( 2 ), ddv.at( 3 ) );
778  propertyMap.insert( p, dd );
779  }
780  else
781  {
782  // remove unused properties
783  layer->removeCustomProperty( newPropertyName );
784  }
785 }
786 
788 {
789  if ( layer->customProperty( "labeling" ).toString() != QLatin1String( "pal" ) )
790  {
791  // for polygons the "over point" (over centroid) placement is better than the default
792  // "around point" (around centroid) which is more suitable for points
793  if ( layer->geometryType() == QGis::Polygon )
795 
796  return; // there's no information available
797  }
798 
799  // NOTE: set defaults for newly added properties, for backwards compatibility
800 
801  enabled = layer->labelsEnabled();
802  drawLabels = layer->customProperty( "labeling/drawLabels", true ).toBool();
803 
804  // text style
805  fieldName = layer->customProperty( "labeling/fieldName" ).toString();
806  isExpression = layer->customProperty( "labeling/isExpression" ).toBool();
807  QFont appFont = QApplication::font();
808  mTextFontFamily = layer->customProperty( "labeling/fontFamily", QVariant( appFont.family() ) ).toString();
809  QString fontFamily = mTextFontFamily;
811  {
812  // trigger to notify user about font family substitution (signal emitted in QgsVectorLayer::prepareLabelingAndDiagrams)
813  mTextFontFound = false;
814 
815  // TODO: update when pref for how to resolve missing family (use matching algorithm or just default font) is implemented
816  // currently only defaults to matching algorithm for resolving [foundry], if a font of similar family is found (default for QFont)
817 
818  // for now, do not use matching algorithm for substitution if family not found, substitute default instead
819  fontFamily = appFont.family();
820  }
821 
822  double fontSize = layer->customProperty( "labeling/fontSize" ).toDouble();
823  fontSizeInMapUnits = layer->customProperty( "labeling/fontSizeInMapUnits" ).toBool();
824  if ( layer->customProperty( "labeling/fontSizeMapUnitScale" ).toString().isEmpty() )
825  {
826  //fallback to older property
827  fontSizeMapUnitScale.minScale = layer->customProperty( "labeling/fontSizeMapUnitMinScale", 0.0 ).toDouble();
828  fontSizeMapUnitScale.maxScale = layer->customProperty( "labeling/fontSizeMapUnitMaxScale", 0.0 ).toDouble();
829  }
830  else
831  {
832  fontSizeMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/fontSizeMapUnitScale" ).toString() );
833  }
834  int fontWeight = layer->customProperty( "labeling/fontWeight" ).toInt();
835  bool fontItalic = layer->customProperty( "labeling/fontItalic" ).toBool();
836  textFont = QFont( fontFamily, fontSize, fontWeight, fontItalic );
837  textFont.setPointSizeF( fontSize ); //double precision needed because of map units
838  textNamedStyle = QgsFontUtils::translateNamedStyle( layer->customProperty( "labeling/namedStyle", QVariant( "" ) ).toString() );
839  QgsFontUtils::updateFontViaStyle( textFont, textNamedStyle ); // must come after textFont.setPointSizeF()
840  textFont.setCapitalization( static_cast< QFont::Capitalization >( layer->customProperty( "labeling/fontCapitals", QVariant( 0 ) ).toUInt() ) );
841  textFont.setUnderline( layer->customProperty( "labeling/fontUnderline" ).toBool() );
842  textFont.setStrikeOut( layer->customProperty( "labeling/fontStrikeout" ).toBool() );
843  textFont.setLetterSpacing( QFont::AbsoluteSpacing, layer->customProperty( "labeling/fontLetterSpacing", QVariant( 0.0 ) ).toDouble() );
844  textFont.setWordSpacing( layer->customProperty( "labeling/fontWordSpacing", QVariant( 0.0 ) ).toDouble() );
845  textColor = _readColor( layer, "labeling/textColor", Qt::black, false );
846  textTransp = layer->customProperty( "labeling/textTransp" ).toInt();
848  static_cast< QgsMapRenderer::BlendMode >( layer->customProperty( "labeling/blendMode", QVariant( QgsMapRenderer::BlendNormal ) ).toUInt() ) );
849  previewBkgrdColor = QColor( layer->customProperty( "labeling/previewBkgrdColor", QVariant( "#ffffff" ) ).toString() );
850 
851 
852  // text formatting
853  wrapChar = layer->customProperty( "labeling/wrapChar" ).toString();
854  multilineHeight = layer->customProperty( "labeling/multilineHeight", QVariant( 1.0 ) ).toDouble();
855  multilineAlign = static_cast< MultiLineAlign >( layer->customProperty( "labeling/multilineAlign", QVariant( MultiLeft ) ).toUInt() );
856  addDirectionSymbol = layer->customProperty( "labeling/addDirectionSymbol" ).toBool();
857  leftDirectionSymbol = layer->customProperty( "labeling/leftDirectionSymbol", QVariant( "<" ) ).toString();
858  rightDirectionSymbol = layer->customProperty( "labeling/rightDirectionSymbol", QVariant( ">" ) ).toString();
859  reverseDirectionSymbol = layer->customProperty( "labeling/reverseDirectionSymbol" ).toBool();
860  placeDirectionSymbol = static_cast< DirectionSymbols >( layer->customProperty( "labeling/placeDirectionSymbol", QVariant( SymbolLeftRight ) ).toUInt() );
861  formatNumbers = layer->customProperty( "labeling/formatNumbers" ).toBool();
862  decimals = layer->customProperty( "labeling/decimals" ).toInt();
863  plusSign = layer->customProperty( "labeling/plussign" ).toBool();
864 
865  // text buffer
866  double bufSize = layer->customProperty( "labeling/bufferSize", QVariant( 0.0 ) ).toDouble();
867 
868  // fix for buffer being keyed off of just its size in the past (<2.0)
869  QVariant drawBuffer = layer->customProperty( "labeling/bufferDraw", QVariant() );
870  if ( drawBuffer.isValid() )
871  {
872  bufferDraw = drawBuffer.toBool();
873  bufferSize = bufSize;
874  }
875  else if ( bufSize != 0.0 )
876  {
877  bufferDraw = true;
878  bufferSize = bufSize;
879  }
880  else
881  {
882  // keep bufferSize at new 1.0 default
883  bufferDraw = false;
884  }
885 
886  bufferSizeInMapUnits = layer->customProperty( "labeling/bufferSizeInMapUnits" ).toBool();
887  if ( layer->customProperty( "labeling/bufferSizeMapUnitScale" ).toString().isEmpty() )
888  {
889  //fallback to older property
890  bufferSizeMapUnitScale.minScale = layer->customProperty( "labeling/bufferSizeMapUnitMinScale", 0.0 ).toDouble();
891  bufferSizeMapUnitScale.maxScale = layer->customProperty( "labeling/bufferSizeMapUnitMaxScale", 0.0 ).toDouble();
892  }
893  else
894  {
895  bufferSizeMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/bufferSizeMapUnitScale" ).toString() );
896  }
897  bufferColor = _readColor( layer, "labeling/bufferColor", Qt::white, false );
898  bufferTransp = layer->customProperty( "labeling/bufferTransp" ).toInt();
900  static_cast< QgsMapRenderer::BlendMode >( layer->customProperty( "labeling/bufferBlendMode", QVariant( QgsMapRenderer::BlendNormal ) ).toUInt() ) );
901  bufferJoinStyle = static_cast< Qt::PenJoinStyle >( layer->customProperty( "labeling/bufferJoinStyle", QVariant( Qt::BevelJoin ) ).toUInt() );
902  bufferNoFill = layer->customProperty( "labeling/bufferNoFill", QVariant( false ) ).toBool();
903 
904  // background
905  shapeDraw = layer->customProperty( "labeling/shapeDraw", QVariant( false ) ).toBool();
906  shapeType = static_cast< ShapeType >( layer->customProperty( "labeling/shapeType", QVariant( ShapeRectangle ) ).toUInt() );
907  shapeSVGFile = layer->customProperty( "labeling/shapeSVGFile", QVariant( "" ) ).toString();
908  shapeSizeType = static_cast< SizeType >( layer->customProperty( "labeling/shapeSizeType", QVariant( SizeBuffer ) ).toUInt() );
909  shapeSize = QPointF( layer->customProperty( "labeling/shapeSizeX", QVariant( 0.0 ) ).toDouble(),
910  layer->customProperty( "labeling/shapeSizeY", QVariant( 0.0 ) ).toDouble() );
911  shapeSizeUnits = static_cast< SizeUnit >( layer->customProperty( "labeling/shapeSizeUnits", QVariant( MM ) ).toUInt() );
912  if ( layer->customProperty( "labeling/shapeSizeMapUnitScale" ).toString().isEmpty() )
913  {
914  //fallback to older property
915  shapeSizeMapUnitScale.minScale = layer->customProperty( "labeling/shapeSizeMapUnitMinScale", 0.0 ).toDouble();
916  shapeSizeMapUnitScale.maxScale = layer->customProperty( "labeling/shapeSizeMapUnitMaxScale", 0.0 ).toDouble();
917  }
918  else
919  {
920  shapeSizeMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/shapeSizeMapUnitScale" ).toString() );
921  }
922  shapeRotationType = static_cast< RotationType >( layer->customProperty( "labeling/shapeRotationType", QVariant( RotationSync ) ).toUInt() );
923  shapeRotation = layer->customProperty( "labeling/shapeRotation", QVariant( 0.0 ) ).toDouble();
924  shapeOffset = QPointF( layer->customProperty( "labeling/shapeOffsetX", QVariant( 0.0 ) ).toDouble(),
925  layer->customProperty( "labeling/shapeOffsetY", QVariant( 0.0 ) ).toDouble() );
926  shapeOffsetUnits = static_cast< SizeUnit >( layer->customProperty( "labeling/shapeOffsetUnits", QVariant( MM ) ).toUInt() );
927  if ( layer->customProperty( "labeling/shapeOffsetMapUnitScale" ).toString().isEmpty() )
928  {
929  //fallback to older property
930  shapeOffsetMapUnitScale.minScale = layer->customProperty( "labeling/shapeOffsetMapUnitMinScale", 0.0 ).toDouble();
931  shapeOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/shapeOffsetMapUnitMaxScale", 0.0 ).toDouble();
932  }
933  else
934  {
935  shapeOffsetMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/shapeOffsetMapUnitScale" ).toString() );
936  }
937  shapeRadii = QPointF( layer->customProperty( "labeling/shapeRadiiX", QVariant( 0.0 ) ).toDouble(),
938  layer->customProperty( "labeling/shapeRadiiY", QVariant( 0.0 ) ).toDouble() );
939  shapeRadiiUnits = static_cast< SizeUnit >( layer->customProperty( "labeling/shapeRadiiUnits", QVariant( MM ) ).toUInt() );
940  if ( layer->customProperty( "labeling/shapeRadiiMapUnitScale" ).toString().isEmpty() )
941  {
942  //fallback to older property
943  shapeRadiiMapUnitScale.minScale = layer->customProperty( "labeling/shapeRadiiMapUnitMinScale", 0.0 ).toDouble();
944  shapeRadiiMapUnitScale.maxScale = layer->customProperty( "labeling/shapeRadiiMapUnitMaxScale", 0.0 ).toDouble();
945  }
946  else
947  {
948  shapeRadiiMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/shapeRadiiMapUnitScale" ).toString() );
949  }
950  shapeFillColor = _readColor( layer, "labeling/shapeFillColor", Qt::white, true );
951  shapeBorderColor = _readColor( layer, "labeling/shapeBorderColor", Qt::darkGray, true );
952  shapeBorderWidth = layer->customProperty( "labeling/shapeBorderWidth", QVariant( .0 ) ).toDouble();
953  shapeBorderWidthUnits = static_cast< SizeUnit >( layer->customProperty( "labeling/shapeBorderWidthUnits", QVariant( MM ) ).toUInt() );
954  if ( layer->customProperty( "labeling/shapeBorderWidthMapUnitScale" ).toString().isEmpty() )
955  {
956  //fallback to older property
957  shapeBorderWidthMapUnitScale.minScale = layer->customProperty( "labeling/shapeBorderWidthMapUnitMinScale", 0.0 ).toDouble();
958  shapeBorderWidthMapUnitScale.maxScale = layer->customProperty( "labeling/shapeBorderWidthMapUnitMaxScale", 0.0 ).toDouble();
959  }
960  else
961  {
962  shapeBorderWidthMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/shapeBorderWidthMapUnitScale" ).toString() );
963  }
964  shapeJoinStyle = static_cast< Qt::PenJoinStyle >( layer->customProperty( "labeling/shapeJoinStyle", QVariant( Qt::BevelJoin ) ).toUInt() );
965  shapeTransparency = layer->customProperty( "labeling/shapeTransparency", QVariant( 0 ) ).toInt();
967  static_cast< QgsMapRenderer::BlendMode >( layer->customProperty( "labeling/shapeBlendMode", QVariant( QgsMapRenderer::BlendNormal ) ).toUInt() ) );
968 
969  // drop shadow
970  shadowDraw = layer->customProperty( "labeling/shadowDraw", QVariant( false ) ).toBool();
971  shadowUnder = static_cast< ShadowType >( layer->customProperty( "labeling/shadowUnder", QVariant( ShadowLowest ) ).toUInt() );//ShadowLowest;
972  shadowOffsetAngle = layer->customProperty( "labeling/shadowOffsetAngle", QVariant( 135 ) ).toInt();
973  shadowOffsetDist = layer->customProperty( "labeling/shadowOffsetDist", QVariant( 1.0 ) ).toDouble();
974  shadowOffsetUnits = static_cast< SizeUnit >( layer->customProperty( "labeling/shadowOffsetUnits", QVariant( MM ) ).toUInt() );
975  if ( layer->customProperty( "labeling/shadowOffsetMapUnitScale" ).toString().isEmpty() )
976  {
977  //fallback to older property
978  shadowOffsetMapUnitScale.minScale = layer->customProperty( "labeling/shadowOffsetMapUnitMinScale", 0.0 ).toDouble();
979  shadowOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/shadowOffsetMapUnitMaxScale", 0.0 ).toDouble();
980  }
981  else
982  {
983  shadowOffsetMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/shadowOffsetMapUnitScale" ).toString() );
984  }
985  shadowOffsetGlobal = layer->customProperty( "labeling/shadowOffsetGlobal", QVariant( true ) ).toBool();
986  shadowRadius = layer->customProperty( "labeling/shadowRadius", QVariant( 1.5 ) ).toDouble();
987  shadowRadiusUnits = static_cast< SizeUnit >( layer->customProperty( "labeling/shadowRadiusUnits", QVariant( MM ) ).toUInt() );
988  if ( layer->customProperty( "labeling/shadowRadiusMapUnitScale" ).toString().isEmpty() )
989  {
990  //fallback to older property
991  shadowRadiusMapUnitScale.minScale = layer->customProperty( "labeling/shadowRadiusMapUnitMinScale", 0.0 ).toDouble();
992  shadowRadiusMapUnitScale.maxScale = layer->customProperty( "labeling/shadowRadiusMapUnitMaxScale", 0.0 ).toDouble();
993  }
994  else
995  {
996  shadowRadiusMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/shadowRadiusMapUnitScale" ).toString() );
997  }
998  shadowRadiusAlphaOnly = layer->customProperty( "labeling/shadowRadiusAlphaOnly", QVariant( false ) ).toBool();
999  shadowTransparency = layer->customProperty( "labeling/shadowTransparency", QVariant( 30 ) ).toInt();
1000  shadowScale = layer->customProperty( "labeling/shadowScale", QVariant( 100 ) ).toInt();
1001  shadowColor = _readColor( layer, "labeling/shadowColor", Qt::black, false );
1003  static_cast< QgsMapRenderer::BlendMode >( layer->customProperty( "labeling/shadowBlendMode", QVariant( QgsMapRenderer::BlendMultiply ) ).toUInt() ) );
1004 
1005  // placement
1006  placement = static_cast< Placement >( layer->customProperty( "labeling/placement" ).toInt() );
1007  placementFlags = layer->customProperty( "labeling/placementFlags" ).toUInt();
1008  centroidWhole = layer->customProperty( "labeling/centroidWhole", QVariant( false ) ).toBool();
1009  centroidInside = layer->customProperty( "labeling/centroidInside", QVariant( false ) ).toBool();
1010  predefinedPositionOrder = QgsLabelingUtils::decodePredefinedPositionOrder( layer->customProperty( "labeling/predefinedPositionOrder" ).toString() );
1012  predefinedPositionOrder = DEFAULT_PLACEMENT_ORDER;
1013  fitInPolygonOnly = layer->customProperty( "labeling/fitInPolygonOnly", QVariant( false ) ).toBool();
1014  dist = layer->customProperty( "labeling/dist" ).toDouble();
1015  distInMapUnits = layer->customProperty( "labeling/distInMapUnits" ).toBool();
1016  if ( layer->customProperty( "labeling/distMapUnitScale" ).toString().isEmpty() )
1017  {
1018  //fallback to older property
1019  distMapUnitScale.minScale = layer->customProperty( "labeling/distMapUnitMinScale", 0.0 ).toDouble();
1020  distMapUnitScale.maxScale = layer->customProperty( "labeling/distMapUnitMaxScale", 0.0 ).toDouble();
1021  }
1022  else
1023  {
1024  distMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/distMapUnitScale" ).toString() );
1025  }
1026  offsetType = static_cast< OffsetType >( layer->customProperty( "labeling/offsetType", QVariant( FromPoint ) ).toUInt() );
1027  quadOffset = static_cast< QuadrantPosition >( layer->customProperty( "labeling/quadOffset", QVariant( QuadrantOver ) ).toUInt() );
1028  xOffset = layer->customProperty( "labeling/xOffset", QVariant( 0.0 ) ).toDouble();
1029  yOffset = layer->customProperty( "labeling/yOffset", QVariant( 0.0 ) ).toDouble();
1030  labelOffsetInMapUnits = layer->customProperty( "labeling/labelOffsetInMapUnits", QVariant( true ) ).toBool();
1031  if ( layer->customProperty( "labeling/labelOffsetMapUnitScale" ).toString().isEmpty() )
1032  {
1033  //fallback to older property
1034  labelOffsetMapUnitScale.minScale = layer->customProperty( "labeling/labelOffsetMapUnitMinScale", 0.0 ).toDouble();
1035  labelOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/labelOffsetMapUnitMaxScale", 0.0 ).toDouble();
1036  }
1037  else
1038  {
1039  labelOffsetMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/labelOffsetMapUnitScale" ).toString() );
1040  }
1041  angleOffset = layer->customProperty( "labeling/angleOffset", QVariant( 0.0 ) ).toDouble();
1042  preserveRotation = layer->customProperty( "labeling/preserveRotation", QVariant( true ) ).toBool();
1043  maxCurvedCharAngleIn = layer->customProperty( "labeling/maxCurvedCharAngleIn", QVariant( 20.0 ) ).toDouble();
1044  maxCurvedCharAngleOut = layer->customProperty( "labeling/maxCurvedCharAngleOut", QVariant( -20.0 ) ).toDouble();
1045  priority = layer->customProperty( "labeling/priority" ).toInt();
1046  repeatDistance = layer->customProperty( "labeling/repeatDistance", 0.0 ).toDouble();
1047  repeatDistanceUnit = static_cast< SizeUnit >( layer->customProperty( "labeling/repeatDistanceUnit", QVariant( MM ) ).toUInt() );
1048  if ( layer->customProperty( "labeling/repeatDistanceMapUnitScale" ).toString().isEmpty() )
1049  {
1050  //fallback to older property
1051  repeatDistanceMapUnitScale.minScale = layer->customProperty( "labeling/repeatDistanceMapUnitMinScale", 0.0 ).toDouble();
1052  repeatDistanceMapUnitScale.maxScale = layer->customProperty( "labeling/repeatDistanceMapUnitMaxScale", 0.0 ).toDouble();
1053  }
1054  else
1055  {
1056  repeatDistanceMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( layer->customProperty( "labeling/repeatDistanceMapUnitScale" ).toString() );
1057  }
1058 
1059  // rendering
1060  int scalemn = layer->customProperty( "labeling/scaleMin", QVariant( 0 ) ).toInt();
1061  int scalemx = layer->customProperty( "labeling/scaleMax", QVariant( 0 ) ).toInt();
1062 
1063  // fix for scale visibility limits being keyed off of just its values in the past (<2.0)
1064  QVariant scalevis = layer->customProperty( "labeling/scaleVisibility", QVariant() );
1065  if ( scalevis.isValid() )
1066  {
1067  scaleVisibility = scalevis.toBool();
1068  scaleMin = scalemn;
1069  scaleMax = scalemx;
1070  }
1071  else if ( scalemn > 0 || scalemx > 0 )
1072  {
1073  scaleVisibility = true;
1074  scaleMin = scalemn;
1075  scaleMax = scalemx;
1076  }
1077  else
1078  {
1079  // keep scaleMin and scaleMax at new 1.0 defaults (1 and 10000000, were 0 and 0)
1080  scaleVisibility = false;
1081  }
1082 
1083 
1084  fontLimitPixelSize = layer->customProperty( "labeling/fontLimitPixelSize", QVariant( false ) ).toBool();
1085  fontMinPixelSize = layer->customProperty( "labeling/fontMinPixelSize", QVariant( 0 ) ).toInt();
1086  fontMaxPixelSize = layer->customProperty( "labeling/fontMaxPixelSize", QVariant( 10000 ) ).toInt();
1087  displayAll = layer->customProperty( "labeling/displayAll", QVariant( false ) ).toBool();
1088  upsidedownLabels = static_cast< UpsideDownLabels >( layer->customProperty( "labeling/upsidedownLabels", QVariant( Upright ) ).toUInt() );
1089 
1090  labelPerPart = layer->customProperty( "labeling/labelPerPart" ).toBool();
1091  mergeLines = layer->customProperty( "labeling/mergeLines" ).toBool();
1092  minFeatureSize = layer->customProperty( "labeling/minFeatureSize" ).toDouble();
1093  limitNumLabels = layer->customProperty( "labeling/limitNumLabels", QVariant( false ) ).toBool();
1094  maxNumLabels = layer->customProperty( "labeling/maxNumLabels", QVariant( 2000 ) ).toInt();
1095  obstacle = layer->customProperty( "labeling/obstacle", QVariant( true ) ).toBool();
1096  obstacleFactor = layer->customProperty( "labeling/obstacleFactor", QVariant( 1.0 ) ).toDouble();
1097  obstacleType = static_cast< ObstacleType >( layer->customProperty( "labeling/obstacleType", QVariant( PolygonInterior ) ).toUInt() );
1098  zIndex = layer->customProperty( "labeling/zIndex", QVariant( 0.0 ) ).toDouble();
1099 
1100  readDataDefinedPropertyMap( layer, nullptr, dataDefinedProperties );
1101 }
1102 
1104 {
1105  // this is a mark that labeling information is present
1106  layer->setCustomProperty( "labeling", "pal" );
1107 
1108  layer->setCustomProperty( "labeling/enabled", enabled );
1109  layer->setCustomProperty( "labeling/drawLabels", drawLabels );
1110 
1111  // text style
1112  layer->setCustomProperty( "labeling/fieldName", fieldName );
1113  layer->setCustomProperty( "labeling/isExpression", isExpression );
1114  layer->setCustomProperty( "labeling/fontFamily", textFont.family() );
1115  layer->setCustomProperty( "labeling/namedStyle", QgsFontUtils::untranslateNamedStyle( textNamedStyle ) );
1116  layer->setCustomProperty( "labeling/fontSize", textFont.pointSizeF() );
1117  layer->setCustomProperty( "labeling/fontSizeInMapUnits", fontSizeInMapUnits );
1118  layer->setCustomProperty( "labeling/fontSizeMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( fontSizeMapUnitScale ) );
1119  layer->setCustomProperty( "labeling/fontWeight", textFont.weight() );
1120  layer->setCustomProperty( "labeling/fontItalic", textFont.italic() );
1121  layer->setCustomProperty( "labeling/fontStrikeout", textFont.strikeOut() );
1122  layer->setCustomProperty( "labeling/fontUnderline", textFont.underline() );
1123  _writeColor( layer, "labeling/textColor", textColor );
1124  layer->setCustomProperty( "labeling/fontCapitals", static_cast< unsigned int >( textFont.capitalization() ) );
1125  layer->setCustomProperty( "labeling/fontLetterSpacing", textFont.letterSpacing() );
1126  layer->setCustomProperty( "labeling/fontWordSpacing", textFont.wordSpacing() );
1127  layer->setCustomProperty( "labeling/textTransp", textTransp );
1128  layer->setCustomProperty( "labeling/blendMode", QgsMapRenderer::getBlendModeEnum( blendMode ) );
1129  layer->setCustomProperty( "labeling/previewBkgrdColor", previewBkgrdColor.name() );
1130 
1131  // text formatting
1132  layer->setCustomProperty( "labeling/wrapChar", wrapChar );
1133  layer->setCustomProperty( "labeling/multilineHeight", multilineHeight );
1134  layer->setCustomProperty( "labeling/multilineAlign", static_cast< unsigned int >( multilineAlign ) );
1135  layer->setCustomProperty( "labeling/addDirectionSymbol", addDirectionSymbol );
1136  layer->setCustomProperty( "labeling/leftDirectionSymbol", leftDirectionSymbol );
1137  layer->setCustomProperty( "labeling/rightDirectionSymbol", rightDirectionSymbol );
1138  layer->setCustomProperty( "labeling/reverseDirectionSymbol", reverseDirectionSymbol );
1139  layer->setCustomProperty( "labeling/placeDirectionSymbol", static_cast< unsigned int >( placeDirectionSymbol ) );
1140  layer->setCustomProperty( "labeling/formatNumbers", formatNumbers );
1141  layer->setCustomProperty( "labeling/decimals", decimals );
1142  layer->setCustomProperty( "labeling/plussign", plusSign );
1143 
1144  // text buffer
1145  layer->setCustomProperty( "labeling/bufferDraw", bufferDraw );
1146  layer->setCustomProperty( "labeling/bufferSize", bufferSize );
1147  layer->setCustomProperty( "labeling/bufferSizeInMapUnits", bufferSizeInMapUnits );
1148  layer->setCustomProperty( "labeling/bufferSizeMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( bufferSizeMapUnitScale ) );
1149  _writeColor( layer, "labeling/bufferColor", bufferColor );
1150  layer->setCustomProperty( "labeling/bufferNoFill", bufferNoFill );
1151  layer->setCustomProperty( "labeling/bufferTransp", bufferTransp );
1152  layer->setCustomProperty( "labeling/bufferJoinStyle", static_cast< unsigned int >( bufferJoinStyle ) );
1153  layer->setCustomProperty( "labeling/bufferBlendMode", QgsMapRenderer::getBlendModeEnum( bufferBlendMode ) );
1154 
1155  // background
1156  layer->setCustomProperty( "labeling/shapeDraw", shapeDraw );
1157  layer->setCustomProperty( "labeling/shapeType", static_cast< unsigned int >( shapeType ) );
1158  layer->setCustomProperty( "labeling/shapeSVGFile", shapeSVGFile );
1159  layer->setCustomProperty( "labeling/shapeSizeType", static_cast< unsigned int >( shapeSizeType ) );
1160  layer->setCustomProperty( "labeling/shapeSizeX", shapeSize.x() );
1161  layer->setCustomProperty( "labeling/shapeSizeY", shapeSize.y() );
1162  layer->setCustomProperty( "labeling/shapeSizeUnits", static_cast< unsigned int >( shapeSizeUnits ) );
1163  layer->setCustomProperty( "labeling/shapeSizeMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shapeSizeMapUnitScale ) );
1164  layer->setCustomProperty( "labeling/shapeRotationType", static_cast< unsigned int >( shapeRotationType ) );
1165  layer->setCustomProperty( "labeling/shapeRotation", shapeRotation );
1166  layer->setCustomProperty( "labeling/shapeOffsetX", shapeOffset.x() );
1167  layer->setCustomProperty( "labeling/shapeOffsetY", shapeOffset.y() );
1168  layer->setCustomProperty( "labeling/shapeOffsetUnits", static_cast< unsigned int >( shapeOffsetUnits ) );
1169  layer->setCustomProperty( "labeling/shapeOffsetMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shapeOffsetMapUnitScale ) );
1170  layer->setCustomProperty( "labeling/shapeRadiiX", shapeRadii.x() );
1171  layer->setCustomProperty( "labeling/shapeRadiiY", shapeRadii.y() );
1172  layer->setCustomProperty( "labeling/shapeRadiiUnits", static_cast< unsigned int >( shapeRadiiUnits ) );
1173  layer->setCustomProperty( "labeling/shapeRadiiMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shapeRadiiMapUnitScale ) );
1174  _writeColor( layer, "labeling/shapeFillColor", shapeFillColor, true );
1175  _writeColor( layer, "labeling/shapeBorderColor", shapeBorderColor, true );
1176  layer->setCustomProperty( "labeling/shapeBorderWidth", shapeBorderWidth );
1177  layer->setCustomProperty( "labeling/shapeBorderWidthUnits", static_cast< unsigned int >( shapeBorderWidthUnits ) );
1178  layer->setCustomProperty( "labeling/shapeBorderWidthMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shapeBorderWidthMapUnitScale ) );
1179  layer->setCustomProperty( "labeling/shapeJoinStyle", static_cast< unsigned int >( shapeJoinStyle ) );
1180  layer->setCustomProperty( "labeling/shapeTransparency", shapeTransparency );
1181  layer->setCustomProperty( "labeling/shapeBlendMode", QgsMapRenderer::getBlendModeEnum( shapeBlendMode ) );
1182 
1183  // drop shadow
1184  layer->setCustomProperty( "labeling/shadowDraw", shadowDraw );
1185  layer->setCustomProperty( "labeling/shadowUnder", static_cast< unsigned int >( shadowUnder ) );
1186  layer->setCustomProperty( "labeling/shadowOffsetAngle", shadowOffsetAngle );
1187  layer->setCustomProperty( "labeling/shadowOffsetDist", shadowOffsetDist );
1188  layer->setCustomProperty( "labeling/shadowOffsetUnits", static_cast< unsigned int >( shadowOffsetUnits ) );
1189  layer->setCustomProperty( "labeling/shadowOffsetMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shadowOffsetMapUnitScale ) );
1190  layer->setCustomProperty( "labeling/shadowOffsetGlobal", shadowOffsetGlobal );
1191  layer->setCustomProperty( "labeling/shadowRadius", shadowRadius );
1192  layer->setCustomProperty( "labeling/shadowRadiusUnits", static_cast< unsigned int >( shadowRadiusUnits ) );
1193  layer->setCustomProperty( "labeling/shadowRadiusMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shadowRadiusMapUnitScale ) );
1194  layer->setCustomProperty( "labeling/shadowRadiusAlphaOnly", shadowRadiusAlphaOnly );
1195  layer->setCustomProperty( "labeling/shadowTransparency", shadowTransparency );
1196  layer->setCustomProperty( "labeling/shadowScale", shadowScale );
1197  _writeColor( layer, "labeling/shadowColor", shadowColor, false );
1198  layer->setCustomProperty( "labeling/shadowBlendMode", QgsMapRenderer::getBlendModeEnum( shadowBlendMode ) );
1199 
1200  // placement
1201  layer->setCustomProperty( "labeling/placement", placement );
1202  layer->setCustomProperty( "labeling/placementFlags", static_cast< unsigned int >( placementFlags ) );
1203  layer->setCustomProperty( "labeling/centroidWhole", centroidWhole );
1204  layer->setCustomProperty( "labeling/centroidInside", centroidInside );
1205  layer->setCustomProperty( "labeling/predefinedPositionOrder", QgsLabelingUtils::encodePredefinedPositionOrder( predefinedPositionOrder ) );
1206  layer->setCustomProperty( "labeling/fitInPolygonOnly", fitInPolygonOnly );
1207  layer->setCustomProperty( "labeling/dist", dist );
1208  layer->setCustomProperty( "labeling/distInMapUnits", distInMapUnits );
1209  layer->setCustomProperty( "labeling/distMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( distMapUnitScale ) );
1210  layer->setCustomProperty( "labeling/offsetType", static_cast< unsigned int >( offsetType ) );
1211  layer->setCustomProperty( "labeling/quadOffset", static_cast< unsigned int >( quadOffset ) );
1212  layer->setCustomProperty( "labeling/xOffset", xOffset );
1213  layer->setCustomProperty( "labeling/yOffset", yOffset );
1214  layer->setCustomProperty( "labeling/labelOffsetInMapUnits", labelOffsetInMapUnits );
1215  layer->setCustomProperty( "labeling/labelOffsetMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( labelOffsetMapUnitScale ) );
1216  layer->setCustomProperty( "labeling/angleOffset", angleOffset );
1217  layer->setCustomProperty( "labeling/preserveRotation", preserveRotation );
1218  layer->setCustomProperty( "labeling/maxCurvedCharAngleIn", maxCurvedCharAngleIn );
1219  layer->setCustomProperty( "labeling/maxCurvedCharAngleOut", maxCurvedCharAngleOut );
1220  layer->setCustomProperty( "labeling/priority", priority );
1221  layer->setCustomProperty( "labeling/repeatDistance", repeatDistance );
1222  layer->setCustomProperty( "labeling/repeatDistanceUnit", repeatDistanceUnit );
1223  layer->setCustomProperty( "labeling/repeatDistanceMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( repeatDistanceMapUnitScale ) );
1224 
1225  // rendering
1226  layer->setCustomProperty( "labeling/scaleVisibility", scaleVisibility );
1227  layer->setCustomProperty( "labeling/scaleMin", scaleMin );
1228  layer->setCustomProperty( "labeling/scaleMax", scaleMax );
1229  layer->setCustomProperty( "labeling/fontLimitPixelSize", fontLimitPixelSize );
1230  layer->setCustomProperty( "labeling/fontMinPixelSize", fontMinPixelSize );
1231  layer->setCustomProperty( "labeling/fontMaxPixelSize", fontMaxPixelSize );
1232  layer->setCustomProperty( "labeling/displayAll", displayAll );
1233  layer->setCustomProperty( "labeling/upsidedownLabels", static_cast< unsigned int >( upsidedownLabels ) );
1234 
1235  layer->setCustomProperty( "labeling/labelPerPart", labelPerPart );
1236  layer->setCustomProperty( "labeling/mergeLines", mergeLines );
1237  layer->setCustomProperty( "labeling/minFeatureSize", minFeatureSize );
1238  layer->setCustomProperty( "labeling/limitNumLabels", limitNumLabels );
1239  layer->setCustomProperty( "labeling/maxNumLabels", maxNumLabels );
1240  layer->setCustomProperty( "labeling/obstacle", obstacle );
1241  layer->setCustomProperty( "labeling/obstacleFactor", obstacleFactor );
1242  layer->setCustomProperty( "labeling/obstacleType", static_cast< unsigned int >( obstacleType ) );
1243  layer->setCustomProperty( "labeling/zIndex", zIndex );
1244 
1245  writeDataDefinedPropertyMap( layer, nullptr, dataDefinedProperties );
1246 }
1247 
1248 
1249 
1251 {
1252  enabled = true;
1253  drawLabels = true;
1254 
1255  // text style
1256  QDomElement textStyleElem = elem.firstChildElement( "text-style" );
1257  fieldName = textStyleElem.attribute( "fieldName" );
1258  isExpression = textStyleElem.attribute( "isExpression" ).toInt();
1259  QFont appFont = QApplication::font();
1260  mTextFontFamily = textStyleElem.attribute( "fontFamily", appFont.family() );
1261  QString fontFamily = mTextFontFamily;
1263  {
1264  // trigger to notify user about font family substitution (signal emitted in QgsVectorLayer::prepareLabelingAndDiagrams)
1265  mTextFontFound = false;
1266 
1267  // TODO: update when pref for how to resolve missing family (use matching algorithm or just default font) is implemented
1268  // currently only defaults to matching algorithm for resolving [foundry], if a font of similar family is found (default for QFont)
1269 
1270  // for now, do not use matching algorithm for substitution if family not found, substitute default instead
1271  fontFamily = appFont.family();
1272  }
1273 
1274  double fontSize = textStyleElem.attribute( "fontSize" ).toDouble();
1275  fontSizeInMapUnits = textStyleElem.attribute( "fontSizeInMapUnits" ).toInt();
1276  if ( !textStyleElem.hasAttribute( "fontSizeMapUnitScale" ) )
1277  {
1278  //fallback to older property
1279  fontSizeMapUnitScale.minScale = textStyleElem.attribute( "fontSizeMapUnitMinScale", "0" ).toDouble();
1280  fontSizeMapUnitScale.maxScale = textStyleElem.attribute( "fontSizeMapUnitMaxScale", "0" ).toDouble();
1281  }
1282  else
1283  {
1284  fontSizeMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( textStyleElem.attribute( "fontSizeMapUnitScale" ) );
1285  }
1286  int fontWeight = textStyleElem.attribute( "fontWeight" ).toInt();
1287  bool fontItalic = textStyleElem.attribute( "fontItalic" ).toInt();
1288  textFont = QFont( fontFamily, fontSize, fontWeight, fontItalic );
1289  textFont.setPointSizeF( fontSize ); //double precision needed because of map units
1290  textNamedStyle = QgsFontUtils::translateNamedStyle( textStyleElem.attribute( "namedStyle" ) );
1291  QgsFontUtils::updateFontViaStyle( textFont, textNamedStyle ); // must come after textFont.setPointSizeF()
1292  textFont.setCapitalization( static_cast< QFont::Capitalization >( textStyleElem.attribute( "fontCapitals", "0" ).toUInt() ) );
1293  textFont.setUnderline( textStyleElem.attribute( "fontUnderline" ).toInt() );
1294  textFont.setStrikeOut( textStyleElem.attribute( "fontStrikeout" ).toInt() );
1295  textFont.setLetterSpacing( QFont::AbsoluteSpacing, textStyleElem.attribute( "fontLetterSpacing", "0" ).toDouble() );
1296  textFont.setWordSpacing( textStyleElem.attribute( "fontWordSpacing", "0" ).toDouble() );
1297  textColor = QgsSymbolLayerV2Utils::decodeColor( textStyleElem.attribute( "textColor", QgsSymbolLayerV2Utils::encodeColor( Qt::black ) ) );
1298  textTransp = textStyleElem.attribute( "textTransp" ).toInt();
1300  static_cast< QgsMapRenderer::BlendMode >( textStyleElem.attribute( "blendMode", QString::number( QgsMapRenderer::BlendNormal ) ).toUInt() ) );
1301  previewBkgrdColor = QColor( textStyleElem.attribute( "previewBkgrdColor", "#ffffff" ) );
1302 
1303 
1304  // text formatting
1305  QDomElement textFormatElem = elem.firstChildElement( "text-format" );
1306  wrapChar = textFormatElem.attribute( "wrapChar" );
1307  multilineHeight = textFormatElem.attribute( "multilineHeight", "1" ).toDouble();
1308  multilineAlign = static_cast< MultiLineAlign >( textFormatElem.attribute( "multilineAlign", QString::number( MultiLeft ) ).toUInt() );
1309  addDirectionSymbol = textFormatElem.attribute( "addDirectionSymbol" ).toInt();
1310  leftDirectionSymbol = textFormatElem.attribute( "leftDirectionSymbol", "<" );
1311  rightDirectionSymbol = textFormatElem.attribute( "rightDirectionSymbol", ">" );
1312  reverseDirectionSymbol = textFormatElem.attribute( "reverseDirectionSymbol" ).toInt();
1313  placeDirectionSymbol = static_cast< DirectionSymbols >( textFormatElem.attribute( "placeDirectionSymbol", QString::number( SymbolLeftRight ) ).toUInt() );
1314  formatNumbers = textFormatElem.attribute( "formatNumbers" ).toInt();
1315  decimals = textFormatElem.attribute( "decimals" ).toInt();
1316  plusSign = textFormatElem.attribute( "plussign" ).toInt();
1317 
1318  // text buffer
1319  QDomElement textBufferElem = elem.firstChildElement( "text-buffer" );
1320  double bufSize = textBufferElem.attribute( "bufferSize", "0" ).toDouble();
1321 
1322  // fix for buffer being keyed off of just its size in the past (<2.0)
1323  QVariant drawBuffer = textBufferElem.attribute( "bufferDraw" );
1324  if ( drawBuffer.isValid() )
1325  {
1326  bufferDraw = drawBuffer.toBool();
1327  bufferSize = bufSize;
1328  }
1329  else if ( bufSize != 0.0 )
1330  {
1331  bufferDraw = true;
1332  bufferSize = bufSize;
1333  }
1334  else
1335  {
1336  // keep bufferSize at new 1.0 default
1337  bufferDraw = false;
1338  }
1339 
1340  bufferSizeInMapUnits = textBufferElem.attribute( "bufferSizeInMapUnits" ).toInt();
1341  if ( !textBufferElem.hasAttribute( "bufferSizeMapUnitScale" ) )
1342  {
1343  //fallback to older property
1344  bufferSizeMapUnitScale.minScale = textBufferElem.attribute( "bufferSizeMapUnitMinScale", "0" ).toDouble();
1345  bufferSizeMapUnitScale.maxScale = textBufferElem.attribute( "bufferSizeMapUnitMaxScale", "0" ).toDouble();
1346  }
1347  else
1348  {
1349  bufferSizeMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( textBufferElem.attribute( "bufferSizeMapUnitScale" ) );
1350  }
1351  bufferColor = QgsSymbolLayerV2Utils::decodeColor( textBufferElem.attribute( "bufferColor", QgsSymbolLayerV2Utils::encodeColor( Qt::white ) ) );
1352  bufferTransp = textBufferElem.attribute( "bufferTransp" ).toInt();
1354  static_cast< QgsMapRenderer::BlendMode >( textBufferElem.attribute( "bufferBlendMode", QString::number( QgsMapRenderer::BlendNormal ) ).toUInt() ) );
1355  bufferJoinStyle = static_cast< Qt::PenJoinStyle >( textBufferElem.attribute( "bufferJoinStyle", QString::number( Qt::BevelJoin ) ).toUInt() );
1356  bufferNoFill = textBufferElem.attribute( "bufferNoFill", "0" ).toInt();
1357 
1358  // background
1359  QDomElement backgroundElem = elem.firstChildElement( "background" );
1360  shapeDraw = backgroundElem.attribute( "shapeDraw", "0" ).toInt();
1361  shapeType = static_cast< ShapeType >( backgroundElem.attribute( "shapeType", QString::number( ShapeRectangle ) ).toUInt() );
1362  shapeSVGFile = backgroundElem.attribute( "shapeSVGFile" );
1363  shapeSizeType = static_cast< SizeType >( backgroundElem.attribute( "shapeSizeType", QString::number( SizeBuffer ) ).toUInt() );
1364  shapeSize = QPointF( backgroundElem.attribute( "shapeSizeX", "0" ).toDouble(),
1365  backgroundElem.attribute( "shapeSizeY", "0" ).toDouble() );
1366  shapeSizeUnits = static_cast< SizeUnit >( backgroundElem.attribute( "shapeSizeUnits", QString::number( MM ) ).toUInt() );
1367  if ( !backgroundElem.hasAttribute( "shapeSizeMapUnitScale" ) )
1368  {
1369  //fallback to older property
1370  shapeSizeMapUnitScale.minScale = backgroundElem.attribute( "shapeSizeMapUnitMinScale", "0" ).toDouble();
1371  shapeSizeMapUnitScale.maxScale = backgroundElem.attribute( "shapeSizeMapUnitMaxScale", "0" ).toDouble();
1372  }
1373  else
1374  {
1375  shapeSizeMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( backgroundElem.attribute( "shapeSizeMapUnitScale" ) );
1376  }
1377  shapeRotationType = static_cast< RotationType >( backgroundElem.attribute( "shapeRotationType", QString::number( RotationSync ) ).toUInt() );
1378  shapeRotation = backgroundElem.attribute( "shapeRotation", "0" ).toDouble();
1379  shapeOffset = QPointF( backgroundElem.attribute( "shapeOffsetX", "0" ).toDouble(),
1380  backgroundElem.attribute( "shapeOffsetY", "0" ).toDouble() );
1381  shapeOffsetUnits = static_cast< SizeUnit >( backgroundElem.attribute( "shapeOffsetUnits", QString::number( MM ) ).toUInt() );
1382  if ( !backgroundElem.hasAttribute( "shapeOffsetMapUnitScale" ) )
1383  {
1384  //fallback to older property
1385  shapeOffsetMapUnitScale.minScale = backgroundElem.attribute( "shapeOffsetMapUnitMinScale", "0" ).toDouble();
1386  shapeOffsetMapUnitScale.maxScale = backgroundElem.attribute( "shapeOffsetMapUnitMaxScale", "0" ).toDouble();
1387  }
1388  else
1389  {
1390  shapeOffsetMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( backgroundElem.attribute( "shapeOffsetMapUnitScale" ) );
1391  }
1392  shapeRadii = QPointF( backgroundElem.attribute( "shapeRadiiX", "0" ).toDouble(),
1393  backgroundElem.attribute( "shapeRadiiY", "0" ).toDouble() );
1394  shapeRadiiUnits = static_cast< SizeUnit >( backgroundElem.attribute( "shapeRadiiUnits", QString::number( MM ) ).toUInt() );
1395  if ( !backgroundElem.hasAttribute( "shapeRadiiMapUnitScale" ) )
1396  {
1397  //fallback to older property
1398  shapeRadiiMapUnitScale.minScale = backgroundElem.attribute( "shapeRadiiMapUnitMinScale", "0" ).toDouble();
1399  shapeRadiiMapUnitScale.maxScale = backgroundElem.attribute( "shapeRadiiMapUnitMaxScale", "0" ).toDouble();
1400  }
1401  else
1402  {
1403  shapeRadiiMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( backgroundElem.attribute( "shapeRadiiMapUnitScale" ) );
1404  }
1405  shapeFillColor = QgsSymbolLayerV2Utils::decodeColor( backgroundElem.attribute( "shapeFillColor", QgsSymbolLayerV2Utils::encodeColor( Qt::white ) ) );
1406  shapeBorderColor = QgsSymbolLayerV2Utils::decodeColor( backgroundElem.attribute( "shapeBorderColor", QgsSymbolLayerV2Utils::encodeColor( Qt::darkGray ) ) );
1407  shapeBorderWidth = backgroundElem.attribute( "shapeBorderWidth", "0" ).toDouble();
1408  shapeBorderWidthUnits = static_cast< SizeUnit >( backgroundElem.attribute( "shapeBorderWidthUnits", QString::number( MM ) ).toUInt() );
1409  if ( !backgroundElem.hasAttribute( "shapeBorderWidthMapUnitScale" ) )
1410  {
1411  //fallback to older property
1412  shapeBorderWidthMapUnitScale.minScale = backgroundElem.attribute( "shapeBorderWidthMapUnitMinScale", "0" ).toDouble();
1413  shapeBorderWidthMapUnitScale.maxScale = backgroundElem.attribute( "shapeBorderWidthMapUnitMaxScale", "0" ).toDouble();
1414  }
1415  else
1416  {
1417  shapeBorderWidthMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( backgroundElem.attribute( "shapeBorderWidthMapUnitScale" ) );
1418  }
1419  shapeJoinStyle = static_cast< Qt::PenJoinStyle >( backgroundElem.attribute( "shapeJoinStyle", QString::number( Qt::BevelJoin ) ).toUInt() );
1420  shapeTransparency = backgroundElem.attribute( "shapeTransparency", "0" ).toInt();
1422  static_cast< QgsMapRenderer::BlendMode >( backgroundElem.attribute( "shapeBlendMode", QString::number( QgsMapRenderer::BlendNormal ) ).toUInt() ) );
1423 
1424  // drop shadow
1425  QDomElement shadowElem = elem.firstChildElement( "shadow" );
1426  shadowDraw = shadowElem.attribute( "shadowDraw", "0" ).toInt();
1427  shadowUnder = static_cast< ShadowType >( shadowElem.attribute( "shadowUnder", QString::number( ShadowLowest ) ).toUInt() );//ShadowLowest ;
1428  shadowOffsetAngle = shadowElem.attribute( "shadowOffsetAngle", "135" ).toInt();
1429  shadowOffsetDist = shadowElem.attribute( "shadowOffsetDist", "1" ).toDouble();
1430  shadowOffsetUnits = static_cast< SizeUnit >( shadowElem.attribute( "shadowOffsetUnits", QString::number( MM ) ).toUInt() );
1431  if ( !shadowElem.hasAttribute( "shadowOffsetMapUnitScale" ) )
1432  {
1433  //fallback to older property
1434  shadowOffsetMapUnitScale.minScale = shadowElem.attribute( "shadowOffsetMapUnitMinScale", "0" ).toDouble();
1435  shadowOffsetMapUnitScale.maxScale = shadowElem.attribute( "shadowOffsetMapUnitMaxScale", "0" ).toDouble();
1436  }
1437  else
1438  {
1439  shadowOffsetMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( shadowElem.attribute( "shadowOffsetMapUnitScale" ) );
1440  }
1441  shadowOffsetGlobal = shadowElem.attribute( "shadowOffsetGlobal", "1" ).toInt();
1442  shadowRadius = shadowElem.attribute( "shadowRadius", "1.5" ).toDouble();
1443  shadowRadiusUnits = static_cast< SizeUnit >( shadowElem.attribute( "shadowRadiusUnits", QString::number( MM ) ).toUInt() );
1444  if ( !shadowElem.hasAttribute( "shadowRadiusMapUnitScale" ) )
1445  {
1446  //fallback to older property
1447  shadowRadiusMapUnitScale.minScale = shadowElem.attribute( "shadowRadiusMapUnitMinScale", "0" ).toDouble();
1448  shadowRadiusMapUnitScale.maxScale = shadowElem.attribute( "shadowRadiusMapUnitMaxScale", "0" ).toDouble();
1449  }
1450  else
1451  {
1452  shadowRadiusMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( shadowElem.attribute( "shadowRadiusMapUnitScale" ) );
1453  }
1454  shadowRadiusAlphaOnly = shadowElem.attribute( "shadowRadiusAlphaOnly", "0" ).toInt();
1455  shadowTransparency = shadowElem.attribute( "shadowTransparency", "30" ).toInt();
1456  shadowScale = shadowElem.attribute( "shadowScale", "100" ).toInt();
1457  shadowColor = QgsSymbolLayerV2Utils::decodeColor( shadowElem.attribute( "shadowColor", QgsSymbolLayerV2Utils::encodeColor( Qt::black ) ) );
1459  static_cast< QgsMapRenderer::BlendMode >( shadowElem.attribute( "shadowBlendMode", QString::number( QgsMapRenderer::BlendMultiply ) ).toUInt() ) );
1460 
1461  // placement
1462  QDomElement placementElem = elem.firstChildElement( "placement" );
1463  placement = static_cast< Placement >( placementElem.attribute( "placement" ).toInt() );
1464  placementFlags = placementElem.attribute( "placementFlags" ).toUInt();
1465  centroidWhole = placementElem.attribute( "centroidWhole", "0" ).toInt();
1466  centroidInside = placementElem.attribute( "centroidInside", "0" ).toInt();
1467  predefinedPositionOrder = QgsLabelingUtils::decodePredefinedPositionOrder( placementElem.attribute( "predefinedPositionOrder" ) );
1469  predefinedPositionOrder = DEFAULT_PLACEMENT_ORDER;
1470  fitInPolygonOnly = placementElem.attribute( "fitInPolygonOnly", "0" ).toInt();
1471  dist = placementElem.attribute( "dist" ).toDouble();
1472  distInMapUnits = placementElem.attribute( "distInMapUnits" ).toInt();
1473  if ( !placementElem.hasAttribute( "distMapUnitScale" ) )
1474  {
1475  //fallback to older property
1476  distMapUnitScale.minScale = placementElem.attribute( "distMapUnitMinScale", "0" ).toDouble();
1477  distMapUnitScale.maxScale = placementElem.attribute( "distMapUnitMaxScale", "0" ).toDouble();
1478  }
1479  else
1480  {
1481  distMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( placementElem.attribute( "distMapUnitScale" ) );
1482  }
1483  offsetType = static_cast< OffsetType >( placementElem.attribute( "offsetType", QString::number( FromPoint ) ).toUInt() );
1484  quadOffset = static_cast< QuadrantPosition >( placementElem.attribute( "quadOffset", QString::number( QuadrantOver ) ).toUInt() );
1485  xOffset = placementElem.attribute( "xOffset", "0" ).toDouble();
1486  yOffset = placementElem.attribute( "yOffset", "0" ).toDouble();
1487  labelOffsetInMapUnits = placementElem.attribute( "labelOffsetInMapUnits", "1" ).toInt();
1488  if ( !placementElem.hasAttribute( "labelOffsetMapUnitScale" ) )
1489  {
1490  //fallback to older property
1491  labelOffsetMapUnitScale.minScale = placementElem.attribute( "labelOffsetMapUnitMinScale", "0" ).toDouble();
1492  labelOffsetMapUnitScale.maxScale = placementElem.attribute( "labelOffsetMapUnitMaxScale", "0" ).toDouble();
1493  }
1494  else
1495  {
1496  labelOffsetMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( placementElem.attribute( "labelOffsetMapUnitScale" ) );
1497  }
1498  angleOffset = placementElem.attribute( "angleOffset", "0" ).toDouble();
1499  preserveRotation = placementElem.attribute( "preserveRotation", "1" ).toInt();
1500  maxCurvedCharAngleIn = placementElem.attribute( "maxCurvedCharAngleIn", "20" ).toDouble();
1501  maxCurvedCharAngleOut = placementElem.attribute( "maxCurvedCharAngleOut", "-20" ).toDouble();
1502  priority = placementElem.attribute( "priority" ).toInt();
1503  repeatDistance = placementElem.attribute( "repeatDistance", "0" ).toDouble();
1504  repeatDistanceUnit = static_cast< SizeUnit >( placementElem.attribute( "repeatDistanceUnit", QString::number( MM ) ).toUInt() );
1505  if ( !placementElem.hasAttribute( "repeatDistanceMapUnitScale" ) )
1506  {
1507  //fallback to older property
1508  repeatDistanceMapUnitScale.minScale = placementElem.attribute( "repeatDistanceMapUnitMinScale", "0" ).toDouble();
1509  repeatDistanceMapUnitScale.maxScale = placementElem.attribute( "repeatDistanceMapUnitMaxScale", "0" ).toDouble();
1510  }
1511  else
1512  {
1513  repeatDistanceMapUnitScale = QgsSymbolLayerV2Utils::decodeMapUnitScale( placementElem.attribute( "repeatDistanceMapUnitScale" ) );
1514  }
1515 
1516  // rendering
1517  QDomElement renderingElem = elem.firstChildElement( "rendering" );
1518  scaleMin = renderingElem.attribute( "scaleMin", "0" ).toInt();
1519  scaleMax = renderingElem.attribute( "scaleMax", "0" ).toInt();
1520  scaleVisibility = renderingElem.attribute( "scaleVisibility" ).toInt();
1521 
1522  fontLimitPixelSize = renderingElem.attribute( "fontLimitPixelSize", "0" ).toInt();
1523  fontMinPixelSize = renderingElem.attribute( "fontMinPixelSize", "0" ).toInt();
1524  fontMaxPixelSize = renderingElem.attribute( "fontMaxPixelSize", "10000" ).toInt();
1525  displayAll = renderingElem.attribute( "displayAll", "0" ).toInt();
1526  upsidedownLabels = static_cast< UpsideDownLabels >( renderingElem.attribute( "upsidedownLabels", QString::number( Upright ) ).toUInt() );
1527 
1528  labelPerPart = renderingElem.attribute( "labelPerPart" ).toInt();
1529  mergeLines = renderingElem.attribute( "mergeLines" ).toInt();
1530  minFeatureSize = renderingElem.attribute( "minFeatureSize" ).toDouble();
1531  limitNumLabels = renderingElem.attribute( "limitNumLabels", "0" ).toInt();
1532  maxNumLabels = renderingElem.attribute( "maxNumLabels", "2000" ).toInt();
1533  obstacle = renderingElem.attribute( "obstacle", "1" ).toInt();
1534  obstacleFactor = renderingElem.attribute( "obstacleFactor", "1" ).toDouble();
1535  obstacleType = static_cast< ObstacleType >( renderingElem.attribute( "obstacleType", QString::number( PolygonInterior ) ).toUInt() );
1536  zIndex = renderingElem.attribute( "zIndex", "0.0" ).toDouble();
1537 
1538  QDomElement ddElem = elem.firstChildElement( "data-defined" );
1539  readDataDefinedPropertyMap( nullptr, &ddElem, dataDefinedProperties );
1540 }
1541 
1542 
1543 
1545 {
1546  // we assume (enabled == true && drawLabels == true) so those are not saved
1547 
1548  // text style
1549  QDomElement textStyleElem = doc.createElement( "text-style" );
1550  textStyleElem.setAttribute( "fieldName", fieldName );
1551  textStyleElem.setAttribute( "isExpression", isExpression );
1552  textStyleElem.setAttribute( "fontFamily", textFont.family() );
1553  textStyleElem.setAttribute( "namedStyle", QgsFontUtils::untranslateNamedStyle( textNamedStyle ) );
1554  textStyleElem.setAttribute( "fontSize", textFont.pointSizeF() );
1555  textStyleElem.setAttribute( "fontSizeInMapUnits", fontSizeInMapUnits );
1556  textStyleElem.setAttribute( "fontSizeMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( fontSizeMapUnitScale ) );
1557  textStyleElem.setAttribute( "fontWeight", textFont.weight() );
1558  textStyleElem.setAttribute( "fontItalic", textFont.italic() );
1559  textStyleElem.setAttribute( "fontStrikeout", textFont.strikeOut() );
1560  textStyleElem.setAttribute( "fontUnderline", textFont.underline() );
1561  textStyleElem.setAttribute( "textColor", QgsSymbolLayerV2Utils::encodeColor( textColor ) );
1562  textStyleElem.setAttribute( "fontCapitals", static_cast< unsigned int >( textFont.capitalization() ) );
1563  textStyleElem.setAttribute( "fontLetterSpacing", textFont.letterSpacing() );
1564  textStyleElem.setAttribute( "fontWordSpacing", textFont.wordSpacing() );
1565  textStyleElem.setAttribute( "textTransp", textTransp );
1566  textStyleElem.setAttribute( "blendMode", QgsMapRenderer::getBlendModeEnum( blendMode ) );
1567  textStyleElem.setAttribute( "previewBkgrdColor", previewBkgrdColor.name() );
1568 
1569  // text formatting
1570  QDomElement textFormatElem = doc.createElement( "text-format" );
1571  textFormatElem.setAttribute( "wrapChar", wrapChar );
1572  textFormatElem.setAttribute( "multilineHeight", multilineHeight );
1573  textFormatElem.setAttribute( "multilineAlign", static_cast< unsigned int >( multilineAlign ) );
1574  textFormatElem.setAttribute( "addDirectionSymbol", addDirectionSymbol );
1575  textFormatElem.setAttribute( "leftDirectionSymbol", leftDirectionSymbol );
1576  textFormatElem.setAttribute( "rightDirectionSymbol", rightDirectionSymbol );
1577  textFormatElem.setAttribute( "reverseDirectionSymbol", reverseDirectionSymbol );
1578  textFormatElem.setAttribute( "placeDirectionSymbol", static_cast< unsigned int >( placeDirectionSymbol ) );
1579  textFormatElem.setAttribute( "formatNumbers", formatNumbers );
1580  textFormatElem.setAttribute( "decimals", decimals );
1581  textFormatElem.setAttribute( "plussign", plusSign );
1582 
1583  // text buffer
1584  QDomElement textBufferElem = doc.createElement( "text-buffer" );
1585  textBufferElem.setAttribute( "bufferDraw", bufferDraw );
1586  textBufferElem.setAttribute( "bufferSize", bufferSize );
1587  textBufferElem.setAttribute( "bufferSizeInMapUnits", bufferSizeInMapUnits );
1588  textBufferElem.setAttribute( "bufferSizeMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( bufferSizeMapUnitScale ) );
1589  textBufferElem.setAttribute( "bufferColor", QgsSymbolLayerV2Utils::encodeColor( bufferColor ) );
1590  textBufferElem.setAttribute( "bufferNoFill", bufferNoFill );
1591  textBufferElem.setAttribute( "bufferTransp", bufferTransp );
1592  textBufferElem.setAttribute( "bufferJoinStyle", static_cast< unsigned int >( bufferJoinStyle ) );
1593  textBufferElem.setAttribute( "bufferBlendMode", QgsMapRenderer::getBlendModeEnum( bufferBlendMode ) );
1594 
1595  // background
1596  QDomElement backgroundElem = doc.createElement( "background" );
1597  backgroundElem.setAttribute( "shapeDraw", shapeDraw );
1598  backgroundElem.setAttribute( "shapeType", static_cast< unsigned int >( shapeType ) );
1599  backgroundElem.setAttribute( "shapeSVGFile", shapeSVGFile );
1600  backgroundElem.setAttribute( "shapeSizeType", static_cast< unsigned int >( shapeSizeType ) );
1601  backgroundElem.setAttribute( "shapeSizeX", shapeSize.x() );
1602  backgroundElem.setAttribute( "shapeSizeY", shapeSize.y() );
1603  backgroundElem.setAttribute( "shapeSizeUnits", static_cast< unsigned int >( shapeSizeUnits ) );
1604  backgroundElem.setAttribute( "shapeSizeMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shapeSizeMapUnitScale ) );
1605  backgroundElem.setAttribute( "shapeRotationType", static_cast< unsigned int >( shapeRotationType ) );
1606  backgroundElem.setAttribute( "shapeRotation", shapeRotation );
1607  backgroundElem.setAttribute( "shapeOffsetX", shapeOffset.x() );
1608  backgroundElem.setAttribute( "shapeOffsetY", shapeOffset.y() );
1609  backgroundElem.setAttribute( "shapeOffsetUnits", static_cast< unsigned int >( shapeOffsetUnits ) );
1610  backgroundElem.setAttribute( "shapeOffsetMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shapeOffsetMapUnitScale ) );
1611  backgroundElem.setAttribute( "shapeRadiiX", shapeRadii.x() );
1612  backgroundElem.setAttribute( "shapeRadiiY", shapeRadii.y() );
1613  backgroundElem.setAttribute( "shapeRadiiUnits", static_cast< unsigned int >( shapeRadiiUnits ) );
1614  backgroundElem.setAttribute( "shapeRadiiMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shapeRadiiMapUnitScale ) );
1615  backgroundElem.setAttribute( "shapeFillColor", QgsSymbolLayerV2Utils::encodeColor( shapeFillColor ) );
1616  backgroundElem.setAttribute( "shapeBorderColor", QgsSymbolLayerV2Utils::encodeColor( shapeBorderColor ) );
1617  backgroundElem.setAttribute( "shapeBorderWidth", shapeBorderWidth );
1618  backgroundElem.setAttribute( "shapeBorderWidthUnits", static_cast< unsigned int >( shapeBorderWidthUnits ) );
1619  backgroundElem.setAttribute( "shapeBorderWidthMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shapeBorderWidthMapUnitScale ) );
1620  backgroundElem.setAttribute( "shapeJoinStyle", static_cast< unsigned int >( shapeJoinStyle ) );
1621  backgroundElem.setAttribute( "shapeTransparency", shapeTransparency );
1622  backgroundElem.setAttribute( "shapeBlendMode", QgsMapRenderer::getBlendModeEnum( shapeBlendMode ) );
1623 
1624  // drop shadow
1625  QDomElement shadowElem = doc.createElement( "shadow" );
1626  shadowElem.setAttribute( "shadowDraw", shadowDraw );
1627  shadowElem.setAttribute( "shadowUnder", static_cast< unsigned int >( shadowUnder ) );
1628  shadowElem.setAttribute( "shadowOffsetAngle", shadowOffsetAngle );
1629  shadowElem.setAttribute( "shadowOffsetDist", shadowOffsetDist );
1630  shadowElem.setAttribute( "shadowOffsetUnits", static_cast< unsigned int >( shadowOffsetUnits ) );
1631  shadowElem.setAttribute( "shadowOffsetMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shadowOffsetMapUnitScale ) );
1632  shadowElem.setAttribute( "shadowOffsetGlobal", shadowOffsetGlobal );
1633  shadowElem.setAttribute( "shadowRadius", shadowRadius );
1634  shadowElem.setAttribute( "shadowRadiusUnits", static_cast< unsigned int >( shadowRadiusUnits ) );
1635  shadowElem.setAttribute( "shadowRadiusMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( shadowRadiusMapUnitScale ) );
1636  shadowElem.setAttribute( "shadowRadiusAlphaOnly", shadowRadiusAlphaOnly );
1637  shadowElem.setAttribute( "shadowTransparency", shadowTransparency );
1638  shadowElem.setAttribute( "shadowScale", shadowScale );
1639  shadowElem.setAttribute( "shadowColor", QgsSymbolLayerV2Utils::encodeColor( shadowColor ) );
1640  shadowElem.setAttribute( "shadowBlendMode", QgsMapRenderer::getBlendModeEnum( shadowBlendMode ) );
1641 
1642  // placement
1643  QDomElement placementElem = doc.createElement( "placement" );
1644  placementElem.setAttribute( "placement", placement );
1645  placementElem.setAttribute( "placementFlags", static_cast< unsigned int >( placementFlags ) );
1646  placementElem.setAttribute( "centroidWhole", centroidWhole );
1647  placementElem.setAttribute( "centroidInside", centroidInside );
1648  placementElem.setAttribute( "predefinedPositionOrder", QgsLabelingUtils::encodePredefinedPositionOrder( predefinedPositionOrder ) );
1649  placementElem.setAttribute( "fitInPolygonOnly", fitInPolygonOnly );
1650  placementElem.setAttribute( "dist", dist );
1651  placementElem.setAttribute( "distInMapUnits", distInMapUnits );
1652  placementElem.setAttribute( "distMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( distMapUnitScale ) );
1653  placementElem.setAttribute( "offsetType", static_cast< unsigned int >( offsetType ) );
1654  placementElem.setAttribute( "quadOffset", static_cast< unsigned int >( quadOffset ) );
1655  placementElem.setAttribute( "xOffset", xOffset );
1656  placementElem.setAttribute( "yOffset", yOffset );
1657  placementElem.setAttribute( "labelOffsetInMapUnits", labelOffsetInMapUnits );
1658  placementElem.setAttribute( "labelOffsetMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( labelOffsetMapUnitScale ) );
1659  placementElem.setAttribute( "angleOffset", angleOffset );
1660  placementElem.setAttribute( "preserveRotation", preserveRotation );
1661  placementElem.setAttribute( "maxCurvedCharAngleIn", maxCurvedCharAngleIn );
1662  placementElem.setAttribute( "maxCurvedCharAngleOut", maxCurvedCharAngleOut );
1663  placementElem.setAttribute( "priority", priority );
1664  placementElem.setAttribute( "repeatDistance", repeatDistance );
1665  placementElem.setAttribute( "repeatDistanceUnit", repeatDistanceUnit );
1666  placementElem.setAttribute( "repeatDistanceMapUnitScale", QgsSymbolLayerV2Utils::encodeMapUnitScale( repeatDistanceMapUnitScale ) );
1667 
1668  // rendering
1669  QDomElement renderingElem = doc.createElement( "rendering" );
1670  renderingElem.setAttribute( "scaleVisibility", scaleVisibility );
1671  renderingElem.setAttribute( "scaleMin", scaleMin );
1672  renderingElem.setAttribute( "scaleMax", scaleMax );
1673  renderingElem.setAttribute( "fontLimitPixelSize", fontLimitPixelSize );
1674  renderingElem.setAttribute( "fontMinPixelSize", fontMinPixelSize );
1675  renderingElem.setAttribute( "fontMaxPixelSize", fontMaxPixelSize );
1676  renderingElem.setAttribute( "displayAll", displayAll );
1677  renderingElem.setAttribute( "upsidedownLabels", static_cast< unsigned int >( upsidedownLabels ) );
1678 
1679  renderingElem.setAttribute( "labelPerPart", labelPerPart );
1680  renderingElem.setAttribute( "mergeLines", mergeLines );
1681  renderingElem.setAttribute( "minFeatureSize", minFeatureSize );
1682  renderingElem.setAttribute( "limitNumLabels", limitNumLabels );
1683  renderingElem.setAttribute( "maxNumLabels", maxNumLabels );
1684  renderingElem.setAttribute( "obstacle", obstacle );
1685  renderingElem.setAttribute( "obstacleFactor", obstacleFactor );
1686  renderingElem.setAttribute( "obstacleType", static_cast< unsigned int >( obstacleType ) );
1687  renderingElem.setAttribute( "zIndex", zIndex );
1688 
1689  QDomElement ddElem = doc.createElement( "data-defined" );
1690  writeDataDefinedPropertyMap( nullptr, &ddElem, dataDefinedProperties );
1691 
1692  QDomElement elem = doc.createElement( "settings" );
1693  elem.appendChild( textStyleElem );
1694  elem.appendChild( textFormatElem );
1695  elem.appendChild( textBufferElem );
1696  elem.appendChild( backgroundElem );
1697  elem.appendChild( shadowElem );
1698  elem.appendChild( placementElem );
1699  elem.appendChild( renderingElem );
1700  elem.appendChild( ddElem );
1701  return elem;
1702 }
1703 
1705  bool active, bool useExpr, const QString& expr, const QString& field )
1706 {
1707  bool defaultVals = ( !active && !useExpr && expr.isEmpty() && field.isEmpty() );
1708 
1709  if ( dataDefinedProperties.contains( p ) )
1710  {
1712  if ( it != dataDefinedProperties.constEnd() )
1713  {
1714  QgsDataDefined* dd = it.value();
1715  dd->setActive( active );
1716  dd->setExpressionString( expr );
1717  dd->setField( field );
1718  dd->setUseExpression( useExpr );
1719  }
1720  }
1721  else if ( !defaultVals )
1722  {
1723  QgsDataDefined* dd = new QgsDataDefined( active, useExpr, expr, field );
1724  dataDefinedProperties.insert( p, dd );
1725  }
1726 }
1727 
1729 {
1731  if ( it != dataDefinedProperties.end() )
1732  {
1733  delete( it.value() );
1735  }
1736 }
1737 
1739 {
1740  qDeleteAll( dataDefinedProperties );
1742 }
1743 
1745 {
1746  // TODO: update or remove this when project settings for labeling are migrated to better XML layout
1747  QString newValue = value;
1748  if ( !value.isEmpty() && !value.contains( "~~" ) )
1749  {
1750  QStringList values;
1751  values << "1"; // all old-style values are active if not empty
1752  values << "0";
1753  values << "";
1754  values << value; // all old-style values are only field names
1755  newValue = values.join( "~~" );
1756  }
1757 
1758  return newValue;
1759 }
1760 
1762 {
1764  return nullptr;
1765 
1767  if ( it != dataDefinedProperties.constEnd() )
1768  {
1769  return it.value();
1770  }
1771  return nullptr;
1772 }
1773 
1775 {
1778  if ( it != dataDefinedProperties.constEnd() )
1779  {
1780  return it.value()->toMap();
1781  }
1782  return map;
1783 }
1784 
1786 {
1788  {
1789  return QVariant();
1790  }
1791 
1792  //try to keep < 2.12 API - handle no passed expression context
1794  if ( !context )
1795  {
1796  scopedEc.reset( new QgsExpressionContext() );
1797  scopedEc->setFeature( f );
1798  scopedEc->setFields( fields );
1799  }
1800  const QgsExpressionContext* ec = context ? context : scopedEc.data();
1801 
1802  QgsDataDefined* dd = nullptr;
1804  if ( it != dataDefinedProperties.constEnd() )
1805  {
1806  dd = it.value();
1807  }
1808 
1809  if ( !dd )
1810  {
1811  return QVariant();
1812  }
1813 
1814  if ( !dd->isActive() )
1815  {
1816  return QVariant();
1817  }
1818 
1819  QVariant result = QVariant();
1820  bool useExpression = dd->useExpression();
1821  QString field = dd->field();
1822 
1823  //QgsDebugMsgLevel( QString( "isActive:" ) + isActive ? "1" : "0", 4 );
1824  //QgsDebugMsgLevel( QString( "useExpression:" ) + useExpression ? "1" : "0", 4 );
1825  //QgsDebugMsgLevel( QString( "expression:" ) + dd->expressionString(), 4 );
1826  //QgsDebugMsgLevel( QString( "field:" ) + field, 4 );
1827 
1828  if ( useExpression && dd->expressionIsPrepared() )
1829  {
1830  QgsExpression* expr = dd->expression();
1831  //QgsDebugMsgLevel( QString( "expr columns:" ) + expr->referencedColumns().join( "," ), 4 );
1832 
1833  result = expr->evaluate( ec );
1834  if ( expr->hasEvalError() )
1835  {
1836  QgsDebugMsgLevel( QString( "Evaluate error:" ) + expr->evalErrorString(), 4 );
1837  return QVariant();
1838  }
1839  }
1840  else if ( !useExpression && !field.isEmpty() )
1841  {
1842  // use direct attribute access instead of evaluating "field" expression (much faster)
1843  int indx = fields.indexFromName( field );
1844  if ( indx != -1 )
1845  {
1846  result = f.attribute( indx );
1847  }
1848  }
1849  return result;
1850 }
1851 
1853 {
1854  // null passed-around QVariant
1855  exprVal.clear();
1857  return false;
1858 
1859  //try to keep < 2.12 API - handle no passed expression context
1861  if ( !context )
1862  {
1863  scopedEc.reset( new QgsExpressionContext() );
1864  scopedEc->setFeature( *mCurFeat );
1865  scopedEc->setFields( mCurFields );
1866  }
1867  QgsExpressionContext* ec = context ? context : scopedEc.data();
1868 
1869  ec->setOriginalValueVariable( originalValue );
1870  QVariant result = dataDefinedValue( p, *mCurFeat, mCurFields, ec );
1871 
1872  if ( result.isValid() && !result.isNull() )
1873  {
1874  //QgsDebugMsgLevel( QString( "result type:" ) + QString( result.typeName() ), 4 );
1875  //QgsDebugMsgLevel( QString( "result string:" ) + result.toString(), 4 );
1876  exprVal = result;
1877  return true;
1878  }
1879 
1880  return false;
1881 }
1882 
1884 {
1886  return false;
1887 
1888  bool isActive = false;
1889 
1891  if ( it != dataDefinedProperties.constEnd() )
1892  {
1893  isActive = it.value()->isActive();
1894  }
1895 
1896  return isActive;
1897 }
1898 
1900 {
1902  return false;
1903 
1904  bool useExpression = false;
1906  if ( it != dataDefinedProperties.constEnd() )
1907  {
1908  useExpression = it.value()->useExpression();
1909  }
1910 
1911  return useExpression;
1912 }
1913 
1914 bool QgsPalLayerSettings::checkMinimumSizeMM( const QgsRenderContext& ct, const QgsGeometry* geom, double minSize ) const
1915 {
1916  return QgsPalLabeling::checkMinimumSizeMM( ct, geom, minSize );
1917 }
1918 
1919 void QgsPalLayerSettings::calculateLabelSize( const QFontMetricsF* fm, QString text, double& labelX, double& labelY, QgsFeature* f, QgsRenderContext *context )
1920 {
1921  if ( !fm || !f )
1922  {
1923  return;
1924  }
1925 
1926  //try to keep < 2.12 API - handle no passed render context
1928  if ( !context )
1929  {
1930  scopedRc.reset( new QgsRenderContext() );
1931  if ( f )
1932  scopedRc->expressionContext().setFeature( *f );
1933  }
1934  QgsRenderContext* rc = context ? context : scopedRc.data();
1935 
1936  QString wrapchr = wrapChar;
1937  double multilineH = multilineHeight;
1938 
1939  bool addDirSymb = addDirectionSymbol;
1940  QString leftDirSymb = leftDirectionSymbol;
1941  QString rightDirSymb = rightDirectionSymbol;
1943 
1944  if ( f == mCurFeat ) // called internally, use any stored data defined values
1945  {
1946  if ( dataDefinedValues.contains( QgsPalLayerSettings::MultiLineWrapChar ) )
1947  {
1948  wrapchr = dataDefinedValues.value( QgsPalLayerSettings::MultiLineWrapChar ).toString();
1949  }
1950 
1951  if ( dataDefinedValues.contains( QgsPalLayerSettings::MultiLineHeight ) )
1952  {
1953  multilineH = dataDefinedValues.value( QgsPalLayerSettings::MultiLineHeight ).toDouble();
1954  }
1955 
1956  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbDraw ) )
1957  {
1958  addDirSymb = dataDefinedValues.value( QgsPalLayerSettings::DirSymbDraw ).toBool();
1959  }
1960 
1961  if ( addDirSymb )
1962  {
1963 
1964  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbLeft ) )
1965  {
1966  leftDirSymb = dataDefinedValues.value( QgsPalLayerSettings::DirSymbLeft ).toString();
1967  }
1968  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbRight ) )
1969  {
1970  rightDirSymb = dataDefinedValues.value( QgsPalLayerSettings::DirSymbRight ).toString();
1971  }
1972 
1973  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbPlacement ) )
1974  {
1975  placeDirSymb = static_cast< QgsPalLayerSettings::DirectionSymbols >( dataDefinedValues.value( QgsPalLayerSettings::DirSymbPlacement ).toInt() );
1976  }
1977 
1978  }
1979 
1980  }
1981  else // called externally with passed-in feature, evaluate data defined
1982  {
1985  if ( exprVal.isValid() )
1986  {
1987  wrapchr = exprVal.toString();
1988  }
1989  exprVal.clear();
1990  rc->expressionContext().setOriginalValueVariable( multilineH );
1992  if ( exprVal.isValid() )
1993  {
1994  bool ok;
1995  double size = exprVal.toDouble( &ok );
1996  if ( ok )
1997  {
1998  multilineH = size;
1999  }
2000  }
2001 
2002  exprVal.clear();
2003  rc->expressionContext().setOriginalValueVariable( addDirSymb );
2005  if ( exprVal.isValid() )
2006  {
2007  addDirSymb = exprVal.toBool();
2008  }
2009 
2010  if ( addDirSymb ) // don't do extra evaluations if not adding a direction symbol
2011  {
2012  exprVal.clear();
2013  rc->expressionContext().setOriginalValueVariable( leftDirSymb );
2015  if ( exprVal.isValid() )
2016  {
2017  leftDirSymb = exprVal.toString();
2018  }
2019  exprVal.clear();
2020  rc->expressionContext().setOriginalValueVariable( rightDirSymb );
2022  if ( exprVal.isValid() )
2023  {
2024  rightDirSymb = exprVal.toString();
2025  }
2026  exprVal.clear();
2027  rc->expressionContext().setOriginalValueVariable( static_cast< int >( placeDirSymb ) );
2029  if ( exprVal.isValid() )
2030  {
2031  bool ok;
2032  int enmint = exprVal.toInt( &ok );
2033  if ( ok )
2034  {
2035  placeDirSymb = static_cast< QgsPalLayerSettings::DirectionSymbols >( enmint );
2036  }
2037  }
2038  }
2039 
2040  }
2041 
2042  if ( wrapchr.isEmpty() )
2043  {
2044  wrapchr = QLatin1String( "\n" ); // default to new line delimiter
2045  }
2046 
2047  //consider the space needed for the direction symbol
2048  if ( addDirSymb && placement == QgsPalLayerSettings::Line
2049  && ( !leftDirSymb.isEmpty() || !rightDirSymb.isEmpty() ) )
2050  {
2051  QString dirSym = leftDirSymb;
2052 
2053  if ( fm->width( rightDirSymb ) > fm->width( dirSym ) )
2054  dirSym = rightDirSymb;
2055 
2056  if ( placeDirSymb == QgsPalLayerSettings::SymbolLeftRight )
2057  {
2058  text.append( dirSym );
2059  }
2060  else
2061  {
2062  text.prepend( dirSym + QLatin1String( "\n" ) ); // SymbolAbove or SymbolBelow
2063  }
2064  }
2065 
2066  double w = 0.0, h = 0.0;
2067  QStringList multiLineSplit = QgsPalLabeling::splitToLines( text, wrapchr );
2068  int lines = multiLineSplit.size();
2069 
2070  double labelHeight = fm->ascent() + fm->descent(); // ignore +1 for baseline
2071 
2072  h += fm->height() + static_cast< double >(( lines - 1 ) * labelHeight * multilineH );
2073  h /= rasterCompressFactor;
2074 
2075  for ( int i = 0; i < lines; ++i )
2076  {
2077  double width = fm->width( multiLineSplit.at( i ) );
2078  if ( width > w )
2079  {
2080  w = width;
2081  }
2082  }
2083  w /= rasterCompressFactor;
2084 
2085 #if 0 // XXX strk
2086  QgsPoint ptSize = xform->toMapCoordinatesF( w, h );
2087  labelX = qAbs( ptSize.x() - ptZero.x() );
2088  labelY = qAbs( ptSize.y() - ptZero.y() );
2089 #else
2090  double uPP = xform->mapUnitsPerPixel();
2091  labelX = w * uPP;
2092  labelY = h * uPP;
2093 #endif
2094 }
2095 
2096 void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &context, const QString& dxfLayer, QgsLabelFeature** labelFeature , QgsGeometry* obstacleGeometry )
2097 {
2098  // either used in QgsPalLabeling (palLayer is set) or in QgsLabelingEngineV2 (labelFeature is set)
2099  Q_ASSERT( labelFeature );
2100 
2101  Q_UNUSED( dxfLayer ); // now handled in QgsDxfLabelProvider
2102 
2103  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2104  mCurFeat = &f;
2105 
2106  // data defined is obstacle? calculate this first, to avoid wasting time working with obstacles we don't require
2107  bool isObstacle = obstacle; // start with layer default
2109  {
2110  isObstacle = exprVal.toBool();
2111  }
2112 
2113  if ( !drawLabels )
2114  {
2115  if ( isObstacle )
2116  {
2117  registerObstacleFeature( f, context, QString(), labelFeature, obstacleGeometry );
2118  }
2119  return;
2120  }
2121 
2122 // mCurFields = &layer->pendingFields();
2123 
2124  // store data defined-derived values for later adding to label feature for use during rendering
2125  dataDefinedValues.clear();
2126 
2127  // data defined show label? defaults to show label if not 0
2129  {
2130  bool showLabel = dataDefinedEvaluate( QgsPalLayerSettings::Show, exprVal, &context.expressionContext(), true );
2131  showLabel &= exprVal.toBool();
2132  QgsDebugMsgLevel( QString( "exprVal Show:%1" ).arg( showLabel ? "true" : "false" ), 4 );
2133  if ( !showLabel )
2134  {
2135  return;
2136  }
2137  }
2138 
2139  // data defined scale visibility?
2140  bool useScaleVisibility = scaleVisibility;
2142  {
2143  QgsDebugMsgLevel( QString( "exprVal ScaleVisibility:%1" ).arg( exprVal.toBool() ? "true" : "false" ), 4 );
2144  useScaleVisibility = exprVal.toBool();
2145  }
2146 
2147  if ( useScaleVisibility )
2148  {
2149  // data defined min scale?
2150  double minScale = scaleMin;
2152  {
2153  QgsDebugMsgLevel( QString( "exprVal MinScale:%1" ).arg( exprVal.toDouble() ), 4 );
2154  bool conversionOk;
2155  double mins = exprVal.toDouble( &conversionOk );
2156  if ( conversionOk )
2157  {
2158  minScale = mins;
2159  }
2160  }
2161 
2162  // scales closer than 1:1
2163  if ( minScale < 0 )
2164  {
2165  minScale = 1 / qAbs( minScale );
2166  }
2167 
2168  if ( !qgsDoubleNear( minScale, 0.0 ) && context.rendererScale() < minScale )
2169  {
2170  return;
2171  }
2172 
2173  // data defined max scale?
2174  double maxScale = scaleMax;
2176  {
2177  QgsDebugMsgLevel( QString( "exprVal MaxScale:%1" ).arg( exprVal.toDouble() ), 4 );
2178  bool conversionOk;
2179  double maxs = exprVal.toDouble( &conversionOk );
2180  if ( conversionOk )
2181  {
2182  maxScale = maxs;
2183  }
2184  }
2185 
2186  // scales closer than 1:1
2187  if ( maxScale < 0 )
2188  {
2189  maxScale = 1 / qAbs( maxScale );
2190  }
2191 
2192  if ( !qgsDoubleNear( maxScale, 0.0 ) && context.rendererScale() > maxScale )
2193  {
2194  return;
2195  }
2196  }
2197 
2198  QFont labelFont = textFont;
2199  // labelFont will be added to label feature for use during label painting
2200 
2201  // data defined font units?
2204  {
2205  QString units = exprVal.toString().trimmed();
2206  QgsDebugMsgLevel( QString( "exprVal Font units:%1" ).arg( units ), 4 );
2207  if ( !units.isEmpty() )
2208  {
2209  fontunits = _decodeUnits( units );
2210  }
2211  }
2212 
2213  //data defined label size?
2214  double fontSize = labelFont.pointSizeF(); // font size doesn't have its own class data member
2215  if ( dataDefinedEvaluate( QgsPalLayerSettings::Size, exprVal, &context.expressionContext(), fontSize ) )
2216  {
2217  QgsDebugMsgLevel( QString( "exprVal Size:%1" ).arg( exprVal.toDouble() ), 4 );
2218  bool ok;
2219  double size = exprVal.toDouble( &ok );
2220  if ( ok )
2221  {
2222  fontSize = size;
2223  }
2224  }
2225  if ( fontSize <= 0.0 )
2226  {
2227  return;
2228  }
2229 
2230  int fontPixelSize = sizeToPixel( fontSize, context, fontunits, true, fontSizeMapUnitScale );
2231  // don't try to show font sizes less than 1 pixel (Qt complains)
2232  if ( fontPixelSize < 1 )
2233  {
2234  return;
2235  }
2236  labelFont.setPixelSize( fontPixelSize );
2237 
2238  // NOTE: labelFont now always has pixelSize set, so pointSize or pointSizeF might return -1
2239 
2240  // defined 'minimum/maximum pixel font size'?
2241  if ( fontunits == QgsPalLayerSettings::MapUnits )
2242  {
2243  bool useFontLimitPixelSize = fontLimitPixelSize;
2245  {
2246  QgsDebugMsgLevel( QString( "exprVal FontLimitPixel:%1" ).arg( exprVal.toBool() ? "true" : "false" ), 4 );
2247  useFontLimitPixelSize = exprVal.toBool();
2248  }
2249 
2250  if ( useFontLimitPixelSize )
2251  {
2252  int fontMinPixel = fontMinPixelSize;
2254  {
2255  bool ok;
2256  int sizeInt = exprVal.toInt( &ok );
2257  QgsDebugMsgLevel( QString( "exprVal FontMinPixel:%1" ).arg( sizeInt ), 4 );
2258  if ( ok )
2259  {
2260  fontMinPixel = sizeInt;
2261  }
2262  }
2263 
2264  int fontMaxPixel = fontMaxPixelSize;
2266  {
2267  bool ok;
2268  int sizeInt = exprVal.toInt( &ok );
2269  QgsDebugMsgLevel( QString( "exprVal FontMaxPixel:%1" ).arg( sizeInt ), 4 );
2270  if ( ok )
2271  {
2272  fontMaxPixel = sizeInt;
2273  }
2274  }
2275 
2276  if ( fontMinPixel > labelFont.pixelSize() || labelFont.pixelSize() > fontMaxPixel )
2277  {
2278  return;
2279  }
2280  }
2281  }
2282 
2283  // NOTE: the following parsing functions calculate and store any data defined values for later use in QgsPalLabeling::drawLabeling
2284  // this is done to provide clarity, and because such parsing is not directly related to PAL feature registration calculations
2285 
2286  // calculate rest of font attributes and store any data defined values
2287  // this is done here for later use in making label backgrounds part of collision management (when implemented)
2288  parseTextStyle( labelFont, fontunits, context );
2289  parseTextFormatting( context );
2290  parseTextBuffer( context );
2291  parseShapeBackground( context );
2292  parseDropShadow( context );
2293 
2294  QString labelText;
2295 
2296  // Check to see if we are a expression string.
2297  if ( isExpression )
2298  {
2300  if ( exp->hasParserError() )
2301  {
2302  QgsDebugMsgLevel( QString( "Expression parser error:%1" ).arg( exp->parserErrorString() ), 4 );
2303  return;
2304  }
2305  exp->setScale( context.rendererScale() );
2306 // QVariant result = exp->evaluate( &f, layer->pendingFields() );
2307  QVariant result = exp->evaluate( &context.expressionContext() ); // expression prepared in QgsPalLabeling::prepareLayer()
2308  if ( exp->hasEvalError() )
2309  {
2310  QgsDebugMsgLevel( QString( "Expression parser eval error:%1" ).arg( exp->evalErrorString() ), 4 );
2311  return;
2312  }
2313  labelText = result.isNull() ? "" : result.toString();
2314  }
2315  else
2316  {
2317  const QVariant &v = f.attribute( fieldIndex );
2318  labelText = v.isNull() ? "" : v.toString();
2319  }
2320 
2321  // data defined format numbers?
2322  bool formatnum = formatNumbers;
2324  {
2325  formatnum = exprVal.toBool();
2326  QgsDebugMsgLevel( QString( "exprVal NumFormat:%1" ).arg( formatnum ? "true" : "false" ), 4 );
2327  }
2328 
2329  // format number if label text is coercible to a number
2330  if ( formatnum )
2331  {
2332  // data defined decimal places?
2333  int decimalPlaces = decimals;
2335  {
2336  bool ok;
2337  int dInt = exprVal.toInt( &ok );
2338  QgsDebugMsgLevel( QString( "exprVal NumDecimals:%1" ).arg( dInt ), 4 );
2339  if ( ok && dInt > 0 ) // needs to be positive
2340  {
2341  decimalPlaces = dInt;
2342  }
2343  }
2344 
2345  // data defined plus sign?
2346  bool signPlus = plusSign;
2348  {
2349  signPlus = exprVal.toBool();
2350  QgsDebugMsgLevel( QString( "exprVal NumPlusSign:%1" ).arg( signPlus ? "true" : "false" ), 4 );
2351  }
2352 
2353  QVariant textV( labelText );
2354  bool ok;
2355  double d = textV.toDouble( &ok );
2356  if ( ok )
2357  {
2358  QString numberFormat;
2359  if ( d > 0 && signPlus )
2360  {
2361  numberFormat.append( '+' );
2362  }
2363  numberFormat.append( "%1" );
2364  labelText = numberFormat.arg( d, 0, 'f', decimalPlaces );
2365  }
2366  }
2367 
2368 
2369  // NOTE: this should come AFTER any option that affects font metrics
2370  QScopedPointer<QFontMetricsF> labelFontMetrics( new QFontMetricsF( labelFont ) );
2371  double labelX, labelY; // will receive label size
2372  calculateLabelSize( labelFontMetrics.data(), labelText, labelX, labelY, mCurFeat, &context );
2373 
2374 
2375  // maximum angle between curved label characters (hardcoded defaults used in QGIS <2.0)
2376  //
2377  double maxcharanglein = 20.0; // range 20.0-60.0
2378  double maxcharangleout = -20.0; // range 20.0-95.0
2379 
2381  {
2382  maxcharanglein = maxCurvedCharAngleIn;
2383  maxcharangleout = maxCurvedCharAngleOut;
2384 
2385  //data defined maximum angle between curved label characters?
2387  {
2388  QString ptstr = exprVal.toString().trimmed();
2389  QgsDebugMsgLevel( QString( "exprVal CurvedCharAngleInOut:%1" ).arg( ptstr ), 4 );
2390 
2391  if ( !ptstr.isEmpty() )
2392  {
2393  QPointF maxcharanglePt = QgsSymbolLayerV2Utils::decodePoint( ptstr );
2394  maxcharanglein = qBound( 20.0, static_cast< double >( maxcharanglePt.x() ), 60.0 );
2395  maxcharangleout = qBound( 20.0, static_cast< double >( maxcharanglePt.y() ), 95.0 );
2396  }
2397  }
2398  // make sure maxcharangleout is always negative
2399  maxcharangleout = -( qAbs( maxcharangleout ) );
2400  }
2401 
2402  // data defined centroid whole or clipped?
2403  bool wholeCentroid = centroidWhole;
2405  {
2406  QString str = exprVal.toString().trimmed();
2407  QgsDebugMsgLevel( QString( "exprVal CentroidWhole:%1" ).arg( str ), 4 );
2408 
2409  if ( !str.isEmpty() )
2410  {
2411  if ( str.compare( "Visible", Qt::CaseInsensitive ) == 0 )
2412  {
2413  wholeCentroid = false;
2414  }
2415  else if ( str.compare( "Whole", Qt::CaseInsensitive ) == 0 )
2416  {
2417  wholeCentroid = true;
2418  }
2419  }
2420  }
2421 
2422  const QgsGeometry* geom = f.constGeometry();
2423  if ( !geom )
2424  {
2425  return;
2426  }
2427 
2428  // whether we're going to create a centroid for polygon
2429  bool centroidPoly = (( placement == QgsPalLayerSettings::AroundPoint
2431  && geom->type() == QGis::Polygon );
2432 
2433  // CLIP the geometry if it is bigger than the extent
2434  // don't clip if centroid is requested for whole feature
2435  bool doClip = false;
2436  if ( !centroidPoly || !wholeCentroid )
2437  {
2438  doClip = true;
2439  }
2440 
2441  const GEOSGeometry* geos_geom = nullptr;
2442  const QgsGeometry* preparedGeom = geom;
2443  QScopedPointer<QgsGeometry> scopedPreparedGeom;
2444  if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, ct, doClip ? extentGeom : nullptr ) )
2445  {
2446  scopedPreparedGeom.reset( QgsPalLabeling::prepareGeometry( geom, context, ct, doClip ? extentGeom : nullptr ) );
2447  if ( !scopedPreparedGeom.data() )
2448  return;
2449  preparedGeom = scopedPreparedGeom.data();
2450  geos_geom = scopedPreparedGeom.data()->asGeos();
2451  }
2452  else
2453  {
2454  geos_geom = geom->asGeos();
2455  }
2456  const GEOSGeometry* geosObstacleGeom = nullptr;
2457  QScopedPointer<QgsGeometry> scopedObstacleGeom;
2458  if ( isObstacle )
2459  {
2460  if ( obstacleGeometry && QgsPalLabeling::geometryRequiresPreparation( obstacleGeometry, context, ct, doClip ? extentGeom : nullptr ) )
2461  {
2462  scopedObstacleGeom.reset( QgsPalLabeling::prepareGeometry( obstacleGeometry, context, ct, doClip ? extentGeom : nullptr ) );
2463  obstacleGeometry = scopedObstacleGeom.data();
2464  }
2465  if ( obstacleGeometry )
2466  {
2467  geosObstacleGeom = obstacleGeometry->asGeos();
2468  }
2469  }
2470 
2471  if ( minFeatureSize > 0 && !checkMinimumSizeMM( context, preparedGeom, minFeatureSize ) )
2472  return;
2473 
2474  if ( !geos_geom )
2475  return; // invalid geometry
2476 
2477  // likelihood exists label will be registered with PAL and may be drawn
2478  // check if max number of features to label (already registered with PAL) has been reached
2479  // Debug output at end of QgsPalLabeling::drawLabeling(), when deleting temp geometries
2480  if ( limitNumLabels )
2481  {
2482  if ( !maxNumLabels )
2483  {
2484  return;
2485  }
2486  if ( mFeatsRegPal >= maxNumLabels )
2487  {
2488  return;
2489  }
2490 
2491  int divNum = static_cast< int >(( static_cast< double >( mFeaturesToLabel ) / maxNumLabels ) + 0.5 );
2492  if ( divNum && ( mFeatsRegPal == static_cast< int >( mFeatsSendingToPal / divNum ) ) )
2493  {
2494  mFeatsSendingToPal += 1;
2495  if ( divNum && mFeatsSendingToPal % divNum )
2496  {
2497  return;
2498  }
2499  }
2500  }
2501 
2502  GEOSGeometry* geos_geom_clone;
2503  if ( GEOSGeomTypeId_r( QgsGeometry::getGEOSHandler(), geos_geom ) == GEOS_POLYGON && repeatDistance > 0 && placement == Line )
2504  {
2505  geos_geom_clone = GEOSBoundary_r( QgsGeometry::getGEOSHandler(), geos_geom );
2506  }
2507  else
2508  {
2509  geos_geom_clone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom );
2510  }
2511  GEOSGeometry* geosObstacleGeomClone = nullptr;
2512  if ( geosObstacleGeom )
2513  {
2514  geosObstacleGeomClone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geosObstacleGeom );
2515  }
2516 
2517 
2518  //data defined position / alignment / rotation?
2519  bool dataDefinedPosition = false;
2520  bool layerDefinedRotation = false;
2521  bool dataDefinedRotation = false;
2522  double xPos = 0.0, yPos = 0.0, angle = 0.0;
2523  bool ddXPos = false, ddYPos = false;
2524  double quadOffsetX = 0.0, quadOffsetY = 0.0;
2525  double offsetX = 0.0, offsetY = 0.0;
2526 
2527  //data defined quadrant offset?
2528  bool ddFixedQuad = false;
2529  QuadrantPosition quadOff = quadOffset;
2530  if ( dataDefinedEvaluate( QgsPalLayerSettings::OffsetQuad, exprVal, &context.expressionContext(), static_cast< int >( quadOff ) ) )
2531  {
2532  bool ok;
2533  int quadInt = exprVal.toInt( &ok );
2534  QgsDebugMsgLevel( QString( "exprVal OffsetQuad:%1" ).arg( quadInt ), 4 );
2535  if ( ok && 0 <= quadInt && quadInt <= 8 )
2536  {
2537  quadOff = static_cast< QuadrantPosition >( quadInt );
2538  ddFixedQuad = true;
2539  }
2540  }
2541 
2542  // adjust quadrant offset of labels
2543  switch ( quadOff )
2544  {
2545  case QuadrantAboveLeft:
2546  quadOffsetX = -1.0;
2547  quadOffsetY = 1.0;
2548  break;
2549  case QuadrantAbove:
2550  quadOffsetX = 0.0;
2551  quadOffsetY = 1.0;
2552  break;
2553  case QuadrantAboveRight:
2554  quadOffsetX = 1.0;
2555  quadOffsetY = 1.0;
2556  break;
2557  case QuadrantLeft:
2558  quadOffsetX = -1.0;
2559  quadOffsetY = 0.0;
2560  break;
2561  case QuadrantRight:
2562  quadOffsetX = 1.0;
2563  quadOffsetY = 0.0;
2564  break;
2565  case QuadrantBelowLeft:
2566  quadOffsetX = -1.0;
2567  quadOffsetY = -1.0;
2568  break;
2569  case QuadrantBelow:
2570  quadOffsetX = 0.0;
2571  quadOffsetY = -1.0;
2572  break;
2573  case QuadrantBelowRight:
2574  quadOffsetX = 1.0;
2575  quadOffsetY = -1.0;
2576  break;
2577  case QuadrantOver:
2578  default:
2579  break;
2580  }
2581 
2582  //data defined label offset?
2583  double xOff = xOffset;
2584  double yOff = yOffset;
2586  {
2587  QString ptstr = exprVal.toString().trimmed();
2588  QgsDebugMsgLevel( QString( "exprVal OffsetXY:%1" ).arg( ptstr ), 4 );
2589 
2590  if ( !ptstr.isEmpty() )
2591  {
2592  QPointF ddOffPt = QgsSymbolLayerV2Utils::decodePoint( ptstr );
2593  xOff = ddOffPt.x();
2594  yOff = ddOffPt.y();
2595  }
2596  }
2597 
2598  // data defined label offset units?
2599  bool offinmapunits = labelOffsetInMapUnits;
2601  {
2602  QString units = exprVal.toString().trimmed();
2603  QgsDebugMsgLevel( QString( "exprVal OffsetUnits:%1" ).arg( units ), 4 );
2604  if ( !units.isEmpty() )
2605  {
2606  offinmapunits = ( _decodeUnits( units ) == QgsPalLayerSettings::MapUnits );
2607  }
2608  }
2609 
2610  // adjust offset of labels to match chosen unit and map scale
2611  // offsets match those of symbology: -x = left, -y = up
2612  double mapUntsPerMM = labelOffsetMapUnitScale.computeMapUnitsPerPixel( context ) * context.scaleFactor();
2613  if ( !qgsDoubleNear( xOff, 0.0 ) )
2614  {
2615  offsetX = xOff; // must be positive to match symbology offset direction
2616  if ( !offinmapunits )
2617  {
2618  offsetX *= mapUntsPerMM; //convert offset from mm to map units
2619  }
2620  }
2621  if ( !qgsDoubleNear( yOff, 0.0 ) )
2622  {
2623  offsetY = -yOff; // must be negative to match symbology offset direction
2624  if ( !offinmapunits )
2625  {
2626  offsetY *= mapUntsPerMM; //convert offset from mm to map units
2627  }
2628  }
2629 
2630  // layer defined rotation?
2631  // only rotate non-pinned OverPoint placements until other placements are supported in pal::Feature
2633  {
2634  layerDefinedRotation = true;
2635  angle = angleOffset * M_PI / 180; // convert to radians
2636  }
2637 
2638  const QgsMapToPixel& m2p = context.mapToPixel();
2639  //data defined rotation?
2641  {
2642  bool ok;
2643  double rotD = exprVal.toDouble( &ok );
2644  QgsDebugMsgLevel( QString( "exprVal Rotation:%1" ).arg( rotD ), 4 );
2645  if ( ok )
2646  {
2647  dataDefinedRotation = true;
2648  // TODO: add setting to disable having data defined rotation follow
2649  // map rotation ?
2650  rotD -= m2p.mapRotation();
2651  angle = rotD * M_PI / 180.0;
2652  }
2653  }
2654 
2656  {
2657  if ( !exprVal.isNull() )
2658  xPos = exprVal.toDouble( &ddXPos );
2659  QgsDebugMsgLevel( QString( "exprVal PositionX:%1" ).arg( xPos ), 4 );
2660 
2662  {
2663  //data defined position. But field values could be NULL -> positions will be generated by PAL
2664  if ( !exprVal.isNull() )
2665  yPos = exprVal.toDouble( &ddYPos );
2666  QgsDebugMsgLevel( QString( "exprVal PositionY:%1" ).arg( yPos ), 4 );
2667 
2668  if ( ddXPos && ddYPos )
2669  {
2670  dataDefinedPosition = true;
2671  // layer rotation set, but don't rotate pinned labels unless data defined
2672  if ( layerDefinedRotation && !dataDefinedRotation )
2673  {
2674  angle = 0.0;
2675  }
2676 
2677  //x/y shift in case of alignment
2678  double xdiff = 0.0;
2679  double ydiff = 0.0;
2680 
2681  //horizontal alignment
2682  if ( dataDefinedEvaluate( QgsPalLayerSettings::Hali, exprVal, &context.expressionContext() ) )
2683  {
2684  QString haliString = exprVal.toString();
2685  QgsDebugMsgLevel( QString( "exprVal Hali:%1" ).arg( haliString ), 4 );
2686  if ( haliString.compare( "Center", Qt::CaseInsensitive ) == 0 )
2687  {
2688  xdiff -= labelX / 2.0;
2689  }
2690  else if ( haliString.compare( "Right", Qt::CaseInsensitive ) == 0 )
2691  {
2692  xdiff -= labelX;
2693  }
2694  }
2695 
2696  //vertical alignment
2697  if ( dataDefinedEvaluate( QgsPalLayerSettings::Vali, exprVal, &context.expressionContext() ) )
2698  {
2699  QString valiString = exprVal.toString();
2700  QgsDebugMsgLevel( QString( "exprVal Vali:%1" ).arg( valiString ), 4 );
2701 
2702  if ( valiString.compare( "Bottom", Qt::CaseInsensitive ) != 0 )
2703  {
2704  if ( valiString.compare( "Top", Qt::CaseInsensitive ) == 0 )
2705  {
2706  ydiff -= labelY;
2707  }
2708  else
2709  {
2710  double descentRatio = labelFontMetrics->descent() / labelFontMetrics->height();
2711  if ( valiString.compare( "Base", Qt::CaseInsensitive ) == 0 )
2712  {
2713  ydiff -= labelY * descentRatio;
2714  }
2715  else //'Cap' or 'Half'
2716  {
2717  double capHeightRatio = ( labelFontMetrics->boundingRect( 'H' ).height() + 1 + labelFontMetrics->descent() ) / labelFontMetrics->height();
2718  ydiff -= labelY * capHeightRatio;
2719  if ( valiString.compare( "Half", Qt::CaseInsensitive ) == 0 )
2720  {
2721  ydiff += labelY * ( capHeightRatio - descentRatio ) / 2.0;
2722  }
2723  }
2724  }
2725  }
2726  }
2727 
2728  if ( dataDefinedRotation )
2729  {
2730  //adjust xdiff and ydiff because the hali/vali point needs to be the rotation center
2731  double xd = xdiff * cos( angle ) - ydiff * sin( angle );
2732  double yd = xdiff * sin( angle ) + ydiff * cos( angle );
2733  xdiff = xd;
2734  ydiff = yd;
2735  }
2736 
2737  //project xPos and yPos from layer to map CRS
2738  double z = 0;
2739  if ( ct )
2740  {
2741  try
2742  {
2743  ct->transformInPlace( xPos, yPos, z );
2744  }
2745  catch ( QgsCsException &e )
2746  {
2747  Q_UNUSED( e );
2748  QgsDebugMsgLevel( QString( "Ignoring feature %1 due transformation exception on data-defined position" ).arg( f.id() ), 4 );
2749  return;
2750  }
2751  }
2752 
2753  //rotate position with map if data-defined
2754  if ( dataDefinedPosition && m2p.mapRotation() )
2755  {
2756  const QgsPoint& center = context.extent().center();
2757  QTransform t = QTransform::fromTranslate( center.x(), center.y() );
2758  t.rotate( -m2p.mapRotation() );
2759  t.translate( -center.x(), -center.y() );
2760  qreal xPosR, yPosR;
2761  qreal xPos_qreal = xPos, yPos_qreal = yPos;
2762  t.map( xPos_qreal, yPos_qreal, &xPosR, &yPosR );
2763  xPos = xPosR;
2764  yPos = yPosR;
2765 
2766  }
2767 
2768  xPos += xdiff;
2769  yPos += ydiff;
2770  }
2771  else
2772  {
2773  // only rotate non-pinned OverPoint placements until other placements are supported in pal::Feature
2774  if ( dataDefinedRotation && placement != QgsPalLayerSettings::OverPoint )
2775  {
2776  angle = 0.0;
2777  }
2778  }
2779  }
2780  }
2781 
2782  // data defined always show?
2783  bool alwaysShow = false;
2785  {
2786  alwaysShow = exprVal.toBool();
2787  }
2788 
2789  // set repeat distance
2790  // data defined repeat distance?
2791  double repeatDist = repeatDistance;
2793  {
2794  bool ok;
2795  double distD = exprVal.toDouble( &ok );
2796  if ( ok )
2797  {
2798  repeatDist = distD;
2799  }
2800  }
2801 
2802  // data defined label-repeat distance units?
2803  bool repeatdistinmapunit = repeatDistanceUnit == QgsPalLayerSettings::MapUnits;
2805  {
2806  QString units = exprVal.toString().trimmed();
2807  QgsDebugMsgLevel( QString( "exprVal RepeatDistanceUnits:%1" ).arg( units ), 4 );
2808  if ( !units.isEmpty() )
2809  {
2810  repeatdistinmapunit = ( _decodeUnits( units ) == QgsPalLayerSettings::MapUnits );
2811  }
2812  }
2813 
2814  if ( !qgsDoubleNear( repeatDist, 0.0 ) )
2815  {
2816  if ( !repeatdistinmapunit )
2817  {
2818  repeatDist *= mapUntsPerMM; //convert repeat distance from mm to map units
2819  }
2820  }
2821 
2822  // feature to the layer
2823  QgsTextLabelFeature* lf = new QgsTextLabelFeature( f.id(), geos_geom_clone, QSizeF( labelX, labelY ) );
2824  mFeatsRegPal++;
2825 
2826  *labelFeature = lf;
2827  ( *labelFeature )->setHasFixedPosition( dataDefinedPosition );
2828  ( *labelFeature )->setFixedPosition( QgsPoint( xPos, yPos ) );
2829  // use layer-level defined rotation, but not if position fixed
2830  ( *labelFeature )->setHasFixedAngle( dataDefinedRotation || ( !dataDefinedPosition && !qgsDoubleNear( angle, 0.0 ) ) );
2831  ( *labelFeature )->setFixedAngle( angle );
2832  ( *labelFeature )->setQuadOffset( QPointF( quadOffsetX, quadOffsetY ) );
2833  ( *labelFeature )->setPositionOffset( QgsPoint( offsetX, offsetY ) );
2834  ( *labelFeature )->setOffsetType( offsetType );
2835  ( *labelFeature )->setAlwaysShow( alwaysShow );
2836  ( *labelFeature )->setRepeatDistance( repeatDist );
2837  ( *labelFeature )->setLabelText( labelText );
2838  if ( geosObstacleGeomClone )
2839  {
2840  ( *labelFeature )->setObstacleGeometry( geosObstacleGeomClone );
2841 
2842  if ( geom->type() == QGis::Point )
2843  {
2844  //register symbol size
2845  ( *labelFeature )->setSymbolSize( QSizeF( obstacleGeometry->boundingBox().width(),
2846  obstacleGeometry->boundingBox().height() ) );
2847  }
2848  }
2849 
2850  //set label's visual margin so that top visual margin is the leading, and bottom margin is the font's descent
2851  //this makes labels align to the font's baseline or highest character
2852  double topMargin = qMax( 0.25 * labelFontMetrics->ascent(), 0.0 );
2853  double bottomMargin = 1.0 + labelFontMetrics->descent();
2854  QgsLabelFeature::VisualMargin vm( topMargin, 0.0, bottomMargin, 0.0 );
2856  ( *labelFeature )->setVisualMargin( vm );
2857 
2858  // store the label's calculated font for later use during painting
2859  QgsDebugMsgLevel( QString( "PAL font stored definedFont: %1, Style: %2" ).arg( labelFont.toString(), labelFont.styleName() ), 4 );
2860  lf->setDefinedFont( labelFont );
2861 
2862  // TODO: only for placement which needs character info
2863  // account for any data defined font metrics adjustments
2864  lf->calculateInfo( placement == QgsPalLayerSettings::Curved, labelFontMetrics.data(), xform, rasterCompressFactor, maxcharanglein, maxcharangleout );
2865  // for labelFeature the LabelInfo is passed to feat when it is registered
2866 
2867  // TODO: allow layer-wide feature dist in PAL...?
2868 
2869  // data defined label-feature distance?
2870  double distance = dist;
2872  {
2873  bool ok;
2874  double distD = exprVal.toDouble( &ok );
2875  if ( ok )
2876  {
2877  distance = distD;
2878  }
2879  }
2880 
2881  // data defined label-feature distance units?
2882  bool distinmapunit = distInMapUnits;
2884  {
2885  QString units = exprVal.toString().trimmed();
2886  QgsDebugMsgLevel( QString( "exprVal DistanceUnits:%1" ).arg( units ), 4 );
2887  if ( !units.isEmpty() )
2888  {
2889  distinmapunit = ( _decodeUnits( units ) == QgsPalLayerSettings::MapUnits );
2890  }
2891  }
2892 
2893  if ( !qgsDoubleNear( distance, 0.0 ) )
2894  {
2895  if ( distinmapunit ) //convert distance from mm/map units to pixels
2896  {
2897  distance /= distMapUnitScale.computeMapUnitsPerPixel( context );
2898  }
2899  else //mm
2900  {
2901  distance *= vectorScaleFactor;
2902  }
2903  double d = qAbs( ptOne.x() - ptZero.x() ) * distance;
2904  ( *labelFeature )->setDistLabel( d );
2905  }
2906 
2907  if ( ddFixedQuad )
2908  {
2909  ( *labelFeature )->setHasFixedQuadrant( true );
2910  }
2911 
2912  // data defined z-index?
2913  double z = zIndex;
2915  {
2916  bool ok;
2917  double zIndexD = exprVal.toDouble( &ok );
2918  if ( ok )
2919  {
2920  z = zIndexD;
2921  }
2922  }
2923  ( *labelFeature )->setZIndex( z );
2924 
2925  // data defined priority?
2927  {
2928  bool ok;
2929  double priorityD = exprVal.toDouble( &ok );
2930  if ( ok )
2931  {
2932  priorityD = qBound( 0.0, priorityD, 10.0 );
2933  priorityD = 1 - priorityD / 10.0; // convert 0..10 --> 1..0
2934  ( *labelFeature )->setPriority( priorityD );
2935  }
2936  }
2937 
2938  ( *labelFeature )->setIsObstacle( isObstacle );
2939 
2940  double featObstacleFactor = obstacleFactor;
2942  {
2943  bool ok;
2944  double factorD = exprVal.toDouble( &ok );
2945  if ( ok )
2946  {
2947  factorD = qBound( 0.0, factorD, 10.0 );
2948  factorD = factorD / 5.0 + 0.0001; // convert 0 -> 10 to 0.0001 -> 2.0
2949  featObstacleFactor = factorD;
2950  }
2951  }
2952  ( *labelFeature )->setObstacleFactor( featObstacleFactor );
2953 
2955  if ( positionOrder.isEmpty() )
2956  positionOrder = QgsPalLayerSettings::DEFAULT_PLACEMENT_ORDER;
2957 
2959  {
2960  QString orderD = exprVal.toString();
2961  positionOrder = QgsLabelingUtils::decodePredefinedPositionOrder( orderD );
2962  }
2963  ( *labelFeature )->setPredefinedPositionOrder( positionOrder );
2964 
2965  // add parameters for data defined labeling to label feature
2966  lf->setDataDefinedValues( dataDefinedValues );
2967 }
2968 
2969 void QgsPalLayerSettings::registerObstacleFeature( QgsFeature& f, QgsRenderContext &context, const QString& dxfLayer, QgsLabelFeature** obstacleFeature, QgsGeometry* obstacleGeometry )
2970 {
2971  Q_UNUSED( dxfLayer ); // now handled in QgsDxfLabelProvider
2972 
2973  mCurFeat = &f;
2974 
2975  const QgsGeometry* geom = nullptr;
2976  if ( obstacleGeometry )
2977  {
2978  geom = obstacleGeometry;
2979  }
2980  else
2981  {
2982  geom = f.constGeometry();
2983  }
2984 
2985  if ( !geom )
2986  {
2987  return;
2988  }
2989 
2990  const GEOSGeometry* geos_geom = nullptr;
2991  QScopedPointer<QgsGeometry> scopedPreparedGeom;
2992 
2993  if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, ct, extentGeom ) )
2994  {
2995  scopedPreparedGeom.reset( QgsPalLabeling::prepareGeometry( geom, context, ct, extentGeom ) );
2996  if ( !scopedPreparedGeom.data() )
2997  return;
2998  geos_geom = scopedPreparedGeom.data()->asGeos();
2999  }
3000  else
3001  {
3002  geos_geom = geom->asGeos();
3003  }
3004 
3005  if ( !geos_geom )
3006  return; // invalid geometry
3007 
3008  GEOSGeometry* geos_geom_clone;
3009  geos_geom_clone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom );
3010 
3011  // feature to the layer
3012  *obstacleFeature = new QgsLabelFeature( f.id(), geos_geom_clone, QSizeF( 0, 0 ) );
3013  ( *obstacleFeature )->setIsObstacle( true );
3014  mFeatsRegPal++;
3015 }
3016 
3017 bool QgsPalLayerSettings::dataDefinedValEval( DataDefinedValueType valType,
3019  QVariant& exprVal, QgsExpressionContext& context, const QVariant& originalValue )
3020 {
3021  if ( dataDefinedEvaluate( p, exprVal, &context, originalValue ) )
3022  {
3023  QString dbgStr = QString( "exprVal %1:" ).arg( mDataDefinedNames.value( p ).first ) + "%1";
3024 
3025  switch ( valType )
3026  {
3027  case DDBool:
3028  {
3029  bool bol = exprVal.toBool();
3030  QgsDebugMsgLevel( dbgStr.arg( bol ? "true" : "false" ), 4 );
3031  dataDefinedValues.insert( p, QVariant( bol ) );
3032  return true;
3033  }
3034  case DDInt:
3035  {
3036  bool ok;
3037  int size = exprVal.toInt( &ok );
3038  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
3039 
3040  if ( ok )
3041  {
3042  dataDefinedValues.insert( p, QVariant( size ) );
3043  return true;
3044  }
3045  return false;
3046  }
3047  case DDIntPos:
3048  {
3049  bool ok;
3050  int size = exprVal.toInt( &ok );
3051  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
3052 
3053  if ( ok && size > 0 )
3054  {
3055  dataDefinedValues.insert( p, QVariant( size ) );
3056  return true;
3057  }
3058  return false;
3059  }
3060  case DDDouble:
3061  {
3062  bool ok;
3063  double size = exprVal.toDouble( &ok );
3064  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
3065 
3066  if ( ok )
3067  {
3068  dataDefinedValues.insert( p, QVariant( size ) );
3069  return true;
3070  }
3071  return false;
3072  }
3073  case DDDoublePos:
3074  {
3075  bool ok;
3076  double size = exprVal.toDouble( &ok );
3077  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
3078 
3079  if ( ok && size > 0.0 )
3080  {
3081  dataDefinedValues.insert( p, QVariant( size ) );
3082  return true;
3083  }
3084  return false;
3085  }
3086  case DDRotation180:
3087  {
3088  bool ok;
3089  double rot = exprVal.toDouble( &ok );
3090  QgsDebugMsgLevel( dbgStr.arg( rot ), 4 );
3091  if ( ok )
3092  {
3093  if ( rot < -180.0 && rot >= -360 )
3094  {
3095  rot += 360;
3096  }
3097  if ( rot > 180.0 && rot <= 360 )
3098  {
3099  rot -= 360;
3100  }
3101  if ( rot >= -180 && rot <= 180 )
3102  {
3103  dataDefinedValues.insert( p, QVariant( rot ) );
3104  return true;
3105  }
3106  }
3107  return false;
3108  }
3109  case DDTransparency:
3110  {
3111  bool ok;
3112  int size = exprVal.toInt( &ok );
3113  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
3114  if ( ok && size >= 0 && size <= 100 )
3115  {
3116  dataDefinedValues.insert( p, QVariant( size ) );
3117  return true;
3118  }
3119  return false;
3120  }
3121  case DDString:
3122  {
3123  QString str = exprVal.toString(); // don't trim whitespace
3124  QgsDebugMsgLevel( dbgStr.arg( str ), 4 );
3125 
3126  dataDefinedValues.insert( p, QVariant( str ) ); // let it stay empty if it is
3127  return true;
3128  }
3129  case DDUnits:
3130  {
3131  QString unitstr = exprVal.toString().trimmed();
3132  QgsDebugMsgLevel( dbgStr.arg( unitstr ), 4 );
3133 
3134  if ( !unitstr.isEmpty() )
3135  {
3136  dataDefinedValues.insert( p, QVariant( static_cast< int >( _decodeUnits( unitstr ) ) ) );
3137  return true;
3138  }
3139  return false;
3140  }
3141  case DDColor:
3142  {
3143  QString colorstr = exprVal.toString().trimmed();
3144  QgsDebugMsgLevel( dbgStr.arg( colorstr ), 4 );
3145  QColor color = QgsSymbolLayerV2Utils::decodeColor( colorstr );
3146 
3147  if ( color.isValid() )
3148  {
3149  dataDefinedValues.insert( p, QVariant( color ) );
3150  return true;
3151  }
3152  return false;
3153  }
3154  case DDJoinStyle:
3155  {
3156  QString joinstr = exprVal.toString().trimmed();
3157  QgsDebugMsgLevel( dbgStr.arg( joinstr ), 4 );
3158 
3159  if ( !joinstr.isEmpty() )
3160  {
3161  dataDefinedValues.insert( p, QVariant( static_cast< int >( _decodePenJoinStyle( joinstr ) ) ) );
3162  return true;
3163  }
3164  return false;
3165  }
3166  case DDBlendMode:
3167  {
3168  QString blendstr = exprVal.toString().trimmed();
3169  QgsDebugMsgLevel( dbgStr.arg( blendstr ), 4 );
3170 
3171  if ( !blendstr.isEmpty() )
3172  {
3173  dataDefinedValues.insert( p, QVariant( static_cast< int >( QgsSymbolLayerV2Utils::decodeBlendMode( blendstr ) ) ) );
3174  return true;
3175  }
3176  return false;
3177  }
3178  case DDPointF:
3179  {
3180  QString ptstr = exprVal.toString().trimmed();
3181  QgsDebugMsgLevel( dbgStr.arg( ptstr ), 4 );
3182 
3183  if ( !ptstr.isEmpty() )
3184  {
3185  dataDefinedValues.insert( p, QVariant( QgsSymbolLayerV2Utils::decodePoint( ptstr ) ) );
3186  return true;
3187  }
3188  return false;
3189  }
3190  }
3191  }
3192  return false;
3193 }
3194 
3195 void QgsPalLayerSettings::parseTextStyle( QFont& labelFont,
3197  QgsRenderContext &context )
3198 {
3199  // NOTE: labelFont already has pixelSize set, so pointSize or pointSizeF might return -1
3200 
3201  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
3202 
3203  // Two ways to generate new data defined font:
3204  // 1) Family + [bold] + [italic] (named style is ignored and font is built off of base family)
3205  // 2) Family + named style (bold or italic is ignored)
3206 
3207  // data defined font family?
3208  QString ddFontFamily( "" );
3209  if ( dataDefinedEvaluate( QgsPalLayerSettings::Family, exprVal, &context.expressionContext(), labelFont.family() ) )
3210  {
3211  QString family = exprVal.toString().trimmed();
3212  QgsDebugMsgLevel( QString( "exprVal Font family:%1" ).arg( family ), 4 );
3213 
3214  if ( labelFont.family() != family )
3215  {
3216  // testing for ddFontFamily in QFontDatabase.families() may be slow to do for every feature
3217  // (i.e. don't use QgsFontUtils::fontFamilyMatchOnSystem( family ) here)
3218  if ( QgsFontUtils::fontFamilyOnSystem( family ) )
3219  {
3220  ddFontFamily = family;
3221  }
3222  }
3223  }
3224 
3225  // data defined named font style?
3226  QString ddFontStyle( "" );
3228  {
3229  QString fontstyle = exprVal.toString().trimmed();
3230  QgsDebugMsgLevel( QString( "exprVal Font style:%1" ).arg( fontstyle ), 4 );
3231  ddFontStyle = fontstyle;
3232  }
3233 
3234  // data defined bold font style?
3235  bool ddBold = false;
3236  if ( dataDefinedEvaluate( QgsPalLayerSettings::Bold, exprVal, &context.expressionContext(), labelFont.bold() ) )
3237  {
3238  bool bold = exprVal.toBool();
3239  QgsDebugMsgLevel( QString( "exprVal Font bold:%1" ).arg( bold ? "true" : "false" ), 4 );
3240  ddBold = bold;
3241  }
3242 
3243  // data defined italic font style?
3244  bool ddItalic = false;
3245  if ( dataDefinedEvaluate( QgsPalLayerSettings::Italic, exprVal, &context.expressionContext(), labelFont.italic() ) )
3246  {
3247  bool italic = exprVal.toBool();
3248  QgsDebugMsgLevel( QString( "exprVal Font italic:%1" ).arg( italic ? "true" : "false" ), 4 );
3249  ddItalic = italic;
3250  }
3251 
3252  // TODO: update when pref for how to resolve missing family (use matching algorithm or just default font) is implemented
3253  // (currently defaults to what has been read in from layer settings)
3254  QFont newFont;
3255  QFont appFont = QApplication::font();
3256  bool newFontBuilt = false;
3257  if ( ddBold || ddItalic )
3258  {
3259  // new font needs built, since existing style needs removed
3260  newFont = QFont( !ddFontFamily.isEmpty() ? ddFontFamily : labelFont.family() );
3261  newFontBuilt = true;
3262  newFont.setBold( ddBold );
3263  newFont.setItalic( ddItalic );
3264  }
3265  else if ( !ddFontStyle.isEmpty()
3266  && ddFontStyle.compare( "Ignore", Qt::CaseInsensitive ) != 0 )
3267  {
3268  if ( !ddFontFamily.isEmpty() )
3269  {
3270  // both family and style are different, build font from database
3271  QFont styledfont = mFontDB.font( ddFontFamily, ddFontStyle, appFont.pointSize() );
3272  if ( appFont != styledfont )
3273  {
3274  newFont = styledfont;
3275  newFontBuilt = true;
3276  }
3277  }
3278 
3279  // update the font face style
3280  QgsFontUtils::updateFontViaStyle( newFontBuilt ? newFont : labelFont, ddFontStyle );
3281  }
3282  else if ( !ddFontFamily.isEmpty() )
3283  {
3284  if ( ddFontStyle.compare( "Ignore", Qt::CaseInsensitive ) != 0 )
3285  {
3286  // just family is different, build font from database
3287  QFont styledfont = mFontDB.font( ddFontFamily, textNamedStyle, appFont.pointSize() );
3288  if ( appFont != styledfont )
3289  {
3290  newFont = styledfont;
3291  newFontBuilt = true;
3292  }
3293  }
3294  else
3295  {
3296  newFont = QFont( ddFontFamily );
3297  newFontBuilt = true;
3298  }
3299  }
3300 
3301  if ( newFontBuilt )
3302  {
3303  // copy over existing font settings
3304  //newFont = newFont.resolve( labelFont ); // should work, but let's be sure what's being copied
3305  newFont.setPixelSize( labelFont.pixelSize() );
3306  newFont.setCapitalization( labelFont.capitalization() );
3307  newFont.setUnderline( labelFont.underline() );
3308  newFont.setStrikeOut( labelFont.strikeOut() );
3309  newFont.setWordSpacing( labelFont.wordSpacing() );
3310  newFont.setLetterSpacing( QFont::AbsoluteSpacing, labelFont.letterSpacing() );
3311 
3312  labelFont = newFont;
3313  }
3314 
3315  // data defined word spacing?
3316  double wordspace = labelFont.wordSpacing();
3317  if ( dataDefinedEvaluate( QgsPalLayerSettings::FontWordSpacing, exprVal, &context.expressionContext(), wordspace ) )
3318  {
3319  bool ok;
3320  double wspacing = exprVal.toDouble( &ok );
3321  QgsDebugMsgLevel( QString( "exprVal FontWordSpacing:%1" ).arg( wspacing ), 4 );
3322  if ( ok )
3323  {
3324  wordspace = wspacing;
3325  }
3326  }
3327  labelFont.setWordSpacing( sizeToPixel( wordspace, context, fontunits, false, fontSizeMapUnitScale ) );
3328 
3329  // data defined letter spacing?
3330  double letterspace = labelFont.letterSpacing();
3331  if ( dataDefinedEvaluate( QgsPalLayerSettings::FontLetterSpacing, exprVal, &context.expressionContext(), letterspace ) )
3332  {
3333  bool ok;
3334  double lspacing = exprVal.toDouble( &ok );
3335  QgsDebugMsgLevel( QString( "exprVal FontLetterSpacing:%1" ).arg( lspacing ), 4 );
3336  if ( ok )
3337  {
3338  letterspace = lspacing;
3339  }
3340  }
3341  labelFont.setLetterSpacing( QFont::AbsoluteSpacing, sizeToPixel( letterspace, context, fontunits, false, fontSizeMapUnitScale ) );
3342 
3343  // data defined font capitalization?
3344  QFont::Capitalization fontcaps = labelFont.capitalization();
3346  {
3347  QString fcase = exprVal.toString().trimmed();
3348  QgsDebugMsgLevel( QString( "exprVal FontCase:%1" ).arg( fcase ), 4 );
3349 
3350  if ( !fcase.isEmpty() )
3351  {
3352  if ( fcase.compare( "NoChange", Qt::CaseInsensitive ) == 0 )
3353  {
3354  fontcaps = QFont::MixedCase;
3355  }
3356  else if ( fcase.compare( "Upper", Qt::CaseInsensitive ) == 0 )
3357  {
3358  fontcaps = QFont::AllUppercase;
3359  }
3360  else if ( fcase.compare( "Lower", Qt::CaseInsensitive ) == 0 )
3361  {
3362  fontcaps = QFont::AllLowercase;
3363  }
3364  else if ( fcase.compare( "Capitalize", Qt::CaseInsensitive ) == 0 )
3365  {
3366  fontcaps = QFont::Capitalize;
3367  }
3368 
3369  if ( fontcaps != labelFont.capitalization() )
3370  {
3371  labelFont.setCapitalization( fontcaps );
3372  }
3373  }
3374  }
3375 
3376  // data defined strikeout font style?
3377  if ( dataDefinedEvaluate( QgsPalLayerSettings::Strikeout, exprVal, &context.expressionContext(), labelFont.strikeOut() ) )
3378  {
3379  bool strikeout = exprVal.toBool();
3380  QgsDebugMsgLevel( QString( "exprVal Font strikeout:%1" ).arg( strikeout ? "true" : "false" ), 4 );
3381  labelFont.setStrikeOut( strikeout );
3382  }
3383 
3384  // data defined underline font style?
3385  if ( dataDefinedEvaluate( QgsPalLayerSettings::Underline, exprVal, &context.expressionContext(), labelFont.underline() ) )
3386  {
3387  bool underline = exprVal.toBool();
3388  QgsDebugMsgLevel( QString( "exprVal Font underline:%1" ).arg( underline ? "true" : "false" ), 4 );
3389  labelFont.setUnderline( underline );
3390  }
3391 
3392  // pass the rest on to QgsPalLabeling::drawLabeling
3393 
3394  // data defined font color?
3395  dataDefinedValEval( DDColor, QgsPalLayerSettings::Color, exprVal, context.expressionContext(), QgsSymbolLayerV2Utils::encodeColor( textColor ) );
3396 
3397  // data defined font transparency?
3398  dataDefinedValEval( DDTransparency, QgsPalLayerSettings::FontTransp, exprVal, context.expressionContext(), textTransp );
3399 
3400  // data defined font blend mode?
3401  dataDefinedValEval( DDBlendMode, QgsPalLayerSettings::FontBlendMode, exprVal, context.expressionContext() );
3402 
3403 }
3404 
3405 void QgsPalLayerSettings::parseTextBuffer( QgsRenderContext &context )
3406 {
3407  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
3408 
3409  // data defined draw buffer?
3410  bool drawBuffer = bufferDraw;
3411  if ( dataDefinedValEval( DDBool, QgsPalLayerSettings::BufferDraw, exprVal, context.expressionContext(), bufferDraw ) )
3412  {
3413  drawBuffer = exprVal.toBool();
3414  }
3415 
3416  if ( !drawBuffer )
3417  {
3418  return;
3419  }
3420 
3421  // data defined buffer size?
3422  double bufrSize = bufferSize;
3423  if ( dataDefinedValEval( DDDoublePos, QgsPalLayerSettings::BufferSize, exprVal, context.expressionContext(), bufferSize ) )
3424  {
3425  bufrSize = exprVal.toDouble();
3426  }
3427 
3428  // data defined buffer transparency?
3429  int bufTransp = bufferTransp;
3430  if ( dataDefinedValEval( DDTransparency, QgsPalLayerSettings::BufferTransp, exprVal, context.expressionContext(), bufferTransp ) )
3431  {
3432  bufTransp = exprVal.toInt();
3433  }
3434 
3435  drawBuffer = ( drawBuffer && bufrSize > 0.0 && bufTransp < 100 );
3436 
3437  if ( !drawBuffer )
3438  {
3439  dataDefinedValues.insert( QgsPalLayerSettings::BufferDraw, QVariant( false ) ); // trigger value
3440  dataDefinedValues.remove( QgsPalLayerSettings::BufferSize );
3441  dataDefinedValues.remove( QgsPalLayerSettings::BufferTransp );
3442  return; // don't bother evaluating values that won't be used
3443  }
3444 
3445  // data defined buffer units?
3446  dataDefinedValEval( DDUnits, QgsPalLayerSettings::BufferUnit, exprVal, context.expressionContext() );
3447 
3448  // data defined buffer color?
3449  dataDefinedValEval( DDColor, QgsPalLayerSettings::BufferColor, exprVal, context.expressionContext(), QgsSymbolLayerV2Utils::encodeColor( bufferColor ) );
3450 
3451  // data defined buffer pen join style?
3453 
3454  // data defined buffer blend mode?
3455  dataDefinedValEval( DDBlendMode, QgsPalLayerSettings::BufferBlendMode, exprVal, context.expressionContext() );
3456 }
3457 
3458 void QgsPalLayerSettings::parseTextFormatting( QgsRenderContext &context )
3459 {
3460  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
3461 
3462  // data defined multiline wrap character?
3463  QString wrapchr = wrapChar;
3464  if ( dataDefinedValEval( DDString, QgsPalLayerSettings::MultiLineWrapChar, exprVal, context.expressionContext(), wrapChar ) )
3465  {
3466  wrapchr = exprVal.toString();
3467  }
3468 
3469  // data defined multiline height?
3470  dataDefinedValEval( DDDouble, QgsPalLayerSettings::MultiLineHeight, exprVal, context.expressionContext() );
3471 
3472  // data defined multiline text align?
3474  {
3475  QString str = exprVal.toString().trimmed();
3476  QgsDebugMsgLevel( QString( "exprVal MultiLineAlignment:%1" ).arg( str ), 4 );
3477 
3478  if ( !str.isEmpty() )
3479  {
3480  // "Left"
3482 
3483  if ( str.compare( "Center", Qt::CaseInsensitive ) == 0 )
3484  {
3486  }
3487  else if ( str.compare( "Right", Qt::CaseInsensitive ) == 0 )
3488  {
3489  aligntype = QgsPalLayerSettings::MultiRight;
3490  }
3491  else if ( str.compare( "Follow", Qt::CaseInsensitive ) == 0 )
3492  {
3494  }
3495  dataDefinedValues.insert( QgsPalLayerSettings::MultiLineAlignment, QVariant( static_cast< int >( aligntype ) ) );
3496  }
3497  }
3498 
3499  // data defined direction symbol?
3500  bool drawDirSymb = addDirectionSymbol;
3501  if ( dataDefinedValEval( DDBool, QgsPalLayerSettings::DirSymbDraw, exprVal, context.expressionContext(), addDirectionSymbol ) )
3502  {
3503  drawDirSymb = exprVal.toBool();
3504  }
3505 
3506  if ( drawDirSymb )
3507  {
3508  // data defined direction left symbol?
3509  dataDefinedValEval( DDString, QgsPalLayerSettings::DirSymbLeft, exprVal, context.expressionContext(), leftDirectionSymbol );
3510 
3511  // data defined direction right symbol?
3512  dataDefinedValEval( DDString, QgsPalLayerSettings::DirSymbRight, exprVal, context.expressionContext(), rightDirectionSymbol );
3513 
3514  // data defined direction symbol placement?
3516  {
3517  QString str = exprVal.toString().trimmed();
3518  QgsDebugMsgLevel( QString( "exprVal DirSymbPlacement:%1" ).arg( str ), 4 );
3519 
3520  if ( !str.isEmpty() )
3521  {
3522  // "LeftRight"
3524 
3525  if ( str.compare( "Above", Qt::CaseInsensitive ) == 0 )
3526  {
3528  }
3529  else if ( str.compare( "Below", Qt::CaseInsensitive ) == 0 )
3530  {
3532  }
3533  dataDefinedValues.insert( QgsPalLayerSettings::DirSymbPlacement, QVariant( static_cast< int >( placetype ) ) );
3534  }
3535  }
3536 
3537  // data defined direction symbol reversed?
3538  dataDefinedValEval( DDBool, QgsPalLayerSettings::DirSymbReverse, exprVal, context.expressionContext(), reverseDirectionSymbol );
3539  }
3540 
3541  // formatting for numbers is inline with generation of base label text and not passed to label painting
3542 }
3543 
3544 void QgsPalLayerSettings::parseShapeBackground( QgsRenderContext &context )
3545 {
3546  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
3547 
3548  // data defined draw shape?
3549  bool drawShape = shapeDraw;
3550  if ( dataDefinedValEval( DDBool, QgsPalLayerSettings::ShapeDraw, exprVal, context.expressionContext(), shapeDraw ) )
3551  {
3552  drawShape = exprVal.toBool();
3553  }
3554 
3555  if ( !drawShape )
3556  {
3557  return;
3558  }
3559 
3560  // data defined shape transparency?
3561  int shapeTransp = shapeTransparency;
3562  if ( dataDefinedValEval( DDTransparency, QgsPalLayerSettings::ShapeTransparency, exprVal, context.expressionContext(), shapeTransparency ) )
3563  {
3564  shapeTransp = exprVal.toInt();
3565  }
3566 
3567  drawShape = ( drawShape && shapeTransp < 100 ); // size is not taken into account (could be)
3568 
3569  if ( !drawShape )
3570  {
3571  dataDefinedValues.insert( QgsPalLayerSettings::ShapeDraw, QVariant( false ) ); // trigger value
3572  dataDefinedValues.remove( QgsPalLayerSettings::ShapeTransparency );
3573  return; // don't bother evaluating values that won't be used
3574  }
3575 
3576  // data defined shape kind?
3579  {
3580  QString skind = exprVal.toString().trimmed();
3581  QgsDebugMsgLevel( QString( "exprVal ShapeKind:%1" ).arg( skind ), 4 );
3582 
3583  if ( !skind.isEmpty() )
3584  {
3585  // "Rectangle"
3587 
3588  if ( skind.compare( "Square", Qt::CaseInsensitive ) == 0 )
3589  {
3591  }
3592  else if ( skind.compare( "Ellipse", Qt::CaseInsensitive ) == 0 )
3593  {
3595  }
3596  else if ( skind.compare( "Circle", Qt::CaseInsensitive ) == 0 )
3597  {
3599  }
3600  else if ( skind.compare( "SVG", Qt::CaseInsensitive ) == 0 )
3601  {
3603  }
3604  shapeKind = shpkind;
3605  dataDefinedValues.insert( QgsPalLayerSettings::ShapeKind, QVariant( static_cast< int >( shpkind ) ) );
3606  }
3607  }
3608 
3609  // data defined shape SVG path?
3610  QString svgPath = shapeSVGFile;
3612  {
3613  QString svgfile = exprVal.toString().trimmed();
3614  QgsDebugMsgLevel( QString( "exprVal ShapeSVGFile:%1" ).arg( svgfile ), 4 );
3615 
3616  // '' empty paths are allowed
3617  svgPath = svgfile;
3618  dataDefinedValues.insert( QgsPalLayerSettings::ShapeSVGFile, QVariant( svgfile ) );
3619  }
3620 
3621  // data defined shape size type?
3624  {
3625  QString stype = exprVal.toString().trimmed();
3626  QgsDebugMsgLevel( QString( "exprVal ShapeSizeType:%1" ).arg( stype ), 4 );
3627 
3628  if ( !stype.isEmpty() )
3629  {
3630  // "Buffer"
3632 
3633  if ( stype.compare( "Fixed", Qt::CaseInsensitive ) == 0 )
3634  {
3636  }
3637  shpSizeType = sizType;
3638  dataDefinedValues.insert( QgsPalLayerSettings::ShapeSizeType, QVariant( static_cast< int >( sizType ) ) );
3639  }
3640  }
3641 
3642  // data defined shape size X? (SVGs only use X for sizing)
3643  double ddShpSizeX = shapeSize.x();
3644  if ( dataDefinedValEval( DDDouble, QgsPalLayerSettings::ShapeSizeX, exprVal, context.expressionContext(), ddShpSizeX ) )
3645  {
3646  ddShpSizeX = exprVal.toDouble();
3647  }
3648 
3649  // data defined shape size Y?
3650  double ddShpSizeY = shapeSize.y();
3651  if ( dataDefinedValEval( DDDouble, QgsPalLayerSettings::ShapeSizeY, exprVal, context.expressionContext(), ddShpSizeY ) )
3652  {
3653  ddShpSizeY = exprVal.toDouble();
3654  }
3655 
3656  // don't continue under certain circumstances (e.g. size is fixed)
3657  bool skip = false;
3658  if ( shapeKind == QgsPalLayerSettings::ShapeSVG
3659  && ( svgPath.isEmpty()
3660  || ( !svgPath.isEmpty()
3661  && shpSizeType == QgsPalLayerSettings::SizeFixed
3662  && ddShpSizeX == 0.0 ) ) )
3663  {
3664  skip = true;
3665  }
3666  if ( shapeKind != QgsPalLayerSettings::ShapeSVG
3667  && shpSizeType == QgsPalLayerSettings::SizeFixed
3668  && ( ddShpSizeX == 0.0 || ddShpSizeY == 0.0 ) )
3669  {
3670  skip = true;
3671  }
3672 
3673  if ( skip )
3674  {
3675  dataDefinedValues.insert( QgsPalLayerSettings::ShapeDraw, QVariant( false ) ); // trigger value
3676  dataDefinedValues.remove( QgsPalLayerSettings::ShapeTransparency );
3677  dataDefinedValues.remove( QgsPalLayerSettings::ShapeKind );
3678  dataDefinedValues.remove( QgsPalLayerSettings::ShapeSVGFile );
3679  dataDefinedValues.remove( QgsPalLayerSettings::ShapeSizeX );
3680  dataDefinedValues.remove( QgsPalLayerSettings::ShapeSizeY );
3681  return; // don't bother evaluating values that won't be used
3682  }
3683 
3684  // data defined shape size units?
3685  dataDefinedValEval( DDUnits, QgsPalLayerSettings::ShapeSizeUnits, exprVal, context.expressionContext() );
3686 
3687  // data defined shape rotation type?
3689  {
3690  QString rotstr = exprVal.toString().trimmed();
3691  QgsDebugMsgLevel( QString( "exprVal ShapeRotationType:%1" ).arg( rotstr ), 4 );
3692 
3693  if ( !rotstr.isEmpty() )
3694  {
3695  // "Sync"
3697 
3698  if ( rotstr.compare( "Offset", Qt::CaseInsensitive ) == 0 )
3699  {
3701  }
3702  else if ( rotstr.compare( "Fixed", Qt::CaseInsensitive ) == 0 )
3703  {
3705  }
3706  dataDefinedValues.insert( QgsPalLayerSettings::ShapeRotationType, QVariant( static_cast< int >( rottype ) ) );
3707  }
3708  }
3709 
3710  // data defined shape rotation?
3711  dataDefinedValEval( DDRotation180, QgsPalLayerSettings::ShapeRotation, exprVal, context.expressionContext(), shapeRotation );
3712 
3713  // data defined shape offset?
3714  dataDefinedValEval( DDPointF, QgsPalLayerSettings::ShapeOffset, exprVal, context.expressionContext(), QgsSymbolLayerV2Utils::encodePoint( shapeOffset ) );
3715 
3716  // data defined shape offset units?
3717  dataDefinedValEval( DDUnits, QgsPalLayerSettings::ShapeOffsetUnits, exprVal, context.expressionContext() );
3718 
3719  // data defined shape radii?
3720  dataDefinedValEval( DDPointF, QgsPalLayerSettings::ShapeRadii, exprVal, context.expressionContext(), QgsSymbolLayerV2Utils::encodePoint( shapeRadii ) );
3721 
3722  // data defined shape radii units?
3723  dataDefinedValEval( DDUnits, QgsPalLayerSettings::ShapeRadiiUnits, exprVal, context.expressionContext() );
3724 
3725  // data defined shape blend mode?
3726  dataDefinedValEval( DDBlendMode, QgsPalLayerSettings::ShapeBlendMode, exprVal, context.expressionContext() );
3727 
3728  // data defined shape fill color?
3729  dataDefinedValEval( DDColor, QgsPalLayerSettings::ShapeFillColor, exprVal, context.expressionContext(), QgsSymbolLayerV2Utils::encodeColor( shapeFillColor ) );
3730 
3731  // data defined shape border color?
3733 
3734  // data defined shape border width?
3735  dataDefinedValEval( DDDoublePos, QgsPalLayerSettings::ShapeBorderWidth, exprVal, context.expressionContext(), shapeBorderWidth );
3736 
3737  // data defined shape border width units?
3738  dataDefinedValEval( DDUnits, QgsPalLayerSettings::ShapeBorderWidthUnits, exprVal, context.expressionContext() );
3739 
3740  // data defined shape join style?
3742 
3743 }
3744 
3745 void QgsPalLayerSettings::parseDropShadow( QgsRenderContext &context )
3746 {
3747  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
3748 
3749  // data defined draw shadow?
3750  bool drawShadow = shadowDraw;
3751  if ( dataDefinedValEval( DDBool, QgsPalLayerSettings::ShadowDraw, exprVal, context.expressionContext(), shadowDraw ) )
3752  {
3753  drawShadow = exprVal.toBool();
3754  }
3755 
3756  if ( !drawShadow )
3757  {
3758  return;
3759  }
3760 
3761  // data defined shadow transparency?
3762  int shadowTransp = shadowTransparency;
3763  if ( dataDefinedValEval( DDTransparency, QgsPalLayerSettings::ShadowTransparency, exprVal, context.expressionContext(), shadowTransparency ) )
3764  {
3765  shadowTransp = exprVal.toInt();
3766  }
3767 
3768  // data defined shadow offset distance?
3769  double shadowOffDist = shadowOffsetDist;
3770  if ( dataDefinedValEval( DDDoublePos, QgsPalLayerSettings::ShadowOffsetDist, exprVal, context.expressionContext(), shadowOffsetDist ) )
3771  {
3772  shadowOffDist = exprVal.toDouble();
3773  }
3774 
3775  // data defined shadow offset distance?
3776  double shadowRad = shadowRadius;
3777  if ( dataDefinedValEval( DDDoublePos, QgsPalLayerSettings::ShadowRadius, exprVal, context.expressionContext(), shadowRadius ) )
3778  {
3779  shadowRad = exprVal.toDouble();
3780  }
3781 
3782  drawShadow = ( drawShadow && shadowTransp < 100 && !( shadowOffDist == 0.0 && shadowRad == 0.0 ) );
3783 
3784  if ( !drawShadow )
3785  {
3786  dataDefinedValues.insert( QgsPalLayerSettings::ShadowDraw, QVariant( false ) ); // trigger value
3787  dataDefinedValues.remove( QgsPalLayerSettings::ShadowTransparency );
3788  dataDefinedValues.remove( QgsPalLayerSettings::ShadowOffsetDist );
3789  dataDefinedValues.remove( QgsPalLayerSettings::ShadowRadius );
3790  return; // don't bother evaluating values that won't be used
3791  }
3792 
3793  // data defined shadow under type?
3795  {
3796  QString str = exprVal.toString().trimmed();
3797  QgsDebugMsgLevel( QString( "exprVal ShadowUnder:%1" ).arg( str ), 4 );
3798 
3799  if ( !str.isEmpty() )
3800  {
3801  // "Lowest"
3803 
3804  if ( str.compare( "Text", Qt::CaseInsensitive ) == 0 )
3805  {
3807  }
3808  else if ( str.compare( "Buffer", Qt::CaseInsensitive ) == 0 )
3809  {
3811  }
3812  else if ( str.compare( "Background", Qt::CaseInsensitive ) == 0 )
3813  {
3815  }
3816  dataDefinedValues.insert( QgsPalLayerSettings::ShadowUnder, QVariant( static_cast< int >( shdwtype ) ) );
3817  }
3818  }
3819 
3820  // data defined shadow offset angle?
3821  dataDefinedValEval( DDRotation180, QgsPalLayerSettings::ShadowOffsetAngle, exprVal, context.expressionContext(), shadowOffsetAngle );
3822 
3823  // data defined shadow offset units?
3824  dataDefinedValEval( DDUnits, QgsPalLayerSettings::ShadowOffsetUnits, exprVal, context.expressionContext() );
3825 
3826  // data defined shadow radius?
3827  dataDefinedValEval( DDDouble, QgsPalLayerSettings::ShadowRadius, exprVal, context.expressionContext(), shadowRadius );
3828 
3829  // data defined shadow radius units?
3830  dataDefinedValEval( DDUnits, QgsPalLayerSettings::ShadowRadiusUnits, exprVal, context.expressionContext() );
3831 
3832  // data defined shadow scale? ( gui bounds to 0-2000, no upper bound here )
3833  dataDefinedValEval( DDIntPos, QgsPalLayerSettings::ShadowScale, exprVal, context.expressionContext(), shadowScale );
3834 
3835  // data defined shadow color?
3836  dataDefinedValEval( DDColor, QgsPalLayerSettings::ShadowColor, exprVal, context.expressionContext(), QgsSymbolLayerV2Utils::encodeColor( shadowColor ) );
3837 
3838  // data defined shadow blend mode?
3839  dataDefinedValEval( DDBlendMode, QgsPalLayerSettings::ShadowBlendMode, exprVal, context.expressionContext() );
3840 }
3841 
3842 int QgsPalLayerSettings::sizeToPixel( double size, const QgsRenderContext& c, SizeUnit unit, bool rasterfactor, const QgsMapUnitScale& mapUnitScale ) const
3843 {
3844  return static_cast< int >( scaleToPixelContext( size, c, unit, rasterfactor, mapUnitScale ) + 0.5 );
3845 }
3846 
3847 double QgsPalLayerSettings::scaleToPixelContext( double size, const QgsRenderContext& c, SizeUnit unit, bool rasterfactor, const QgsMapUnitScale& mapUnitScale ) const
3848 {
3849  // if render context is that of device (i.e. not a scaled map), just return size
3850  double mapUnitsPerPixel = mapUnitScale.computeMapUnitsPerPixel( c );
3851 
3852  if ( unit == MapUnits && mapUnitsPerPixel > 0.0 )
3853  {
3854  size = size / mapUnitsPerPixel * ( rasterfactor ? c.rasterScaleFactor() : 1 );
3855  }
3856  else // e.g. in points or mm
3857  {
3858  double ptsTomm = ( unit == Points ? 0.352778 : 1 );
3859  size *= ptsTomm * c.scaleFactor() * ( rasterfactor ? c.rasterScaleFactor() : 1 );
3860  }
3861  return size;
3862 }
3863 
3864 // -------------
3865 
3867  : mEngine( new QgsLabelingEngineV2() )
3868 {
3869 }
3870 
3872 {
3873  delete mEngine;
3874  mEngine = nullptr;
3875 }
3876 
3878 {
3879  return staticWillUseLayer( layer );
3880 }
3881 
3883 {
3884  QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( layerID ) );
3885  if ( !layer )
3886  return false;
3887  return staticWillUseLayer( layer );
3888 }
3889 
3890 
3892 {
3893  // don't do QgsPalLayerSettings::readFromLayer( layer ) if not needed
3894  bool enabled = false;
3895  if ( layer->customProperty( "labeling" ).toString() == "pal" )
3896  enabled = layer->labelsEnabled() || layer->diagramsEnabled();
3897  else if ( layer->labeling()->type() == "rule-based" )
3898  return true;
3899 
3900  return enabled;
3901 }
3902 
3903 
3905 {
3906 }
3907 
3909 {
3910  Q_UNUSED( layerID );
3911 }
3912 
3913 
3915 {
3916  if ( !willUseLayer( layer ) )
3917  {
3918  return 0;
3919  }
3920 
3921  if ( !layer->labeling() )
3922  return 0;
3923 
3924  QgsVectorLayerLabelProvider* lp = layer->labeling()->provider( layer );
3925  if ( !lp )
3926  return 0;
3927 
3928  //QgsVectorLayerLabelProvider* lp = new QgsVectorLayerLabelProvider( layer, false );
3929  // need to be added before calling prepare() - uses map settings from engine
3930  mEngine->addProvider( lp );
3931  mLabelProviders[layer->id()] = lp; // fast lookup table by layer ID
3932 
3933  if ( !lp->prepare( ctx, attrNames ) )
3934  {
3935  mEngine->removeProvider( lp );
3936  return 0;
3937  }
3938 
3939  return 1; // init successful
3940 }
3941 
3943 {
3945  // need to be added before calling prepare() - uses map settings from engine
3946  mEngine->addProvider( dp );
3947  mDiagramProviders[layer->id()] = dp; // fast lookup table by layer ID
3948 
3949  if ( !dp->prepare( ctx, attrNames ) )
3950  {
3951  mEngine->removeProvider( dp );
3952  return 0;
3953  }
3954 
3955  return 1;
3956 }
3957 
3959 {
3960  QgsDebugMsg( "Called addDiagramLayer()... need to use prepareDiagramLayer() instead!" );
3961  Q_UNUSED( layer );
3962  Q_UNUSED( s );
3963  return 0;
3964 }
3965 
3966 void QgsPalLabeling::registerFeature( const QString& layerID, QgsFeature& f, QgsRenderContext &context, const QString& dxfLayer )
3967 {
3968  Q_UNUSED( dxfLayer ); // now handled by QgsDxfLabelProvider
3969  if ( QgsVectorLayerLabelProvider* provider = mLabelProviders.value( layerID, nullptr ) )
3970  provider->registerFeature( f, context );
3971 }
3972 
3974 {
3975  if ( !geometry )
3976  {
3977  return false;
3978  }
3979 
3980  //requires reprojection
3981  if ( ct )
3982  return true;
3983 
3984  //requires fixing
3985  if ( geometry->type() == QGis::Polygon && !geometry->isGeosValid() )
3986  return true;
3987 
3988  //requires rotation
3989  const QgsMapToPixel& m2p = context.mapToPixel();
3990  if ( !qgsDoubleNear( m2p.mapRotation(), 0 ) )
3991  return true;
3992 
3993  //requires clip
3994  if ( clipGeometry && !clipGeometry->contains( geometry ) )
3995  return true;
3996 
3997  return false;
3998 }
3999 
4000 QStringList QgsPalLabeling::splitToLines( const QString &text, const QString &wrapCharacter )
4001 {
4002  QStringList multiLineSplit;
4003  if ( !wrapCharacter.isEmpty() && wrapCharacter != QLatin1String( "\n" ) )
4004  {
4005  //wrap on both the wrapchr and new line characters
4006  Q_FOREACH ( const QString& line, text.split( wrapCharacter ) )
4007  {
4008  multiLineSplit.append( line.split( '\n' ) );
4009  }
4010  }
4011  else
4012  {
4013  multiLineSplit = text.split( '\n' );
4014  }
4015 
4016  return multiLineSplit;
4017 }
4018 
4020 {
4021  QStringList graphemes;
4022  QTextBoundaryFinder boundaryFinder( QTextBoundaryFinder::Grapheme, text );
4023  int currentBoundary = -1;
4024  int previousBoundary = 0;
4025  while (( currentBoundary = boundaryFinder.toNextBoundary() ) > 0 )
4026  {
4027  graphemes << text.mid( previousBoundary, currentBoundary - previousBoundary );
4028  previousBoundary = currentBoundary;
4029  }
4030  return graphemes;
4031 }
4032 
4034 {
4035  if ( !geometry )
4036  {
4037  return nullptr;
4038  }
4039 
4040  //don't modify the feature's geometry so that geometry based expressions keep working
4041  QgsGeometry* geom = new QgsGeometry( *geometry );
4042  QScopedPointer<QgsGeometry> clonedGeometry( geom );
4043 
4044  //reproject the geometry if necessary
4045  if ( ct )
4046  {
4047  try
4048  {
4049  geom->transform( *ct );
4050  }
4051  catch ( QgsCsException &cse )
4052  {
4053  Q_UNUSED( cse );
4054  QgsDebugMsgLevel( QString( "Ignoring feature due to transformation exception" ), 4 );
4055  return nullptr;
4056  }
4057  }
4058 
4059  // Rotate the geometry if needed, before clipping
4060  const QgsMapToPixel& m2p = context.mapToPixel();
4061  if ( !qgsDoubleNear( m2p.mapRotation(), 0 ) )
4062  {
4063  QgsPoint center = context.extent().center();
4064 
4065  if ( ct )
4066  {
4067  try
4068  {
4069  center = ct->transform( center );
4070  }
4071  catch ( QgsCsException &cse )
4072  {
4073  Q_UNUSED( cse );
4074  QgsDebugMsgLevel( QString( "Ignoring feature due to transformation exception" ), 4 );
4075  return nullptr;
4076  }
4077  }
4078 
4079  if ( geom->rotate( m2p.mapRotation(), center ) )
4080  {
4081  QgsDebugMsg( QString( "Error rotating geometry" ).arg( geom->exportToWkt() ) );
4082  return nullptr;
4083  }
4084  }
4085 
4086  if ( !geom->asGeos() )
4087  return nullptr; // there is something really wrong with the geometry
4088 
4089  // fix invalid polygons
4090  if ( geom->type() == QGis::Polygon && !geom->isGeosValid() )
4091  {
4092  QgsGeometry* bufferGeom = geom->buffer( 0, 0 );
4093  if ( !bufferGeom )
4094  {
4095  return nullptr;
4096  }
4097  geom = bufferGeom;
4098  clonedGeometry.reset( geom );
4099  }
4100 
4101  if ( clipGeometry && !clipGeometry->contains( geom ) )
4102  {
4103  QgsGeometry* clipGeom = geom->intersection( clipGeometry ); // creates new geometry
4104  if ( !clipGeom )
4105  {
4106  return nullptr;
4107  }
4108  geom = clipGeom;
4109  clonedGeometry.reset( geom );
4110  }
4111 
4112  return clonedGeometry.take();
4113 }
4114 
4115 bool QgsPalLabeling::checkMinimumSizeMM( const QgsRenderContext& context, const QgsGeometry* geom, double minSize )
4116 {
4117  if ( minSize <= 0 )
4118  {
4119  return true;
4120  }
4121 
4122  if ( !geom )
4123  {
4124  return false;
4125  }
4126 
4127  QGis::GeometryType featureType = geom->type();
4128  if ( featureType == QGis::Point ) //minimum size does not apply to point features
4129  {
4130  return true;
4131  }
4132 
4133  double mapUnitsPerMM = context.mapToPixel().mapUnitsPerPixel() * context.scaleFactor();
4134  if ( featureType == QGis::Line )
4135  {
4136  double length = geom->length();
4137  if ( length >= 0.0 )
4138  {
4139  return ( length >= ( minSize * mapUnitsPerMM ) );
4140  }
4141  }
4142  else if ( featureType == QGis::Polygon )
4143  {
4144  double area = geom->area();
4145  if ( area >= 0.0 )
4146  {
4147  return ( sqrt( area ) >= ( minSize * mapUnitsPerMM ) );
4148  }
4149  }
4150  return true; //should never be reached. Return true in this case to label such geometries anyway.
4151 }
4152 
4154 {
4155  if ( QgsVectorLayerDiagramProvider* provider = mDiagramProviders.value( layerID, nullptr ) )
4156  provider->registerFeature( feat, context );
4157 }
4158 
4159 
4161 {
4162  init( mr->mapSettings() );
4163 }
4164 
4165 
4166 void QgsPalLabeling::init( const QgsMapSettings& mapSettings )
4167 {
4168  mEngine->setMapSettings( mapSettings );
4169 }
4170 
4172 {
4173  delete mEngine;
4174  mEngine = new QgsLabelingEngineV2();
4175 }
4176 
4178 {
4179  Q_UNUSED( layerName );
4180  return mInvalidLayerSettings;
4181 }
4182 
4185 {
4186  //font color
4187  if ( ddValues.contains( QgsPalLayerSettings::Color ) )
4188  {
4189  QVariant ddColor = ddValues.value( QgsPalLayerSettings::Color );
4190  tmpLyr.textColor = ddColor.value<QColor>();
4191  }
4192 
4193  //font transparency
4194  if ( ddValues.contains( QgsPalLayerSettings::FontTransp ) )
4195  {
4196  tmpLyr.textTransp = ddValues.value( QgsPalLayerSettings::FontTransp ).toInt();
4197  }
4198 
4199  tmpLyr.textColor.setAlphaF(( 100.0 - static_cast< double >( tmpLyr.textTransp ) ) / 100.0 );
4200 
4201  //font blend mode
4202  if ( ddValues.contains( QgsPalLayerSettings::FontBlendMode ) )
4203  {
4204  tmpLyr.blendMode = static_cast< QPainter::CompositionMode >( ddValues.value( QgsPalLayerSettings::FontBlendMode ).toInt() );
4205  }
4206 }
4207 
4210 {
4212  {
4213  tmpLyr.wrapChar = ddValues.value( QgsPalLayerSettings::MultiLineWrapChar ).toString();
4214  }
4215 
4216  if ( !tmpLyr.wrapChar.isEmpty() || tmpLyr.getLabelExpression()->expression().contains( "wordwrap" ) )
4217  {
4218 
4220  {
4221  tmpLyr.multilineHeight = ddValues.value( QgsPalLayerSettings::MultiLineHeight ).toDouble();
4222  }
4223 
4225  {
4227  }
4228 
4229  }
4230 
4231  if ( ddValues.contains( QgsPalLayerSettings::DirSymbDraw ) )
4232  {
4233  tmpLyr.addDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbDraw ).toBool();
4234  }
4235 
4236  if ( tmpLyr.addDirectionSymbol )
4237  {
4238 
4239  if ( ddValues.contains( QgsPalLayerSettings::DirSymbLeft ) )
4240  {
4241  tmpLyr.leftDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbLeft ).toString();
4242  }
4243  if ( ddValues.contains( QgsPalLayerSettings::DirSymbRight ) )
4244  {
4245  tmpLyr.rightDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbRight ).toString();
4246  }
4247 
4249  {
4251  }
4252 
4254  {
4256  }
4257 
4258  }
4259 }
4260 
4263 {
4264  //buffer draw
4265  if ( ddValues.contains( QgsPalLayerSettings::BufferDraw ) )
4266  {
4267  tmpLyr.bufferDraw = ddValues.value( QgsPalLayerSettings::BufferDraw ).toBool();
4268  }
4269 
4270  if ( !tmpLyr.bufferDraw )
4271  {
4272  // tmpLyr.bufferSize > 0.0 && tmpLyr.bufferTransp < 100 figured in during evaluation
4273  return; // don't continue looking for unused values
4274  }
4275 
4276  //buffer size
4277  if ( ddValues.contains( QgsPalLayerSettings::BufferSize ) )
4278  {
4279  tmpLyr.bufferSize = ddValues.value( QgsPalLayerSettings::BufferSize ).toDouble();
4280  }
4281 
4282  //buffer transparency
4283  if ( ddValues.contains( QgsPalLayerSettings::BufferTransp ) )
4284  {
4285  tmpLyr.bufferTransp = ddValues.value( QgsPalLayerSettings::BufferTransp ).toInt();
4286  }
4287 
4288  //buffer size units
4289  if ( ddValues.contains( QgsPalLayerSettings::BufferUnit ) )
4290  {
4292  tmpLyr.bufferSizeInMapUnits = ( bufunit == QgsPalLayerSettings::MapUnits );
4293  }
4294 
4295  //buffer color
4296  if ( ddValues.contains( QgsPalLayerSettings::BufferColor ) )
4297  {
4298  QVariant ddColor = ddValues.value( QgsPalLayerSettings::BufferColor );
4299  tmpLyr.bufferColor = ddColor.value<QColor>();
4300  }
4301 
4302  // apply any transparency
4303  tmpLyr.bufferColor.setAlphaF(( 100.0 - static_cast< double >( tmpLyr.bufferTransp ) ) / 100.0 );
4304 
4305  //buffer pen join style
4307  {
4308  tmpLyr.bufferJoinStyle = static_cast< Qt::PenJoinStyle >( ddValues.value( QgsPalLayerSettings::BufferJoinStyle ).toInt() );
4309  }
4310 
4311  //buffer blend mode
4313  {
4314  tmpLyr.bufferBlendMode = static_cast< QPainter::CompositionMode >( ddValues.value( QgsPalLayerSettings::BufferBlendMode ).toInt() );
4315  }
4316 }
4317 
4320 {
4321  //shape draw
4322  if ( ddValues.contains( QgsPalLayerSettings::ShapeDraw ) )
4323  {
4324  tmpLyr.shapeDraw = ddValues.value( QgsPalLayerSettings::ShapeDraw ).toBool();
4325  }
4326 
4327  if ( !tmpLyr.shapeDraw )
4328  {
4329  return; // don't continue looking for unused values
4330  }
4331 
4332  if ( ddValues.contains( QgsPalLayerSettings::ShapeKind ) )
4333  {
4334  tmpLyr.shapeType = static_cast< QgsPalLayerSettings::ShapeType >( ddValues.value( QgsPalLayerSettings::ShapeKind ).toInt() );
4335  }
4336 
4337  if ( ddValues.contains( QgsPalLayerSettings::ShapeSVGFile ) )
4338  {
4339  tmpLyr.shapeSVGFile = ddValues.value( QgsPalLayerSettings::ShapeSVGFile ).toString();
4340  }
4341 
4342  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeType ) )
4343  {
4344  tmpLyr.shapeSizeType = static_cast< QgsPalLayerSettings::SizeType >( ddValues.value( QgsPalLayerSettings::ShapeSizeType ).toInt() );
4345  }
4346 
4347  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeX ) )
4348  {
4349  tmpLyr.shapeSize.setX( ddValues.value( QgsPalLayerSettings::ShapeSizeX ).toDouble() );
4350  }
4351  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeY ) )
4352  {
4353  tmpLyr.shapeSize.setY( ddValues.value( QgsPalLayerSettings::ShapeSizeY ).toDouble() );
4354  }
4355 
4357  {
4358  tmpLyr.shapeSizeUnits = static_cast< QgsPalLayerSettings::SizeUnit >( ddValues.value( QgsPalLayerSettings::ShapeSizeUnits ).toInt() );
4359  }
4360 
4362  {
4364  }
4365 
4366  if ( ddValues.contains( QgsPalLayerSettings::ShapeRotation ) )
4367  {
4368  tmpLyr.shapeRotation = ddValues.value( QgsPalLayerSettings::ShapeRotation ).toDouble();
4369  }
4370 
4371  if ( ddValues.contains( QgsPalLayerSettings::ShapeOffset ) )
4372  {
4373  tmpLyr.shapeOffset = ddValues.value( QgsPalLayerSettings::ShapeOffset ).toPointF();
4374  }
4375 
4377  {
4378  tmpLyr.shapeOffsetUnits = static_cast< QgsPalLayerSettings::SizeUnit >( ddValues.value( QgsPalLayerSettings::ShapeOffsetUnits ).toInt() );
4379  }
4380 
4381  if ( ddValues.contains( QgsPalLayerSettings::ShapeRadii ) )
4382  {
4383  tmpLyr.shapeRadii = ddValues.value( QgsPalLayerSettings::ShapeRadii ).toPointF();
4384  }
4385 
4387  {
4388  tmpLyr.shapeRadiiUnits = static_cast< QgsPalLayerSettings::SizeUnit >( ddValues.value( QgsPalLayerSettings::ShapeRadiiUnits ).toInt() );
4389  }
4390 
4392  {
4393  tmpLyr.shapeTransparency = ddValues.value( QgsPalLayerSettings::ShapeTransparency ).toInt();
4394  }
4395 
4397  {
4398  tmpLyr.shapeBlendMode = static_cast< QPainter::CompositionMode >( ddValues.value( QgsPalLayerSettings::ShapeBlendMode ).toInt() );
4399  }
4400 
4402  {
4403  QVariant ddColor = ddValues.value( QgsPalLayerSettings::ShapeFillColor );
4404  tmpLyr.shapeFillColor = ddColor.value<QColor>();
4405  }
4406 
4408  {
4410  tmpLyr.shapeBorderColor = ddColor.value<QColor>();
4411  }
4412 
4414  {
4415  tmpLyr.shapeBorderWidth = ddValues.value( QgsPalLayerSettings::ShapeBorderWidth ).toDouble();
4416  }
4417 
4419  {
4421  }
4422 
4424  {
4425  tmpLyr.shapeJoinStyle = static_cast< Qt::PenJoinStyle >( ddValues.value( QgsPalLayerSettings::ShapeJoinStyle ).toInt() );
4426  }
4427 }
4428 
4431 {
4432  //shadow draw
4433  if ( ddValues.contains( QgsPalLayerSettings::ShadowDraw ) )
4434  {
4435  tmpLyr.shadowDraw = ddValues.value( QgsPalLayerSettings::ShadowDraw ).toBool();
4436  }
4437 
4438  if ( !tmpLyr.shadowDraw )
4439  {
4440  return; // don't continue looking for unused values
4441  }
4442 
4443  if ( ddValues.contains( QgsPalLayerSettings::ShadowUnder ) )
4444  {
4445  tmpLyr.shadowUnder = static_cast< QgsPalLayerSettings::ShadowType >( ddValues.value( QgsPalLayerSettings::ShadowUnder ).toInt() );
4446  }
4447 
4449  {
4450  tmpLyr.shadowOffsetAngle = ddValues.value( QgsPalLayerSettings::ShadowOffsetAngle ).toInt();
4451  }
4452 
4454  {
4455  tmpLyr.shadowOffsetDist = ddValues.value( QgsPalLayerSettings::ShadowOffsetDist ).toDouble();
4456  }
4457 
4459  {
4461  }
4462 
4463  if ( ddValues.contains( QgsPalLayerSettings::ShadowRadius ) )
4464  {
4465  tmpLyr.shadowRadius = ddValues.value( QgsPalLayerSettings::ShadowRadius ).toDouble();
4466  }
4467 
4469  {
4471  }
4472 
4474  {
4476  }
4477 
4478  if ( ddValues.contains( QgsPalLayerSettings::ShadowScale ) )
4479  {
4480  tmpLyr.shadowScale = ddValues.value( QgsPalLayerSettings::ShadowScale ).toInt();
4481  }
4482 
4483  if ( ddValues.contains( QgsPalLayerSettings::ShadowColor ) )
4484  {
4485  QVariant ddColor = ddValues.value( QgsPalLayerSettings::ShadowColor );
4486  tmpLyr.shadowColor = ddColor.value<QColor>();
4487  }
4488 
4490  {
4491  tmpLyr.shadowBlendMode = static_cast< QPainter::CompositionMode >( ddValues.value( QgsPalLayerSettings::ShadowBlendMode ).toInt() );
4492  }
4493 }
4494 
4495 
4496 
4498 {
4499  mEngine->run( context );
4500 }
4501 
4503 {
4504 }
4505 
4507 {
4509 }
4510 
4512 {
4514 }
4515 
4517 {
4518  return mEngine->takeResults();
4519 }
4520 
4521 void QgsPalLabeling::numCandidatePositions( int& candPoint, int& candLine, int& candPolygon )
4522 {
4523  mEngine->numCandidatePositions( candPoint, candLine, candPolygon );
4524 }
4525 
4526 void QgsPalLabeling::setNumCandidatePositions( int candPoint, int candLine, int candPolygon )
4527 {
4528  mEngine->setNumCandidatePositions( candPoint, candLine, candPolygon );
4529 }
4530 
4532 {
4533  mEngine->setSearchMethod( s );
4534 }
4535 
4537 {
4538  return mEngine->searchMethod();
4539 }
4540 
4542 {
4544 }
4545 
4547 {
4549 }
4550 
4552 {
4554 }
4555 
4557 {
4559 }
4560 
4562 {
4564 }
4565 
4567 {
4569 }
4570 
4572 {
4574 }
4575 
4577 {
4579 }
4580 
4582 {
4584 }
4585 
4587 {
4589 }
4590 
4592 {
4594 }
4595 
4597 {
4599 }
4600 
4602 {
4603  QgsPoint outPt = xform->transform( lp->getX(), lp->getY() );
4604 
4605  painter->save();
4606 
4607 #if 0 // TODO: generalize some of this
4608  double w = lp->getWidth();
4609  double h = lp->getHeight();
4610  double cx = lp->getX() + w / 2.0;
4611  double cy = lp->getY() + h / 2.0;
4612  double scale = 1.0 / xform->mapUnitsPerPixel();
4613  double rotation = xform->mapRotation();
4614  double sw = w * scale;
4615  double sh = h * scale;
4616  QRectF rect( -sw / 2, -sh / 2, sw, sh );
4617 
4618  painter->translate( xform->transform( QPointF( cx, cy ) ).toQPointF() );
4619  if ( rotation )
4620  {
4621  // Only if not horizontal
4622  if ( lp->getFeaturePart()->getLayer()->getArrangement() != P_POINT &&
4623  lp->getFeaturePart()->getLayer()->getArrangement() != P_POINT_OVER &&
4624  lp->getFeaturePart()->getLayer()->getArrangement() != P_HORIZ )
4625  {
4626  painter->rotate( rotation );
4627  }
4628  }
4629  painter->translate( rect.bottomLeft() );
4630  painter->rotate( -lp->getAlpha() * 180 / M_PI );
4631  painter->translate( -rect.bottomLeft() );
4632 #else
4633  QgsPoint outPt2 = xform->transform( lp->getX() + lp->getWidth(), lp->getY() + lp->getHeight() );
4634  QRectF rect( 0, 0, outPt2.x() - outPt.x(), outPt2.y() - outPt.y() );
4635  painter->translate( QPointF( outPt.x(), outPt.y() ) );
4636  painter->rotate( -lp->getAlpha() * 180 / M_PI );
4637 #endif
4638 
4639  if ( lp->conflictsWithObstacle() )
4640  {
4641  painter->setPen( QColor( 255, 0, 0, 64 ) );
4642  }
4643  else
4644  {
4645  painter->setPen( QColor( 0, 0, 0, 64 ) );
4646  }
4647  painter->drawRect( rect );
4648  painter->restore();
4649 
4650  // save the rect
4651  rect.moveTo( outPt.x(), outPt.y() );
4652  if ( candidates )
4653  candidates->append( QgsLabelCandidate( rect, lp->cost() * 1000 ) );
4654 
4655  // show all parts of the multipart label
4656  if ( lp->getNextPart() )
4657  drawLabelCandidateRect( lp->getNextPart(), painter, xform, candidates );
4658 }
4659 
4660 
4662  const QgsLabelComponent& component,
4663  const QgsPalLayerSettings& tmpLyr )
4664 {
4665  QPainter* p = context.painter();
4666 
4667  double penSize = tmpLyr.scaleToPixelContext( tmpLyr.bufferSize, context,
4669 
4670  QPainterPath path;
4671  path.setFillRule( Qt::WindingFill );
4672  path.addText( 0, 0, tmpLyr.textFont, component.text() );
4673  QPen pen( tmpLyr.bufferColor );
4674  pen.setWidthF( penSize );
4675  pen.setJoinStyle( tmpLyr.bufferJoinStyle );
4676  QColor tmpColor( tmpLyr.bufferColor );
4677  // honor pref for whether to fill buffer interior
4678  if ( tmpLyr.bufferNoFill )
4679  {
4680  tmpColor.setAlpha( 0 );
4681  }
4682 
4683  // store buffer's drawing in QPicture for drop shadow call
4684  QPicture buffPict;
4685  QPainter buffp;
4686  buffp.begin( &buffPict );
4687  buffp.setPen( pen );
4688  buffp.setBrush( tmpColor );
4689  buffp.drawPath( path );
4690  buffp.end();
4691 
4692  if ( tmpLyr.shadowDraw && tmpLyr.shadowUnder == QgsPalLayerSettings::ShadowBuffer )
4693  {
4694  QgsLabelComponent bufferComponent = component;
4695  bufferComponent.setOrigin( QgsPoint( 0.0, 0.0 ) );
4696  bufferComponent.setPicture( &buffPict );
4697  bufferComponent.setPictureBuffer( penSize / 2.0 );
4698  drawLabelShadow( context, bufferComponent, tmpLyr );
4699  }
4700 
4701  p->save();
4702  if ( context.useAdvancedEffects() )
4703  {
4704  p->setCompositionMode( tmpLyr.bufferBlendMode );
4705  }
4706 // p->setPen( pen );
4707 // p->setBrush( tmpColor );
4708 // p->drawPath( path );
4709 
4710  // scale for any print output or image saving @ specific dpi
4711  p->scale( component.dpiRatio(), component.dpiRatio() );
4712  _fixQPictureDPI( p );
4713  p->drawPicture( 0, 0, buffPict );
4714  p->restore();
4715 }
4716 
4718  QgsLabelComponent component,
4719  const QgsPalLayerSettings& tmpLyr )
4720 {
4721  QPainter* p = context.painter();
4722  double labelWidth = component.size().x(), labelHeight = component.size().y();
4723  //QgsDebugMsgLevel( QString( "Background label rotation: %1" ).arg( component.rotation() ), 4 );
4724 
4725  // shared calculations between shapes and SVG
4726 
4727  // configure angles, set component rotation and rotationOffset
4729  {
4730  component.setRotation( -( component.rotation() * 180 / M_PI ) ); // RotationSync
4731  component.setRotationOffset(
4733  }
4734  else // RotationFixed
4735  {
4736  component.setRotation( 0.0 ); // don't use label's rotation
4737  component.setRotationOffset( tmpLyr.shapeRotation );
4738  }
4739 
4740  // mm to map units conversion factor
4741  double mmToMapUnits = tmpLyr.shapeSizeMapUnitScale.computeMapUnitsPerPixel( context ) * context.scaleFactor();
4742 
4743  // TODO: the following label-buffered generated shapes and SVG symbols should be moved into marker symbology classes
4744 
4745  if ( tmpLyr.shapeType == QgsPalLayerSettings::ShapeSVG )
4746  {
4747  // all calculations done in shapeSizeUnits, which are then passed to symbology class for painting
4748 
4749  if ( tmpLyr.shapeSVGFile.isEmpty() )
4750  return;
4751 
4752  double sizeOut = 0.0;
4753  // only one size used for SVG sizing/scaling (no use of shapeSize.y() or Y field in gui)
4755  {
4756  sizeOut = tmpLyr.shapeSize.x();
4757  }
4758  else if ( tmpLyr.shapeSizeType == QgsPalLayerSettings::SizeBuffer )
4759  {
4760  // add buffer to greatest dimension of label
4761  if ( labelWidth >= labelHeight )
4762  sizeOut = labelWidth;
4763  else if ( labelHeight > labelWidth )
4764  sizeOut = labelHeight;
4765 
4766  // label size in map units, convert to shapeSizeUnits, if different
4767  if ( tmpLyr.shapeSizeUnits == QgsPalLayerSettings::MM )
4768  {
4769  sizeOut /= mmToMapUnits;
4770  }
4771 
4772  // add buffer
4773  sizeOut += tmpLyr.shapeSize.x() * 2;
4774  }
4775 
4776  // don't bother rendering symbols smaller than 1x1 pixels in size
4777  // TODO: add option to not show any svgs under/over a certian size
4778  if ( tmpLyr.scaleToPixelContext( sizeOut, context, tmpLyr.shapeSizeUnits, false, tmpLyr.shapeSizeMapUnitScale ) < 1.0 )
4779  return;
4780 
4781  QgsStringMap map; // for SVG symbology marker
4783  map["size"] = QString::number( sizeOut );
4784  map["size_unit"] = QgsSymbolLayerV2Utils::encodeOutputUnit(
4786  map["angle"] = QString::number( 0.0 ); // angle is handled by this local painter
4787 
4788  // offset is handled by this local painter
4789  // TODO: see why the marker renderer doesn't seem to translate offset *after* applying rotation
4790  //map["offset"] = QgsSymbolLayerV2Utils::encodePoint( tmpLyr.shapeOffset );
4791  //map["offset_unit"] = QgsUnitTypes::encodeUnit(
4792  // tmpLyr.shapeOffsetUnits == QgsPalLayerSettings::MapUnits ? QgsSymbolV2::MapUnit : QgsSymbolV2::MM );
4793 
4794  map["fill"] = tmpLyr.shapeFillColor.name();
4795  map["outline"] = tmpLyr.shapeBorderColor.name();
4796  map["outline-width"] = QString::number( tmpLyr.shapeBorderWidth );
4797 
4798  // TODO: fix overriding SVG symbol's border width/units in QgsSvgCache
4799  // currently broken, fall back to symbol's
4800  //map["outline_width_unit"] = QgsUnitTypes::encodeUnit(
4801  // tmpLyr.shapeBorderWidthUnits == QgsPalLayerSettings::MapUnits ? QgsSymbolV2::MapUnit : QgsSymbolV2::MM );
4802 
4803  if ( tmpLyr.shadowDraw && tmpLyr.shadowUnder == QgsPalLayerSettings::ShadowShape )
4804  {
4805  // configure SVG shadow specs
4806  QgsStringMap shdwmap( map );
4807  shdwmap["fill"] = tmpLyr.shadowColor.name();
4808  shdwmap["outline"] = tmpLyr.shadowColor.name();
4809  shdwmap["size"] = QString::number( sizeOut * tmpLyr.rasterCompressFactor );
4810 
4811  // store SVG's drawing in QPicture for drop shadow call
4812  QPicture svgPict;
4813  QPainter svgp;
4814  svgp.begin( &svgPict );
4815 
4816  // draw shadow symbol
4817 
4818  // clone current render context map unit/mm conversion factors, but not
4819  // other map canvas parameters, then substitute this painter for use in symbology painting
4820  // NOTE: this is because the shadow needs to be scaled correctly for output to map canvas,
4821  // but will be created relative to the SVG's computed size, not the current map canvas
4822  QgsRenderContext shdwContext;
4823  shdwContext.setMapToPixel( context.mapToPixel() );
4824  shdwContext.setScaleFactor( context.scaleFactor() );
4825  shdwContext.setPainter( &svgp );
4826 
4827  QgsSymbolLayerV2* symShdwL = QgsSvgMarkerSymbolLayerV2::create( shdwmap );
4828  QgsSvgMarkerSymbolLayerV2* svgShdwM = static_cast<QgsSvgMarkerSymbolLayerV2*>( symShdwL );
4829  QgsSymbolV2RenderContext svgShdwContext( shdwContext, QgsSymbolV2::Mixed,
4830  ( 100.0 - static_cast< double >( tmpLyr.shapeTransparency ) ) / 100.0 );
4831 
4832  double svgSize = tmpLyr.scaleToPixelContext( sizeOut, context, tmpLyr.shapeSizeUnits, true, tmpLyr.shapeSizeMapUnitScale );
4833  svgShdwM->renderPoint( QPointF( svgSize / 2, -svgSize / 2 ), svgShdwContext );
4834  svgp.end();
4835 
4836  component.setPicture( &svgPict );
4837  // TODO: when SVG symbol's border width/units is fixed in QgsSvgCache, adjust for it here
4838  component.setPictureBuffer( 0.0 );
4839 
4840  component.setSize( QgsPoint( svgSize, svgSize ) );
4841  component.setOffset( QgsPoint( 0.0, 0.0 ) );
4842 
4843  // rotate about origin center of SVG
4844  p->save();
4845  p->translate( component.center().x(), component.center().y() );
4846  p->rotate( component.rotation() );
4847  p->scale( 1.0 / tmpLyr.rasterCompressFactor, 1.0 / tmpLyr.rasterCompressFactor );
4848  double xoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.x(), context, tmpLyr.shapeOffsetUnits, true, tmpLyr.shapeOffsetMapUnitScale );
4849  double yoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.y(), context, tmpLyr.shapeOffsetUnits, true, tmpLyr.shapeOffsetMapUnitScale );
4850  p->translate( QPointF( xoff, yoff ) );
4851  p->rotate( component.rotationOffset() );
4852  p->translate( -svgSize / 2, svgSize / 2 );
4853 
4854  drawLabelShadow( context, component, tmpLyr );
4855  p->restore();
4856 
4857  delete svgShdwM;
4858  svgShdwM = nullptr;
4859  }
4860 
4861  // draw the actual symbol
4863  QgsSvgMarkerSymbolLayerV2* svgM = static_cast<QgsSvgMarkerSymbolLayerV2*>( symL );
4864  QgsSymbolV2RenderContext svgContext( context, QgsSymbolV2::Mixed,
4865  ( 100.0 - static_cast< double >( tmpLyr.shapeTransparency ) ) / 100.0 );
4866 
4867  p->save();
4868  if ( context.useAdvancedEffects() )
4869  {
4870  p->setCompositionMode( tmpLyr.shapeBlendMode );
4871  }
4872  p->translate( component.center().x(), component.center().y() );
4873  p->rotate( component.rotation() );
4874  double xoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.x(), context, tmpLyr.shapeOffsetUnits, false, tmpLyr.shapeOffsetMapUnitScale );
4875  double yoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.y(), context, tmpLyr.shapeOffsetUnits, false, tmpLyr.shapeOffsetMapUnitScale );
4876  p->translate( QPointF( xoff, yoff ) );
4877  p->rotate( component.rotationOffset() );
4878  svgM->renderPoint( QPointF( 0, 0 ), svgContext );
4879  p->setCompositionMode( QPainter::CompositionMode_SourceOver ); // just to be sure
4880  p->restore();
4881 
4882  delete svgM;
4883  svgM = nullptr;
4884 
4885  }
4886  else // Generated Shapes
4887  {
4888  // all calculations done in shapeSizeUnits
4889 
4890  double w = labelWidth / ( tmpLyr.shapeSizeUnits == QgsPalLayerSettings::MM ? mmToMapUnits : 1 );
4891  double h = labelHeight / ( tmpLyr.shapeSizeUnits == QgsPalLayerSettings::MM ? mmToMapUnits : 1 );
4892 
4893  double xsize = tmpLyr.shapeSize.x();
4894  double ysize = tmpLyr.shapeSize.y();
4895 
4897  {
4898  w = xsize;
4899  h = ysize;
4900  }
4901  else if ( tmpLyr.shapeSizeType == QgsPalLayerSettings::SizeBuffer )
4902  {
4904  {
4905  if ( w > h )
4906  h = w;
4907  else if ( h > w )
4908  w = h;
4909  }
4910  else if ( tmpLyr.shapeType == QgsPalLayerSettings::ShapeCircle )
4911  {
4912  // start with label bound by circle
4913  h = sqrt( pow( w, 2 ) + pow( h, 2 ) );
4914  w = h;
4915  }
4916  else if ( tmpLyr.shapeType == QgsPalLayerSettings::ShapeEllipse )
4917  {
4918  // start with label bound by ellipse
4919  h = h / sqrt( 2.0 ) * 2;
4920  w = w / sqrt( 2.0 ) * 2;
4921  }
4922 
4923  w += xsize * 2;
4924  h += ysize * 2;
4925  }
4926 
4927  // convert everything over to map pixels from here on
4928  w = tmpLyr.scaleToPixelContext( w, context, tmpLyr.shapeSizeUnits, true, tmpLyr.shapeSizeMapUnitScale );
4929  h = tmpLyr.scaleToPixelContext( h, context, tmpLyr.shapeSizeUnits, true, tmpLyr.shapeSizeMapUnitScale );
4930 
4931  // offsets match those of symbology: -x = left, -y = up
4932  QRectF rect( -w / 2.0, - h / 2.0, w, h );
4933 
4934  if ( rect.isNull() )
4935  return;
4936 
4937  p->save();
4938  p->translate( QPointF( component.center().x(), component.center().y() ) );
4939  p->rotate( component.rotation() );
4940  double xoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.x(), context, tmpLyr.shapeOffsetUnits, false, tmpLyr.shapeOffsetMapUnitScale );
4941  double yoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.y(), context, tmpLyr.shapeOffsetUnits, false, tmpLyr.shapeOffsetMapUnitScale );
4942  p->translate( QPointF( xoff, yoff ) );
4943  p->rotate( component.rotationOffset() );
4944 
4945  double penSize = tmpLyr.scaleToPixelContext( tmpLyr.shapeBorderWidth, context, tmpLyr.shapeBorderWidthUnits, true, tmpLyr.shapeBorderWidthMapUnitScale );
4946 
4947  QPen pen;
4948  if ( tmpLyr.shapeBorderWidth > 0 )
4949  {
4950  pen.setColor( tmpLyr.shapeBorderColor );
4951  pen.setWidthF( penSize );
4953  pen.setJoinStyle( tmpLyr.shapeJoinStyle );
4954  }
4955  else
4956  {
4957  pen = Qt::NoPen;
4958  }
4959 
4960  // store painting in QPicture for shadow drawing
4961  QPicture shapePict;
4962  QPainter shapep;
4963  shapep.begin( &shapePict );
4964  shapep.setPen( pen );
4965  shapep.setBrush( tmpLyr.shapeFillColor );
4966 
4969  {
4971  {
4972  shapep.drawRoundedRect( rect, tmpLyr.shapeRadii.x(), tmpLyr.shapeRadii.y(), Qt::RelativeSize );
4973  }
4974  else
4975  {
4976  double xRadius = tmpLyr.scaleToPixelContext( tmpLyr.shapeRadii.x(), context, tmpLyr.shapeRadiiUnits, true, tmpLyr.shapeRadiiMapUnitScale );
4977  double yRadius = tmpLyr.scaleToPixelContext( tmpLyr.shapeRadii.y(), context, tmpLyr.shapeRadiiUnits, true, tmpLyr.shapeRadiiMapUnitScale );
4978  shapep.drawRoundedRect( rect, xRadius, yRadius );
4979  }
4980  }
4981  else if ( tmpLyr.shapeType == QgsPalLayerSettings::ShapeEllipse
4983  {
4984  shapep.drawEllipse( rect );
4985  }
4986  shapep.end();
4987 
4988  p->scale( 1.0 / tmpLyr.rasterCompressFactor, 1.0 / tmpLyr.rasterCompressFactor );
4989 
4990  if ( tmpLyr.shadowDraw && tmpLyr.shadowUnder == QgsPalLayerSettings::ShadowShape )
4991  {
4992  component.setPicture( &shapePict );
4993  component.setPictureBuffer( penSize / 2.0 );
4994 
4995  component.setSize( QgsPoint( rect.width(), rect.height() ) );
4996  component.setOffset( QgsPoint( rect.width() / 2, -rect.height() / 2 ) );
4997  drawLabelShadow( context, component, tmpLyr );
4998  }
4999 
5000  p->setOpacity(( 100.0 - static_cast< double >( tmpLyr.shapeTransparency ) ) / 100.0 );
5001  if ( context.useAdvancedEffects() )
5002  {
5003  p->setCompositionMode( tmpLyr.shapeBlendMode );
5004  }
5005 
5006  // scale for any print output or image saving @ specific dpi
5007  p->scale( component.dpiRatio(), component.dpiRatio() );
5008  _fixQPictureDPI( p );
5009  p->drawPicture( 0, 0, shapePict );
5010  p->restore();
5011  }
5012 }
5013 
5015  const QgsLabelComponent& component,
5016  const QgsPalLayerSettings& tmpLyr )
5017 {
5018  // incoming component sizes should be multiplied by rasterCompressFactor, as
5019  // this allows shadows to be created at paint device dpi (e.g. high resolution),
5020  // then scale device painter by 1.0 / rasterCompressFactor for output
5021 
5022  QPainter* p = context.painter();
5023  double componentWidth = component.size().x(), componentHeight = component.size().y();
5024  double xOffset = component.offset().x(), yOffset = component.offset().y();
5025  double pictbuffer = component.pictureBuffer();
5026 
5027  // generate pixmap representation of label component drawing
5028  bool mapUnits = ( tmpLyr.shadowRadiusUnits == QgsPalLayerSettings::MapUnits );
5029  double radius = tmpLyr.scaleToPixelContext( tmpLyr.shadowRadius, context, tmpLyr.shadowRadiusUnits, !mapUnits, tmpLyr.shadowRadiusMapUnitScale );
5030  radius /= ( mapUnits ? tmpLyr.vectorScaleFactor / component.dpiRatio() : 1 );
5031  radius = static_cast< int >( radius + 0.5 );
5032 
5033  // TODO: add labeling gui option to adjust blurBufferClippingScale to minimize pixels, or
5034  // to ensure shadow isn't clipped too tight. (Or, find a better method of buffering)
5035  double blurBufferClippingScale = 3.75;
5036  int blurbuffer = ( radius > 17 ? 16 : radius ) * blurBufferClippingScale;
5037 
5038  QImage blurImg( componentWidth + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ),
5039  componentHeight + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ),
5040  QImage::Format_ARGB32_Premultiplied );
5041 
5042  // TODO: add labeling gui option to not show any shadows under/over a certian size
5043  // keep very small QImages from causing paint device issues, i.e. must be at least > 1
5044  int minBlurImgSize = 1;
5045  // max limitation on QgsSvgCache is 10,000 for screen, which will probably be reasonable for future caching here, too
5046  // 4 x QgsSvgCache limit for output to print/image at higher dpi
5047  // TODO: should it be higher, scale with dpi, or have no limit? Needs testing with very large labels rendered at high dpi output
5048  int maxBlurImgSize = 40000;
5049  if ( blurImg.isNull()
5050  || ( blurImg.width() < minBlurImgSize || blurImg.height() < minBlurImgSize )
5051  || ( blurImg.width() > maxBlurImgSize || blurImg.height() > maxBlurImgSize ) )
5052  return;
5053 
5054  blurImg.fill( QColor( Qt::transparent ).rgba() );
5055  QPainter pictp;
5056  if ( !pictp.begin( &blurImg ) )
5057  return;
5058  pictp.setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform );
5059  QPointF imgOffset( blurbuffer + pictbuffer + xOffset,
5060  blurbuffer + pictbuffer + componentHeight + yOffset );
5061 
5062  pictp.drawPicture( imgOffset,
5063  *component.picture() );
5064 
5065  // overlay shadow color
5066  pictp.setCompositionMode( QPainter::CompositionMode_SourceIn );
5067  pictp.fillRect( blurImg.rect(), tmpLyr.shadowColor );
5068  pictp.end();
5069 
5070  // blur the QImage in-place
5071  if ( tmpLyr.shadowRadius > 0.0 && radius > 0 )
5072  {
5073  QgsSymbolLayerV2Utils::blurImageInPlace( blurImg, blurImg.rect(), radius, tmpLyr.shadowRadiusAlphaOnly );
5074  }
5075 
5076  if ( tmpLyr.showingShadowRects ) // engine setting, not per layer
5077  {
5078  // debug rect for QImage shadow registration and clipping visualization
5079  QPainter picti;
5080  picti.begin( &blurImg );
5081  picti.setBrush( Qt::Dense7Pattern );
5082  QPen imgPen( QColor( 0, 0, 255, 255 ) );
5083  imgPen.setWidth( 1 );
5084  picti.setPen( imgPen );
5085  picti.setOpacity( 0.1 );
5086  picti.drawRect( 0, 0, blurImg.width(), blurImg.height() );
5087  picti.end();
5088  }
5089 
5090  double offsetDist = tmpLyr.scaleToPixelContext( tmpLyr.shadowOffsetDist, context, tmpLyr.shadowOffsetUnits, true, tmpLyr.shadowOffsetMapUnitScale );
5091  double angleRad = tmpLyr.shadowOffsetAngle * M_PI / 180; // to radians
5092  if ( tmpLyr.shadowOffsetGlobal )
5093  {
5094  // TODO: check for differences in rotation origin and cw/ccw direction,
5095  // when this shadow function is used for something other than labels
5096 
5097  // it's 0-->cw-->360 for labels
5098  //QgsDebugMsgLevel( QString( "Shadow aggregated label rotation (degrees): %1" ).arg( component.rotation() + component.rotationOffset() ), 4 );
5099  angleRad -= ( component.rotation() * M_PI / 180 + component.rotationOffset() * M_PI / 180 );
5100  }
5101 
5102  QPointF transPt( -offsetDist * cos( angleRad + M_PI / 2 ),
5103  -offsetDist * sin( angleRad + M_PI / 2 ) );
5104 
5105  p->save();
5106  p->setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform );
5107  if ( context.useAdvancedEffects() )
5108  {
5109  p->setCompositionMode( tmpLyr.shadowBlendMode );
5110  }
5111  p->setOpacity(( 100.0 - static_cast< double >( tmpLyr.shadowTransparency ) ) / 100.0 );
5112 
5113  double scale = static_cast< double >( tmpLyr.shadowScale ) / 100.0;
5114  // TODO: scale from center/center, left/center or left/top, instead of default left/bottom?
5115  p->scale( scale, scale );
5116  if ( component.useOrigin() )
5117  {
5118  p->translate( component.origin().x(), component.origin().y() );
5119  }
5120  p->translate( transPt );
5121  p->translate( -imgOffset.x(),
5122  -imgOffset.y() );
5123  p->drawImage( 0, 0, blurImg );
5124  p->restore();
5125 
5126  // debug rects
5127  if ( tmpLyr.showingShadowRects ) // engine setting, not per layer
5128  {
5129  // draw debug rect for QImage painting registration
5130  p->save();
5131  p->setBrush( Qt::NoBrush );
5132  QPen imgPen( QColor( 255, 0, 0, 10 ) );
5133  imgPen.setWidth( 2 );
5134  imgPen.setStyle( Qt::DashLine );
5135  p->setPen( imgPen );
5136  p->scale( scale, scale );
5137  if ( component.useOrigin() )
5138  {
5139  p->translate( component.origin().x(), component.origin().y() );
5140  }
5141  p->translate( transPt );
5142  p->translate( -imgOffset.x(),
5143  -imgOffset.y() );
5144  p->drawRect( 0, 0, blurImg.width(), blurImg.height() );
5145  p->restore();
5146 
5147  // draw debug rect for passed in component dimensions
5148  p->save();
5149  p->setBrush( Qt::NoBrush );
5150  QPen componentRectPen( QColor( 0, 255, 0, 70 ) );
5151  componentRectPen.setWidth( 1 );
5152  if ( component.useOrigin() )
5153  {
5154  p->translate( component.origin().x(), component.origin().y() );
5155  }
5156  p->setPen( componentRectPen );
5157  p->drawRect( QRect( -xOffset, -componentHeight - yOffset, componentWidth, componentHeight ) );
5158  p->restore();
5159  }
5160 }
5161 
5163 {
5165 }
5166 
5168 {
5170 }
5171 
5173 {
5174  QgsProject::instance()->removeEntry( "PAL", "/SearchMethod" );
5175  QgsProject::instance()->removeEntry( "PAL", "/CandidatesPoint" );
5176  QgsProject::instance()->removeEntry( "PAL", "/CandidatesLine" );
5177  QgsProject::instance()->removeEntry( "PAL", "/CandidatesPolygon" );
5178  QgsProject::instance()->removeEntry( "PAL", "/ShowingCandidates" );
5179  QgsProject::instance()->removeEntry( "PAL", "/ShowingShadowRects" );
5180  QgsProject::instance()->removeEntry( "PAL", "/ShowingAllLabels" );
5181  QgsProject::instance()->removeEntry( "PAL", "/ShowingPartialsLabels" );
5182  QgsProject::instance()->removeEntry( "PAL", "/DrawOutlineLabels" );
5183 }
5184 
5186 {
5187  QgsPalLabeling* lbl = new QgsPalLabeling();
5194  return lbl;
5195 }
5196 
5197 
5199 {
5200  mLabelSearchTree = new QgsLabelSearchTree();
5201 }
5202 
5204 {
5205  delete mLabelSearchTree;
5206  mLabelSearchTree = nullptr;
5207 }
5208 
5210 {
5211  QList<QgsLabelPosition> positions;
5212 
5213  QList<QgsLabelPosition*> positionPointers;
5214  if ( mLabelSearchTree )
5215  {
5216  mLabelSearchTree->label( p, positionPointers );
5217  QList<QgsLabelPosition*>::const_iterator pointerIt = positionPointers.constBegin();
5218  for ( ; pointerIt != positionPointers.constEnd(); ++pointerIt )
5219  {
5220  positions.push_back( QgsLabelPosition( **pointerIt ) );
5221  }
5222  }
5223 
5224  return positions;
5225 }
5226 
5228 {
5229  QList<QgsLabelPosition> positions;
5230 
5231  QList<QgsLabelPosition*> positionPointers;
5232  if ( mLabelSearchTree )
5233  {
5234  mLabelSearchTree->labelsInRect( r, positionPointers );
5235  QList<QgsLabelPosition*>::const_iterator pointerIt = positionPointers.constBegin();
5236  for ( ; pointerIt != positionPointers.constEnd(); ++pointerIt )
5237  {
5238  positions.push_back( QgsLabelPosition( **pointerIt ) );
5239  }
5240  }
5241 
5242  return positions;
5243 }
const QgsMapSettings & mapSettings()
bridge to QgsMapSettings
virtual void registerDiagramFeature(const QString &layerID, QgsFeature &feat, QgsRenderContext &context) override
called for every diagram feature
QgsFeatureId id() const
Get the feature ID for this feature.
Definition: qgsfeature.cpp:65
QTransform fromTranslate(qreal dx, qreal dy)
Label below point, slightly right of center.
static QString encodeOutputUnit(QgsSymbolV2::OutputUnit unit)
static void _fixQPictureDPI(QPainter *p)
Class for parsing and evaluation of expressions (formerly called "search strings").
void setShowingCandidates(bool showing)
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
void setActive(bool active)
void setOpacity(qreal opacity)
A rectangle specified with double values.
Definition: qgsrectangle.h:35
static QgsGeometry * prepareGeometry(const QgsGeometry *geometry, QgsRenderContext &context, const QgsCoordinateTransform *ct, QgsGeometry *clipGeometry=nullptr)
Prepares a geometry for registration with PAL.
Label on bottom-left of point.
void setStyle(Qt::PenStyle style)
QHash< QString, QgsVectorLayerLabelProvider * > mLabelProviders
hashtable of label providers, being filled during labeling (key = layer ID)
QString & append(QChar ch)
bool hasParserError() const
Returns true if an error occurred when parsing the input expression.
static void dataDefinedShapeBackground(QgsPalLayerSettings &tmpLyr, const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &ddValues)
bool dataDefinedIsActive(QgsPalLayerSettings::DataDefinedProperties p) const
Whether data definition is active.
iterator erase(iterator pos)
QgsMapUnitScale shapeSizeMapUnitScale
bool diagramsEnabled() const
Returns whether the layer contains diagrams which are enabled and should be drawn.
static void dataDefinedTextStyle(QgsPalLayerSettings &tmpLyr, const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &ddValues)
A container class for data source field mapping or expression.
QgsMapUnitScale shadowRadiusMapUnitScale
bool end()
bool contains(const Key &key) const
GeometryType
Definition: qgis.h:111
Q_DECL_DEPRECATED QVariant evaluate(const QgsFeature *f)
Evaluate the feature and return the result.
int pixelSize() const
void setOrigin(const QgsPoint &point)
void fillRect(const QRectF &rectangle, const QBrush &brush)
void setCompositionMode(CompositionMode mode)
virtual bool willUseLayer(QgsVectorLayer *layer) override
called to find out whether the layer is used for labeling
virtual bool prepare(const QgsRenderContext &context, QStringList &attributeNames)
Prepare for registration of features.
void setNumCandidatePositions(int candPoint, int candLine, int candPolygon)
QVariant dataDefinedValue(QgsPalLayerSettings::DataDefinedProperties p, QgsFeature &f, const QgsFields &fields, const QgsExpressionContext *context=nullptr) const
Get data defined property value from expression string or attribute field name.
void registerFeature(QgsFeature &f, QgsRenderContext &context, const QString &dxfLayer, QgsLabelFeature **labelFeature=nullptr, QgsGeometry *obstacleGeometry=nullptr)
Register a feature for labelling.
QDomNode appendChild(const QDomNode &newChild)
void push_back(const T &value)
QString name() const
double getWidth() const
QgsLabelingResults * takeResults()
Return pointer to recently computed results (in drawLabeling()) and pass the ownership of results to ...
QString attribute(const QString &name, const QString &defValue) const
QString field() const
Get the field which this QgsDataDefined represents.
A class to query the labeling structure at a given point (small wraper around pal RTree class) ...
UpsideDownLabels upsidedownLabels
double obstacleFactor
Obstacle factor, where 1.0 = default, < 1.0 more likely to be covered by labels, 1.0 less likely to be covered
Label on top-left of point.
qreal pointSizeF() const
void setShowingPartialsLabels(bool showing)
#define QgsDebugMsg(str)
Definition: qgslogger.h:33
void setSearchMethod(Search s)
int weight() const
QPoint map(const QPoint &point) const
void loadEngineSettings()
load/save engine settings to project file
Whether to show debugging rectangles for drop shadows.
QStringList split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
static QString encodeColor(const QColor &color)
static void drawLabelCandidateRect(pal::LabelPosition *lp, QPainter *painter, const QgsMapToPixel *xform, QList< QgsLabelCandidate > *candidates=nullptr)
QPainter::CompositionMode bufferBlendMode
QString & prepend(QChar ch)
double rendererScale() const
double rotationOffset() const
void renderPoint(QPointF point, QgsSymbolV2RenderContext &context) override
QgsMapUnitScale shadowOffsetMapUnitScale
const QgsPoint & size() const
void scale(qreal sx, qreal sy)
double computeMapUnitsPerPixel(const QgsRenderContext &c) const
Computes a map units per pixel scaling factor, respecting the minimum and maximum scales set for the ...
void addProvider(QgsAbstractLabelProvider *provider)
Add provider of label features. Takes ownership of the provider.
const_iterator constBegin() const
QgsPoint transform(const QgsPoint &p) const
Transform the point from map (world) coordinates to device coordinates.
const T & at(int i) const
void setCustomProperty(const QString &key, const QVariant &value)
Set a custom property for layer.
double cost() const
Returns the candidate label position&#39;s geographical cost.
QgsRectangle boundingBox() const
Returns the bounding box of this feature.
QuadrantPosition quadOffset
void setUnderline(bool enable)
static void drawLabelBuffer(QgsRenderContext &context, const QgsLabelComponent &component, const QgsPalLayerSettings &tmpLyr)
static QgsMapRenderer::BlendMode getBlendModeEnum(QPainter::CompositionMode blendMode)
Returns a BlendMode corresponding to a QPainter::CompositionMode.
QGis::GeometryType type() const
Returns type of the geometry as a QGis::GeometryType.
virtual Q_DECL_DEPRECATED int addDiagramLayer(QgsVectorLayer *layer, const QgsDiagramLayerSettings *s) override
adds a diagram layer to the labeling engine
Class that adds extra information to QgsLabelFeature for text labels.
void save()
void numCandidatePositions(int &candPoint, int &candLine, int &candPolygon)
The QgsLabelingEngineV2 class provides map labeling functionality.
void setDefinedFont(const QFont &f)
Set font to be used for rendering.
QgsExpression * expression()
T value() const
Container of fields for a vector layer.
Definition: qgsfield.h:187
Label on top of point, slightly right of center.
static QgsPalLayerSettings fromLayer(QgsVectorLayer *layer)
The QgsVectorLayerLabelProvider class implements a label provider for vector layers.
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:76
void setJoinStyle(Qt::PenJoinStyle style)
void setAlpha(int alpha)
bool drawLabels
Whether to draw labels for this layer.
QHash< QString, QgsVectorLayerDiagramProvider * > mDiagramProviders
hashtable of diagram providers (key = layer ID)
void readFromLayer(QgsVectorLayer *layer)
static QPointF decodePoint(const QString &str)
QString expressionString() const
Returns the expression string of this QgsDataDefined.
const QgsRectangle & extent() const
const_iterator constFind(const Key &key) const
static void dataDefinedDropShadow(QgsPalLayerSettings &tmpLyr, const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &ddValues)
Capitalization capitalization() const
QgsMapUnitScale repeatDistanceMapUnitScale
static QString encodeMapUnitScale(const QgsMapUnitScale &mapUnitScale)
MultiLineAlign multilineAlign
QgsPoint transform(const QgsPoint &p, TransformDirection direction=ForwardTransform) const
Transform the point from Source Coordinate System to Destination Coordinate System If the direction i...
void removeDataDefinedProperty(QgsPalLayerSettings::DataDefinedProperties p)
Set a property to static instead data defined.
double scaleFactor() const
QString join(const QString &separator) const
bool isNull() const
FeaturePart * getFeaturePart()
return the feature corresponding to this labelposition
void readSettingsFromProject()
Read configuration of the labeling engine from the current project file.
void rotate(qreal angle)
static QgsSymbolLayerV2 * create(const QgsStringMap &properties=QgsStringMap())
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:187
void addText(const QPointF &point, const QFont &font, const QString &text)
const QgsPoint & origin() const
bool dataDefinedEvaluate(QgsPalLayerSettings::DataDefinedProperties p, QVariant &exprVal, QgsExpressionContext *context=nullptr, const QVariant &originalValue=QVariant()) const
Get data defined property value from expression string or attribute field name.
double dpiRatio() const
A non GUI class for rendering a map layer set onto a QPainter.
static bool geometryRequiresPreparation(const QgsGeometry *geometry, QgsRenderContext &context, const QgsCoordinateTransform *ct, QgsGeometry *clipGeometry=nullptr)
Checks whether a geometry requires preparation before registration with PAL.
void setNumCandidatePositions(int candPoint, int candLine, int candPolygon)
Set number of candidate positions that will be generated for each label feature.
QVector< PredefinedPointPosition > predefinedPositionOrder
Ordered list of predefined label positions for points.
void clear()
static QString translateNamedStyle(const QString &namedStyle)
Returns the localized named style of a font, if such a translation is available.
double toDouble(bool *ok) const
static QStringList splitToLines(const QString &text, const QString &wrapCharacter)
Splits a text string to a list of separate lines, using a specified wrap character.
const QgsPoint & center() const
virtual bool prepare(const QgsRenderContext &context, QStringList &attributeNames)
Prepare for registration of features.
double mapRotation() const
Return current map rotation in degrees.
qreal width(const QString &text) const
bool qgsDoubleNear(double a, double b, double epsilon=4 *DBL_EPSILON)
Definition: qgis.h:285
double maxScale
The maximum scale, or 0.0 if unset.
void setRotationOffset(const double rotation)
double x() const
Get the x value of the point.
Definition: qgspoint.h:128
bool bold() const
static void drawLabelBackground(QgsRenderContext &context, QgsLabelComponent component, const QgsPalLayerSettings &tmpLyr)
Qt::PenJoinStyle bufferJoinStyle
int size() const
QgsMapLayer * mapLayer(const QString &theLayerId)
Retrieve a pointer to a loaded layer by id.
double zIndex
Z-Index of label, where labels with a higher z-index are rendered on top of labels with a lower z-ind...
void setHasFixedPosition(bool enabled)
Set whether the label should use a fixed position instead of being automatically placed.
bool italic() const
void reset(T *other)
QgsMapUnitScale fontSizeMapUnitScale
const QgsPoint & offset() const
The QgsMapSettings class contains configuration for rendering of the map.
QgsMapUnitScale shapeBorderWidthMapUnitScale
QString styleName() const
virtual Q_DECL_DEPRECATED void init(QgsMapRenderer *mr) override
called when we&#39;re going to start with rendering
QgsLabelingResults * results() const
For internal use by the providers.
bool useAdvancedEffects() const
Returns true if advanced effects such as blend modes such be used.
bool dataDefinedUseExpression(QgsPalLayerSettings::DataDefinedProperties p) const
Whether data definition is set to use an expression.
void removeProvider(QgsAbstractLabelProvider *provider)
Remove provider if the provider&#39;s initialization failed. Provider instance is deleted.
static bool staticWillUseLayer(QgsVectorLayer *layer)
called to find out whether the layer is used for labeling
void setBold(bool enable)
virtual void clearActiveLayer(const QString &layerID) override
clears data defined objects from PAL layer settings for a registered layer
QgsGeometry * extentGeom
bool conflictsWithObstacle() const
Returns whether the position is marked as conflicting with an obstacle feature.
void drawRect(const QRectF &rectangle)
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:34
QList< QgsLabelPosition > labelsWithinRect(const QgsRectangle &r) const
return infos about labels within a given (map) rectangle
void setPixelSize(int pixelSize)
void setUseExpression(bool use)
Controls if the field or the expression part is active.
void setSearchMethod(QgsPalLabeling::Search s)
Set which search method to use for removal collisions between labels.
Mixed units in symbol layers.
Definition: qgssymbolv2.h:66
double rotation() const
bool contains(const QgsPoint *p) const
Test for containment of a point (uses GEOS)
QTransform & translate(qreal dx, qreal dy)
The output shall be in millimeters.
Definition: qgssymbolv2.h:64
static QPainter::CompositionMode decodeBlendMode(const QString &s)
ObstacleType obstacleType
Controls how features act as obstacles for labels.
void setRotation(const double rotation)
QFont font()
QString number(int n, int base)
qreal x() const
qreal y() const
void append(const T &value)
static void dataDefinedTextBuffer(QgsPalLayerSettings &tmpLyr, const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &ddValues)
void setIsObstacle(bool enabled)
Sets whether the feature will act as an obstacle for labels.
bool setFromXmlElement(const QDomElement &element)
Sets the properties of the data defined container from an XML element.
void setScaleFactor(double factor)
Label on left of point.
uint toUInt(bool *ok) const
QDomDocument ownerDocument() const
const QgsCoordinateTransform * ct
int toInt(bool *ok) const
bool isNull() const
bool useOrigin() const
QgsMapUnitScale shapeRadiiMapUnitScale
const QgsAbstractVectorLayerLabeling * labeling() const
Access to labeling configuration.
Offset distance applies from point geometry.
const QPicture * picture() const
void fill(uint pixelValue)
void setFillRule(Qt::FillRule fillRule)
static QString encodePoint(QPointF point)
bool hasAttribute(const QString &name) const
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:34
QgsPalLayerSettings mInvalidLayerSettings
SizeUnit shapeBorderWidthUnits
QPainter::CompositionMode blendMode
Whether to draw rectangles of generated candidates (good for debugging)
int red() const
static bool fontFamilyOnSystem(const QString &family)
Check whether font family is on system in a quick manner, which does not compare [foundry].
void setPen(const QColor &color)
Labels can be placed above a line feature.
QList< QgsLabelPosition > labelsAtPosition(const QgsPoint &p) const
return infos about labels at a given (map) position
int width() const
void drawEllipse(const QRectF &rectangle)
qreal letterSpacing() const
void setAttribute(const QString &name, const QString &value)
void setField(const QString &field)
Set the field name which this QgsDataDefined represents.
The QgsVectorLayerDiagramProvider class implements support for diagrams within the labeling engine...
QString updateDataDefinedString(const QString &value)
Convert old property value to new one as delimited values.
void drawRoundedRect(const QRectF &rect, qreal xRadius, qreal yRadius, Qt::SizeMode mode)
QString name() const
Gets the name of the field.
Definition: qgsfield.cpp:84
int toInt(bool *ok, int base) const
bool isEmpty() const
void setDataDefinedValues(const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &values)
Set data-defined values.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
virtual void drawLabeling(QgsRenderContext &context) override
called when the map is drawn and labels should be placed
virtual QgsAttrPalIndexNameHash palAttributeIndexNames() const
Return list of indexes to names for QgsPalLabeling fix.
Q_DECL_DEPRECATED QgsPalLayerSettings & layer(const QString &layerName) override
bool isEmpty() const
QRect rect() const
QString trimmed() const
static QString encodePenJoinStyle(Qt::PenJoinStyle style)
const_iterator constEnd() const
QDomElement toXmlElement(QDomDocument &document, const QString &elementName) const
Returns a DOM element containing the properties of the data defined container.
static QString symbolNameToPath(QString name)
Get symbol&#39;s path from its name.
double getY(int i=0) const
get the down-left y coordinate
The output shall be in map unitx.
Definition: qgssymbolv2.h:65
#define M_PI
Arranges candidates in a circle around a point (or centroid of a polygon).
const QgsMapToPixel * xform
void calculateInfo(bool curvedLabeling, QFontMetricsF *fm, const QgsMapToPixel *xform, double fontScale, double maxinangle, double maxoutangle)
calculate data for info(). setDefinedFont() must have been called already.
QMap< QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined * > dataDefinedProperties
Map of current data defined properties.
QPaintDevice * device() const
void setWidthF(qreal width)
void readXml(QDomElement &elem)
Read settings from a DOM element.
void setBrush(const QBrush &brush)
void setPainter(QPainter *p)
bool isShowingPartialsLabels() const
double rasterScaleFactor() const
QString id() const
Get this layer&#39;s unique ID, this ID is used to access this layer from map layer registry.
bool removeEntry(const QString &scope, const QString &key)
Remove the given key.
const T & value() const
bool underline() const
QgsMapUnitScale bufferSizeMapUnitScale
double mapUnitsPerPixel() const
Return current map units per pixel.
QGis::GeometryType geometryType() const
Returns point, line or polygon.
OffsetType
Behaviour modifier for label offset and distance, only applies in some label placement modes...
QgsFeature * mCurFeat
LabelPosition * getNextPart() const
void calculateLabelSize(const QFontMetricsF *fm, QString text, double &labelX, double &labelY, QgsFeature *f=nullptr, QgsRenderContext *context=nullptr)
void removeCustomProperty(const QString &key)
Remove a custom property from layer.
QPainter::CompositionMode shapeBlendMode
iterator end()
double scaleToPixelContext(double size, const QgsRenderContext &c, SizeUnit unit, bool rasterfactor=false, const QgsMapUnitScale &mapUnitScale=QgsMapUnitScale()) const
Calculates size (considering output size should be in pixel or map units, scale factors and optionall...
const Key & key() const
QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
void setColor(const QColor &color)
const GEOSGeometry * asGeos(double precision=0) const
Returns a geos geometry.
T & value() const
QgsDataDefined * dataDefinedProperty(QgsPalLayerSettings::DataDefinedProperties p)
Get a data defined property pointer.
Stores visual margins for labels (left, right, top and bottom)
const T & value() const
static QPainter::CompositionMode getCompositionMode(BlendMode blendMode)
Returns a QPainter::CompositionMode corresponding to a BlendMode.
const QgsField & at(int i) const
Get field at particular index (must be in range 0..N-1)
Definition: qgsfield.cpp:385
double getX(int i=0) const
get the down-left x coordinate
SizeUnit
Units used for option sizes, before being converted to rendered sizes.
Search searchMethod() const
int alpha() const
QMap< QString, QString > dataDefinedMap(QgsPalLayerSettings::DataDefinedProperties p) const
Get property value as separate values split into Qmap.
QgsGeometry * buffer(double distance, int segments) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
A class to represent a point.
Definition: qgspoint.h:65
static Qt::PenJoinStyle _decodePenJoinStyle(const QString &str)
Qt::PenJoinStyle shapeJoinStyle
void writeSettingsToProject()
Write configuration of the labeling engine to the current project file.
virtual QgsPalLabeling * clone() override
called when passing engine among map renderers
bool useExpression() const
Returns if the field or the expression part is active.
int indexFromName(const QString &name) const
Look up field&#39;s index from name. Returns -1 on error.
Definition: qgsfield.cpp:424
int logicalDpiX() const
int logicalDpiY() const
bool drawLabelRectOnly() const
Returns whether the engine will only draw the outline rectangles of labels, not the label contents th...
T * data() const
int green() const
double ANALYSIS_EXPORT angle(Point3D *p1, Point3D *p2, Point3D *p3, Point3D *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored)
const T value(const Key &key) const
void setWordSpacing(qreal spacing)
bool testFlag(Flag f) const
Test whether a particular flag is enabled.
bool isNull() const
bool contains(QChar ch, Qt::CaseSensitivity cs) const
void clear()
void setMapSettings(const QgsMapSettings &mapSettings)
Associate map settings instance.
QgsExpressionContext & expressionContext()
Gets the expression context.
double length() const
Returns the length of geometry using GEOS.
void run(QgsRenderContext &context)
compute the labeling with given map settings and providers
double getAlpha() const
get alpha
void setItalic(bool enable)
void setPointSizeF(qreal pointSize)
Q_GUI_EXPORT int qt_defaultDpiX()
QgsPoint toMapCoordinatesF(double x, double y) const
Transform device coordinates to map (world) coordinates.
bool isNull() const
unsigned int placementFlags
Whether to draw all labels even if there would be collisions.
QgsPalLayerSettings & operator=(const QgsPalLayerSettings &s)
copy operator - only copies the permanent members
Whether to use also label candidates that are partially outside of the map view.
void setRenderHints(QFlags< QPainter::RenderHint > hints, bool on)
void restore()
const Key key(const T &value) const
Placement
Placement modes which determine how label candidates are generated for a feature. ...
QTransform & rotate(qreal angle, Qt::Axis axis)
QgsGeometry * intersection(const QgsGeometry *geometry) const
Returns a geometry representing the points shared by this geometry and other.
static QString encodePredefinedPositionOrder(const QVector< QgsPalLayerSettings::PredefinedPointPosition > &positions)
Encodes an ordered list of predefined point label positions to a string.
static QString untranslateNamedStyle(const QString &namedStyle)
Returns the english named style of a font, if possible.
bool isShowingCandidates() const
static QColor _readColor(QgsVectorLayer *layer, const QString &property, const QColor &defaultColor=Qt::black, bool withAlpha=true)
Q_GUI_EXPORT int qt_defaultDpiY()
int blue() const
QgsExpression * getLabelExpression()
Returns the QgsExpression for this label settings.
Arranges candidates over a point (or centroid of a polygon), or at a preset offset from the point...
void setDrawingOutlineLabels(bool outline)
Contains information about the context of a rendering operation.
void setShowingShadowRectangles(bool showing)
void setPicture(QPicture *picture)
virtual int prepareDiagramLayer(QgsVectorLayer *layer, QStringList &attrNames, QgsRenderContext &ctx) override
adds a diagram layer to the labeling engine
static bool fontFamilyMatchOnSystem(const QString &family, QString *chosen=nullptr, bool *match=nullptr)
Check whether font family is on system.
virtual const QgsFields & fields() const =0
Return a map of indexes with field names for this layer.
void setDataDefinedProperty(QgsPalLayerSettings::DataDefinedProperties p, bool active, bool useExpr, const QString &expr, const QString &field)
Set a property as data defined.
static QgsMapLayerRegistry * instance()
Returns the instance pointer, creating the object on the first call.
void drawImage(const QRectF &target, const QImage &image, const QRectF &source, QFlags< Qt::ImageConversionFlag > flags)
QPainter * painter()
The QgsLabelFeature class describes a feature that should be used within the labeling engine...
qreal width() const
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
Definition: qgsfeature.cpp:271
QString mid(int position, int n) const
void drawPath(const QPainterPath &path)
Whether to only draw the label rect and not the actual label text (used for unit tests) ...
void setOffset(const QgsPoint &point)
static QgsPalLayerSettings::SizeUnit _decodeUnits(const QString &str)
static GEOSContextHandle_t getGEOSHandler()
Return GEOS context handle.
void setWidth(int width)
double getHeight() const
QgsMapUnitScale distMapUnitScale
QString toString() const
Struct for storing maximum and minimum scales for measurements in map units.
qreal ascent() const
bool fitInPolygonOnly
True if only labels which completely fit within a polygon are allowed.
virtual Q_DECL_DEPRECATED QList< QgsLabelPosition > labelsWithinRect(const QgsRectangle &r) override
return infos about labels within a given (map) rectangle
bool isEmpty() const
bool isEmpty() const
bool expressionIsPrepared() const
Returns whether the data defined object&#39;s expression is prepared.
QString family() const
int rotate(double rotation, const QgsPoint &center)
Rotate this geometry around the Z axis.
static bool updateFontViaStyle(QFont &f, const QString &fontstyle, bool fallback=false)
Updates font with named style and retain all font properties.
void setX(qreal x)
void setY(qreal y)
int sizeToPixel(double size, const QgsRenderContext &c, SizeUnit unit, bool rasterfactor=false, const QgsMapUnitScale &mapUnitScale=QgsMapUnitScale()) const
Calculates pixel size (considering output size should be in pixel or map units, scale factors and opt...
OffsetType offsetType
Offset type for layer (only applies in certain placement modes)
static QgsProject * instance()
access to canonical QgsProject instance
Definition: qgsproject.cpp:381
QDomElement firstChildElement(const QString &tagName) const
virtual void clearActiveLayers() override
clears all PAL layer settings for registered layers
QPointF bottomLeft() const
void setMapToPixel(const QgsMapToPixel &mtp)
static QStringList splitToGraphemes(const QString &text)
Splits a text string to a list of graphemes, which are the smallest allowable character divisions in ...
int size() const
Return number of items.
Definition: qgsfield.cpp:370
const QgsGeometry * constGeometry() const
Gets a const pointer to the geometry object associated with this feature.
Definition: qgsfeature.cpp:82
QgsPalLabeling::Search searchMethod() const
Which search method to use for removal collisions between labels.
qreal descent() const
Class for doing transforms between two map coordinate systems.
void setStrikeOut(bool enable)
static void _writeColor(QgsVectorLayer *layer, const QString &property, const QColor &color, bool withAlpha=true)
LabelPosition is a candidate feature label position.
Definition: labelposition.h:50
bool toBool() const
void translate(const QPointF &offset)
int transform(const QgsCoordinateTransform &ct)
Transform this geometry as described by CoordinateTransform ct.
void setCapitalization(Capitalization caps)
QDomElement writeXml(QDomDocument &doc)
Write settings into a DOM element.
const QgsMapToPixel & mapToPixel() const
void writeToLayer(QgsVectorLayer *layer)
QString expression() const
Return the original, unmodified expression string.
double y() const
Get the y value of the point.
Definition: qgspoint.h:136
Label on right of point.
void removeAllDataDefinedProperties()
Clear all data-defined properties.
void setAlphaF(qreal alpha)
bool isValid() const
virtual int prepareLayer(QgsVectorLayer *layer, QStringList &attrNames, QgsRenderContext &ctx) override
hook called when drawing layer before issuing select()
qreal height() const
int height() const
double toDouble(bool *ok) const
static QColor decodeColor(const QString &str)
Signifies that the AboveLine and BelowLine flags should respect the map&#39;s orientation rather than the...
double pictureBuffer() const
iterator insert(const Key &key, const T &value)
QPainter::CompositionMode shadowBlendMode
bool isExpression
Is this label made from a expression string eg FieldName || &#39;mm&#39;.
virtual Q_DECL_DEPRECATED QList< QgsLabelPosition > labelsAtPosition(const QgsPoint &p) override
return infos about labels at a given (map) position
void setSize(const QgsPoint &point)
Class that stores computed placement from labeling engine.
bool isShowingAllLabels() const
void setShowingAllLabels(bool showing)
virtual QString type() const =0
Unique type string of the labeling configuration implementation.
bool isEmpty() const
Custom exception class for Coordinate Reference System related exceptions.
void drawPicture(const QPointF &point, const QPicture &picture)
static QVector< QgsPalLayerSettings::PredefinedPointPosition > decodePredefinedPositionOrder(const QString &positionString)
Decodes a string to an ordered list of predefined point label positions.
bool isShowingShadowRectangles() const
QgsMapUnitScale shapeOffsetMapUnitScale
static QgsMapUnitScale decodeMapUnitScale(const QString &str)
QString exportToWkt(int precision=17) const
Exports the geometry to WKT.
QgsVectorDataProvider * dataProvider()
Returns the data provider.
void setPictureBuffer(const double buffer)
const_iterator constEnd() const
QDomElement createElement(const QString &tagName)
Q_DECL_DEPRECATED const QList< QgsLabelCandidate > & candidates()
bool strikeOut() const
const_iterator constBegin() const
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
bool isDrawingOutlineLabels() const
void setScale(double scale)
double width() const
Width of the rectangle.
Definition: qgsrectangle.h:207
static bool checkMinimumSizeMM(const QgsRenderContext &context, const QgsGeometry *geom, double minSize)
Checks whether a geometry exceeds the minimum required size for a geometry to be labeled.
Represents a vector layer which manages a vector based data sets.
bool begin(QPaintDevice *device)
double minScale
The minimum scale, or 0.0 if unset.
int compare(const QString &other) const
void setDrawLabelRectOnly(bool drawRect)
Sets whether the engine should only draw the outline rectangles of labels, not the label contents the...
bool isGeosValid() const
Checks validity of the geometry using GEOS.
QFont font(const QString &family, const QString &style, int pointSize) const
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for the context.
QString parserErrorString() const
Returns parser error.
void setLetterSpacing(SpacingType type, qreal spacing)
QString arg(qlonglong a, int fieldWidth, int base, const QChar &fillChar) const
void setFlag(Flag f, bool enabled=true)
Set whether a particual flag is enabled.
QString toString() const
QString text() const
Whether to render labels as text or outlines.
static void blurImageInPlace(QImage &image, QRect rect, int radius, bool alphaOnly)
Blurs an image in place, e.g.
QgsPoint center() const
Center point of the rectangle.
Definition: qgsrectangle.h:217
QString evalErrorString() const
Returns evaluation error.
void setExpressionString(const QString &expr)
Sets the expression for this QgsDataDefined.
bool isActive() const
iterator find(const Key &key)
QgsLabelingResults * takeResults()
Return pointer to recently computed results and pass the ownership of results to the caller...
Maintains current state of more grainular and temporal values when creating/painting component parts ...
virtual void registerFeature(const QString &layerID, QgsFeature &feat, QgsRenderContext &context, const QString &dxfLayer=QString::null) override
Register a feature for labelling.
RotationType shapeRotationType
double area() const
Returns the area of the geometry using GEOS.
virtual QgsVectorLayerLabelProvider * provider(QgsVectorLayer *layer) const =0
Factory for label provider implementation.
int pointSize() const
QgsMapUnitScale labelOffsetMapUnitScale
void numCandidatePositions(int &candPoint, int &candLine, int &candPolygon)
Get number of candidate positions that will be generated for each label feature (default to 8) ...
bool hasNext() const
virtual void exit() override
called when we&#39;re done with rendering
qreal height() const
double height() const
Height of the rectangle.
Definition: qgsrectangle.h:212
qreal wordSpacing() const
void moveTo(qreal x, qreal y)
const T value(const Key &key) const
uint toUInt(bool *ok, int base) const
int remove(const Key &key)
ObstacleType
Valid obstacle types, which affect how features within the layer will act as obstacles for labels...
DirectionSymbols placeDirectionSymbol
QPointF toQPointF() const
Converts a point to a QPointF.
Definition: qgspoint.cpp:121
static void drawLabelShadow(QgsRenderContext &context, const QgsLabelComponent &component, const QgsPalLayerSettings &tmpLyr)
static void dataDefinedTextFormatting(QgsPalLayerSettings &tmpLyr, const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &ddValues)
QgsLabelingEngineV2 * mEngine
New labeling engine to interface with PAL.