QGIS API Documentation  2.11.0-Master
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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 "qgspalgeometry.h"
20 
21 #include <list>
22 
23 #include <pal/pal.h>
24 #include <pal/feature.h>
25 #include <pal/layer.h>
26 #include <pal/palgeometry.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 
47 #include <qgslogger.h>
48 #include <qgsvectorlayer.h>
49 #include <qgsmaplayerregistry.h>
50 #include <qgsvectordataprovider.h>
51 #include <qgsgeometry.h>
52 #include <qgsmaprenderer.h>
53 #include <qgsmarkersymbollayerv2.h>
54 #include <qgsproject.h>
55 #include "qgssymbolv2.h"
56 #include "qgssymbollayerv2utils.h"
57 #include <QMessageBox>
58 
59 
60 Q_GUI_EXPORT extern int qt_defaultDpiX();
61 Q_GUI_EXPORT extern int qt_defaultDpiY();
62 
63 static void _fixQPictureDPI( QPainter* p )
64 {
65  // QPicture makes an assumption that we drawing to it with system DPI.
66  // Then when being drawn, it scales the painter. The following call
67  // negates the effect. There is no way of setting QPicture's DPI.
68  // See QTBUG-20361
69  p->scale(( double )qt_defaultDpiX() / p->device()->logicalDpiX(),
70  ( double )qt_defaultDpiY() / p->device()->logicalDpiY() );
71 }
72 
73 
74 using namespace pal;
75 
76 // -------------
77 
79  : upsidedownLabels( Upright )
80  , palLayer( NULL )
81  , mCurFeat( 0 )
82  , mCurFields( 0 )
83  , xform( NULL )
84  , ct( NULL )
85  , extentGeom( NULL )
86  , mFeaturesToLabel( 0 )
87  , mFeatsSendingToPal( 0 )
88  , mFeatsRegPal( 0 )
89  , expression( 0 )
90 {
91  enabled = false;
92  drawLabels = true;
93  isExpression = false;
94  fieldIndex = 0;
95 
96  // text style
98  textNamedStyle = QString( "" );
99  fontSizeInMapUnits = false;
100  textColor = Qt::black;
101  textTransp = 0;
102  blendMode = QPainter::CompositionMode_SourceOver;
103  previewBkgrdColor = Qt::white;
104  // font processing info
105  mTextFontFound = true;
107 
108  // text formatting
109  wrapChar = "";
110  multilineHeight = 1.0;
112  addDirectionSymbol = false;
113  leftDirectionSymbol = QString( "<" );
114  rightDirectionSymbol = QString( ">" );
115  reverseDirectionSymbol = false;
117  formatNumbers = false;
118  decimals = 3;
119  plusSign = false;
120 
121  // text buffer
122  bufferDraw = false;
123  bufferSize = 1.0;
124  bufferSizeInMapUnits = false;
125  bufferColor = Qt::white;
126  bufferTransp = 0;
127  bufferNoFill = false;
128  bufferJoinStyle = Qt::BevelJoin;
129  bufferBlendMode = QPainter::CompositionMode_SourceOver;
130 
131  // shape background
132  shapeDraw = false;
134  shapeSVGFile = QString();
136  shapeSize = QPointF( 0.0, 0.0 );
137  shapeSizeUnits = MM;
139  shapeRotation = 0.0;
140  shapeOffset = QPointF( 0.0, 0.0 );
142  shapeRadii = QPointF( 0.0, 0.0 );
144  shapeFillColor = Qt::white;
145  shapeBorderColor = Qt::darkGray;
146  shapeBorderWidth = 0.0;
148  shapeJoinStyle = Qt::BevelJoin;
149  shapeTransparency = 0;
150  shapeBlendMode = QPainter::CompositionMode_SourceOver;
151 
152  // drop shadow
153  shadowDraw = false;
155  shadowOffsetAngle = 135;
156  shadowOffsetDist = 1.0;
158  shadowOffsetGlobal = true;
159  shadowRadius = 1.5;
161  shadowRadiusAlphaOnly = false;
162  shadowTransparency = 30;
163  shadowScale = 100;
164  shadowColor = Qt::black;
165  shadowBlendMode = QPainter::CompositionMode_Multiply;
166 
167  // placement
170  centroidWhole = false;
171  centroidInside = false;
172  fitInPolygonOnly = false;
174  xOffset = 0;
175  yOffset = 0;
176  labelOffsetInMapUnits = true;
177  dist = 0;
178  distInMapUnits = false;
179  angleOffset = 0;
180  preserveRotation = true;
181  maxCurvedCharAngleIn = 20.0;
182  maxCurvedCharAngleOut = -20.0;
183  priority = 5;
184  repeatDistance = 0;
186 
187  // rendering
188  scaleVisibility = false;
189  scaleMin = 1;
190  scaleMax = 10000000;
191  fontLimitPixelSize = false;
192  fontMinPixelSize = 0; //trigger to turn it on by default for map unit labels
193  fontMaxPixelSize = 10000;
194  displayAll = false;
196 
197  labelPerPart = false;
198  mergeLines = false;
199  minFeatureSize = 0.0;
200  limitNumLabels = false;
201  maxNumLabels = 2000;
202  obstacle = true;
203  obstacleFactor = 1.0;
205 
206  // scale factors
207  vectorScaleFactor = 1.0;
208  rasterCompressFactor = 1.0;
209 
210  // data defined string and old-style index values
211  // NOTE: in QPair use -1 for second value (other values are for old-style layer properties migration)
212 
213  // text style
214  mDataDefinedNames.insert( Size, QPair<QString, int>( "Size", 0 ) );
215  mDataDefinedNames.insert( Bold, QPair<QString, int>( "Bold", 1 ) );
216  mDataDefinedNames.insert( Italic, QPair<QString, int>( "Italic", 2 ) );
217  mDataDefinedNames.insert( Underline, QPair<QString, int>( "Underline", 3 ) );
218  mDataDefinedNames.insert( Color, QPair<QString, int>( "Color", 4 ) );
219  mDataDefinedNames.insert( Strikeout, QPair<QString, int>( "Strikeout", 5 ) );
220  mDataDefinedNames.insert( Family, QPair<QString, int>( "Family", 6 ) );
221  mDataDefinedNames.insert( FontStyle, QPair<QString, int>( "FontStyle", -1 ) );
222  mDataDefinedNames.insert( FontSizeUnit, QPair<QString, int>( "FontSizeUnit", -1 ) );
223  mDataDefinedNames.insert( FontTransp, QPair<QString, int>( "FontTransp", 18 ) );
224  mDataDefinedNames.insert( FontCase, QPair<QString, int>( "FontCase", -1 ) );
225  mDataDefinedNames.insert( FontLetterSpacing, QPair<QString, int>( "FontLetterSpacing", -1 ) );
226  mDataDefinedNames.insert( FontWordSpacing, QPair<QString, int>( "FontWordSpacing", -1 ) );
227  mDataDefinedNames.insert( FontBlendMode, QPair<QString, int>( "FontBlendMode", -1 ) );
228 
229  // text formatting
230  mDataDefinedNames.insert( MultiLineWrapChar, QPair<QString, int>( "MultiLineWrapChar", -1 ) );
231  mDataDefinedNames.insert( MultiLineHeight, QPair<QString, int>( "MultiLineHeight", -1 ) );
232  mDataDefinedNames.insert( MultiLineAlignment, QPair<QString, int>( "MultiLineAlignment", -1 ) );
233  mDataDefinedNames.insert( DirSymbDraw, QPair<QString, int>( "DirSymbDraw", -1 ) );
234  mDataDefinedNames.insert( DirSymbLeft, QPair<QString, int>( "DirSymbLeft", -1 ) );
235  mDataDefinedNames.insert( DirSymbRight, QPair<QString, int>( "DirSymbRight", -1 ) );
236  mDataDefinedNames.insert( DirSymbPlacement, QPair<QString, int>( "DirSymbPlacement", -1 ) );
237  mDataDefinedNames.insert( DirSymbReverse, QPair<QString, int>( "DirSymbReverse", -1 ) );
238  mDataDefinedNames.insert( NumFormat, QPair<QString, int>( "NumFormat", -1 ) );
239  mDataDefinedNames.insert( NumDecimals, QPair<QString, int>( "NumDecimals", -1 ) );
240  mDataDefinedNames.insert( NumPlusSign, QPair<QString, int>( "NumPlusSign", -1 ) );
241 
242  // text buffer
243  mDataDefinedNames.insert( BufferDraw, QPair<QString, int>( "BufferDraw", -1 ) );
244  mDataDefinedNames.insert( BufferSize, QPair<QString, int>( "BufferSize", 7 ) );
245  mDataDefinedNames.insert( BufferUnit, QPair<QString, int>( "BufferUnit", -1 ) );
246  mDataDefinedNames.insert( BufferColor, QPair<QString, int>( "BufferColor", 8 ) );
247  mDataDefinedNames.insert( BufferTransp, QPair<QString, int>( "BufferTransp", 19 ) );
248  mDataDefinedNames.insert( BufferJoinStyle, QPair<QString, int>( "BufferJoinStyle", -1 ) );
249  mDataDefinedNames.insert( BufferBlendMode, QPair<QString, int>( "BufferBlendMode", -1 ) );
250 
251  // background
252  mDataDefinedNames.insert( ShapeDraw, QPair<QString, int>( "ShapeDraw", -1 ) );
253  mDataDefinedNames.insert( ShapeKind, QPair<QString, int>( "ShapeKind", -1 ) );
254  mDataDefinedNames.insert( ShapeSVGFile, QPair<QString, int>( "ShapeSVGFile", -1 ) );
255  mDataDefinedNames.insert( ShapeSizeType, QPair<QString, int>( "ShapeSizeType", -1 ) );
256  mDataDefinedNames.insert( ShapeSizeX, QPair<QString, int>( "ShapeSizeX", -1 ) );
257  mDataDefinedNames.insert( ShapeSizeY, QPair<QString, int>( "ShapeSizeY", -1 ) );
258  mDataDefinedNames.insert( ShapeSizeUnits, QPair<QString, int>( "ShapeSizeUnits", -1 ) );
259  mDataDefinedNames.insert( ShapeRotationType, QPair<QString, int>( "ShapeRotationType", -1 ) );
260  mDataDefinedNames.insert( ShapeRotation, QPair<QString, int>( "ShapeRotation", -1 ) );
261  mDataDefinedNames.insert( ShapeOffset, QPair<QString, int>( "ShapeOffset", -1 ) );
262  mDataDefinedNames.insert( ShapeOffsetUnits, QPair<QString, int>( "ShapeOffsetUnits", -1 ) );
263  mDataDefinedNames.insert( ShapeRadii, QPair<QString, int>( "ShapeRadii", -1 ) );
264  mDataDefinedNames.insert( ShapeRadiiUnits, QPair<QString, int>( "ShapeRadiiUnits", -1 ) );
265  mDataDefinedNames.insert( ShapeTransparency, QPair<QString, int>( "ShapeTransparency", -1 ) );
266  mDataDefinedNames.insert( ShapeBlendMode, QPair<QString, int>( "ShapeBlendMode", -1 ) );
267  mDataDefinedNames.insert( ShapeFillColor, QPair<QString, int>( "ShapeFillColor", -1 ) );
268  mDataDefinedNames.insert( ShapeBorderColor, QPair<QString, int>( "ShapeBorderColor", -1 ) );
269  mDataDefinedNames.insert( ShapeBorderWidth, QPair<QString, int>( "ShapeBorderWidth", -1 ) );
270  mDataDefinedNames.insert( ShapeBorderWidthUnits, QPair<QString, int>( "ShapeBorderWidthUnits", -1 ) );
271  mDataDefinedNames.insert( ShapeJoinStyle, QPair<QString, int>( "ShapeJoinStyle", -1 ) );
272 
273  // drop shadow
274  mDataDefinedNames.insert( ShadowDraw, QPair<QString, int>( "ShadowDraw", -1 ) );
275  mDataDefinedNames.insert( ShadowUnder, QPair<QString, int>( "ShadowUnder", -1 ) );
276  mDataDefinedNames.insert( ShadowOffsetAngle, QPair<QString, int>( "ShadowOffsetAngle", -1 ) );
277  mDataDefinedNames.insert( ShadowOffsetDist, QPair<QString, int>( "ShadowOffsetDist", -1 ) );
278  mDataDefinedNames.insert( ShadowOffsetUnits, QPair<QString, int>( "ShadowOffsetUnits", -1 ) );
279  mDataDefinedNames.insert( ShadowRadius, QPair<QString, int>( "ShadowRadius", -1 ) );
280  mDataDefinedNames.insert( ShadowRadiusUnits, QPair<QString, int>( "ShadowRadiusUnits", -1 ) );
281  mDataDefinedNames.insert( ShadowTransparency, QPair<QString, int>( "ShadowTransparency", -1 ) );
282  mDataDefinedNames.insert( ShadowScale, QPair<QString, int>( "ShadowScale", -1 ) );
283  mDataDefinedNames.insert( ShadowColor, QPair<QString, int>( "ShadowColor", -1 ) );
284  mDataDefinedNames.insert( ShadowBlendMode, QPair<QString, int>( "ShadowBlendMode", -1 ) );
285 
286  // placement
287  mDataDefinedNames.insert( CentroidWhole, QPair<QString, int>( "CentroidWhole", -1 ) );
288  mDataDefinedNames.insert( OffsetQuad, QPair<QString, int>( "OffsetQuad", -1 ) );
289  mDataDefinedNames.insert( OffsetXY, QPair<QString, int>( "OffsetXY", -1 ) );
290  mDataDefinedNames.insert( OffsetUnits, QPair<QString, int>( "OffsetUnits", -1 ) );
291  mDataDefinedNames.insert( LabelDistance, QPair<QString, int>( "LabelDistance", 13 ) );
292  mDataDefinedNames.insert( DistanceUnits, QPair<QString, int>( "DistanceUnits", -1 ) );
293  mDataDefinedNames.insert( OffsetRotation, QPair<QString, int>( "OffsetRotation", -1 ) );
294  mDataDefinedNames.insert( CurvedCharAngleInOut, QPair<QString, int>( "CurvedCharAngleInOut", -1 ) );
295  mDataDefinedNames.insert( RepeatDistance, QPair<QString, int>( "RepeatDistance", -1 ) );
296  mDataDefinedNames.insert( RepeatDistanceUnit, QPair<QString, int>( "RepeatDistanceUnit", -1 ) );
297  mDataDefinedNames.insert( Priority, QPair<QString, int>( "Priority", -1 ) );
298  mDataDefinedNames.insert( IsObstacle, QPair<QString, int>( "IsObstacle", -1 ) );
299  mDataDefinedNames.insert( ObstacleFactor, QPair<QString, int>( "ObstacleFactor", -1 ) );
300 
301  // (data defined only)
302  mDataDefinedNames.insert( PositionX, QPair<QString, int>( "PositionX", 9 ) );
303  mDataDefinedNames.insert( PositionY, QPair<QString, int>( "PositionY", 10 ) );
304  mDataDefinedNames.insert( Hali, QPair<QString, int>( "Hali", 11 ) );
305  mDataDefinedNames.insert( Vali, QPair<QString, int>( "Vali", 12 ) );
306  mDataDefinedNames.insert( Rotation, QPair<QString, int>( "Rotation", 14 ) );
307 
308  //rendering
309  mDataDefinedNames.insert( ScaleVisibility, QPair<QString, int>( "ScaleVisibility", -1 ) );
310  mDataDefinedNames.insert( MinScale, QPair<QString, int>( "MinScale", 16 ) );
311  mDataDefinedNames.insert( MaxScale, QPair<QString, int>( "MaxScale", 17 ) );
312  mDataDefinedNames.insert( FontLimitPixel, QPair<QString, int>( "FontLimitPixel", -1 ) );
313  mDataDefinedNames.insert( FontMinPixel, QPair<QString, int>( "FontMinPixel", -1 ) );
314  mDataDefinedNames.insert( FontMaxPixel, QPair<QString, int>( "FontMaxPixel", -1 ) );
315  // (data defined only)
316  mDataDefinedNames.insert( Show, QPair<QString, int>( "Show", 15 ) );
317  mDataDefinedNames.insert( AlwaysShow, QPair<QString, int>( "AlwaysShow", 20 ) );
318 
319  // temp stuff for when drawing label components (don't copy)
320  showingShadowRects = false;
321 }
322 
324  : palLayer( NULL )
325  , mCurFeat( NULL )
326  , mCurFields( NULL )
327  , fieldIndex( 0 )
328  , xform( NULL )
329  , ct( NULL )
330  , extentGeom( NULL )
331  , mFeaturesToLabel( 0 )
332  , mFeatsSendingToPal( 0 )
333  , mFeatsRegPal( 0 )
334  , showingShadowRects( false )
335  , expression( NULL )
336 {
337  // copy only permanent stuff
338 
339  enabled = s.enabled;
341 
342  // text style
343  fieldName = s.fieldName;
345  textFont = s.textFont;
349  textColor = s.textColor;
351  blendMode = s.blendMode;
353  // font processing info
356 
357  // text formatting
358  wrapChar = s.wrapChar;
367  decimals = s.decimals;
368  plusSign = s.plusSign;
369 
370  // text buffer
380 
381  // placement
382  placement = s.placement;
388  xOffset = s.xOffset;
389  yOffset = s.yOffset;
392  dist = s.dist;
399  priority = s.priority;
403 
404  // rendering
406  scaleMin = s.scaleMin;
407  scaleMax = s.scaleMax;
413 
419  obstacle = s.obstacle;
422 
423  // shape background
424  shapeDraw = s.shapeDraw;
425  shapeType = s.shapeType;
428  shapeSize = s.shapeSize;
447 
448  // drop shadow
464 
465  // data defined
467  mDataDefinedNames = s.mDataDefinedNames;
468 
469  // scale factors
472 }
473 
474 
476 {
477  // pal layer is deleted internally in PAL
478 
479  delete ct;
480  delete expression;
481  delete extentGeom;
482 
483  // clear pointers to QgsDataDefined objects
485 }
486 
487 
489 {
490  QgsPalLayerSettings settings;
491  settings.readFromLayer( layer );
492  return settings;
493 }
494 
495 
497 {
498  if ( expression == NULL )
499  {
500  expression = new QgsExpression( fieldName );
501  }
502  return expression;
503 }
504 
505 static QColor _readColor( QgsVectorLayer* layer, QString property, QColor defaultColor = Qt::black, bool withAlpha = true )
506 {
507  int r = layer->customProperty( property + "R", QVariant( defaultColor.red() ) ).toInt();
508  int g = layer->customProperty( property + "G", QVariant( defaultColor.green() ) ).toInt();
509  int b = layer->customProperty( property + "B", QVariant( defaultColor.blue() ) ).toInt();
510  int a = withAlpha ? layer->customProperty( property + "A", QVariant( defaultColor.alpha() ) ).toInt() : 255;
511  return QColor( r, g, b, a );
512 }
513 
514 static void _writeColor( QgsVectorLayer* layer, QString property, QColor color, bool withAlpha = true )
515 {
516  layer->setCustomProperty( property + "R", color.red() );
517  layer->setCustomProperty( property + "G", color.green() );
518  layer->setCustomProperty( property + "B", color.blue() );
519  if ( withAlpha )
520  layer->setCustomProperty( property + "A", color.alpha() );
521 }
522 
524 {
525  if ( str.compare( "Point", Qt::CaseInsensitive ) == 0
526  || str.compare( "Points", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Points;
527  if ( str.compare( "MapUnit", Qt::CaseInsensitive ) == 0
528  || str.compare( "MapUnits", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::MapUnits;
529  if ( str.compare( "Percent", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Percent;
530  return QgsPalLayerSettings::MM; // "MM"
531 }
532 
533 static Qt::PenJoinStyle _decodePenJoinStyle( const QString& str )
534 {
535  if ( str.compare( "Miter", Qt::CaseInsensitive ) == 0 ) return Qt::MiterJoin;
536  if ( str.compare( "Round", Qt::CaseInsensitive ) == 0 ) return Qt::RoundJoin;
537  return Qt::BevelJoin; // "Bevel"
538 }
539 
540 void QgsPalLayerSettings::readDataDefinedPropertyMap( QgsVectorLayer* layer,
542 {
543  if ( !layer )
544  {
545  return;
546  }
547 
549  while ( i.hasNext() )
550  {
551  i.next();
552  readDataDefinedProperty( layer, i.key(), propertyMap );
553  }
554 }
555 
556 void QgsPalLayerSettings::writeDataDefinedPropertyMap( QgsVectorLayer* layer,
558 {
559  if ( !layer )
560  {
561  return;
562  }
563 
565  while ( i.hasNext() )
566  {
567  i.next();
568  QString newPropertyName = "labeling/dataDefined/" + i.value().first;
569  QVariant propertyValue = QVariant();
570 
572  if ( it != propertyMap.constEnd() )
573  {
574  QgsDataDefined* dd = it.value();
575  if ( dd )
576  {
577  bool active = dd->isActive();
578  bool useExpr = dd->useExpression();
579  QString expr = dd->expressionString();
580  QString field = dd->field();
581 
582  bool defaultVals = ( !active && !useExpr && expr.isEmpty() && field.isEmpty() );
583 
584  if ( !defaultVals )
585  {
586  // TODO: update this when project settings for labeling are migrated to better XML layout
587  QStringList values;
588  values << ( active ? "1" : "0" );
589  values << ( useExpr ? "1" : "0" );
590  values << expr;
591  values << field;
592  if ( !values.isEmpty() )
593  {
594  propertyValue = QVariant( values.join( "~~" ) );
595  }
596  }
597  }
598  }
599 
600  if ( propertyValue.isValid() )
601  {
602  layer->setCustomProperty( newPropertyName, propertyValue );
603  }
604  else
605  {
606  // remove unused properties
607  layer->removeCustomProperty( newPropertyName );
608  }
609 
610  if ( layer->customProperty( newPropertyName, QVariant() ).isValid() && i.value().second > -1 )
611  {
612  // remove old-style field index-based property, if still present
613  layer->removeCustomProperty( QString( "labeling/dataDefinedProperty" ) + QString::number( i.value().second ) );
614  }
615  }
616 }
617 
618 void QgsPalLayerSettings::readDataDefinedProperty( QgsVectorLayer* layer,
621 {
622  QString newPropertyName = "labeling/dataDefined/" + mDataDefinedNames.value( p ).first;
623  QVariant newPropertyField = layer->customProperty( newPropertyName, QVariant() );
624 
625  QString ddString = QString();
626  if ( newPropertyField.isValid() )
627  {
628  ddString = newPropertyField.toString();
629  }
630  else // maybe working with old-style field index-based property (< QGIS 2.0)
631  {
632  int oldIndx = mDataDefinedNames.value( p ).second;
633 
634  if ( oldIndx < 0 ) // something went wrong and we are working with new-style
635  {
636  return;
637  }
638 
639  QString oldPropertyName = "labeling/dataDefinedProperty" + QString::number( oldIndx );
640  QVariant oldPropertyField = layer->customProperty( oldPropertyName, QVariant() );
641 
642  if ( !oldPropertyField.isValid() )
643  {
644  return;
645  }
646 
647  // switch from old-style field index- to name-based properties
648  bool conversionOk;
649  int indx = oldPropertyField.toInt( &conversionOk );
650 
651  if ( conversionOk )
652  {
653  // Fix to migrate from old-style vector api, where returned QMap keys possibly
654  // had 'holes' in sequence of field indices, e.g. 0,2,3
655  // QgsAttrPalIndexNameHash provides a means of access field name in sequences from
656  // providers that procuded holes (e.g. PostGIS skipped geom column), otherwise it is empty
657  QgsAttrPalIndexNameHash oldIndicesToNames = layer->dataProvider()->palAttributeIndexNames();
658 
659  if ( !oldIndicesToNames.isEmpty() )
660  {
661  ddString = oldIndicesToNames.value( indx );
662  }
663  else
664  {
665  QgsFields fields = layer->dataProvider()->fields();
666  if ( indx < fields.size() ) // in case field count has changed
667  {
668  ddString = fields.at( indx ).name();
669  }
670  }
671  }
672 
673  if ( !ddString.isEmpty() )
674  {
675  //upgrade any existing property to field name-based
676  layer->setCustomProperty( newPropertyName, QVariant( updateDataDefinedString( ddString ) ) );
677 
678  // fix for buffer drawing triggered off of just its data defined size in the past (<2.0)
679  if ( oldIndx == 7 ) // old bufferSize enum
680  {
681  bufferDraw = true;
682  layer->setCustomProperty( "labeling/bufferDraw", true );
683  }
684 
685  // fix for scale visibility limits triggered off of just its data defined values in the past (<2.0)
686  if ( oldIndx == 16 || oldIndx == 17 ) // old minScale and maxScale enums
687  {
688  scaleVisibility = true;
689  layer->setCustomProperty( "labeling/scaleVisibility", true );
690  }
691  }
692 
693  // remove old-style field index-based property
694  layer->removeCustomProperty( oldPropertyName );
695  }
696 
697  if ( !ddString.isEmpty() && ddString != QString( "0~~0~~~~" ) )
698  {
699  // TODO: update this when project settings for labeling are migrated to better XML layout
700  QString newStyleString = updateDataDefinedString( ddString );
701  QStringList ddv = newStyleString.split( "~~" );
702 
703  QgsDataDefined* dd = new QgsDataDefined( ddv.at( 0 ).toInt(), ddv.at( 1 ).toInt(), ddv.at( 2 ), ddv.at( 3 ) );
704  propertyMap.insert( p, dd );
705  }
706  else
707  {
708  // remove unused properties
709  layer->removeCustomProperty( newPropertyName );
710  }
711 }
712 
714 {
715  if ( layer->customProperty( "labeling" ).toString() != QString( "pal" ) )
716  {
717  // for polygons the "over point" (over centroid) placement is better than the default
718  // "around point" (around centroid) which is more suitable for points
719  if ( layer->geometryType() == QGis::Polygon )
721 
722  return; // there's no information available
723  }
724 
725  // NOTE: set defaults for newly added properties, for backwards compatibility
726 
727  enabled = layer->labelsEnabled();
728  drawLabels = layer->customProperty( "labeling/drawLabels", true ).toBool();
729 
730  // text style
731  fieldName = layer->customProperty( "labeling/fieldName" ).toString();
732  isExpression = layer->customProperty( "labeling/isExpression" ).toBool();
733  QFont appFont = QApplication::font();
734  mTextFontFamily = layer->customProperty( "labeling/fontFamily", QVariant( appFont.family() ) ).toString();
735  QString fontFamily = mTextFontFamily;
737  {
738  // trigger to notify user about font family substitution (signal emitted in QgsVectorLayer::prepareLabelingAndDiagrams)
739  mTextFontFound = false;
740 
741  // TODO: update when pref for how to resolve missing family (use matching algorithm or just default font) is implemented
742  // currently only defaults to matching algorithm for resolving [foundry], if a font of similar family is found (default for QFont)
743 
744  // for now, do not use matching algorithm for substitution if family not found, substitute default instead
745  fontFamily = appFont.family();
746  }
747 
748  double fontSize = layer->customProperty( "labeling/fontSize" ).toDouble();
749  fontSizeInMapUnits = layer->customProperty( "labeling/fontSizeInMapUnits" ).toBool();
750  fontSizeMapUnitScale.minScale = layer->customProperty( "labeling/fontSizeMapUnitMinScale", 0.0 ).toDouble();
751  fontSizeMapUnitScale.maxScale = layer->customProperty( "labeling/fontSizeMapUnitMaxScale", 0.0 ).toDouble();
752  int fontWeight = layer->customProperty( "labeling/fontWeight" ).toInt();
753  bool fontItalic = layer->customProperty( "labeling/fontItalic" ).toBool();
754  textFont = QFont( fontFamily, fontSize, fontWeight, fontItalic );
755  textFont.setPointSizeF( fontSize ); //double precision needed because of map units
756  textNamedStyle = QgsFontUtils::translateNamedStyle( layer->customProperty( "labeling/namedStyle", QVariant( "" ) ).toString() );
757  QgsFontUtils::updateFontViaStyle( textFont, textNamedStyle ); // must come after textFont.setPointSizeF()
758  textFont.setCapitalization(( QFont::Capitalization )layer->customProperty( "labeling/fontCapitals", QVariant( 0 ) ).toUInt() );
759  textFont.setUnderline( layer->customProperty( "labeling/fontUnderline" ).toBool() );
760  textFont.setStrikeOut( layer->customProperty( "labeling/fontStrikeout" ).toBool() );
761  textFont.setLetterSpacing( QFont::AbsoluteSpacing, layer->customProperty( "labeling/fontLetterSpacing", QVariant( 0.0 ) ).toDouble() );
762  textFont.setWordSpacing( layer->customProperty( "labeling/fontWordSpacing", QVariant( 0.0 ) ).toDouble() );
763  textColor = _readColor( layer, "labeling/textColor", Qt::black, false );
764  textTransp = layer->customProperty( "labeling/textTransp" ).toInt();
766  ( QgsMapRenderer::BlendMode )layer->customProperty( "labeling/blendMode", QVariant( QgsMapRenderer::BlendNormal ) ).toUInt() );
767  previewBkgrdColor = QColor( layer->customProperty( "labeling/previewBkgrdColor", QVariant( "#ffffff" ) ).toString() );
768 
769 
770  // text formatting
771  wrapChar = layer->customProperty( "labeling/wrapChar" ).toString();
772  multilineHeight = layer->customProperty( "labeling/multilineHeight", QVariant( 1.0 ) ).toDouble();
773  multilineAlign = ( MultiLineAlign )layer->customProperty( "labeling/multilineAlign", QVariant( MultiLeft ) ).toUInt();
774  addDirectionSymbol = layer->customProperty( "labeling/addDirectionSymbol" ).toBool();
775  leftDirectionSymbol = layer->customProperty( "labeling/leftDirectionSymbol", QVariant( "<" ) ).toString();
776  rightDirectionSymbol = layer->customProperty( "labeling/rightDirectionSymbol", QVariant( ">" ) ).toString();
777  reverseDirectionSymbol = layer->customProperty( "labeling/reverseDirectionSymbol" ).toBool();
778  placeDirectionSymbol = ( DirectionSymbols )layer->customProperty( "labeling/placeDirectionSymbol", QVariant( SymbolLeftRight ) ).toUInt();
779  formatNumbers = layer->customProperty( "labeling/formatNumbers" ).toBool();
780  decimals = layer->customProperty( "labeling/decimals" ).toInt();
781  plusSign = layer->customProperty( "labeling/plussign" ).toInt();
782 
783  // text buffer
784  double bufSize = layer->customProperty( "labeling/bufferSize", QVariant( 0.0 ) ).toDouble();
785 
786  // fix for buffer being keyed off of just its size in the past (<2.0)
787  QVariant drawBuffer = layer->customProperty( "labeling/bufferDraw", QVariant() );
788  if ( drawBuffer.isValid() )
789  {
790  bufferDraw = drawBuffer.toBool();
791  bufferSize = bufSize;
792  }
793  else if ( bufSize != 0.0 )
794  {
795  bufferDraw = true;
796  bufferSize = bufSize;
797  }
798  else
799  {
800  // keep bufferSize at new 1.0 default
801  bufferDraw = false;
802  }
803 
804  bufferSizeInMapUnits = layer->customProperty( "labeling/bufferSizeInMapUnits" ).toBool();
805  bufferSizeMapUnitScale.minScale = layer->customProperty( "labeling/bufferSizeMapUnitMinScale", 0.0 ).toDouble();
806  bufferSizeMapUnitScale.maxScale = layer->customProperty( "labeling/bufferSizeMapUnitMaxScale", 0.0 ).toDouble();
807  bufferColor = _readColor( layer, "labeling/bufferColor", Qt::white, false );
808  bufferTransp = layer->customProperty( "labeling/bufferTransp" ).toInt();
810  ( QgsMapRenderer::BlendMode )layer->customProperty( "labeling/bufferBlendMode", QVariant( QgsMapRenderer::BlendNormal ) ).toUInt() );
811  bufferJoinStyle = ( Qt::PenJoinStyle )layer->customProperty( "labeling/bufferJoinStyle", QVariant( Qt::BevelJoin ) ).toUInt();
812  bufferNoFill = layer->customProperty( "labeling/bufferNoFill", QVariant( false ) ).toBool();
813 
814  // background
815  shapeDraw = layer->customProperty( "labeling/shapeDraw", QVariant( false ) ).toBool();
816  shapeType = ( ShapeType )layer->customProperty( "labeling/shapeType", QVariant( ShapeRectangle ) ).toUInt();
817  shapeSVGFile = layer->customProperty( "labeling/shapeSVGFile", QVariant( "" ) ).toString();
818  shapeSizeType = ( SizeType )layer->customProperty( "labeling/shapeSizeType", QVariant( SizeBuffer ) ).toUInt();
819  shapeSize = QPointF( layer->customProperty( "labeling/shapeSizeX", QVariant( 0.0 ) ).toDouble(),
820  layer->customProperty( "labeling/shapeSizeY", QVariant( 0.0 ) ).toDouble() );
821  shapeSizeUnits = ( SizeUnit )layer->customProperty( "labeling/shapeSizeUnits", QVariant( MM ) ).toUInt();
822  shapeSizeMapUnitScale.minScale = layer->customProperty( "labeling/shapeSizeMapUnitMinScale", 0.0 ).toDouble();
823  shapeSizeMapUnitScale.maxScale = layer->customProperty( "labeling/shapeSizeMapUnitMaxScale", 0.0 ).toDouble();
824  shapeRotationType = ( RotationType )layer->customProperty( "labeling/shapeRotationType", QVariant( RotationSync ) ).toUInt();
825  shapeRotation = layer->customProperty( "labeling/shapeRotation", QVariant( 0.0 ) ).toDouble();
826  shapeOffset = QPointF( layer->customProperty( "labeling/shapeOffsetX", QVariant( 0.0 ) ).toDouble(),
827  layer->customProperty( "labeling/shapeOffsetY", QVariant( 0.0 ) ).toDouble() );
828  shapeOffsetUnits = ( SizeUnit )layer->customProperty( "labeling/shapeOffsetUnits", QVariant( MM ) ).toUInt();
829  shapeOffsetMapUnitScale.minScale = layer->customProperty( "labeling/shapeOffsetMapUnitMinScale", 0.0 ).toDouble();
830  shapeOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/shapeOffsetMapUnitMaxScale", 0.0 ).toDouble();
831  shapeRadii = QPointF( layer->customProperty( "labeling/shapeRadiiX", QVariant( 0.0 ) ).toDouble(),
832  layer->customProperty( "labeling/shapeRadiiY", QVariant( 0.0 ) ).toDouble() );
833  shapeRadiiUnits = ( SizeUnit )layer->customProperty( "labeling/shapeRadiiUnits", QVariant( MM ) ).toUInt();
834  shapeRadiiMapUnitScale.minScale = layer->customProperty( "labeling/shapeRaddiMapUnitMinScale", 0.0 ).toDouble();
835  shapeRadiiMapUnitScale.maxScale = layer->customProperty( "labeling/shapeRaddiMapUnitMaxScale", 0.0 ).toDouble();
836  shapeFillColor = _readColor( layer, "labeling/shapeFillColor", Qt::white, true );
837  shapeBorderColor = _readColor( layer, "labeling/shapeBorderColor", Qt::darkGray, true );
838  shapeBorderWidth = layer->customProperty( "labeling/shapeBorderWidth", QVariant( .0 ) ).toDouble();
839  shapeBorderWidthUnits = ( SizeUnit )layer->customProperty( "labeling/shapeBorderWidthUnits", QVariant( MM ) ).toUInt();
840  shapeBorderWidthMapUnitScale.minScale = layer->customProperty( "labeling/shapeBorderWidthMapUnitMinScale", 0.0 ).toDouble();
841  shapeBorderWidthMapUnitScale.maxScale = layer->customProperty( "labeling/shapeBorderWidthMapUnitMaxScale", 0.0 ).toDouble();
842  shapeJoinStyle = ( Qt::PenJoinStyle )layer->customProperty( "labeling/shapeJoinStyle", QVariant( Qt::BevelJoin ) ).toUInt();
843  shapeTransparency = layer->customProperty( "labeling/shapeTransparency", QVariant( 0 ) ).toInt();
845  ( QgsMapRenderer::BlendMode )layer->customProperty( "labeling/shapeBlendMode", QVariant( QgsMapRenderer::BlendNormal ) ).toUInt() );
846 
847  // drop shadow
848  shadowDraw = layer->customProperty( "labeling/shadowDraw", QVariant( false ) ).toBool();
849  shadowUnder = ( ShadowType )layer->customProperty( "labeling/shadowUnder", QVariant( ShadowLowest ) ).toUInt();//ShadowLowest;
850  shadowOffsetAngle = layer->customProperty( "labeling/shadowOffsetAngle", QVariant( 135 ) ).toInt();
851  shadowOffsetDist = layer->customProperty( "labeling/shadowOffsetDist", QVariant( 1.0 ) ).toDouble();
852  shadowOffsetUnits = ( SizeUnit )layer->customProperty( "labeling/shadowOffsetUnits", QVariant( MM ) ).toUInt();
853  shadowOffsetMapUnitScale.minScale = layer->customProperty( "labeling/shadowOffsetMapUnitMinScale", 0.0 ).toDouble();
854  shadowOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/shadowOffsetMapUnitMaxScale", 0.0 ).toDouble();
855  shadowOffsetGlobal = layer->customProperty( "labeling/shadowOffsetGlobal", QVariant( true ) ).toBool();
856  shadowRadius = layer->customProperty( "labeling/shadowRadius", QVariant( 1.5 ) ).toDouble();
857  shadowRadiusUnits = ( SizeUnit )layer->customProperty( "labeling/shadowRadiusUnits", QVariant( MM ) ).toUInt();
858  shadowRadiusMapUnitScale.minScale = layer->customProperty( "labeling/shadowRadiusMapUnitMinScale", 0.0 ).toDouble();
859  shadowRadiusMapUnitScale.maxScale = layer->customProperty( "labeling/shadowRadiusMapUnitMaxScale", 0.0 ).toDouble();
860  shadowRadiusAlphaOnly = layer->customProperty( "labeling/shadowRadiusAlphaOnly", QVariant( false ) ).toBool();
861  shadowTransparency = layer->customProperty( "labeling/shadowTransparency", QVariant( 30 ) ).toInt();
862  shadowScale = layer->customProperty( "labeling/shadowScale", QVariant( 100 ) ).toInt();
863  shadowColor = _readColor( layer, "labeling/shadowColor", Qt::black, false );
865  ( QgsMapRenderer::BlendMode )layer->customProperty( "labeling/shadowBlendMode", QVariant( QgsMapRenderer::BlendMultiply ) ).toUInt() );
866 
867  // placement
868  placement = ( Placement )layer->customProperty( "labeling/placement" ).toInt();
869  placementFlags = layer->customProperty( "labeling/placementFlags" ).toUInt();
870  centroidWhole = layer->customProperty( "labeling/centroidWhole", QVariant( false ) ).toBool();
871  centroidInside = layer->customProperty( "labeling/centroidInside", QVariant( false ) ).toBool();
872  fitInPolygonOnly = layer->customProperty( "labeling/fitInPolygonOnly", QVariant( false ) ).toBool();
873  dist = layer->customProperty( "labeling/dist" ).toDouble();
874  distInMapUnits = layer->customProperty( "labeling/distInMapUnits" ).toBool();
875  distMapUnitScale.minScale = layer->customProperty( "labeling/distMapUnitMinScale", 0.0 ).toDouble();
876  distMapUnitScale.maxScale = layer->customProperty( "labeling/distMapUnitMaxScale", 0.0 ).toDouble();
877  quadOffset = ( QuadrantPosition )layer->customProperty( "labeling/quadOffset", QVariant( QuadrantOver ) ).toUInt();
878  xOffset = layer->customProperty( "labeling/xOffset", QVariant( 0.0 ) ).toDouble();
879  yOffset = layer->customProperty( "labeling/yOffset", QVariant( 0.0 ) ).toDouble();
880  labelOffsetInMapUnits = layer->customProperty( "labeling/labelOffsetInMapUnits", QVariant( true ) ).toBool();
881  labelOffsetMapUnitScale.minScale = layer->customProperty( "labeling/labelOffsetMapUnitMinScale", 0.0 ).toDouble();
882  labelOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/labelOffsetMapUnitMaxScale", 0.0 ).toDouble();
883  angleOffset = layer->customProperty( "labeling/angleOffset", QVariant( 0.0 ) ).toDouble();
884  preserveRotation = layer->customProperty( "labeling/preserveRotation", QVariant( true ) ).toBool();
885  maxCurvedCharAngleIn = layer->customProperty( "labeling/maxCurvedCharAngleIn", QVariant( 20.0 ) ).toDouble();
886  maxCurvedCharAngleOut = layer->customProperty( "labeling/maxCurvedCharAngleOut", QVariant( -20.0 ) ).toDouble();
887  priority = layer->customProperty( "labeling/priority" ).toInt();
888  repeatDistance = layer->customProperty( "labeling/repeatDistance", 0.0 ).toDouble();
889  repeatDistanceUnit = ( SizeUnit ) layer->customProperty( "labeling/repeatDistanceUnit", QVariant( MM ) ).toUInt();
890  repeatDistanceMapUnitScale.minScale = layer->customProperty( "labeling/repeatDistanceMapUnitMinScale", 0.0 ).toDouble();
891  repeatDistanceMapUnitScale.maxScale = layer->customProperty( "labeling/repeatDistanceMapUnitMaxScale", 0.0 ).toDouble();
892 
893  // rendering
894  int scalemn = layer->customProperty( "labeling/scaleMin", QVariant( 0 ) ).toInt();
895  int scalemx = layer->customProperty( "labeling/scaleMax", QVariant( 0 ) ).toInt();
896 
897  // fix for scale visibility limits being keyed off of just its values in the past (<2.0)
898  QVariant scalevis = layer->customProperty( "labeling/scaleVisibility", QVariant() );
899  if ( scalevis.isValid() )
900  {
901  scaleVisibility = scalevis.toBool();
902  scaleMin = scalemn;
903  scaleMax = scalemx;
904  }
905  else if ( scalemn > 0 || scalemx > 0 )
906  {
907  scaleVisibility = true;
908  scaleMin = scalemn;
909  scaleMax = scalemx;
910  }
911  else
912  {
913  // keep scaleMin and scaleMax at new 1.0 defaults (1 and 10000000, were 0 and 0)
914  scaleVisibility = false;
915  }
916 
917 
918  fontLimitPixelSize = layer->customProperty( "labeling/fontLimitPixelSize", QVariant( false ) ).toBool();
919  fontMinPixelSize = layer->customProperty( "labeling/fontMinPixelSize", QVariant( 0 ) ).toInt();
920  fontMaxPixelSize = layer->customProperty( "labeling/fontMaxPixelSize", QVariant( 10000 ) ).toInt();
921  displayAll = layer->customProperty( "labeling/displayAll", QVariant( false ) ).toBool();
922  upsidedownLabels = ( UpsideDownLabels )layer->customProperty( "labeling/upsidedownLabels", QVariant( Upright ) ).toUInt();
923 
924  labelPerPart = layer->customProperty( "labeling/labelPerPart" ).toBool();
925  mergeLines = layer->customProperty( "labeling/mergeLines" ).toBool();
926  minFeatureSize = layer->customProperty( "labeling/minFeatureSize" ).toDouble();
927  limitNumLabels = layer->customProperty( "labeling/limitNumLabels", QVariant( false ) ).toBool();
928  maxNumLabels = layer->customProperty( "labeling/maxNumLabels", QVariant( 2000 ) ).toInt();
929  obstacle = layer->customProperty( "labeling/obstacle", QVariant( true ) ).toBool();
930  obstacleFactor = layer->customProperty( "labeling/obstacleFactor", QVariant( 1.0 ) ).toDouble();
931  obstacleType = ( ObstacleType )layer->customProperty( "labeling/obstacleType", QVariant( PolygonInterior ) ).toUInt();
932 
933  readDataDefinedPropertyMap( layer, dataDefinedProperties );
934 }
935 
937 {
938  // this is a mark that labeling information is present
939  layer->setCustomProperty( "labeling", "pal" );
940 
941  layer->setCustomProperty( "labeling/enabled", enabled );
942  layer->setCustomProperty( "labeling/drawLabels", drawLabels );
943 
944  // text style
945  layer->setCustomProperty( "labeling/fieldName", fieldName );
946  layer->setCustomProperty( "labeling/isExpression", isExpression );
947  layer->setCustomProperty( "labeling/fontFamily", textFont.family() );
948  layer->setCustomProperty( "labeling/namedStyle", QgsFontUtils::untranslateNamedStyle( textNamedStyle ) );
949  layer->setCustomProperty( "labeling/fontSize", textFont.pointSizeF() );
950  layer->setCustomProperty( "labeling/fontSizeInMapUnits", fontSizeInMapUnits );
951  layer->setCustomProperty( "labeling/fontSizeMapUnitMinScale", fontSizeMapUnitScale.minScale );
952  layer->setCustomProperty( "labeling/fontSizeMapUnitMaxScale", fontSizeMapUnitScale.maxScale );
953  layer->setCustomProperty( "labeling/fontWeight", textFont.weight() );
954  layer->setCustomProperty( "labeling/fontItalic", textFont.italic() );
955  layer->setCustomProperty( "labeling/fontBold", textFont.bold() );
956  layer->setCustomProperty( "labeling/fontStrikeout", textFont.strikeOut() );
957  layer->setCustomProperty( "labeling/fontUnderline", textFont.underline() );
958  _writeColor( layer, "labeling/textColor", textColor );
959  layer->setCustomProperty( "labeling/fontCapitals", ( unsigned int )textFont.capitalization() );
960  layer->setCustomProperty( "labeling/fontLetterSpacing", textFont.letterSpacing() );
961  layer->setCustomProperty( "labeling/fontWordSpacing", textFont.wordSpacing() );
962  layer->setCustomProperty( "labeling/textTransp", textTransp );
963  layer->setCustomProperty( "labeling/blendMode", QgsMapRenderer::getBlendModeEnum( blendMode ) );
964  layer->setCustomProperty( "labeling/previewBkgrdColor", previewBkgrdColor.name() );
965 
966  // text formatting
967  layer->setCustomProperty( "labeling/wrapChar", wrapChar );
968  layer->setCustomProperty( "labeling/multilineHeight", multilineHeight );
969  layer->setCustomProperty( "labeling/multilineAlign", ( unsigned int )multilineAlign );
970  layer->setCustomProperty( "labeling/addDirectionSymbol", addDirectionSymbol );
971  layer->setCustomProperty( "labeling/leftDirectionSymbol", leftDirectionSymbol );
972  layer->setCustomProperty( "labeling/rightDirectionSymbol", rightDirectionSymbol );
973  layer->setCustomProperty( "labeling/reverseDirectionSymbol", reverseDirectionSymbol );
974  layer->setCustomProperty( "labeling/placeDirectionSymbol", ( unsigned int )placeDirectionSymbol );
975  layer->setCustomProperty( "labeling/formatNumbers", formatNumbers );
976  layer->setCustomProperty( "labeling/decimals", decimals );
977  layer->setCustomProperty( "labeling/plussign", plusSign );
978 
979  // text buffer
980  layer->setCustomProperty( "labeling/bufferDraw", bufferDraw );
981  layer->setCustomProperty( "labeling/bufferSize", bufferSize );
982  layer->setCustomProperty( "labeling/bufferSizeInMapUnits", bufferSizeInMapUnits );
983  layer->setCustomProperty( "labeling/bufferSizeMapUnitMinScale", bufferSizeMapUnitScale.minScale );
984  layer->setCustomProperty( "labeling/bufferSizeMapUnitMaxScale", bufferSizeMapUnitScale.maxScale );
985  _writeColor( layer, "labeling/bufferColor", bufferColor );
986  layer->setCustomProperty( "labeling/bufferNoFill", bufferNoFill );
987  layer->setCustomProperty( "labeling/bufferTransp", bufferTransp );
988  layer->setCustomProperty( "labeling/bufferJoinStyle", ( unsigned int )bufferJoinStyle );
989  layer->setCustomProperty( "labeling/bufferBlendMode", QgsMapRenderer::getBlendModeEnum( bufferBlendMode ) );
990 
991  // background
992  layer->setCustomProperty( "labeling/shapeDraw", shapeDraw );
993  layer->setCustomProperty( "labeling/shapeType", ( unsigned int )shapeType );
994  layer->setCustomProperty( "labeling/shapeSVGFile", shapeSVGFile );
995  layer->setCustomProperty( "labeling/shapeSizeType", ( unsigned int )shapeSizeType );
996  layer->setCustomProperty( "labeling/shapeSizeX", shapeSize.x() );
997  layer->setCustomProperty( "labeling/shapeSizeY", shapeSize.y() );
998  layer->setCustomProperty( "labeling/shapeSizeUnits", ( unsigned int )shapeSizeUnits );
999  layer->setCustomProperty( "labeling/shapeSizeMapUnitMinScale", shapeSizeMapUnitScale.minScale );
1000  layer->setCustomProperty( "labeling/shapeSizeMapUnitMaxScale", shapeSizeMapUnitScale.maxScale );
1001  layer->setCustomProperty( "labeling/shapeRotationType", ( unsigned int )shapeRotationType );
1002  layer->setCustomProperty( "labeling/shapeRotation", shapeRotation );
1003  layer->setCustomProperty( "labeling/shapeOffsetX", shapeOffset.x() );
1004  layer->setCustomProperty( "labeling/shapeOffsetY", shapeOffset.y() );
1005  layer->setCustomProperty( "labeling/shapeOffsetUnits", ( unsigned int )shapeOffsetUnits );
1006  layer->setCustomProperty( "labeling/shapeOffsetMapUnitMinScale", shapeOffsetMapUnitScale.minScale );
1007  layer->setCustomProperty( "labeling/shapeOffsetMapUnitMaxScale", shapeOffsetMapUnitScale.maxScale );
1008  layer->setCustomProperty( "labeling/shapeRadiiX", shapeRadii.x() );
1009  layer->setCustomProperty( "labeling/shapeRadiiY", shapeRadii.y() );
1010  layer->setCustomProperty( "labeling/shapeRadiiUnits", ( unsigned int )shapeRadiiUnits );
1011  layer->setCustomProperty( "labeling/shapeRadiiMapUnitMinScale", shapeRadiiMapUnitScale.minScale );
1012  layer->setCustomProperty( "labeling/shapeRadiiMapUnitMaxScale", shapeRadiiMapUnitScale.maxScale );
1013  _writeColor( layer, "labeling/shapeFillColor", shapeFillColor, true );
1014  _writeColor( layer, "labeling/shapeBorderColor", shapeBorderColor, true );
1015  layer->setCustomProperty( "labeling/shapeBorderWidth", shapeBorderWidth );
1016  layer->setCustomProperty( "labeling/shapeBorderWidthUnits", ( unsigned int )shapeBorderWidthUnits );
1017  layer->setCustomProperty( "labeling/shapeBorderWidthMapUnitMinScale", shapeBorderWidthMapUnitScale.minScale );
1018  layer->setCustomProperty( "labeling/shapeBorderWidthMapUnitMaxScale", shapeBorderWidthMapUnitScale.maxScale );
1019  layer->setCustomProperty( "labeling/shapeJoinStyle", ( unsigned int )shapeJoinStyle );
1020  layer->setCustomProperty( "labeling/shapeTransparency", shapeTransparency );
1021  layer->setCustomProperty( "labeling/shapeBlendMode", QgsMapRenderer::getBlendModeEnum( shapeBlendMode ) );
1022 
1023  // drop shadow
1024  layer->setCustomProperty( "labeling/shadowDraw", shadowDraw );
1025  layer->setCustomProperty( "labeling/shadowUnder", ( unsigned int )shadowUnder );
1026  layer->setCustomProperty( "labeling/shadowOffsetAngle", shadowOffsetAngle );
1027  layer->setCustomProperty( "labeling/shadowOffsetDist", shadowOffsetDist );
1028  layer->setCustomProperty( "labeling/shadowOffsetUnits", ( unsigned int )shadowOffsetUnits );
1029  layer->setCustomProperty( "labeling/shadowOffsetMapUnitMinScale", shadowOffsetMapUnitScale.minScale );
1030  layer->setCustomProperty( "labeling/shadowOffsetMapUnitMaxScale", shadowOffsetMapUnitScale.maxScale );
1031  layer->setCustomProperty( "labeling/shadowOffsetGlobal", shadowOffsetGlobal );
1032  layer->setCustomProperty( "labeling/shadowRadius", shadowRadius );
1033  layer->setCustomProperty( "labeling/shadowRadiusUnits", ( unsigned int )shadowRadiusUnits );
1034  layer->setCustomProperty( "labeling/shadowRadiusMapUnitMinScale", shadowRadiusMapUnitScale.minScale );
1035  layer->setCustomProperty( "labeling/shadowRadiusMapUnitMaxScale", shadowRadiusMapUnitScale.maxScale );
1036  layer->setCustomProperty( "labeling/shadowRadiusAlphaOnly", shadowRadiusAlphaOnly );
1037  layer->setCustomProperty( "labeling/shadowTransparency", shadowTransparency );
1038  layer->setCustomProperty( "labeling/shadowScale", shadowScale );
1039  _writeColor( layer, "labeling/shadowColor", shadowColor, false );
1040  layer->setCustomProperty( "labeling/shadowBlendMode", QgsMapRenderer::getBlendModeEnum( shadowBlendMode ) );
1041 
1042  // placement
1043  layer->setCustomProperty( "labeling/placement", placement );
1044  layer->setCustomProperty( "labeling/placementFlags", ( unsigned int )placementFlags );
1045  layer->setCustomProperty( "labeling/centroidWhole", centroidWhole );
1046  layer->setCustomProperty( "labeling/centroidInside", centroidInside );
1047  layer->setCustomProperty( "labeling/fitInPolygonOnly", fitInPolygonOnly );
1048  layer->setCustomProperty( "labeling/dist", dist );
1049  layer->setCustomProperty( "labeling/distInMapUnits", distInMapUnits );
1050  layer->setCustomProperty( "labeling/distMapUnitMinScale", distMapUnitScale.minScale );
1051  layer->setCustomProperty( "labeling/distMapUnitMaxScale", distMapUnitScale.maxScale );
1052  layer->setCustomProperty( "labeling/quadOffset", ( unsigned int )quadOffset );
1053  layer->setCustomProperty( "labeling/xOffset", xOffset );
1054  layer->setCustomProperty( "labeling/yOffset", yOffset );
1055  layer->setCustomProperty( "labeling/labelOffsetInMapUnits", labelOffsetInMapUnits );
1056  layer->setCustomProperty( "labeling/labelOffsetMapUnitMinScale", labelOffsetMapUnitScale.minScale );
1057  layer->setCustomProperty( "labeling/labelOffsetMapUnitMaxScale", labelOffsetMapUnitScale.maxScale );
1058  layer->setCustomProperty( "labeling/angleOffset", angleOffset );
1059  layer->setCustomProperty( "labeling/preserveRotation", preserveRotation );
1060  layer->setCustomProperty( "labeling/maxCurvedCharAngleIn", maxCurvedCharAngleIn );
1061  layer->setCustomProperty( "labeling/maxCurvedCharAngleOut", maxCurvedCharAngleOut );
1062  layer->setCustomProperty( "labeling/priority", priority );
1063  layer->setCustomProperty( "labeling/repeatDistance", repeatDistance );
1064  layer->setCustomProperty( "labeling/repeatDistanceUnit", repeatDistanceUnit );
1065  layer->setCustomProperty( "labeling/repeatDistanceMapUnitMinScale", repeatDistanceMapUnitScale.minScale );
1066  layer->setCustomProperty( "labeling/repeatDistanceMapUnitMaxScale", repeatDistanceMapUnitScale.maxScale );
1067 
1068  // rendering
1069  layer->setCustomProperty( "labeling/scaleVisibility", scaleVisibility );
1070  layer->setCustomProperty( "labeling/scaleMin", scaleMin );
1071  layer->setCustomProperty( "labeling/scaleMax", scaleMax );
1072  layer->setCustomProperty( "labeling/fontLimitPixelSize", fontLimitPixelSize );
1073  layer->setCustomProperty( "labeling/fontMinPixelSize", fontMinPixelSize );
1074  layer->setCustomProperty( "labeling/fontMaxPixelSize", fontMaxPixelSize );
1075  layer->setCustomProperty( "labeling/displayAll", displayAll );
1076  layer->setCustomProperty( "labeling/upsidedownLabels", ( unsigned int )upsidedownLabels );
1077 
1078  layer->setCustomProperty( "labeling/labelPerPart", labelPerPart );
1079  layer->setCustomProperty( "labeling/mergeLines", mergeLines );
1080  layer->setCustomProperty( "labeling/minFeatureSize", minFeatureSize );
1081  layer->setCustomProperty( "labeling/limitNumLabels", limitNumLabels );
1082  layer->setCustomProperty( "labeling/maxNumLabels", maxNumLabels );
1083  layer->setCustomProperty( "labeling/obstacle", obstacle );
1084  layer->setCustomProperty( "labeling/obstacleFactor", obstacleFactor );
1085  layer->setCustomProperty( "labeling/obstacleType", ( unsigned int )obstacleType );
1086 
1087  writeDataDefinedPropertyMap( layer, dataDefinedProperties );
1088 }
1089 
1091  bool active, bool useExpr, const QString& expr, const QString& field )
1092 {
1093  bool defaultVals = ( !active && !useExpr && expr.isEmpty() && field.isEmpty() );
1094 
1095  if ( dataDefinedProperties.contains( p ) )
1096  {
1098  if ( it != dataDefinedProperties.constEnd() )
1099  {
1100  QgsDataDefined* dd = it.value();
1101  dd->setActive( active );
1102  dd->setUseExpression( useExpr );
1103  dd->setExpressionString( expr );
1104  dd->setField( field );
1105  }
1106  }
1107  else if ( !defaultVals )
1108  {
1109  QgsDataDefined* dd = new QgsDataDefined( active, useExpr, expr, field );
1110  dataDefinedProperties.insert( p, dd );
1111  }
1112 }
1113 
1115 {
1117  if ( it != dataDefinedProperties.end() )
1118  {
1119  delete( it.value() );
1121  }
1122 }
1123 
1125 {
1126  // TODO: update or remove this when project settings for labeling are migrated to better XML layout
1127  QString newValue = value;
1128  if ( !value.isEmpty() && !value.contains( "~~" ) )
1129  {
1130  QStringList values;
1131  values << "1"; // all old-style values are active if not empty
1132  values << "0";
1133  values << "";
1134  values << value; // all old-style values are only field names
1135  newValue = values.join( "~~" );
1136  }
1137 
1138  return newValue;
1139 }
1140 
1142 {
1144  if ( it != dataDefinedProperties.constEnd() )
1145  {
1146  return it.value();
1147  }
1148  return 0;
1149 }
1150 
1152 {
1155  if ( it != dataDefinedProperties.constEnd() )
1156  {
1157  return it.value()->toMap();
1158  }
1159  return map;
1160 }
1161 
1163 {
1164  if ( !dataDefinedProperties.contains( p ) )
1165  {
1166  return QVariant();
1167  }
1168 
1169  QgsDataDefined* dd = 0;
1171  if ( it != dataDefinedProperties.constEnd() )
1172  {
1173  dd = it.value();
1174  }
1175 
1176  if ( !dd )
1177  {
1178  return QVariant();
1179  }
1180 
1181  if ( !dd->isActive() )
1182  {
1183  return QVariant();
1184  }
1185 
1186  QVariant result = QVariant();
1187  bool useExpression = dd->useExpression();
1188  QString field = dd->field();
1189 
1190  //QgsDebugMsgLevel( QString( "isActive:" ) + isActive ? "1" : "0", 4 );
1191  //QgsDebugMsgLevel( QString( "useExpression:" ) + useExpression ? "1" : "0", 4 );
1192  //QgsDebugMsgLevel( QString( "expression:" ) + dd->expressionString(), 4 );
1193  //QgsDebugMsgLevel( QString( "field:" ) + field, 4 );
1194 
1195  if ( useExpression && dd->expressionIsPrepared() )
1196  {
1197  QgsExpression* expr = dd->expression();
1198  //QgsDebugMsgLevel( QString( "expr columns:" ) + expr->referencedColumns().join( "," ), 4 );
1199 
1200  result = expr->evaluate( &f );
1201  if ( expr->hasEvalError() )
1202  {
1203  QgsDebugMsgLevel( QString( "Evaluate error:" ) + expr->evalErrorString(), 4 );
1204  return QVariant();
1205  }
1206  }
1207  else if ( !useExpression && !field.isEmpty() )
1208  {
1209  // use direct attribute access instead of evaluating "field" expression (much faster)
1210  int indx = fields.indexFromName( field );
1211  if ( indx != -1 )
1212  {
1213  result = f.attribute( indx );
1214  }
1215  }
1216  return result;
1217 }
1218 
1220 {
1221  // null passed-around QVariant
1222  exprVal.clear();
1223 
1224  QVariant result = dataDefinedValue( p, *mCurFeat, *mCurFields );
1225 
1226  if ( result.isValid() && !result.isNull() )
1227  {
1228  //QgsDebugMsgLevel( QString( "result type:" ) + QString( result.typeName() ), 4 );
1229  //QgsDebugMsgLevel( QString( "result string:" ) + result.toString(), 4 );
1230  exprVal = result;
1231  return true;
1232  }
1233 
1234  return false;
1235 }
1236 
1238 {
1239  bool isActive = false;
1241  if ( it != dataDefinedProperties.constEnd() )
1242  {
1243  isActive = it.value()->isActive();
1244  }
1245 
1246  return isActive;
1247 }
1248 
1250 {
1251  bool useExpression = false;
1253  if ( it != dataDefinedProperties.constEnd() )
1254  {
1255  useExpression = it.value()->useExpression();
1256  }
1257 
1258  return useExpression;
1259 }
1260 
1261 bool QgsPalLayerSettings::checkMinimumSizeMM( const QgsRenderContext& ct, const QgsGeometry* geom, double minSize ) const
1262 {
1263  return QgsPalLabeling::checkMinimumSizeMM( ct, geom, minSize );
1264 }
1265 
1266 void QgsPalLayerSettings::calculateLabelSize( const QFontMetricsF* fm, QString text, double& labelX, double& labelY, QgsFeature* f )
1267 {
1268  if ( !fm || !f )
1269  {
1270  return;
1271  }
1272 
1273  QString wrapchr = wrapChar;
1274  double multilineH = multilineHeight;
1275 
1276  bool addDirSymb = addDirectionSymbol;
1277  QString leftDirSymb = leftDirectionSymbol;
1278  QString rightDirSymb = rightDirectionSymbol;
1280 
1281  if ( f == mCurFeat ) // called internally, use any stored data defined values
1282  {
1283  if ( dataDefinedValues.contains( QgsPalLayerSettings::MultiLineWrapChar ) )
1284  {
1285  wrapchr = dataDefinedValues.value( QgsPalLayerSettings::MultiLineWrapChar ).toString();
1286  }
1287 
1288  if ( dataDefinedValues.contains( QgsPalLayerSettings::MultiLineHeight ) )
1289  {
1290  multilineH = dataDefinedValues.value( QgsPalLayerSettings::MultiLineHeight ).toDouble();
1291  }
1292 
1293  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbDraw ) )
1294  {
1295  addDirSymb = dataDefinedValues.value( QgsPalLayerSettings::DirSymbDraw ).toBool();
1296  }
1297 
1298  if ( addDirSymb )
1299  {
1300 
1301  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbLeft ) )
1302  {
1303  leftDirSymb = dataDefinedValues.value( QgsPalLayerSettings::DirSymbLeft ).toString();
1304  }
1305  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbRight ) )
1306  {
1307  rightDirSymb = dataDefinedValues.value( QgsPalLayerSettings::DirSymbRight ).toString();
1308  }
1309 
1310  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbPlacement ) )
1311  {
1312  placeDirSymb = ( QgsPalLayerSettings::DirectionSymbols )dataDefinedValues.value( QgsPalLayerSettings::DirSymbPlacement ).toInt();
1313  }
1314 
1315  }
1316 
1317  }
1318  else // called externally with passed-in feature, evaluate data defined
1319  {
1321  if ( exprVal.isValid() )
1322  {
1323  wrapchr = exprVal.toString();
1324  }
1325  exprVal.clear();
1327  if ( exprVal.isValid() )
1328  {
1329  bool ok;
1330  double size = exprVal.toDouble( &ok );
1331  if ( ok )
1332  {
1333  multilineH = size;
1334  }
1335  }
1336 
1337  exprVal.clear();
1339  if ( exprVal.isValid() )
1340  {
1341  addDirSymb = exprVal.toBool();
1342  }
1343 
1344  if ( addDirSymb ) // don't do extra evaluations if not adding a direction symbol
1345  {
1346  exprVal.clear();
1348  if ( exprVal.isValid() )
1349  {
1350  leftDirSymb = exprVal.toString();
1351  }
1352  exprVal.clear();
1354  if ( exprVal.isValid() )
1355  {
1356  rightDirSymb = exprVal.toString();
1357  }
1358  exprVal.clear();
1360  if ( exprVal.isValid() )
1361  {
1362  bool ok;
1363  int enmint = exprVal.toInt( &ok );
1364  if ( ok )
1365  {
1366  placeDirSymb = ( QgsPalLayerSettings::DirectionSymbols )enmint;
1367  }
1368  }
1369  }
1370 
1371  }
1372 
1373  if ( wrapchr.isEmpty() )
1374  {
1375  wrapchr = QString( "\n" ); // default to new line delimiter
1376  }
1377 
1378  //consider the space needed for the direction symbol
1379  if ( addDirSymb && placement == QgsPalLayerSettings::Line
1380  && ( !leftDirSymb.isEmpty() || !rightDirSymb.isEmpty() ) )
1381  {
1382  QString dirSym = leftDirSymb;
1383 
1384  if ( fm->width( rightDirSymb ) > fm->width( dirSym ) )
1385  dirSym = rightDirSymb;
1386 
1387  if ( placeDirSymb == QgsPalLayerSettings::SymbolLeftRight )
1388  {
1389  text.append( dirSym );
1390  }
1391  else
1392  {
1393  text.prepend( dirSym + QString( "\n" ) ); // SymbolAbove or SymbolBelow
1394  }
1395  }
1396 
1397  double w = 0.0, h = 0.0;
1398  QStringList multiLineSplit = QgsPalLabeling::splitToLines( text, wrapchr );
1399  int lines = multiLineSplit.size();
1400 
1401  double labelHeight = fm->ascent() + fm->descent(); // ignore +1 for baseline
1402 
1403  h += fm->height() + ( double )(( lines - 1 ) * labelHeight * multilineH );
1404  h /= rasterCompressFactor;
1405 
1406  for ( int i = 0; i < lines; ++i )
1407  {
1408  double width = fm->width( multiLineSplit.at( i ) );
1409  if ( width > w )
1410  {
1411  w = width;
1412  }
1413  }
1414  w /= rasterCompressFactor;
1415 
1416 #if 0 // XXX strk
1417  QgsPoint ptSize = xform->toMapCoordinatesF( w, h );
1418  labelX = qAbs( ptSize.x() - ptZero.x() );
1419  labelY = qAbs( ptSize.y() - ptZero.y() );
1420 #else
1421  double uPP = xform->mapUnitsPerPixel();
1422  labelX = w * uPP;
1423  labelY = h * uPP;
1424 #endif
1425 }
1426 
1428 {
1429  if ( !drawLabels )
1430  {
1431  if ( obstacle )
1432  {
1433  registerObstacleFeature( f, context, dxfLayer );
1434  }
1435  return;
1436  }
1437 
1438  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
1439  mCurFeat = &f;
1440 // mCurFields = &layer->pendingFields();
1441 
1442  // store data defined-derived values for later adding to QgsPalGeometry for use during rendering
1443  dataDefinedValues.clear();
1444 
1445  // data defined show label? defaults to show label if not 0
1447  {
1448  bool showLabel = dataDefinedEvaluate( QgsPalLayerSettings::Show, exprVal );
1449  showLabel = exprVal.toBool();
1450  QgsDebugMsgLevel( QString( "exprVal Show:%1" ).arg( showLabel ? "true" : "false" ), 4 );
1451  if ( !showLabel )
1452  {
1453  return;
1454  }
1455  }
1456 
1457  // data defined scale visibility?
1458  bool useScaleVisibility = scaleVisibility;
1460  {
1461  QgsDebugMsgLevel( QString( "exprVal ScaleVisibility:%1" ).arg( exprVal.toBool() ? "true" : "false" ), 4 );
1462  useScaleVisibility = exprVal.toBool();
1463  }
1464 
1465  if ( useScaleVisibility )
1466  {
1467  // data defined min scale?
1468  double minScale = scaleMin;
1470  {
1471  QgsDebugMsgLevel( QString( "exprVal MinScale:%1" ).arg( exprVal.toDouble() ), 4 );
1472  bool conversionOk;
1473  double mins = exprVal.toDouble( &conversionOk );
1474  if ( conversionOk )
1475  {
1476  minScale = mins;
1477  }
1478  }
1479 
1480  // scales closer than 1:1
1481  if ( minScale < 0 )
1482  {
1483  minScale = 1 / qAbs( minScale );
1484  }
1485 
1486  if ( minScale != 0 && context.rendererScale() < minScale )
1487  {
1488  return;
1489  }
1490 
1491  // data defined max scale?
1492  double maxScale = scaleMax;
1494  {
1495  QgsDebugMsgLevel( QString( "exprVal MaxScale:%1" ).arg( exprVal.toDouble() ), 4 );
1496  bool conversionOk;
1497  double maxs = exprVal.toDouble( &conversionOk );
1498  if ( conversionOk )
1499  {
1500  maxScale = maxs;
1501  }
1502  }
1503 
1504  // scales closer than 1:1
1505  if ( maxScale < 0 )
1506  {
1507  maxScale = 1 / qAbs( maxScale );
1508  }
1509 
1510  if ( maxScale != 0 && context.rendererScale() > maxScale )
1511  {
1512  return;
1513  }
1514  }
1515 
1516  QFont labelFont = textFont;
1517  // labelFont will be added to label's QgsPalGeometry for use during label painting
1518 
1519  // data defined font units?
1522  {
1523  QString units = exprVal.toString().trimmed();
1524  QgsDebugMsgLevel( QString( "exprVal Font units:%1" ).arg( units ), 4 );
1525  if ( !units.isEmpty() )
1526  {
1527  fontunits = _decodeUnits( units );
1528  }
1529  }
1530 
1531  //data defined label size?
1532  double fontSize = labelFont.pointSizeF(); // font size doesn't have its own class data member
1534  {
1535  QgsDebugMsgLevel( QString( "exprVal Size:%1" ).arg( exprVal.toDouble() ), 4 );
1536  bool ok;
1537  double size = exprVal.toDouble( &ok );
1538  if ( ok )
1539  {
1540  fontSize = size;
1541  }
1542  }
1543  if ( fontSize <= 0.0 )
1544  {
1545  return;
1546  }
1547 
1548  int fontPixelSize = sizeToPixel( fontSize, context, fontunits, true, fontSizeMapUnitScale );
1549  // don't try to show font sizes less than 1 pixel (Qt complains)
1550  if ( fontPixelSize < 1 )
1551  {
1552  return;
1553  }
1554  labelFont.setPixelSize( fontPixelSize );
1555 
1556  // NOTE: labelFont now always has pixelSize set, so pointSize or pointSizeF might return -1
1557 
1558  // defined 'minimum/maximum pixel font size'?
1559  if ( fontunits == QgsPalLayerSettings::MapUnits )
1560  {
1561  bool useFontLimitPixelSize = fontLimitPixelSize;
1563  {
1564  QgsDebugMsgLevel( QString( "exprVal FontLimitPixel:%1" ).arg( exprVal.toBool() ? "true" : "false" ), 4 );
1565  useFontLimitPixelSize = exprVal.toBool();
1566  }
1567 
1568  if ( useFontLimitPixelSize )
1569  {
1570  int fontMinPixel = fontMinPixelSize;
1572  {
1573  bool ok;
1574  int sizeInt = exprVal.toInt( &ok );
1575  QgsDebugMsgLevel( QString( "exprVal FontMinPixel:%1" ).arg( sizeInt ), 4 );
1576  if ( ok )
1577  {
1578  fontMinPixel = sizeInt;
1579  }
1580  }
1581 
1582  int fontMaxPixel = fontMaxPixelSize;
1584  {
1585  bool ok;
1586  int sizeInt = exprVal.toInt( &ok );
1587  QgsDebugMsgLevel( QString( "exprVal FontMaxPixel:%1" ).arg( sizeInt ), 4 );
1588  if ( ok )
1589  {
1590  fontMaxPixel = sizeInt;
1591  }
1592  }
1593 
1594  if ( fontMinPixel > labelFont.pixelSize() || labelFont.pixelSize() > fontMaxPixel )
1595  {
1596  return;
1597  }
1598  }
1599  }
1600 
1601  // NOTE: the following parsing functions calculate and store any data defined values for later use in QgsPalLabeling::drawLabeling
1602  // this is done to provide clarity, and because such parsing is not directly related to PAL feature registration calculations
1603 
1604  // calculate rest of font attributes and store any data defined values
1605  // this is done here for later use in making label backgrounds part of collision management (when implemented)
1606  parseTextStyle( labelFont, fontunits, context );
1607  parseTextFormatting();
1608  parseTextBuffer();
1609  parseShapeBackground();
1610  parseDropShadow();
1611 
1612  QString labelText;
1613 
1614  // Check to see if we are a expression string.
1615  if ( isExpression )
1616  {
1618  if ( exp->hasParserError() )
1619  {
1620  QgsDebugMsgLevel( QString( "Expression parser error:%1" ).arg( exp->parserErrorString() ), 4 );
1621  return;
1622  }
1623  exp->setScale( context.rendererScale() );
1624 // QVariant result = exp->evaluate( &f, layer->pendingFields() );
1625  QVariant result = exp->evaluate( &f ); // expression prepared in QgsPalLabeling::prepareLayer()
1626  if ( exp->hasEvalError() )
1627  {
1628  QgsDebugMsgLevel( QString( "Expression parser eval error:%1" ).arg( exp->evalErrorString() ), 4 );
1629  return;
1630  }
1631  labelText = result.isNull() ? "" : result.toString();
1632  }
1633  else
1634  {
1635  const QVariant &v = f.attribute( fieldIndex );
1636  labelText = v.isNull() ? "" : v.toString();
1637  }
1638 
1639  // data defined format numbers?
1640  bool formatnum = formatNumbers;
1642  {
1643  formatnum = exprVal.toBool();
1644  QgsDebugMsgLevel( QString( "exprVal NumFormat:%1" ).arg( formatnum ? "true" : "false" ), 4 );
1645  }
1646 
1647  // format number if label text is coercible to a number
1648  if ( formatnum )
1649  {
1650  // data defined decimal places?
1651  int decimalPlaces = decimals;
1653  {
1654  bool ok;
1655  int dInt = exprVal.toInt( &ok );
1656  QgsDebugMsgLevel( QString( "exprVal NumDecimals:%1" ).arg( dInt ), 4 );
1657  if ( ok && dInt > 0 ) // needs to be positive
1658  {
1659  decimalPlaces = dInt;
1660  }
1661  }
1662 
1663  // data defined plus sign?
1664  bool signPlus = plusSign;
1666  {
1667  signPlus = exprVal.toBool();
1668  QgsDebugMsgLevel( QString( "exprVal NumPlusSign:%1" ).arg( signPlus ? "true" : "false" ), 4 );
1669  }
1670 
1671  QVariant textV( labelText );
1672  bool ok;
1673  double d = textV.toDouble( &ok );
1674  if ( ok )
1675  {
1676  QString numberFormat;
1677  if ( d > 0 && signPlus )
1678  {
1679  numberFormat.append( "+" );
1680  }
1681  numberFormat.append( "%1" );
1682  labelText = numberFormat.arg( d, 0, 'f', decimalPlaces );
1683  }
1684  }
1685 
1686 
1687  // NOTE: this should come AFTER any option that affects font metrics
1688  QFontMetricsF* labelFontMetrics = new QFontMetricsF( labelFont );
1689  double labelX, labelY; // will receive label size
1690  calculateLabelSize( labelFontMetrics, labelText, labelX, labelY, mCurFeat );
1691 
1692 
1693  // maximum angle between curved label characters (hardcoded defaults used in QGIS <2.0)
1694  //
1695  double maxcharanglein = 20.0; // range 20.0-60.0
1696  double maxcharangleout = -20.0; // range 20.0-95.0
1697 
1699  {
1700  maxcharanglein = maxCurvedCharAngleIn;
1701  maxcharangleout = maxCurvedCharAngleOut;
1702 
1703  //data defined maximum angle between curved label characters?
1705  {
1706  QString ptstr = exprVal.toString().trimmed();
1707  QgsDebugMsgLevel( QString( "exprVal CurvedCharAngleInOut:%1" ).arg( ptstr ), 4 );
1708 
1709  if ( !ptstr.isEmpty() )
1710  {
1711  QPointF maxcharanglePt = QgsSymbolLayerV2Utils::decodePoint( ptstr );
1712  maxcharanglein = qBound( 20.0, ( double )maxcharanglePt.x(), 60.0 );
1713  maxcharangleout = qBound( 20.0, ( double )maxcharanglePt.y(), 95.0 );
1714  }
1715  }
1716  // make sure maxcharangleout is always negative
1717  maxcharangleout = -( qAbs( maxcharangleout ) );
1718  }
1719 
1720  // data defined centroid whole or clipped?
1721  bool wholeCentroid = centroidWhole;
1723  {
1724  QString str = exprVal.toString().trimmed();
1725  QgsDebugMsgLevel( QString( "exprVal CentroidWhole:%1" ).arg( str ), 4 );
1726 
1727  if ( !str.isEmpty() )
1728  {
1729  if ( str.compare( "Visible", Qt::CaseInsensitive ) == 0 )
1730  {
1731  wholeCentroid = false;
1732  }
1733  else if ( str.compare( "Whole", Qt::CaseInsensitive ) == 0 )
1734  {
1735  wholeCentroid = true;
1736  }
1737  }
1738  }
1739 
1740  const QgsGeometry* geom = f.constGeometry();
1741  if ( !geom )
1742  {
1743  return;
1744  }
1745 
1746  // whether we're going to create a centroid for polygon
1747  bool centroidPoly = (( placement == QgsPalLayerSettings::AroundPoint
1749  && geom->type() == QGis::Polygon );
1750 
1751  // CLIP the geometry if it is bigger than the extent
1752  // don't clip if centroid is requested for whole feature
1753  bool doClip = false;
1754  if ( !centroidPoly || ( centroidPoly && !wholeCentroid ) )
1755  {
1756  doClip = true;
1757  }
1758 
1759  const GEOSGeometry* geos_geom = 0;
1760  const QgsGeometry* preparedGeom = geom;
1761  QScopedPointer<QgsGeometry> scopedPreparedGeom;
1762 
1763  if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, ct, doClip ? extentGeom : 0 ) )
1764  {
1765  scopedPreparedGeom.reset( QgsPalLabeling::prepareGeometry( geom, context, ct, doClip ? extentGeom : 0 ) );
1766  if ( !scopedPreparedGeom.data() )
1767  return;
1768  preparedGeom = scopedPreparedGeom.data();
1769  geos_geom = scopedPreparedGeom.data()->asGeos();
1770  }
1771  else
1772  {
1773  geos_geom = geom->asGeos();
1774  }
1775 
1776  if ( minFeatureSize > 0 && !checkMinimumSizeMM( context, preparedGeom, minFeatureSize ) )
1777  return;
1778 
1779  if ( geos_geom == NULL )
1780  return; // invalid geometry
1781 
1782  // likelihood exists label will be registered with PAL and may be drawn
1783  // check if max number of features to label (already registered with PAL) has been reached
1784  // Debug output at end of QgsPalLabeling::drawLabeling(), when deleting temp geometries
1785  if ( limitNumLabels )
1786  {
1787  if ( !maxNumLabels )
1788  {
1789  return;
1790  }
1792  if ( mFeatsRegPal >= maxNumLabels )
1793  {
1794  return;
1795  }
1796 
1797  int divNum = ( int )((( double )mFeaturesToLabel / maxNumLabels ) + 0.5 );
1798  if ( divNum && ( mFeatsRegPal == ( int )( mFeatsSendingToPal / divNum ) ) )
1799  {
1800  mFeatsSendingToPal += 1;
1801  if ( divNum && mFeatsSendingToPal % divNum )
1802  {
1803  return;
1804  }
1805  }
1806  }
1807 
1808  GEOSGeometry* geos_geom_clone;
1809  if ( GEOSGeomTypeId_r( QgsGeometry::getGEOSHandler(), geos_geom ) == GEOS_POLYGON && repeatDistance > 0 && placement == Line )
1810  {
1811  geos_geom_clone = GEOSBoundary_r( QgsGeometry::getGEOSHandler(), geos_geom );
1812  }
1813  else
1814  {
1815  geos_geom_clone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom );
1816  }
1817 
1818  //data defined position / alignment / rotation?
1819  bool dataDefinedPosition = false;
1820  bool labelIsPinned = false;
1821  bool layerDefinedRotation = false;
1822  bool dataDefinedRotation = false;
1823  double xPos = 0.0, yPos = 0.0, angle = 0.0;
1824  bool ddXPos = false, ddYPos = false;
1825  double quadOffsetX = 0.0, quadOffsetY = 0.0;
1826  double offsetX = 0.0, offsetY = 0.0;
1827 
1828  //data defined quadrant offset?
1829  bool ddFixedQuad = false;
1830  QuadrantPosition quadOff = quadOffset;
1832  {
1833  bool ok;
1834  int quadInt = exprVal.toInt( &ok );
1835  QgsDebugMsgLevel( QString( "exprVal OffsetQuad:%1" ).arg( quadInt ), 4 );
1836  if ( ok && 0 <= quadInt && quadInt <= 8 )
1837  {
1838  quadOff = ( QuadrantPosition )quadInt;
1839  ddFixedQuad = true;
1840  }
1841  }
1842 
1843  // adjust quadrant offset of labels
1844  switch ( quadOff )
1845  {
1846  case QuadrantAboveLeft:
1847  quadOffsetX = -1.0;
1848  quadOffsetY = 1.0;
1849  break;
1850  case QuadrantAbove:
1851  quadOffsetX = 0.0;
1852  quadOffsetY = 1.0;
1853  break;
1854  case QuadrantAboveRight:
1855  quadOffsetX = 1.0;
1856  quadOffsetY = 1.0;
1857  break;
1858  case QuadrantLeft:
1859  quadOffsetX = -1.0;
1860  quadOffsetY = 0.0;
1861  break;
1862  case QuadrantRight:
1863  quadOffsetX = 1.0;
1864  quadOffsetY = 0.0;
1865  break;
1866  case QuadrantBelowLeft:
1867  quadOffsetX = -1.0;
1868  quadOffsetY = -1.0;
1869  break;
1870  case QuadrantBelow:
1871  quadOffsetX = 0.0;
1872  quadOffsetY = -1.0;
1873  break;
1874  case QuadrantBelowRight:
1875  quadOffsetX = 1.0;
1876  quadOffsetY = -1.0;
1877  break;
1878  case QuadrantOver:
1879  default:
1880  break;
1881  }
1882 
1883  //data defined label offset?
1884  double xOff = xOffset;
1885  double yOff = yOffset;
1887  {
1888  QString ptstr = exprVal.toString().trimmed();
1889  QgsDebugMsgLevel( QString( "exprVal OffsetXY:%1" ).arg( ptstr ), 4 );
1890 
1891  if ( !ptstr.isEmpty() )
1892  {
1893  QPointF ddOffPt = QgsSymbolLayerV2Utils::decodePoint( ptstr );
1894  xOff = ddOffPt.x();
1895  yOff = ddOffPt.y();
1896  }
1897  }
1898 
1899  // data defined label offset units?
1900  bool offinmapunits = labelOffsetInMapUnits;
1902  {
1903  QString units = exprVal.toString().trimmed();
1904  QgsDebugMsgLevel( QString( "exprVal OffsetUnits:%1" ).arg( units ), 4 );
1905  if ( !units.isEmpty() )
1906  {
1907  offinmapunits = ( _decodeUnits( units ) == QgsPalLayerSettings::MapUnits );
1908  }
1909  }
1910 
1911  // adjust offset of labels to match chosen unit and map scale
1912  // offsets match those of symbology: -x = left, -y = up
1913  double mapUntsPerMM = labelOffsetMapUnitScale.computeMapUnitsPerPixel( context ) * context.scaleFactor();
1914  if ( xOff != 0 )
1915  {
1916  offsetX = xOff; // must be positive to match symbology offset direction
1917  if ( !offinmapunits )
1918  {
1919  offsetX *= mapUntsPerMM; //convert offset from mm to map units
1920  }
1921  }
1922  if ( yOff != 0 )
1923  {
1924  offsetY = -yOff; // must be negative to match symbology offset direction
1925  if ( !offinmapunits )
1926  {
1927  offsetY *= mapUntsPerMM; //convert offset from mm to map units
1928  }
1929  }
1930 
1931  // layer defined rotation?
1932  // only rotate non-pinned OverPoint placements until other placements are supported in pal::Feature
1933  if ( placement == QgsPalLayerSettings::OverPoint && angleOffset != 0 )
1934  {
1935  layerDefinedRotation = true;
1936  angle = angleOffset * M_PI / 180; // convert to radians
1937  }
1938 
1939  const QgsMapToPixel& m2p = context.mapToPixel();
1940  //data defined rotation?
1942  {
1943  bool ok;
1944  double rotD = exprVal.toDouble( &ok );
1945  QgsDebugMsgLevel( QString( "exprVal Rotation:%1" ).arg( rotD ), 4 );
1946  if ( ok )
1947  {
1948  dataDefinedRotation = true;
1949  // TODO: add setting to disable having data defined rotation follow
1950  // map rotation ?
1951  rotD -= m2p.mapRotation();
1952  angle = rotD * M_PI / 180.0;
1953  }
1954  }
1955 
1957  {
1958  if ( !exprVal.isNull() )
1959  xPos = exprVal.toDouble( &ddXPos );
1960  QgsDebugMsgLevel( QString( "exprVal PositionX:%1" ).arg( xPos ), 4 );
1961 
1963  {
1964  //data defined position. But field values could be NULL -> positions will be generated by PAL
1965  if ( !exprVal.isNull() )
1966  yPos = exprVal.toDouble( &ddYPos );
1967  QgsDebugMsgLevel( QString( "exprVal PositionY:%1" ).arg( yPos ), 4 );
1968 
1969  if ( ddXPos && ddYPos )
1970  {
1971  dataDefinedPosition = true;
1972  labelIsPinned = true;
1973  // layer rotation set, but don't rotate pinned labels unless data defined
1974  if ( layerDefinedRotation && !dataDefinedRotation )
1975  {
1976  angle = 0.0;
1977  }
1978 
1979  //x/y shift in case of alignment
1980  double xdiff = 0.0;
1981  double ydiff = 0.0;
1982 
1983  //horizontal alignment
1985  {
1986  QString haliString = exprVal.toString();
1987  QgsDebugMsgLevel( QString( "exprVal Hali:%1" ).arg( haliString ), 4 );
1988  if ( haliString.compare( "Center", Qt::CaseInsensitive ) == 0 )
1989  {
1990  xdiff -= labelX / 2.0;
1991  }
1992  else if ( haliString.compare( "Right", Qt::CaseInsensitive ) == 0 )
1993  {
1994  xdiff -= labelX;
1995  }
1996  }
1997 
1998  //vertical alignment
2000  {
2001  QString valiString = exprVal.toString();
2002  QgsDebugMsgLevel( QString( "exprVal Vali:%1" ).arg( valiString ), 4 );
2003 
2004  if ( valiString.compare( "Bottom", Qt::CaseInsensitive ) != 0 )
2005  {
2006  if ( valiString.compare( "Top", Qt::CaseInsensitive ) == 0 )
2007  {
2008  ydiff -= labelY;
2009  }
2010  else
2011  {
2012  double descentRatio = labelFontMetrics->descent() / labelFontMetrics->height();
2013  if ( valiString.compare( "Base", Qt::CaseInsensitive ) == 0 )
2014  {
2015  ydiff -= labelY * descentRatio;
2016  }
2017  else //'Cap' or 'Half'
2018  {
2019  double capHeightRatio = ( labelFontMetrics->boundingRect( 'H' ).height() + 1 + labelFontMetrics->descent() ) / labelFontMetrics->height();
2020  ydiff -= labelY * capHeightRatio;
2021  if ( valiString.compare( "Half", Qt::CaseInsensitive ) == 0 )
2022  {
2023  ydiff += labelY * ( capHeightRatio - descentRatio ) / 2.0;
2024  }
2025  }
2026  }
2027  }
2028  }
2029 
2030  if ( dataDefinedRotation )
2031  {
2032  //adjust xdiff and ydiff because the hali/vali point needs to be the rotation center
2033  double xd = xdiff * cos( angle ) - ydiff * sin( angle );
2034  double yd = xdiff * sin( angle ) + ydiff * cos( angle );
2035  xdiff = xd;
2036  ydiff = yd;
2037  }
2038 
2039  //project xPos and yPos from layer to map CRS
2040  double z = 0;
2041  if ( ct )
2042  {
2043  try
2044  {
2045  ct->transformInPlace( xPos, yPos, z );
2046  }
2047  catch ( QgsCsException &e )
2048  {
2049  Q_UNUSED( e );
2050  QgsDebugMsgLevel( QString( "Ignoring feature %1 due transformation exception on data-defined position" ).arg( f.id() ), 4 );
2051  return;
2052  }
2053  }
2054 
2055  //rotate position with map if data-defined
2056  if ( dataDefinedPosition && m2p.mapRotation() )
2057  {
2058  const QgsPoint& center = context.extent().center();
2059  QTransform t = QTransform::fromTranslate( center.x(), center.y() );
2060  t.rotate( -m2p.mapRotation() );
2061  t.translate( -center.x(), -center.y() );
2062  qreal xPosR, yPosR;
2063  t.map( xPos, yPos, &xPosR, &yPosR );
2064  xPos = xPosR; yPos = yPosR;
2065  }
2066 
2067  xPos += xdiff;
2068  yPos += ydiff;
2069  }
2070  else
2071  {
2072  // only rotate non-pinned OverPoint placements until other placements are supported in pal::Feature
2073  if ( dataDefinedRotation && placement != QgsPalLayerSettings::OverPoint )
2074  {
2075  angle = 0.0;
2076  }
2077  }
2078  }
2079  }
2080 
2081  // data defined always show?
2082  bool alwaysShow = false;
2084  {
2085  alwaysShow = exprVal.toBool();
2086  }
2087 
2088  QgsPalGeometry* lbl = new QgsPalGeometry(
2089  f.id(),
2090  labelText,
2091  geos_geom_clone,
2092  labelFont.letterSpacing(),
2093  labelFont.wordSpacing(),
2094  placement == QgsPalLayerSettings::Curved );
2095 
2096  lbl->setDxfLayer( dxfLayer );
2097 
2098  // record the created geometry - it will be deleted at the end.
2099  geometries.append( lbl );
2100 
2101  // store the label's calculated font for later use during painting
2102  QgsDebugMsgLevel( QString( "PAL font stored definedFont: %1, Style: %2" ).arg( labelFont.toString() ).arg( labelFont.styleName() ), 4 );
2103  lbl->setDefinedFont( labelFont );
2104 
2105  // set repeat distance
2106  // data defined repeat distance?
2107  double repeatDist = repeatDistance;
2109  {
2110  bool ok;
2111  double distD = exprVal.toDouble( &ok );
2112  if ( ok )
2113  {
2114  repeatDist = distD;
2115  }
2116  }
2117 
2118  // data defined label-repeat distance units?
2119  bool repeatdistinmapunit = repeatDistanceUnit == QgsPalLayerSettings::MapUnits;
2121  {
2122  QString units = exprVal.toString().trimmed();
2123  QgsDebugMsgLevel( QString( "exprVal RepeatDistanceUnits:%1" ).arg( units ), 4 );
2124  if ( !units.isEmpty() )
2125  {
2126  repeatdistinmapunit = ( _decodeUnits( units ) == QgsPalLayerSettings::MapUnits );
2127  }
2128  }
2129 
2130  if ( !qgsDoubleNear( repeatDist, 0.0 ) )
2131  {
2132  if ( !repeatdistinmapunit )
2133  {
2134  repeatDist *= mapUntsPerMM; //convert repeat distance from mm to map units
2135  }
2136  }
2137 
2138  // feature to the layer
2139  try
2140  {
2141  if ( !palLayer->registerFeature( lbl->strId(), lbl, labelX, labelY, labelText,
2142  xPos, yPos, dataDefinedPosition, angle, dataDefinedRotation,
2143  quadOffsetX, quadOffsetY, offsetX, offsetY, alwaysShow, repeatDist ) )
2144  return;
2145  }
2146  catch ( std::exception &e )
2147  {
2148  Q_UNUSED( e );
2149  QgsDebugMsgLevel( QString( "Ignoring feature %1 due PAL exception:" ).arg( f.id() ) + QString::fromLatin1( e.what() ), 4 );
2150  return;
2151  }
2152 
2153  // TODO: only for placement which needs character info
2154  pal::Feature* feat = palLayer->getFeature( lbl->strId() );
2155  // account for any data defined font metrics adjustments
2156  feat->setLabelInfo( lbl->info( labelFontMetrics, xform, rasterCompressFactor, maxcharanglein, maxcharangleout ) );
2157  delete labelFontMetrics;
2158 
2159  // TODO: allow layer-wide feature dist in PAL...?
2160 
2161  // data defined label-feature distance?
2162  double distance = dist;
2164  {
2165  bool ok;
2166  double distD = exprVal.toDouble( &ok );
2167  if ( ok )
2168  {
2169  distance = distD;
2170  }
2171  }
2172 
2173  // data defined label-feature distance units?
2174  bool distinmapunit = distInMapUnits;
2176  {
2177  QString units = exprVal.toString().trimmed();
2178  QgsDebugMsgLevel( QString( "exprVal DistanceUnits:%1" ).arg( units ), 4 );
2179  if ( !units.isEmpty() )
2180  {
2181  distinmapunit = ( _decodeUnits( units ) == QgsPalLayerSettings::MapUnits );
2182  }
2183  }
2184 
2185  if ( distance != 0 )
2186  {
2187  if ( distinmapunit ) //convert distance from mm/map units to pixels
2188  {
2189  distance /= distMapUnitScale.computeMapUnitsPerPixel( context );
2190  }
2191  else //mm
2192  {
2193  distance *= vectorScaleFactor;
2194  }
2195  feat->setDistLabel( qAbs( ptOne.x() - ptZero.x() )* distance );
2196  }
2197 
2198  if ( ddFixedQuad )
2199  {
2200  feat->setFixedQuadrant( true );
2201  }
2202 
2203  // data defined priority?
2205  {
2206  bool ok;
2207  double priorityD = exprVal.toDouble( &ok );
2208  if ( ok )
2209  {
2210  priorityD = qBound( 0.0, priorityD, 10.0 );
2211  priorityD = 1 - priorityD / 10.0; // convert 0..10 --> 1..0
2212  feat->setPriority( priorityD );
2213  }
2214  }
2215 
2216  // data defined is obstacle?
2218  {
2219  feat->setIsObstacle( exprVal.toBool() );
2220  }
2221 
2222  double featObstacleFactor = obstacleFactor;
2224  {
2225  bool ok;
2226  double factorD = exprVal.toDouble( &ok );
2227  if ( ok )
2228  {
2229  factorD = qBound( 0.0, factorD, 10.0 );
2230  factorD = factorD / 5.0 + 0.0001; // convert 0 -> 10 to 0.0001 -> 2.0
2231  featObstacleFactor = factorD;
2232  }
2233  }
2234  feat->setObstacleFactor( featObstacleFactor );
2235 
2236  //add parameters for data defined labeling to QgsPalGeometry
2238  for ( ; dIt != dataDefinedValues.constEnd(); ++dIt )
2239  {
2240  lbl->addDataDefinedValue( dIt.key(), dIt.value() );
2241  }
2242 
2243  // set geometry's pinned property
2244  lbl->setIsPinned( labelIsPinned );
2245 }
2246 
2247 void QgsPalLayerSettings::registerObstacleFeature( QgsFeature& f, const QgsRenderContext& context, QString dxfLayer )
2248 {
2249  mCurFeat = &f;
2250 
2251  const QgsGeometry* geom = f.constGeometry();
2252  if ( !geom )
2253  {
2254  return;
2255  }
2256 
2257  const GEOSGeometry* geos_geom = 0;
2258  QScopedPointer<QgsGeometry> scopedPreparedGeom;
2259 
2261  {
2262  scopedPreparedGeom.reset( QgsPalLabeling::prepareGeometry( geom, context, ct, extentGeom ) );
2263  if ( !scopedPreparedGeom.data() )
2264  return;
2265  geos_geom = scopedPreparedGeom.data()->asGeos();
2266  }
2267  else
2268  {
2269  geos_geom = geom->asGeos();
2270  }
2271 
2272  if ( geos_geom == NULL )
2273  return; // invalid geometry
2274 
2275  GEOSGeometry* geos_geom_clone;
2276  geos_geom_clone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom );
2277 
2278  QgsPalGeometry* lbl = new QgsPalGeometry( f.id(), QString(), geos_geom_clone );
2279 
2280  lbl->setDxfLayer( dxfLayer );
2281 
2282  // record the created geometry - it will be deleted at the end.
2283  geometries.append( lbl );
2284 
2285  // feature to the layer
2286  try
2287  {
2288  if ( !palLayer->registerFeature( lbl->strId(), lbl, 0, 0 ) )
2289  return;
2290  }
2291  catch ( std::exception &e )
2292  {
2293  Q_UNUSED( e );
2294  QgsDebugMsgLevel( QString( "Ignoring feature %1 due PAL exception:" ).arg( f.id() ) + QString::fromLatin1( e.what() ), 4 );
2295  return;
2296  }
2297 }
2298 
2299 bool QgsPalLayerSettings::dataDefinedValEval( const QString& valType,
2301  QVariant& exprVal )
2302 {
2303  if ( dataDefinedEvaluate( p, exprVal ) )
2304  {
2305  QString dbgStr = QString( "exprVal %1:" ).arg( mDataDefinedNames.value( p ).first ) + "%1";
2306 
2307  if ( valType == QString( "bool" ) )
2308  {
2309  bool bol = exprVal.toBool();
2310  QgsDebugMsgLevel( dbgStr.arg( bol ? "true" : "false" ), 4 );
2311  dataDefinedValues.insert( p, QVariant( bol ) );
2312  return true;
2313  }
2314  if ( valType == QString( "int" ) )
2315  {
2316  bool ok;
2317  int size = exprVal.toInt( &ok );
2318  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2319 
2320  if ( ok )
2321  {
2322  dataDefinedValues.insert( p, QVariant( size ) );
2323  return true;
2324  }
2325  }
2326  if ( valType == QString( "intpos" ) )
2327  {
2328  bool ok;
2329  int size = exprVal.toInt( &ok );
2330  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2331 
2332  if ( ok && size > 0 )
2333  {
2334  dataDefinedValues.insert( p, QVariant( size ) );
2335  return true;
2336  }
2337  }
2338  if ( valType == QString( "double" ) )
2339  {
2340  bool ok;
2341  double size = exprVal.toDouble( &ok );
2342  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2343 
2344  if ( ok )
2345  {
2346  dataDefinedValues.insert( p, QVariant( size ) );
2347  return true;
2348  }
2349  }
2350  if ( valType == QString( "doublepos" ) )
2351  {
2352  bool ok;
2353  double size = exprVal.toDouble( &ok );
2354  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2355 
2356  if ( ok && size > 0.0 )
2357  {
2358  dataDefinedValues.insert( p, QVariant( size ) );
2359  return true;
2360  }
2361  }
2362  if ( valType == QString( "rotation180" ) )
2363  {
2364  bool ok;
2365  double rot = exprVal.toDouble( &ok );
2366  QgsDebugMsgLevel( dbgStr.arg( rot ), 4 );
2367  if ( ok )
2368  {
2369  if ( rot < -180.0 && rot >= -360 )
2370  {
2371  rot += 360;
2372  }
2373  if ( rot > 180.0 && rot <= 360 )
2374  {
2375  rot -= 360;
2376  }
2377  if ( rot >= -180 && rot <= 180 )
2378  {
2379  dataDefinedValues.insert( p, QVariant( rot ) );
2380  return true;
2381  }
2382  }
2383  }
2384  if ( valType == QString( "transp" ) )
2385  {
2386  bool ok;
2387  int size = exprVal.toInt( &ok );
2388  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2389  if ( ok && size >= 0 && size <= 100 )
2390  {
2391  dataDefinedValues.insert( p, QVariant( size ) );
2392  return true;
2393  }
2394  }
2395  if ( valType == QString( "string" ) )
2396  {
2397  QString str = exprVal.toString(); // don't trim whitespace
2398  QgsDebugMsgLevel( dbgStr.arg( str ), 4 );
2399 
2400  dataDefinedValues.insert( p, QVariant( str ) ); // let it stay empty if it is
2401  return true;
2402  }
2403  if ( valType == QString( "units" ) )
2404  {
2405  QString unitstr = exprVal.toString().trimmed();
2406  QgsDebugMsgLevel( dbgStr.arg( unitstr ), 4 );
2407 
2408  if ( !unitstr.isEmpty() )
2409  {
2410  dataDefinedValues.insert( p, QVariant(( int )_decodeUnits( unitstr ) ) );
2411  return true;
2412  }
2413  }
2414  if ( valType == QString( "color" ) )
2415  {
2416  QString colorstr = exprVal.toString().trimmed();
2417  QgsDebugMsgLevel( dbgStr.arg( colorstr ), 4 );
2418  QColor color = QgsSymbolLayerV2Utils::decodeColor( colorstr );
2419 
2420  if ( color.isValid() )
2421  {
2422  dataDefinedValues.insert( p, QVariant( color ) );
2423  return true;
2424  }
2425  }
2426  if ( valType == QString( "joinstyle" ) )
2427  {
2428  QString joinstr = exprVal.toString().trimmed();
2429  QgsDebugMsgLevel( dbgStr.arg( joinstr ), 4 );
2430 
2431  if ( !joinstr.isEmpty() )
2432  {
2433  dataDefinedValues.insert( p, QVariant(( int )_decodePenJoinStyle( joinstr ) ) );
2434  return true;
2435  }
2436  }
2437  if ( valType == QString( "blendmode" ) )
2438  {
2439  QString blendstr = exprVal.toString().trimmed();
2440  QgsDebugMsgLevel( dbgStr.arg( blendstr ), 4 );
2441 
2442  if ( !blendstr.isEmpty() )
2443  {
2444  dataDefinedValues.insert( p, QVariant(( int )QgsSymbolLayerV2Utils::decodeBlendMode( blendstr ) ) );
2445  return true;
2446  }
2447  }
2448  if ( valType == QString( "pointf" ) )
2449  {
2450  QString ptstr = exprVal.toString().trimmed();
2451  QgsDebugMsgLevel( dbgStr.arg( ptstr ), 4 );
2452 
2453  if ( !ptstr.isEmpty() )
2454  {
2455  dataDefinedValues.insert( p, QVariant( QgsSymbolLayerV2Utils::decodePoint( ptstr ) ) );
2456  return true;
2457  }
2458  }
2459  }
2460  return false;
2461 }
2462 
2463 void QgsPalLayerSettings::parseTextStyle( QFont& labelFont,
2465  const QgsRenderContext& context )
2466 {
2467  // NOTE: labelFont already has pixelSize set, so pointSize or pointSizeF might return -1
2468 
2469  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2470 
2471  // Two ways to generate new data defined font:
2472  // 1) Family + [bold] + [italic] (named style is ignored and font is built off of base family)
2473  // 2) Family + named style (bold or italic is ignored)
2474 
2475  // data defined font family?
2476  QString ddFontFamily( "" );
2478  {
2479  QString family = exprVal.toString().trimmed();
2480  QgsDebugMsgLevel( QString( "exprVal Font family:%1" ).arg( family ), 4 );
2481 
2482  if ( labelFont.family() != family )
2483  {
2484  // testing for ddFontFamily in QFontDatabase.families() may be slow to do for every feature
2485  // (i.e. don't use QgsFontUtils::fontFamilyMatchOnSystem( family ) here)
2486  if ( QgsFontUtils::fontFamilyOnSystem( family ) )
2487  {
2488  ddFontFamily = family;
2489  }
2490  }
2491  }
2492 
2493  // data defined named font style?
2494  QString ddFontStyle( "" );
2496  {
2497  QString fontstyle = exprVal.toString().trimmed();
2498  QgsDebugMsgLevel( QString( "exprVal Font style:%1" ).arg( fontstyle ), 4 );
2499  ddFontStyle = fontstyle;
2500  }
2501 
2502  // data defined bold font style?
2503  bool ddBold = false;
2505  {
2506  bool bold = exprVal.toBool();
2507  QgsDebugMsgLevel( QString( "exprVal Font bold:%1" ).arg( bold ? "true" : "false" ), 4 );
2508  ddBold = bold;
2509  }
2510 
2511  // data defined italic font style?
2512  bool ddItalic = false;
2514  {
2515  bool italic = exprVal.toBool();
2516  QgsDebugMsgLevel( QString( "exprVal Font italic:%1" ).arg( italic ? "true" : "false" ), 4 );
2517  ddItalic = italic;
2518  }
2519 
2520  // TODO: update when pref for how to resolve missing family (use matching algorithm or just default font) is implemented
2521  // (currently defaults to what has been read in from layer settings)
2522  QFont newFont;
2523  QFont appFont = QApplication::font();
2524  bool newFontBuilt = false;
2525  if ( ddBold || ddItalic )
2526  {
2527  // new font needs built, since existing style needs removed
2528  newFont = QFont( !ddFontFamily.isEmpty() ? ddFontFamily : labelFont.family() );
2529  newFontBuilt = true;
2530  newFont.setBold( ddBold );
2531  newFont.setItalic( ddItalic );
2532  }
2533  else if ( !ddFontStyle.isEmpty()
2534  && ddFontStyle.compare( "Ignore", Qt::CaseInsensitive ) != 0 )
2535  {
2536  if ( !ddFontFamily.isEmpty() )
2537  {
2538  // both family and style are different, build font from database
2539  QFont styledfont = mFontDB.font( ddFontFamily, ddFontStyle, appFont.pointSize() );
2540  if ( appFont != styledfont )
2541  {
2542  newFont = styledfont;
2543  newFontBuilt = true;
2544  }
2545  }
2546 
2547  // update the font face style
2548  QgsFontUtils::updateFontViaStyle( newFontBuilt ? newFont : labelFont, ddFontStyle );
2549  }
2550  else if ( !ddFontFamily.isEmpty() )
2551  {
2552  if ( ddFontStyle.compare( "Ignore", Qt::CaseInsensitive ) != 0 )
2553  {
2554  // just family is different, build font from database
2555  QFont styledfont = mFontDB.font( ddFontFamily, textNamedStyle, appFont.pointSize() );
2556  if ( appFont != styledfont )
2557  {
2558  newFont = styledfont;
2559  newFontBuilt = true;
2560  }
2561  }
2562  else
2563  {
2564  newFont = QFont( ddFontFamily );
2565  newFontBuilt = true;
2566  }
2567  }
2568 
2569  if ( newFontBuilt )
2570  {
2571  // copy over existing font settings
2572  //newFont = newFont.resolve( labelFont ); // should work, but let's be sure what's being copied
2573  newFont.setPixelSize( labelFont.pixelSize() );
2574  newFont.setCapitalization( labelFont.capitalization() );
2575  newFont.setUnderline( labelFont.underline() );
2576  newFont.setStrikeOut( labelFont.strikeOut() );
2577  newFont.setWordSpacing( labelFont.wordSpacing() );
2578  newFont.setLetterSpacing( QFont::AbsoluteSpacing, labelFont.letterSpacing() );
2579 
2580  labelFont = newFont;
2581  }
2582 
2583  // data defined word spacing?
2584  double wordspace = labelFont.wordSpacing();
2586  {
2587  bool ok;
2588  double wspacing = exprVal.toDouble( &ok );
2589  QgsDebugMsgLevel( QString( "exprVal FontWordSpacing:%1" ).arg( wspacing ), 4 );
2590  if ( ok )
2591  {
2592  wordspace = wspacing;
2593  }
2594  }
2595  labelFont.setWordSpacing( sizeToPixel( wordspace, context, fontunits, false, fontSizeMapUnitScale ) );
2596 
2597  // data defined letter spacing?
2598  double letterspace = labelFont.letterSpacing();
2600  {
2601  bool ok;
2602  double lspacing = exprVal.toDouble( &ok );
2603  QgsDebugMsgLevel( QString( "exprVal FontLetterSpacing:%1" ).arg( lspacing ), 4 );
2604  if ( ok )
2605  {
2606  letterspace = lspacing;
2607  }
2608  }
2609  labelFont.setLetterSpacing( QFont::AbsoluteSpacing, sizeToPixel( letterspace, context, fontunits, false, fontSizeMapUnitScale ) );
2610 
2611  // data defined font capitalization?
2612  QFont::Capitalization fontcaps = labelFont.capitalization();
2614  {
2615  QString fcase = exprVal.toString().trimmed();
2616  QgsDebugMsgLevel( QString( "exprVal FontCase:%1" ).arg( fcase ), 4 );
2617 
2618  if ( !fcase.isEmpty() )
2619  {
2620  if ( fcase.compare( "NoChange", Qt::CaseInsensitive ) == 0 )
2621  {
2622  fontcaps = QFont::MixedCase;
2623  }
2624  else if ( fcase.compare( "Upper", Qt::CaseInsensitive ) == 0 )
2625  {
2626  fontcaps = QFont::AllUppercase;
2627  }
2628  else if ( fcase.compare( "Lower", Qt::CaseInsensitive ) == 0 )
2629  {
2630  fontcaps = QFont::AllLowercase;
2631  }
2632  else if ( fcase.compare( "Capitalize", Qt::CaseInsensitive ) == 0 )
2633  {
2634  fontcaps = QFont::Capitalize;
2635  }
2636 
2637  if ( fontcaps != labelFont.capitalization() )
2638  {
2639  labelFont.setCapitalization( fontcaps );
2640  }
2641  }
2642  }
2643 
2644  // data defined strikeout font style?
2646  {
2647  bool strikeout = exprVal.toBool();
2648  QgsDebugMsgLevel( QString( "exprVal Font strikeout:%1" ).arg( strikeout ? "true" : "false" ), 4 );
2649  labelFont.setStrikeOut( strikeout );
2650  }
2651 
2652  // data defined underline font style?
2654  {
2655  bool underline = exprVal.toBool();
2656  QgsDebugMsgLevel( QString( "exprVal Font underline:%1" ).arg( underline ? "true" : "false" ), 4 );
2657  labelFont.setUnderline( underline );
2658  }
2659 
2660  // pass the rest on to QgsPalLabeling::drawLabeling
2661 
2662  // data defined font color?
2663  dataDefinedValEval( "color", QgsPalLayerSettings::Color, exprVal );
2664 
2665  // data defined font transparency?
2666  dataDefinedValEval( "transp", QgsPalLayerSettings::FontTransp, exprVal );
2667 
2668  // data defined font blend mode?
2669  dataDefinedValEval( "blendmode", QgsPalLayerSettings::FontBlendMode, exprVal );
2670 
2671 }
2672 
2673 void QgsPalLayerSettings::parseTextBuffer()
2674 {
2675  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2676 
2677  // data defined draw buffer?
2678  bool drawBuffer = bufferDraw;
2679  if ( dataDefinedValEval( "bool", QgsPalLayerSettings::BufferDraw, exprVal ) )
2680  {
2681  drawBuffer = exprVal.toBool();
2682  }
2683 
2684  if ( !drawBuffer )
2685  {
2686  return;
2687  }
2688 
2689  // data defined buffer size?
2690  double bufrSize = bufferSize;
2691  if ( dataDefinedValEval( "doublepos", QgsPalLayerSettings::BufferSize, exprVal ) )
2692  {
2693  bufrSize = exprVal.toDouble();
2694  }
2695 
2696  // data defined buffer transparency?
2697  int bufTransp = bufferTransp;
2698  if ( dataDefinedValEval( "transp", QgsPalLayerSettings::BufferTransp, exprVal ) )
2699  {
2700  bufTransp = exprVal.toInt();
2701  }
2702 
2703  drawBuffer = ( drawBuffer && bufrSize > 0.0 && bufTransp < 100 );
2704 
2705  if ( !drawBuffer )
2706  {
2707  dataDefinedValues.insert( QgsPalLayerSettings::BufferDraw, QVariant( false ) ); // trigger value
2708  dataDefinedValues.remove( QgsPalLayerSettings::BufferSize );
2709  dataDefinedValues.remove( QgsPalLayerSettings::BufferTransp );
2710  return; // don't bother evaluating values that won't be used
2711  }
2712 
2713  // data defined buffer units?
2714  dataDefinedValEval( "units", QgsPalLayerSettings::BufferUnit, exprVal );
2715 
2716  // data defined buffer color?
2717  dataDefinedValEval( "color", QgsPalLayerSettings::BufferColor, exprVal );
2718 
2719  // data defined buffer pen join style?
2720  dataDefinedValEval( "joinstyle", QgsPalLayerSettings::BufferJoinStyle, exprVal );
2721 
2722  // data defined buffer blend mode?
2723  dataDefinedValEval( "blendmode", QgsPalLayerSettings::BufferBlendMode, exprVal );
2724 }
2725 
2726 void QgsPalLayerSettings::parseTextFormatting()
2727 {
2728  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2729 
2730  // data defined multiline wrap character?
2731  QString wrapchr = wrapChar;
2732  if ( dataDefinedValEval( "string", QgsPalLayerSettings::MultiLineWrapChar, exprVal ) )
2733  {
2734  wrapchr = exprVal.toString();
2735  }
2736 
2737  // data defined multiline height?
2738  dataDefinedValEval( "double", QgsPalLayerSettings::MultiLineHeight, exprVal );
2739 
2740  // data defined multiline text align?
2742  {
2743  QString str = exprVal.toString().trimmed();
2744  QgsDebugMsgLevel( QString( "exprVal MultiLineAlignment:%1" ).arg( str ), 4 );
2745 
2746  if ( !str.isEmpty() )
2747  {
2748  // "Left"
2750 
2751  if ( str.compare( "Center", Qt::CaseInsensitive ) == 0 )
2752  {
2754  }
2755  else if ( str.compare( "Right", Qt::CaseInsensitive ) == 0 )
2756  {
2757  aligntype = QgsPalLayerSettings::MultiRight;
2758  }
2759  else if ( str.compare( "Follow", Qt::CaseInsensitive ) == 0 )
2760  {
2762  }
2763  dataDefinedValues.insert( QgsPalLayerSettings::MultiLineAlignment, QVariant(( int )aligntype ) );
2764  }
2765  }
2766 
2767  // data defined direction symbol?
2768  bool drawDirSymb = addDirectionSymbol;
2769  if ( dataDefinedValEval( "bool", QgsPalLayerSettings::DirSymbDraw, exprVal ) )
2770  {
2771  drawDirSymb = exprVal.toBool();
2772  }
2773 
2774  if ( drawDirSymb )
2775  {
2776  // data defined direction left symbol?
2777  dataDefinedValEval( "string", QgsPalLayerSettings::DirSymbLeft, exprVal );
2778 
2779  // data defined direction right symbol?
2780  dataDefinedValEval( "string", QgsPalLayerSettings::DirSymbRight, exprVal );
2781 
2782  // data defined direction symbol placement?
2784  {
2785  QString str = exprVal.toString().trimmed();
2786  QgsDebugMsgLevel( QString( "exprVal DirSymbPlacement:%1" ).arg( str ), 4 );
2787 
2788  if ( !str.isEmpty() )
2789  {
2790  // "LeftRight"
2792 
2793  if ( str.compare( "Above", Qt::CaseInsensitive ) == 0 )
2794  {
2796  }
2797  else if ( str.compare( "Below", Qt::CaseInsensitive ) == 0 )
2798  {
2800  }
2801  dataDefinedValues.insert( QgsPalLayerSettings::DirSymbPlacement, QVariant(( int )placetype ) );
2802  }
2803  }
2804 
2805  // data defined direction symbol reversed?
2806  dataDefinedValEval( "bool", QgsPalLayerSettings::DirSymbReverse, exprVal );
2807  }
2808 
2809  // formatting for numbers is inline with generation of base label text and not passed to label painting
2810 }
2811 
2812 void QgsPalLayerSettings::parseShapeBackground()
2813 {
2814  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2815 
2816  // data defined draw shape?
2817  bool drawShape = shapeDraw;
2818  if ( dataDefinedValEval( "bool", QgsPalLayerSettings::ShapeDraw, exprVal ) )
2819  {
2820  drawShape = exprVal.toBool();
2821  }
2822 
2823  if ( !drawShape )
2824  {
2825  return;
2826  }
2827 
2828  // data defined shape transparency?
2829  int shapeTransp = shapeTransparency;
2830  if ( dataDefinedValEval( "transp", QgsPalLayerSettings::ShapeTransparency, exprVal ) )
2831  {
2832  shapeTransp = exprVal.toInt();
2833  }
2834 
2835  drawShape = ( drawShape && shapeTransp < 100 ); // size is not taken into account (could be)
2836 
2837  if ( !drawShape )
2838  {
2839  dataDefinedValues.insert( QgsPalLayerSettings::ShapeDraw, QVariant( false ) ); // trigger value
2840  dataDefinedValues.remove( QgsPalLayerSettings::ShapeTransparency );
2841  return; // don't bother evaluating values that won't be used
2842  }
2843 
2844  // data defined shape kind?
2847  {
2848  QString skind = exprVal.toString().trimmed();
2849  QgsDebugMsgLevel( QString( "exprVal ShapeKind:%1" ).arg( skind ), 4 );
2850 
2851  if ( !skind.isEmpty() )
2852  {
2853  // "Rectangle"
2855 
2856  if ( skind.compare( "Square", Qt::CaseInsensitive ) == 0 )
2857  {
2859  }
2860  else if ( skind.compare( "Ellipse", Qt::CaseInsensitive ) == 0 )
2861  {
2863  }
2864  else if ( skind.compare( "Circle", Qt::CaseInsensitive ) == 0 )
2865  {
2867  }
2868  else if ( skind.compare( "SVG", Qt::CaseInsensitive ) == 0 )
2869  {
2871  }
2872  shapeKind = shpkind;
2873  dataDefinedValues.insert( QgsPalLayerSettings::ShapeKind, QVariant(( int )shpkind ) );
2874  }
2875  }
2876 
2877  // data defined shape SVG path?
2878  QString svgPath = shapeSVGFile;
2880  {
2881  QString svgfile = exprVal.toString().trimmed();
2882  QgsDebugMsgLevel( QString( "exprVal ShapeSVGFile:%1" ).arg( svgfile ), 4 );
2883 
2884  // '' empty paths are allowed
2885  svgPath = svgfile;
2886  dataDefinedValues.insert( QgsPalLayerSettings::ShapeSVGFile, QVariant( svgfile ) );
2887  }
2888 
2889  // data defined shape size type?
2892  {
2893  QString stype = exprVal.toString().trimmed();
2894  QgsDebugMsgLevel( QString( "exprVal ShapeSizeType:%1" ).arg( stype ), 4 );
2895 
2896  if ( !stype.isEmpty() )
2897  {
2898  // "Buffer"
2900 
2901  if ( stype.compare( "Fixed", Qt::CaseInsensitive ) == 0 )
2902  {
2904  }
2905  shpSizeType = sizType;
2906  dataDefinedValues.insert( QgsPalLayerSettings::ShapeSizeType, QVariant(( int )sizType ) );
2907  }
2908  }
2909 
2910  // data defined shape size X? (SVGs only use X for sizing)
2911  double ddShpSizeX = shapeSize.x();
2912  if ( dataDefinedValEval( "double", QgsPalLayerSettings::ShapeSizeX, exprVal ) )
2913  {
2914  ddShpSizeX = exprVal.toDouble();
2915  }
2916 
2917  // data defined shape size Y?
2918  double ddShpSizeY = shapeSize.y();
2919  if ( dataDefinedValEval( "double", QgsPalLayerSettings::ShapeSizeY, exprVal ) )
2920  {
2921  ddShpSizeY = exprVal.toDouble();
2922  }
2923 
2924  // don't continue under certain circumstances (e.g. size is fixed)
2925  bool skip = false;
2926  if ( shapeKind == QgsPalLayerSettings::ShapeSVG
2927  && ( svgPath.isEmpty()
2928  || ( !svgPath.isEmpty()
2929  && shpSizeType == QgsPalLayerSettings::SizeFixed
2930  && ddShpSizeX == 0.0 ) ) )
2931  {
2932  skip = true;
2933  }
2934  if ( shapeKind != QgsPalLayerSettings::ShapeSVG
2935  && shpSizeType == QgsPalLayerSettings::SizeFixed
2936  && ( ddShpSizeX == 0.0 || ddShpSizeY == 0.0 ) )
2937  {
2938  skip = true;
2939  }
2940 
2941  if ( skip )
2942  {
2943  dataDefinedValues.insert( QgsPalLayerSettings::ShapeDraw, QVariant( false ) ); // trigger value
2944  dataDefinedValues.remove( QgsPalLayerSettings::ShapeTransparency );
2945  dataDefinedValues.remove( QgsPalLayerSettings::ShapeKind );
2946  dataDefinedValues.remove( QgsPalLayerSettings::ShapeSVGFile );
2947  dataDefinedValues.remove( QgsPalLayerSettings::ShapeSizeX );
2948  dataDefinedValues.remove( QgsPalLayerSettings::ShapeSizeY );
2949  return; // don't bother evaluating values that won't be used
2950  }
2951 
2952  // data defined shape size units?
2953  dataDefinedValEval( "units", QgsPalLayerSettings::ShapeSizeUnits, exprVal );
2954 
2955  // data defined shape rotation type?
2957  {
2958  QString rotstr = exprVal.toString().trimmed();
2959  QgsDebugMsgLevel( QString( "exprVal ShapeRotationType:%1" ).arg( rotstr ), 4 );
2960 
2961  if ( !rotstr.isEmpty() )
2962  {
2963  // "Sync"
2965 
2966  if ( rotstr.compare( "Offset", Qt::CaseInsensitive ) == 0 )
2967  {
2969  }
2970  else if ( rotstr.compare( "Fixed", Qt::CaseInsensitive ) == 0 )
2971  {
2973  }
2974  dataDefinedValues.insert( QgsPalLayerSettings::ShapeRotationType, QVariant(( int )rottype ) );
2975  }
2976  }
2977 
2978  // data defined shape rotation?
2979  dataDefinedValEval( "rotation180", QgsPalLayerSettings::ShapeRotation, exprVal );
2980 
2981  // data defined shape offset?
2982  dataDefinedValEval( "pointf", QgsPalLayerSettings::ShapeOffset, exprVal );
2983 
2984  // data defined shape offset units?
2985  dataDefinedValEval( "units", QgsPalLayerSettings::ShapeOffsetUnits, exprVal );
2986 
2987  // data defined shape radii?
2988  dataDefinedValEval( "pointf", QgsPalLayerSettings::ShapeRadii, exprVal );
2989 
2990  // data defined shape radii units?
2991  dataDefinedValEval( "units", QgsPalLayerSettings::ShapeRadiiUnits, exprVal );
2992 
2993  // data defined shape blend mode?
2994  dataDefinedValEval( "blendmode", QgsPalLayerSettings::ShapeBlendMode, exprVal );
2995 
2996  // data defined shape fill color?
2997  dataDefinedValEval( "color", QgsPalLayerSettings::ShapeFillColor, exprVal );
2998 
2999  // data defined shape border color?
3000  dataDefinedValEval( "color", QgsPalLayerSettings::ShapeBorderColor, exprVal );
3001 
3002  // data defined shape border width?
3003  dataDefinedValEval( "doublepos", QgsPalLayerSettings::ShapeBorderWidth, exprVal );
3004 
3005  // data defined shape border width units?
3006  dataDefinedValEval( "units", QgsPalLayerSettings::ShapeBorderWidthUnits, exprVal );
3007 
3008  // data defined shape join style?
3009  dataDefinedValEval( "joinstyle", QgsPalLayerSettings::ShapeJoinStyle, exprVal );
3010 
3011 }
3012 
3013 void QgsPalLayerSettings::parseDropShadow()
3014 {
3015  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
3016 
3017  // data defined draw shadow?
3018  bool drawShadow = shadowDraw;
3019  if ( dataDefinedValEval( "bool", QgsPalLayerSettings::ShadowDraw, exprVal ) )
3020  {
3021  drawShadow = exprVal.toBool();
3022  }
3023 
3024  if ( !drawShadow )
3025  {
3026  return;
3027  }
3028 
3029  // data defined shadow transparency?
3030  int shadowTransp = shadowTransparency;
3031  if ( dataDefinedValEval( "transp", QgsPalLayerSettings::ShadowTransparency, exprVal ) )
3032  {
3033  shadowTransp = exprVal.toInt();
3034  }
3035 
3036  // data defined shadow offset distance?
3037  double shadowOffDist = shadowOffsetDist;
3038  if ( dataDefinedValEval( "doublepos", QgsPalLayerSettings::ShadowOffsetDist, exprVal ) )
3039  {
3040  shadowOffDist = exprVal.toDouble();
3041  }
3042 
3043  // data defined shadow offset distance?
3044  double shadowRad = shadowRadius;
3045  if ( dataDefinedValEval( "doublepos", QgsPalLayerSettings::ShadowRadius, exprVal ) )
3046  {
3047  shadowRad = exprVal.toDouble();
3048  }
3049 
3050  drawShadow = ( drawShadow && shadowTransp < 100 && !( shadowOffDist == 0.0 && shadowRad == 0.0 ) );
3051 
3052  if ( !drawShadow )
3053  {
3054  dataDefinedValues.insert( QgsPalLayerSettings::ShadowDraw, QVariant( false ) ); // trigger value
3055  dataDefinedValues.remove( QgsPalLayerSettings::ShadowTransparency );
3056  dataDefinedValues.remove( QgsPalLayerSettings::ShadowOffsetDist );
3057  dataDefinedValues.remove( QgsPalLayerSettings::ShadowRadius );
3058  return; // don't bother evaluating values that won't be used
3059  }
3060 
3061  // data defined shadow under type?
3063  {
3064  QString str = exprVal.toString().trimmed();
3065  QgsDebugMsgLevel( QString( "exprVal ShadowUnder:%1" ).arg( str ), 4 );
3066 
3067  if ( !str.isEmpty() )
3068  {
3069  // "Lowest"
3071 
3072  if ( str.compare( "Text", Qt::CaseInsensitive ) == 0 )
3073  {
3075  }
3076  else if ( str.compare( "Buffer", Qt::CaseInsensitive ) == 0 )
3077  {
3079  }
3080  else if ( str.compare( "Background", Qt::CaseInsensitive ) == 0 )
3081  {
3083  }
3084  dataDefinedValues.insert( QgsPalLayerSettings::ShadowUnder, QVariant(( int )shdwtype ) );
3085  }
3086  }
3087 
3088  // data defined shadow offset angle?
3089  dataDefinedValEval( "rotation180", QgsPalLayerSettings::ShadowOffsetAngle, exprVal );
3090 
3091  // data defined shadow offset units?
3092  dataDefinedValEval( "units", QgsPalLayerSettings::ShadowOffsetUnits, exprVal );
3093 
3094  // data defined shadow radius?
3095  dataDefinedValEval( "double", QgsPalLayerSettings::ShadowRadius, exprVal );
3096 
3097  // data defined shadow radius units?
3098  dataDefinedValEval( "units", QgsPalLayerSettings::ShadowRadiusUnits, exprVal );
3099 
3100  // data defined shadow scale? ( gui bounds to 0-2000, no upper bound here )
3101  dataDefinedValEval( "intpos", QgsPalLayerSettings::ShadowScale, exprVal );
3102 
3103  // data defined shadow color?
3104  dataDefinedValEval( "color", QgsPalLayerSettings::ShadowColor, exprVal );
3105 
3106  // data defined shadow blend mode?
3107  dataDefinedValEval( "blendmode", QgsPalLayerSettings::ShadowBlendMode, exprVal );
3108 }
3109 
3110 int QgsPalLayerSettings::sizeToPixel( double size, const QgsRenderContext& c, SizeUnit unit, bool rasterfactor, const QgsMapUnitScale& mapUnitScale ) const
3111 {
3112  return ( int )( scaleToPixelContext( size, c, unit, rasterfactor, mapUnitScale ) + 0.5 );
3113 }
3114 
3115 double QgsPalLayerSettings::scaleToPixelContext( double size, const QgsRenderContext& c, SizeUnit unit, bool rasterfactor, const QgsMapUnitScale& mapUnitScale ) const
3116 {
3117  // if render context is that of device (i.e. not a scaled map), just return size
3118  double mapUnitsPerPixel = mapUnitScale.computeMapUnitsPerPixel( c );
3119 
3120  if ( unit == MapUnits && mapUnitsPerPixel > 0.0 )
3121  {
3122  size = size / mapUnitsPerPixel * ( rasterfactor ? c.rasterScaleFactor() : 1 );
3123  }
3124  else // e.g. in points or mm
3125  {
3126  double ptsTomm = ( unit == Points ? 0.352778 : 1 );
3127  size *= ptsTomm * c.scaleFactor() * ( rasterfactor ? c.rasterScaleFactor() : 1 );
3128  }
3129  return size;
3130 }
3131 
3132 // -------------
3133 
3135  : mMapSettings( NULL ), mPal( NULL )
3136  , mResults( 0 )
3137 {
3138 
3139  // find out engine defaults
3140  Pal p;
3141  mCandPoint = p.getPointP();
3142  mCandLine = p.getLineP();
3143  mCandPolygon = p.getPolyP();
3144 
3145  switch ( p.getSearch() )
3146  {
3147  case CHAIN: mSearch = Chain; break;
3148  case POPMUSIC_TABU: mSearch = Popmusic_Tabu; break;
3149  case POPMUSIC_CHAIN: mSearch = Popmusic_Chain; break;
3151  case FALP: mSearch = Falp; break;
3152  }
3153 
3154  mShowingCandidates = false;
3155  mShowingShadowRects = false;
3156  mShowingAllLabels = false;
3158  mDrawOutlineLabels = true;
3159 }
3160 
3162 {
3163  // make sure we've freed everything
3164  exit();
3165 
3167 
3168  delete mResults;
3169  mResults = 0;
3170 }
3171 
3173 {
3174  return staticWillUseLayer( layer );
3175 }
3176 
3178 {
3179  QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( layerID ) );
3180  if ( !layer )
3181  return false;
3182  return staticWillUseLayer( layer );
3183 }
3184 
3185 
3187 {
3188  // don't do QgsPalLayerSettings::readFromLayer( layer ) if not needed
3189  bool enabled = false;
3190  if ( layer->customProperty( "labeling" ).toString() == QString( "pal" ) )
3191  enabled = layer->labelsEnabled() || layer->diagramsEnabled();
3192 
3193  return enabled;
3194 }
3195 
3196 
3198 {
3200  for ( lit = mActiveLayers.begin(); lit != mActiveLayers.end(); ++lit )
3201  {
3202  clearActiveLayer( lit.key() );
3203  }
3204  mActiveLayers.clear();
3205 }
3206 
3208 {
3209  QgsPalLayerSettings& lyr = mActiveLayers[layerID];
3210 
3211  // delete all QgsDataDefined objects (which also deletes their QgsExpression object)
3213  for ( ; it != lyr.dataDefinedProperties.constEnd(); ++it )
3214  {
3215  delete( it.value() );
3216  it.value() = 0;
3217  }
3219 }
3220 
3222 {
3223  Q_ASSERT( mMapSettings != NULL );
3224 
3225  if ( !willUseLayer( layer ) || !layer->labelsEnabled() )
3226  {
3227  return 0;
3228  }
3229 
3230  QgsDebugMsgLevel( "PREPARE LAYER " + layer->id(), 4 );
3231 
3232  // start with a temporary settings class, find out labeling info
3233  QgsPalLayerSettings lyrTmp;
3234  lyrTmp.readFromLayer( layer );
3235 
3236  if ( lyrTmp.drawLabels )
3237  {
3238  if ( lyrTmp.fieldName.isEmpty() )
3239  {
3240  return 0;
3241  }
3242 
3243  if ( lyrTmp.isExpression )
3244  {
3245  QgsExpression exp( lyrTmp.fieldName );
3246  if ( exp.hasEvalError() )
3247  {
3248  QgsDebugMsgLevel( "Prepare error:" + exp.evalErrorString(), 4 );
3249  return 0;
3250  }
3251  }
3252  else
3253  {
3254  // If we aren't an expression, we check to see if we can find the column.
3255  if ( layer->fieldNameIndex( lyrTmp.fieldName ) == -1 )
3256  {
3257  return 0;
3258  }
3259  }
3260  }
3261 
3262  // add layer settings to the pallabeling hashtable: <QgsVectorLayer*, QgsPalLayerSettings>
3263  mActiveLayers.insert( layer->id(), lyrTmp );
3264  // start using the reference to the layer in hashtable instead of local instance
3265  QgsPalLayerSettings& lyr = mActiveLayers[layer->id()];
3266 
3267  lyr.mCurFields = &( layer->pendingFields() );
3268 
3269  if ( lyrTmp.drawLabels )
3270  {
3271  // add field indices for label's text, from expression or field
3272  if ( lyr.isExpression )
3273  {
3274  // prepare expression for use in QgsPalLayerSettings::registerFeature()
3275  QgsExpression* exp = lyr.getLabelExpression();
3276  exp->prepare( layer->pendingFields() );
3277  if ( exp->hasEvalError() )
3278  {
3279  QgsDebugMsgLevel( "Prepare error:" + exp->evalErrorString(), 4 );
3280  }
3281  foreach ( QString name, exp->referencedColumns() )
3282  {
3283  QgsDebugMsgLevel( "REFERENCED COLUMN = " + name, 4 );
3284  attrNames.append( name );
3285  }
3286  }
3287  else
3288  {
3289  attrNames.append( lyr.fieldName );
3290  }
3291 
3292  // add field indices of data defined expression or field
3294  for ( ; dIt != lyr.dataDefinedProperties.constEnd(); ++dIt )
3295  {
3296  QgsDataDefined* dd = dIt.value();
3297  if ( !dd->isActive() )
3298  {
3299  continue;
3300  }
3301 
3302  // NOTE: the following also prepares any expressions for later use
3303 
3304  // store parameters for data defined expressions
3305  QMap<QString, QVariant> exprParams;
3306  exprParams.insert( "scale", ctx.rendererScale() );
3307 
3308  dd->setExpressionParams( exprParams );
3309 
3310  // this will return columns for expressions or field name, depending upon what is set to be used
3311  QStringList cols = dd->referencedColumns( layer ); // <-- prepares any expressions, too
3312 
3313  //QgsDebugMsgLevel( QString( "Data defined referenced columns:" ) + cols.join( "," ), 4 );
3314  foreach ( QString name, cols )
3315  {
3316  attrNames.append( name );
3317  }
3318  }
3319  }
3320 
3321  // how to place the labels
3322  Arrangement arrangement;
3323  switch ( lyr.placement )
3324  {
3325  case QgsPalLayerSettings::AroundPoint: arrangement = P_POINT; break;
3326  case QgsPalLayerSettings::OverPoint: arrangement = P_POINT_OVER; break;
3327  case QgsPalLayerSettings::Line: arrangement = P_LINE; break;
3328  case QgsPalLayerSettings::Curved: arrangement = P_CURVED; break;
3329  case QgsPalLayerSettings::Horizontal: arrangement = P_HORIZ; break;
3330  case QgsPalLayerSettings::Free: arrangement = P_FREE; break;
3331  default: Q_ASSERT( "unsupported placement" && 0 ); return 0;
3332  }
3333 
3334  // create the pal layer
3335  double priority = 1 - lyr.priority / 10.0; // convert 0..10 --> 1..0
3336 
3337  Layer* l = mPal->addLayer( layer->id(),
3338  arrangement,
3339  priority, lyr.obstacle, true, lyr.drawLabels,
3340  lyr.displayAll );
3341 
3342  if ( lyr.placementFlags )
3343  l->setArrangementFlags(( LineArrangementFlags )lyr.placementFlags );
3344 
3345  // set label mode (label per feature is the default)
3346  l->setLabelMode( lyr.labelPerPart ? Layer::LabelPerFeaturePart : Layer::LabelPerFeature );
3347 
3348  // set whether adjacent lines should be merged
3350 
3351  // set obstacle type
3352  switch ( lyr.obstacleType )
3353  {
3354  case PolygonInterior:
3356  break;
3357  case PolygonBoundary:
3359  break;
3360  }
3361 
3362  // set whether location of centroid must be inside of polygons
3364 
3365  // set whether labels must fall completely within the polygon
3367 
3368  // set how to show upside-down labels
3369  Layer::UpsideDownLabels upsdnlabels;
3370  switch ( lyr.upsidedownLabels )
3371  {
3372  case QgsPalLayerSettings::Upright: upsdnlabels = Layer::Upright; break;
3373  case QgsPalLayerSettings::ShowDefined: upsdnlabels = Layer::ShowDefined; break;
3374  case QgsPalLayerSettings::ShowAll: upsdnlabels = Layer::ShowAll; break;
3375  default: Q_ASSERT( "unsupported upside-down label setting" && 0 ); return 0;
3376  }
3377  l->setUpsidedownLabels( upsdnlabels );
3378 
3379 // // fix for font size in map units causing font to show pointsize at small map scales
3380 // int pixelFontSize = lyr.sizeToPixel( lyr.textFont.pointSizeF(), ctx,
3381 // lyr.fontSizeInMapUnits ? QgsPalLayerSettings::MapUnits : QgsPalLayerSettings::Points,
3382 // true );
3383 
3384 // if ( pixelFontSize < 1 )
3385 // {
3386 // lyr.textFont.setPointSize( 1 );
3387 // lyr.textFont.setPixelSize( 1 );
3388 // }
3389 // else
3390 // {
3391 // lyr.textFont.setPixelSize( pixelFontSize );
3392 // }
3393 
3394 // // scale spacing sizes if using map units
3395 // if ( lyr.fontSizeInMapUnits )
3396 // {
3397 // double spacingPixelSize;
3398 // if ( lyr.textFont.wordSpacing() != 0 )
3399 // {
3400 // spacingPixelSize = lyr.textFont.wordSpacing() / ctx.mapToPixel().mapUnitsPerPixel() * ctx.rasterScaleFactor();
3401 // lyr.textFont.setWordSpacing( spacingPixelSize );
3402 // }
3403 
3404 // if ( lyr.textFont.letterSpacing() != 0 )
3405 // {
3406 // spacingPixelSize = lyr.textFont.letterSpacing() / ctx.mapToPixel().mapUnitsPerPixel() * ctx.rasterScaleFactor();
3407 // lyr.textFont.setLetterSpacing( QFont::AbsoluteSpacing, spacingPixelSize );
3408 // }
3409 // }
3410 
3411  //raster and vector scale factors
3412  lyr.vectorScaleFactor = ctx.scaleFactor();
3414 
3415  // save the pal layer to our layer context (with some additional info)
3416  lyr.palLayer = l;
3417  lyr.fieldIndex = layer->fieldNameIndex( lyr.fieldName );
3418 
3419  lyr.xform = &mMapSettings->mapToPixel();
3420  lyr.ct = 0;
3422  lyr.ct = ctx.coordinateTransform()->clone();
3423  lyr.ptZero = lyr.xform->toMapCoordinates( 0, 0 );
3424  lyr.ptOne = lyr.xform->toMapCoordinates( 1, 0 );
3425 
3426  // rect for clipping
3428  if ( !qgsDoubleNear( mMapSettings->rotation(), 0.0 ) )
3429  {
3430  //PAL features are prerotated, so extent also needs to be unrotated
3432  }
3433 
3434  lyr.mFeatsSendingToPal = 0;
3435 
3436  return 1; // init successful
3437 }
3438 
3440 {
3441  double priority = 1 - s->priority / 10.0; // convert 0..10 --> 1..0
3442  Layer* l = mPal->addLayer( layer->id().append( "d" ).toUtf8().data(), pal::Arrangement( s->placement ), priority, s->obstacle, true, true );
3443  l->setArrangementFlags(( LineArrangementFlags )s->placementFlags );
3444 
3445  mActiveDiagramLayers.insert( layer->id(), *s );
3446  // initialize the local copy
3448 
3449  s2.palLayer = l;
3450  s2.ct = 0;
3452  s2.ct = new QgsCoordinateTransform( layer->crs(), mMapSettings->destinationCrs() );
3453 
3454  s2.xform = &mMapSettings->mapToPixel();
3455 
3456  s2.fields = layer->pendingFields();
3457 
3458  s2.renderer = layer->diagramRenderer()->clone();
3459 
3460  return 1;
3461 }
3462 
3463 void QgsPalLabeling::registerFeature( const QString& layerID, QgsFeature& f, const QgsRenderContext& context, QString dxfLayer )
3464 {
3465  QgsPalLayerSettings& lyr = mActiveLayers[layerID];
3466  lyr.registerFeature( f, context, dxfLayer );
3467 }
3468 
3469 bool QgsPalLabeling::geometryRequiresPreparation( const QgsGeometry* geometry, const QgsRenderContext& context, const QgsCoordinateTransform* ct, QgsGeometry* clipGeometry )
3470 {
3471  if ( !geometry )
3472  {
3473  return false;
3474  }
3475 
3476  //requires reprojection
3477  if ( ct )
3478  return true;
3479 
3480  //requires fixing
3481  if ( geometry->type() == QGis::Polygon && !geometry->isGeosValid() )
3482  return true;
3483 
3484  //requires rotation
3485  const QgsMapToPixel& m2p = context.mapToPixel();
3486  if ( !qgsDoubleNear( m2p.mapRotation(), 0 ) )
3487  return true;
3488 
3489  //requires clip
3490  if ( clipGeometry && !clipGeometry->contains( geometry ) )
3491  return true;
3492 
3493  return false;
3494 }
3495 
3496 QStringList QgsPalLabeling::splitToLines( const QString &text, const QString &wrapCharacter )
3497 {
3498  QStringList multiLineSplit;
3499  if ( !wrapCharacter.isEmpty() && wrapCharacter != QString( "\n" ) )
3500  {
3501  //wrap on both the wrapchr and new line characters
3502  foreach ( QString line, text.split( wrapCharacter ) )
3503  {
3504  multiLineSplit.append( line.split( QString( "\n" ) ) );
3505  }
3506  }
3507  else
3508  {
3509  multiLineSplit = text.split( "\n" );
3510  }
3511 
3512  return multiLineSplit;
3513 }
3514 
3516 {
3517  QStringList graphemes;
3518  QTextBoundaryFinder boundaryFinder( QTextBoundaryFinder::Grapheme, text );
3519  int currentBoundary = -1;
3520  int previousBoundary = 0;
3521  while (( currentBoundary = boundaryFinder.toNextBoundary() ) > 0 )
3522  {
3523  graphemes << text.mid( previousBoundary, currentBoundary - previousBoundary );
3524  previousBoundary = currentBoundary;
3525  }
3526  return graphemes;
3527 }
3528 
3530 {
3531  if ( !geometry )
3532  {
3533  return 0;
3534  }
3535 
3536  //don't modify the feature's geometry so that geometry based expressions keep working
3537  QgsGeometry* geom = new QgsGeometry( *geometry );
3538  QScopedPointer<QgsGeometry> clonedGeometry( geom );
3539 
3540  //reproject the geometry if necessary
3541  if ( ct )
3542  {
3543  try
3544  {
3545  geom->transform( *ct );
3546  }
3547  catch ( QgsCsException &cse )
3548  {
3549  Q_UNUSED( cse );
3550  QgsDebugMsgLevel( QString( "Ignoring feature due to transformation exception" ), 4 );
3551  return 0;
3552  }
3553  }
3554 
3555  // Rotate the geometry if needed, before clipping
3556  const QgsMapToPixel& m2p = context.mapToPixel();
3557  if ( !qgsDoubleNear( m2p.mapRotation(), 0 ) )
3558  {
3559  QgsPoint center = context.extent().center();
3560 
3561  if ( ct )
3562  {
3563  try
3564  {
3565  center = ct->transform( center );
3566  }
3567  catch ( QgsCsException &cse )
3568  {
3569  Q_UNUSED( cse );
3570  QgsDebugMsgLevel( QString( "Ignoring feature due to transformation exception" ), 4 );
3571  return 0;
3572  }
3573  }
3574 
3575  if ( geom->rotate( m2p.mapRotation(), center ) )
3576  {
3577  QgsDebugMsg( QString( "Error rotating geometry" ).arg( geom->exportToWkt() ) );
3578  return 0;
3579  }
3580  }
3581 
3582  if ( !geom->asGeos() )
3583  return 0; // there is something really wrong with the geometry
3584 
3585  // fix invalid polygons
3586  if ( geom->type() == QGis::Polygon && !geom->isGeosValid() )
3587  {
3588  QgsGeometry* bufferGeom = geom->buffer( 0, 0 );
3589  if ( !bufferGeom )
3590  {
3591  return 0;
3592  }
3593  geom = bufferGeom;
3594  clonedGeometry.reset( geom );
3595  }
3596 
3597  if ( clipGeometry && !clipGeometry->contains( geom ) )
3598  {
3599  QgsGeometry* clipGeom = geom->intersection( clipGeometry ); // creates new geometry
3600  if ( !clipGeom )
3601  {
3602  return 0;
3603  }
3604  geom = clipGeom;
3605  clonedGeometry.reset( geom );
3606  }
3607 
3608  return clonedGeometry.take();
3609 }
3610 
3611 bool QgsPalLabeling::checkMinimumSizeMM( const QgsRenderContext& context, const QgsGeometry* geom, double minSize )
3612 {
3613  if ( minSize <= 0 )
3614  {
3615  return true;
3616  }
3617 
3618  if ( !geom )
3619  {
3620  return false;
3621  }
3622 
3623  QGis::GeometryType featureType = geom->type();
3624  if ( featureType == QGis::Point ) //minimum size does not apply to point features
3625  {
3626  return true;
3627  }
3628 
3629  double mapUnitsPerMM = context.mapToPixel().mapUnitsPerPixel() * context.scaleFactor();
3630  if ( featureType == QGis::Line )
3631  {
3632  double length = geom->length();
3633  if ( length >= 0.0 )
3634  {
3635  return ( length >= ( minSize * mapUnitsPerMM ) );
3636  }
3637  }
3638  else if ( featureType == QGis::Polygon )
3639  {
3640  double area = geom->area();
3641  if ( area >= 0.0 )
3642  {
3643  return ( sqrt( area ) >= ( minSize * mapUnitsPerMM ) );
3644  }
3645  }
3646  return true; //should never be reached. Return true in this case to label such geometries anyway.
3647 }
3648 
3649 void QgsPalLabeling::registerDiagramFeature( const QString& layerID, QgsFeature& feat, const QgsRenderContext& context )
3650 {
3651  //get diagram layer settings, diagram renderer
3653  if ( layerIt == mActiveDiagramLayers.constEnd() )
3654  {
3655  return;
3656  }
3657 
3658  QgsDiagramRendererV2* dr = layerIt.value().renderer;
3659  if ( dr )
3660  {
3661  QList<QgsDiagramSettings> settingList = dr->diagramSettings();
3662  if ( settingList.size() > 0 )
3663  {
3664  double minScale = settingList.at( 0 ).minScaleDenominator;
3665  if ( minScale > 0 && context.rendererScale() < minScale )
3666  {
3667  return;
3668  }
3669 
3670  double maxScale = settingList.at( 0 ).maxScaleDenominator;
3671  if ( maxScale > 0 && context.rendererScale() > maxScale )
3672  {
3673  return;
3674  }
3675  }
3676  }
3677 
3678  //convert geom to geos
3679  const QgsGeometry* geom = feat.constGeometry();
3681  if ( !qgsDoubleNear( mMapSettings->rotation(), 0.0 ) )
3682  {
3683  //PAL features are prerotated, so extent also needs to be unrotated
3684  extentGeom->rotate( -mMapSettings->rotation(), mMapSettings->visibleExtent().center() );
3685  }
3686 
3687  const GEOSGeometry* geos_geom = 0;
3688  QScopedPointer<QgsGeometry> preparedGeom;
3689  if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, layerIt.value().ct, extentGeom.data() ) )
3690  {
3691  preparedGeom.reset( QgsPalLabeling::prepareGeometry( geom, context, layerIt.value().ct, extentGeom.data() ) );
3692  if ( !preparedGeom.data() )
3693  return;
3694  geos_geom = preparedGeom.data()->asGeos();
3695  }
3696  else
3697  {
3698  geos_geom = geom->asGeos();
3699  }
3700 
3701  if ( geos_geom == 0 )
3702  {
3703  return; // invalid geometry
3704  }
3705 
3706  //create PALGeometry with diagram = true
3707  QgsPalGeometry* lbl = new QgsPalGeometry( feat.id(), "", GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom ) );
3708  lbl->setIsDiagram( true );
3709 
3710  // record the created geometry - it will be deleted at the end.
3711  layerIt.value().geometries.append( lbl );
3712 
3713  double diagramWidth = 0;
3714  double diagramHeight = 0;
3715  if ( dr )
3716  {
3717  QSizeF diagSize = dr->sizeMapUnits( feat, context );
3718  if ( diagSize.isValid() )
3719  {
3720  diagramWidth = diagSize.width();
3721  diagramHeight = diagSize.height();
3722  }
3723 
3724  //append the diagram attributes to lbl
3725  lbl->setDiagramAttributes( feat.attributes() );
3726  }
3727 
3728  // feature to the layer
3729  bool alwaysShow = layerIt.value().showAll;
3730  int ddColX = layerIt.value().xPosColumn;
3731  int ddColY = layerIt.value().yPosColumn;
3732  double ddPosX = 0.0;
3733  double ddPosY = 0.0;
3734  bool ddPos = ( ddColX >= 0 && ddColY >= 0 );
3735  if ( ddPos )
3736  {
3737  bool posXOk, posYOk;
3738  ddPosX = feat.attribute( ddColX ).toDouble( &posXOk );
3739  ddPosY = feat.attribute( ddColY ).toDouble( &posYOk );
3740  if ( !posXOk || !posYOk )
3741  {
3742  ddPos = false;
3743  }
3744  else
3745  {
3746  const QgsCoordinateTransform* ct = layerIt.value().ct;
3747  if ( ct )
3748  {
3749  double z = 0;
3750  ct->transformInPlace( ddPosX, ddPosY, z );
3751  }
3752  //data defined diagram position is always centered
3753  ddPosX -= diagramWidth / 2.0;
3754  ddPosY -= diagramHeight / 2.0;
3755  }
3756  }
3757 
3758  try
3759  {
3760  if ( !layerIt.value().palLayer->registerFeature( lbl->strId(), lbl, diagramWidth, diagramHeight, "", ddPosX, ddPosY, ddPos, 0.0, true, 0, 0, 0, 0, alwaysShow ) )
3761  {
3762  return;
3763  }
3764  }
3765  catch ( std::exception &e )
3766  {
3767  Q_UNUSED( e );
3768  QgsDebugMsgLevel( QString( "Ignoring feature %1 due PAL exception:" ).arg( feat.id() ) + QString::fromLatin1( e.what() ), 4 );
3769  return;
3770  }
3771 
3772  pal::Feature* palFeat = layerIt.value().palLayer->getFeature( lbl->strId() );
3773  QgsPoint ptZero = layerIt.value().xform->toMapCoordinates( 0, 0 );
3774  QgsPoint ptOne = layerIt.value().xform->toMapCoordinates( 1, 0 );
3775  palFeat->setDistLabel( qAbs( ptOne.x() - ptZero.x() ) * layerIt.value().dist );
3776 }
3777 
3778 
3780 {
3781  init( mr->mapSettings() );
3782 }
3783 
3784 void QgsPalLabeling::init( const QgsMapSettings& mapSettings )
3785 {
3786  mMapSettings = &mapSettings;
3787 
3788  // delete if exists already
3789  if ( mPal )
3790  delete mPal;
3791 
3792  mPal = new Pal;
3793 
3794  SearchMethod s;
3795  switch ( mSearch )
3796  {
3797  default:
3798  case Chain: s = CHAIN; break;
3799  case Popmusic_Tabu: s = POPMUSIC_TABU; break;
3800  case Popmusic_Chain: s = POPMUSIC_CHAIN; break;
3801  case Popmusic_Tabu_Chain: s = POPMUSIC_TABU_CHAIN; break;
3802  case Falp: s = FALP; break;
3803  }
3804  mPal->setSearch( s );
3805 
3806  // set number of candidates generated per feature
3808  mPal->setLineP( mCandLine );
3810 
3812 
3813  clearActiveLayers(); // free any previous QgsDataDefined objects
3815 }
3816 
3818 {
3819  delete mPal;
3820  mPal = NULL;
3821  mMapSettings = NULL;
3822 }
3823 
3825 {
3827  for ( lit = mActiveLayers.begin(); lit != mActiveLayers.end(); ++lit )
3828  {
3829  if ( lit.key() == layerName )
3830  {
3831  return lit.value();
3832  }
3833  }
3834  return mInvalidLayerSettings;
3835 }
3836 
3839 {
3840  //font color
3841  if ( ddValues.contains( QgsPalLayerSettings::Color ) )
3842  {
3843  QVariant ddColor = ddValues.value( QgsPalLayerSettings::Color );
3844  tmpLyr.textColor = ddColor.value<QColor>();
3845  }
3846 
3847  //font transparency
3848  if ( ddValues.contains( QgsPalLayerSettings::FontTransp ) )
3849  {
3850  tmpLyr.textTransp = ddValues.value( QgsPalLayerSettings::FontTransp ).toInt();
3851  }
3852 
3853  tmpLyr.textColor.setAlphaF(( 100.0 - ( double )( tmpLyr.textTransp ) ) / 100.0 );
3854 
3855  //font blend mode
3856  if ( ddValues.contains( QgsPalLayerSettings::FontBlendMode ) )
3857  {
3858  tmpLyr.blendMode = ( QPainter::CompositionMode )ddValues.value( QgsPalLayerSettings::FontBlendMode ).toInt();
3859  }
3860 }
3861 
3864 {
3866  {
3867  tmpLyr.wrapChar = ddValues.value( QgsPalLayerSettings::MultiLineWrapChar ).toString();
3868  }
3869 
3870  if ( !tmpLyr.wrapChar.isEmpty() || tmpLyr.getLabelExpression()->expression().contains( "wordwrap" ) )
3871  {
3872 
3874  {
3875  tmpLyr.multilineHeight = ddValues.value( QgsPalLayerSettings::MultiLineHeight ).toDouble();
3876  }
3877 
3879  {
3881  }
3882 
3883  }
3884 
3885  if ( ddValues.contains( QgsPalLayerSettings::DirSymbDraw ) )
3886  {
3887  tmpLyr.addDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbDraw ).toBool();
3888  }
3889 
3890  if ( tmpLyr.addDirectionSymbol )
3891  {
3892 
3893  if ( ddValues.contains( QgsPalLayerSettings::DirSymbLeft ) )
3894  {
3895  tmpLyr.leftDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbLeft ).toString();
3896  }
3897  if ( ddValues.contains( QgsPalLayerSettings::DirSymbRight ) )
3898  {
3899  tmpLyr.rightDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbRight ).toString();
3900  }
3901 
3903  {
3905  }
3906 
3908  {
3910  }
3911 
3912  }
3913 }
3914 
3917 {
3918  //buffer draw
3919  if ( ddValues.contains( QgsPalLayerSettings::BufferDraw ) )
3920  {
3921  tmpLyr.bufferDraw = ddValues.value( QgsPalLayerSettings::BufferDraw ).toBool();
3922  }
3923 
3924  if ( !tmpLyr.bufferDraw )
3925  {
3926  // tmpLyr.bufferSize > 0.0 && tmpLyr.bufferTransp < 100 figured in during evaluation
3927  return; // don't continue looking for unused values
3928  }
3929 
3930  //buffer size
3931  if ( ddValues.contains( QgsPalLayerSettings::BufferSize ) )
3932  {
3933  tmpLyr.bufferSize = ddValues.value( QgsPalLayerSettings::BufferSize ).toDouble();
3934  }
3935 
3936  //buffer transparency
3937  if ( ddValues.contains( QgsPalLayerSettings::BufferTransp ) )
3938  {
3939  tmpLyr.bufferTransp = ddValues.value( QgsPalLayerSettings::BufferTransp ).toInt();
3940  }
3941 
3942  //buffer size units
3943  if ( ddValues.contains( QgsPalLayerSettings::BufferUnit ) )
3944  {
3946  tmpLyr.bufferSizeInMapUnits = ( bufunit == QgsPalLayerSettings::MapUnits );
3947  }
3948 
3949  //buffer color
3950  if ( ddValues.contains( QgsPalLayerSettings::BufferColor ) )
3951  {
3952  QVariant ddColor = ddValues.value( QgsPalLayerSettings::BufferColor );
3953  tmpLyr.bufferColor = ddColor.value<QColor>();
3954  }
3955 
3956  // apply any transparency
3957  tmpLyr.bufferColor.setAlphaF(( 100.0 - ( double )( tmpLyr.bufferTransp ) ) / 100.0 );
3958 
3959  //buffer pen join style
3961  {
3962  tmpLyr.bufferJoinStyle = ( Qt::PenJoinStyle )ddValues.value( QgsPalLayerSettings::BufferJoinStyle ).toInt();
3963  }
3964 
3965  //buffer blend mode
3967  {
3968  tmpLyr.bufferBlendMode = ( QPainter::CompositionMode )ddValues.value( QgsPalLayerSettings::BufferBlendMode ).toInt();
3969  }
3970 }
3971 
3974 {
3975  //shape draw
3976  if ( ddValues.contains( QgsPalLayerSettings::ShapeDraw ) )
3977  {
3978  tmpLyr.shapeDraw = ddValues.value( QgsPalLayerSettings::ShapeDraw ).toBool();
3979  }
3980 
3981  if ( !tmpLyr.shapeDraw )
3982  {
3983  return; // don't continue looking for unused values
3984  }
3985 
3986  if ( ddValues.contains( QgsPalLayerSettings::ShapeKind ) )
3987  {
3989  }
3990 
3991  if ( ddValues.contains( QgsPalLayerSettings::ShapeSVGFile ) )
3992  {
3993  tmpLyr.shapeSVGFile = ddValues.value( QgsPalLayerSettings::ShapeSVGFile ).toString();
3994  }
3995 
3996  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeType ) )
3997  {
3999  }
4000 
4001  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeX ) )
4002  {
4003  tmpLyr.shapeSize.setX( ddValues.value( QgsPalLayerSettings::ShapeSizeX ).toDouble() );
4004  }
4005  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeY ) )
4006  {
4007  tmpLyr.shapeSize.setY( ddValues.value( QgsPalLayerSettings::ShapeSizeY ).toDouble() );
4008  }
4009 
4011  {
4013  }
4014 
4016  {
4018  }
4019 
4020  if ( ddValues.contains( QgsPalLayerSettings::ShapeRotation ) )
4021  {
4022  tmpLyr.shapeRotation = ddValues.value( QgsPalLayerSettings::ShapeRotation ).toDouble();
4023  }
4024 
4025  if ( ddValues.contains( QgsPalLayerSettings::ShapeOffset ) )
4026  {
4027  tmpLyr.shapeOffset = ddValues.value( QgsPalLayerSettings::ShapeOffset ).toPointF();
4028  }
4029 
4031  {
4033  }
4034 
4035  if ( ddValues.contains( QgsPalLayerSettings::ShapeRadii ) )
4036  {
4037  tmpLyr.shapeRadii = ddValues.value( QgsPalLayerSettings::ShapeRadii ).toPointF();
4038  }
4039 
4041  {
4043  }
4044 
4046  {
4047  tmpLyr.shapeTransparency = ddValues.value( QgsPalLayerSettings::ShapeTransparency ).toInt();
4048  }
4049 
4051  {
4052  tmpLyr.shapeBlendMode = ( QPainter::CompositionMode )ddValues.value( QgsPalLayerSettings::ShapeBlendMode ).toInt();
4053  }
4054 
4056  {
4057  QVariant ddColor = ddValues.value( QgsPalLayerSettings::ShapeFillColor );
4058  tmpLyr.shapeFillColor = ddColor.value<QColor>();
4059  }
4060 
4062  {
4064  tmpLyr.shapeBorderColor = ddColor.value<QColor>();
4065  }
4066 
4068  {
4069  tmpLyr.shapeBorderWidth = ddValues.value( QgsPalLayerSettings::ShapeBorderWidth ).toDouble();
4070  }
4071 
4073  {
4075  }
4076 
4078  {
4079  tmpLyr.shapeJoinStyle = ( Qt::PenJoinStyle )ddValues.value( QgsPalLayerSettings::ShapeJoinStyle ).toInt();
4080  }
4081 }
4082 
4085 {
4086  //shadow draw
4087  if ( ddValues.contains( QgsPalLayerSettings::ShadowDraw ) )
4088  {
4089  tmpLyr.shadowDraw = ddValues.value( QgsPalLayerSettings::ShadowDraw ).toBool();
4090  }
4091 
4092  if ( !tmpLyr.shadowDraw )
4093  {
4094  return; // don't continue looking for unused values
4095  }
4096 
4097  if ( ddValues.contains( QgsPalLayerSettings::ShadowUnder ) )
4098  {
4100  }
4101 
4103  {
4104  tmpLyr.shadowOffsetAngle = ddValues.value( QgsPalLayerSettings::ShadowOffsetAngle ).toInt();
4105  }
4106 
4108  {
4109  tmpLyr.shadowOffsetDist = ddValues.value( QgsPalLayerSettings::ShadowOffsetDist ).toDouble();
4110  }
4111 
4113  {
4115  }
4116 
4117  if ( ddValues.contains( QgsPalLayerSettings::ShadowRadius ) )
4118  {
4119  tmpLyr.shadowRadius = ddValues.value( QgsPalLayerSettings::ShadowRadius ).toDouble();
4120  }
4121 
4123  {
4125  }
4126 
4128  {
4130  }
4131 
4132  if ( ddValues.contains( QgsPalLayerSettings::ShadowScale ) )
4133  {
4134  tmpLyr.shadowScale = ddValues.value( QgsPalLayerSettings::ShadowScale ).toInt();
4135  }
4136 
4137  if ( ddValues.contains( QgsPalLayerSettings::ShadowColor ) )
4138  {
4139  QVariant ddColor = ddValues.value( QgsPalLayerSettings::ShadowColor );
4140  tmpLyr.shadowColor = ddColor.value<QColor>();
4141  }
4142 
4144  {
4145  tmpLyr.shadowBlendMode = ( QPainter::CompositionMode )ddValues.value( QgsPalLayerSettings::ShadowBlendMode ).toInt();
4146  }
4147 }
4148 
4149 
4150 // helper function for checking for job cancellation within PAL
4151 static bool _palIsCancelled( void* ctx )
4152 {
4153  return (( QgsRenderContext* ) ctx )->renderingStopped();
4154 }
4155 
4157 {
4158  Q_ASSERT( mMapSettings != NULL );
4159  QPainter* painter = context.painter();
4160 
4162  if ( !qgsDoubleNear( mMapSettings->rotation(), 0.0 ) )
4163  {
4164  //PAL features are prerotated, so extent also needs to be unrotated
4165  extentGeom->rotate( -mMapSettings->rotation(), mMapSettings->visibleExtent().center() );
4166  }
4167 
4168  QgsRectangle extent = extentGeom->boundingBox();
4169  delete extentGeom;
4170 
4172 
4173  delete mResults;
4175 
4176  QTime t;
4177  t.start();
4178 
4179  // do the labeling itself
4180  double bbox[] = { extent.xMinimum(), extent.yMinimum(), extent.xMaximum(), extent.yMaximum() };
4181 
4182  std::list<LabelPosition*>* labels;
4183  pal::Problem *problem;
4184  try
4185  {
4186  problem = mPal->extractProblem( bbox );
4187  }
4188  catch ( std::exception& e )
4189  {
4190  Q_UNUSED( e );
4191  QgsDebugMsgLevel( "PAL EXCEPTION :-( " + QString::fromLatin1( e.what() ), 4 );
4192  //mActiveLayers.clear(); // clean up
4193  return;
4194  }
4195 
4196  if ( context.renderingStopped() )
4197  {
4198  delete problem;
4199  return; // it has been cancelled
4200  }
4201 
4202 #if 1 // XXX strk
4203  // features are pre-rotated but not scaled/translated,
4204  // so we only disable rotation here. Ideally, they'd be
4205  // also pre-scaled/translated, as suggested here:
4206  // http://hub.qgis.org/issues/11856
4208  xform.setMapRotation( 0, 0, 0 );
4209 #else
4210  const QgsMapToPixel& xform = mMapSettings->mapToPixel();
4211 #endif
4212 
4213  // draw rectangles with all candidates
4214  // this is done before actual solution of the problem
4215  // before number of candidates gets reduced
4216  mCandidates.clear();
4217  if ( mShowingCandidates && problem )
4218  {
4219  painter->setPen( QColor( 0, 0, 0, 64 ) );
4220  painter->setBrush( Qt::NoBrush );
4221  for ( int i = 0; i < problem->getNumFeatures(); i++ )
4222  {
4223  for ( int j = 0; j < problem->getFeatureCandidateCount( i ); j++ )
4224  {
4225  pal::LabelPosition* lp = problem->getFeatureCandidate( i, j );
4226 
4227  drawLabelCandidateRect( lp, painter, &xform );
4228  }
4229  }
4230  }
4231 
4232  // find the solution
4233  labels = mPal->solveProblem( problem, mShowingAllLabels );
4234 
4235  QgsDebugMsgLevel( QString( "LABELING work: %1 ms ... labels# %2" ).arg( t.elapsed() ).arg( labels->size() ), 4 );
4236  t.restart();
4237 
4238  if ( context.renderingStopped() )
4239  {
4240  delete problem;
4241  delete labels;
4243  return;
4244  }
4245 
4246  painter->setRenderHint( QPainter::Antialiasing );
4247 
4248  // draw the labels
4249  std::list<LabelPosition*>::iterator it = labels->begin();
4250  for ( ; it != labels->end(); ++it )
4251  {
4252  if ( context.renderingStopped() )
4253  break;
4254 
4255  QgsPalGeometry* palGeometry = dynamic_cast< QgsPalGeometry* >(( *it )->getFeaturePart()->getUserGeometry() );
4256  if ( !palGeometry )
4257  {
4258  continue;
4259  }
4260 
4261  //layer names
4262  QString layerName = ( *it )->getLayerName();
4263  if ( palGeometry->isDiagram() )
4264  {
4265  QgsFeature feature;
4266  //render diagram
4268  for ( dit = mActiveDiagramLayers.begin(); dit != mActiveDiagramLayers.end(); ++dit )
4269  {
4270  if ( QString( dit.key() + "d" ) == layerName )
4271  {
4272  feature.setFields( dit.value().fields );
4273  palGeometry->feature( feature );
4274 
4275  //calculate top-left point for diagram
4276  //first, calculate the centroid of the label (accounts for PAL creating
4277  //rotated labels when we do not want to draw the diagrams rotated)
4278  double centerX = 0;
4279  double centerY = 0;
4280  for ( int i = 0; i < 4; ++i )
4281  {
4282  centerX += ( *it )->getX( i );
4283  centerY += ( *it )->getY( i );
4284  }
4285  QgsPoint outPt( centerX / 4.0, centerY / 4.0 );
4286  //then, calculate the top left point for the diagram with this center position
4287  QgsPoint centerPt = xform.transform( outPt.x() - ( *it )->getWidth() / 2,
4288  outPt.y() - ( *it )->getHeight() / 2 );
4289 
4290  dit.value().renderer->renderDiagram( feature, context, centerPt.toQPointF() );
4291  }
4292  }
4293 
4294  //insert into label search tree to manipulate position interactively
4295  if ( mResults->mLabelSearchTree )
4296  {
4297  //for diagrams, remove the additional 'd' at the end of the layer id
4298  QString layerId = layerName;
4299  layerId.chop( 1 );
4300  mResults->mLabelSearchTree->insertLabel( *it, QString( palGeometry->strId() ).toInt(), layerId, QString( "" ), QFont(), true, false );
4301  }
4302  continue;
4303  }
4304 
4305  const QgsPalLayerSettings& lyr = layer( layerName );
4306  if ( !lyr.drawLabels )
4307  continue;
4308 
4309  // Copy to temp, editable layer settings
4310  // these settings will be changed by any data defined values, then used for rendering label components
4311  // settings may be adjusted during rendering of components
4312  QgsPalLayerSettings tmpLyr( lyr );
4313 
4314  // apply any previously applied data defined settings for the label
4316 
4317  //font
4318  QFont dFont = palGeometry->definedFont();
4319  QgsDebugMsgLevel( QString( "PAL font tmpLyr: %1, Style: %2" ).arg( tmpLyr.textFont.toString() ).arg( tmpLyr.textFont.styleName() ), 4 );
4320  QgsDebugMsgLevel( QString( "PAL font definedFont: %1, Style: %2" ).arg( dFont.toString() ).arg( dFont.styleName() ), 4 );
4321  tmpLyr.textFont = dFont;
4322 
4324  {
4325  //calculate font alignment based on label quadrant
4326  switch (( *it )->getQuadrant() )
4327  {
4328  case LabelPosition::QuadrantAboveLeft:
4329  case LabelPosition::QuadrantLeft:
4330  case LabelPosition::QuadrantBelowLeft:
4332  break;
4333  case LabelPosition::QuadrantAbove:
4334  case LabelPosition::QuadrantOver:
4335  case LabelPosition::QuadrantBelow:
4337  break;
4338  case LabelPosition::QuadrantAboveRight:
4339  case LabelPosition::QuadrantRight:
4340  case LabelPosition::QuadrantBelowRight:
4342  break;
4343  }
4344  }
4345 
4346  // update tmpLyr with any data defined text style values
4347  dataDefinedTextStyle( tmpLyr, ddValues );
4348 
4349  // update tmpLyr with any data defined text buffer values
4350  dataDefinedTextBuffer( tmpLyr, ddValues );
4351 
4352  // update tmpLyr with any data defined text formatting values
4353  dataDefinedTextFormatting( tmpLyr, ddValues );
4354 
4355  // update tmpLyr with any data defined shape background values
4356  dataDefinedShapeBackground( tmpLyr, ddValues );
4357 
4358  // update tmpLyr with any data defined drop shadow values
4359  dataDefinedDropShadow( tmpLyr, ddValues );
4360 
4361 
4363 
4364  // Render the components of a label in reverse order
4365  // (backgrounds -> text)
4366 
4367  if ( tmpLyr.shadowDraw && tmpLyr.shadowUnder == QgsPalLayerSettings::ShadowLowest )
4368  {
4369  if ( tmpLyr.shapeDraw )
4370  {
4372  }
4373  else if ( tmpLyr.bufferDraw )
4374  {
4376  }
4377  else
4378  {
4380  }
4381  }
4382 
4383  if ( tmpLyr.shapeDraw )
4384  {
4385  drawLabel( *it, context, tmpLyr, LabelShape );
4386  }
4387 
4388  if ( tmpLyr.bufferDraw )
4389  {
4390  drawLabel( *it, context, tmpLyr, LabelBuffer );
4391  }
4392 
4393  drawLabel( *it, context, tmpLyr, LabelText );
4394 
4395  if ( mResults->mLabelSearchTree )
4396  {
4397  QString labeltext = (( QgsPalGeometry* )( *it )->getFeaturePart()->getUserGeometry() )->text();
4398  mResults->mLabelSearchTree->insertLabel( *it, QString( palGeometry->strId() ).toInt(), layerName, labeltext, dFont, false, palGeometry->isPinned() );
4399  }
4400  }
4401 
4402  // Reset composition mode for further drawing operations
4403  painter->setCompositionMode( QPainter::CompositionMode_SourceOver );
4404 
4405  QgsDebugMsgLevel( QString( "LABELING draw: %1 ms" ).arg( t.elapsed() ), 4 );
4406 
4407  delete problem;
4408  delete labels;
4410 }
4411 
4413 {
4414  // delete all allocated geometries for features
4416  for ( lit = mActiveLayers.begin(); lit != mActiveLayers.end(); ++lit )
4417  {
4418  QgsPalLayerSettings& lyr = lit.value();
4419  for ( QList<QgsPalGeometry*>::iterator git = lyr.geometries.begin(); git != lyr.geometries.end(); ++git )
4420  delete *git;
4421  if ( lyr.limitNumLabels )
4422  {
4423  QgsDebugMsgLevel( QString( "mFeaturesToLabel: %1" ).arg( lyr.mFeaturesToLabel ), 4 );
4424  QgsDebugMsgLevel( QString( "maxNumLabels: %1" ).arg( lyr.maxNumLabels ), 4 );
4425  QgsDebugMsgLevel( QString( "mFeatsSendingToPal: %1" ).arg( lyr.mFeatsSendingToPal ), 4 );
4426  QgsDebugMsgLevel( QString( "mFeatsRegPal: %1" ).arg( lyr.geometries.count() ), 4 );
4427  }
4428  lyr.geometries.clear();
4429  }
4430 
4431  //delete all allocated geometries for diagrams
4433  for ( ; dIt != mActiveDiagramLayers.end(); ++dIt )
4434  {
4435  QgsDiagramLayerSettings& dls = dIt.value();
4436  for ( QList<QgsPalGeometry*>::iterator git = dls.geometries.begin(); git != dls.geometries.end(); ++git )
4437  {
4438  delete *git;
4439  }
4440  dls.geometries.clear();
4441  }
4442 }
4443 
4445 {
4447 }
4448 
4450 {
4452 }
4453 
4455 {
4456  if ( mResults )
4457  {