QGIS API Documentation  2.7.0-Master
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules 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 <geos_c.h>
32 
33 #include <cmath>
34 
35 #include <QApplication>
36 #include <QByteArray>
37 #include <QString>
38 #include <QFontMetrics>
39 #include <QTime>
40 #include <QPainter>
41 
42 #include "diagram/qgsdiagram.h"
43 #include "qgsdiagramrendererv2.h"
44 #include "qgsfontutils.h"
45 #include "qgslabelsearchtree.h"
46 #include "qgsexpression.h"
47 #include "qgsdatadefined.h"
48 
49 #include <qgslogger.h>
50 #include <qgsvectorlayer.h>
51 #include <qgsmaplayerregistry.h>
52 #include <qgsvectordataprovider.h>
53 #include <qgsgeometry.h>
54 #include <qgsmaprenderer.h>
55 #include <qgsmarkersymbollayerv2.h>
56 #include <qgsproject.h>
57 #include "qgssymbolv2.h"
58 #include "qgssymbollayerv2utils.h"
59 #include <QMessageBox>
60 
61 
62 Q_GUI_EXPORT extern int qt_defaultDpiX();
63 Q_GUI_EXPORT extern int qt_defaultDpiY();
64 
65 static void _fixQPictureDPI( QPainter* p )
66 {
67  // QPicture makes an assumption that we drawing to it with system DPI.
68  // Then when being drawn, it scales the painter. The following call
69  // negates the effect. There is no way of setting QPicture's DPI.
70  // See QTBUG-20361
71  p->scale(( double )qt_defaultDpiX() / p->device()->logicalDpiX(),
72  ( double )qt_defaultDpiY() / p->device()->logicalDpiY() );
73 }
74 
75 
76 using namespace pal;
77 
78 // -------------
79 
81  : palLayer( NULL )
82  , mCurFeat( 0 )
83  , mCurFields( 0 )
84  , ct( NULL )
85  , extentGeom( NULL )
86  , mFeaturesToLabel( 0 )
87  , mFeatsSendingToPal( 0 )
88  , mFeatsRegPal( 0 )
89  , expression( NULL )
90 {
91  enabled = false;
92 
93  // text style
94  textFont = QApplication::font();
95  textNamedStyle = QString( "" );
96  fontSizeInMapUnits = false;
97  textColor = Qt::black;
98  textTransp = 0;
99  blendMode = QPainter::CompositionMode_SourceOver;
100  previewBkgrdColor = Qt::white;
101  // font processing info
102  mTextFontFound = true;
103  mTextFontFamily = QApplication::font().family();
104 
105  // text formatting
106  wrapChar = "";
107  multilineHeight = 1.0;
109  addDirectionSymbol = false;
110  leftDirectionSymbol = QString( "<" );
111  rightDirectionSymbol = QString( ">" );
112  reverseDirectionSymbol = false;
114  formatNumbers = false;
115  decimals = 3;
116  plusSign = false;
117 
118  // text buffer
119  bufferDraw = false;
120  bufferSize = 1.0;
121  bufferSizeInMapUnits = false;
122  bufferColor = Qt::white;
123  bufferTransp = 0;
124  bufferNoFill = false;
125  bufferJoinStyle = Qt::BevelJoin;
126  bufferBlendMode = QPainter::CompositionMode_SourceOver;
127 
128  // shape background
129  shapeDraw = false;
131  shapeSVGFile = QString();
133  shapeSize = QPointF( 0.0, 0.0 );
134  shapeSizeUnits = MM;
136  shapeRotation = 0.0;
137  shapeOffset = QPointF( 0.0, 0.0 );
139  shapeRadii = QPointF( 0.0, 0.0 );
141  shapeFillColor = Qt::white;
142  shapeBorderColor = Qt::darkGray;
143  shapeBorderWidth = 0.0;
145  shapeJoinStyle = Qt::BevelJoin;
146  shapeTransparency = 0;
147  shapeBlendMode = QPainter::CompositionMode_SourceOver;
148 
149  // drop shadow
150  shadowDraw = false;
152  shadowOffsetAngle = 135;
153  shadowOffsetDist = 1.0;
155  shadowOffsetGlobal = true;
156  shadowRadius = 1.5;
158  shadowRadiusAlphaOnly = false;
159  shadowTransparency = 30;
160  shadowScale = 100;
161  shadowColor = Qt::black;
162  shadowBlendMode = QPainter::CompositionMode_Multiply;
163 
164  // placement
166  placementFlags = 0;
167  centroidWhole = false;
168  centroidInside = false;
170  xOffset = 0;
171  yOffset = 0;
172  labelOffsetInMapUnits = true;
173  dist = 0;
174  distInMapUnits = false;
175  angleOffset = 0;
176  preserveRotation = true;
177  maxCurvedCharAngleIn = 20.0;
178  maxCurvedCharAngleOut = -20.0;
179  priority = 5;
180  repeatDistance = 0;
182 
183  // rendering
184  scaleVisibility = false;
185  scaleMin = 1;
186  scaleMax = 10000000;
187  fontLimitPixelSize = false;
188  fontMinPixelSize = 0; //trigger to turn it on by default for map unit labels
189  fontMaxPixelSize = 10000;
190  displayAll = false;
192 
193  labelPerPart = false;
194  mergeLines = false;
195  minFeatureSize = 0.0;
196  limitNumLabels = false;
197  maxNumLabels = 2000;
198  obstacle = true;
199 
200  // scale factors
201  vectorScaleFactor = 1.0;
202  rasterCompressFactor = 1.0;
203 
204  // data defined string and old-style index values
205  // NOTE: in QPair use -1 for second value (other values are for old-style layer properties migration)
206 
207  // text style
208  mDataDefinedNames.insert( Size, QPair<QString, int>( "Size", 0 ) );
209  mDataDefinedNames.insert( Bold, QPair<QString, int>( "Bold", 1 ) );
210  mDataDefinedNames.insert( Italic, QPair<QString, int>( "Italic", 2 ) );
211  mDataDefinedNames.insert( Underline, QPair<QString, int>( "Underline", 3 ) );
212  mDataDefinedNames.insert( Color, QPair<QString, int>( "Color", 4 ) );
213  mDataDefinedNames.insert( Strikeout, QPair<QString, int>( "Strikeout", 5 ) );
214  mDataDefinedNames.insert( Family, QPair<QString, int>( "Family", 6 ) );
215  mDataDefinedNames.insert( FontStyle, QPair<QString, int>( "FontStyle", -1 ) );
216  mDataDefinedNames.insert( FontSizeUnit, QPair<QString, int>( "FontSizeUnit", -1 ) );
217  mDataDefinedNames.insert( FontTransp, QPair<QString, int>( "FontTransp", 18 ) );
218  mDataDefinedNames.insert( FontCase, QPair<QString, int>( "FontCase", -1 ) );
219  mDataDefinedNames.insert( FontLetterSpacing, QPair<QString, int>( "FontLetterSpacing", -1 ) );
220  mDataDefinedNames.insert( FontWordSpacing, QPair<QString, int>( "FontWordSpacing", -1 ) );
221  mDataDefinedNames.insert( FontBlendMode, QPair<QString, int>( "FontBlendMode", -1 ) );
222 
223  // text formatting
224  mDataDefinedNames.insert( MultiLineWrapChar, QPair<QString, int>( "MultiLineWrapChar", -1 ) );
225  mDataDefinedNames.insert( MultiLineHeight, QPair<QString, int>( "MultiLineHeight", -1 ) );
226  mDataDefinedNames.insert( MultiLineAlignment, QPair<QString, int>( "MultiLineAlignment", -1 ) );
227  mDataDefinedNames.insert( DirSymbDraw, QPair<QString, int>( "DirSymbDraw", -1 ) );
228  mDataDefinedNames.insert( DirSymbLeft, QPair<QString, int>( "DirSymbLeft", -1 ) );
229  mDataDefinedNames.insert( DirSymbRight, QPair<QString, int>( "DirSymbRight", -1 ) );
230  mDataDefinedNames.insert( DirSymbPlacement, QPair<QString, int>( "DirSymbPlacement", -1 ) );
231  mDataDefinedNames.insert( DirSymbReverse, QPair<QString, int>( "DirSymbReverse", -1 ) );
232  mDataDefinedNames.insert( NumFormat, QPair<QString, int>( "NumFormat", -1 ) );
233  mDataDefinedNames.insert( NumDecimals, QPair<QString, int>( "NumDecimals", -1 ) );
234  mDataDefinedNames.insert( NumPlusSign, QPair<QString, int>( "NumPlusSign", -1 ) );
235 
236  // text buffer
237  mDataDefinedNames.insert( BufferDraw, QPair<QString, int>( "BufferDraw", -1 ) );
238  mDataDefinedNames.insert( BufferSize, QPair<QString, int>( "BufferSize", 7 ) );
239  mDataDefinedNames.insert( BufferUnit, QPair<QString, int>( "BufferUnit", -1 ) );
240  mDataDefinedNames.insert( BufferColor, QPair<QString, int>( "BufferColor", 8 ) );
241  mDataDefinedNames.insert( BufferTransp, QPair<QString, int>( "BufferTransp", 19 ) );
242  mDataDefinedNames.insert( BufferJoinStyle, QPair<QString, int>( "BufferJoinStyle", -1 ) );
243  mDataDefinedNames.insert( BufferBlendMode, QPair<QString, int>( "BufferBlendMode", -1 ) );
244 
245  // background
246  mDataDefinedNames.insert( ShapeDraw, QPair<QString, int>( "ShapeDraw", -1 ) );
247  mDataDefinedNames.insert( ShapeKind, QPair<QString, int>( "ShapeKind", -1 ) );
248  mDataDefinedNames.insert( ShapeSVGFile, QPair<QString, int>( "ShapeSVGFile", -1 ) );
249  mDataDefinedNames.insert( ShapeSizeType, QPair<QString, int>( "ShapeSizeType", -1 ) );
250  mDataDefinedNames.insert( ShapeSizeX, QPair<QString, int>( "ShapeSizeX", -1 ) );
251  mDataDefinedNames.insert( ShapeSizeY, QPair<QString, int>( "ShapeSizeY", -1 ) );
252  mDataDefinedNames.insert( ShapeSizeUnits, QPair<QString, int>( "ShapeSizeUnits", -1 ) );
253  mDataDefinedNames.insert( ShapeRotationType, QPair<QString, int>( "ShapeRotationType", -1 ) );
254  mDataDefinedNames.insert( ShapeRotation, QPair<QString, int>( "ShapeRotation", -1 ) );
255  mDataDefinedNames.insert( ShapeOffset, QPair<QString, int>( "ShapeOffset", -1 ) );
256  mDataDefinedNames.insert( ShapeOffsetUnits, QPair<QString, int>( "ShapeOffsetUnits", -1 ) );
257  mDataDefinedNames.insert( ShapeRadii, QPair<QString, int>( "ShapeRadii", -1 ) );
258  mDataDefinedNames.insert( ShapeRadiiUnits, QPair<QString, int>( "ShapeRadiiUnits", -1 ) );
259  mDataDefinedNames.insert( ShapeTransparency, QPair<QString, int>( "ShapeTransparency", -1 ) );
260  mDataDefinedNames.insert( ShapeBlendMode, QPair<QString, int>( "ShapeBlendMode", -1 ) );
261  mDataDefinedNames.insert( ShapeFillColor, QPair<QString, int>( "ShapeFillColor", -1 ) );
262  mDataDefinedNames.insert( ShapeBorderColor, QPair<QString, int>( "ShapeBorderColor", -1 ) );
263  mDataDefinedNames.insert( ShapeBorderWidth, QPair<QString, int>( "ShapeBorderWidth", -1 ) );
264  mDataDefinedNames.insert( ShapeBorderWidthUnits, QPair<QString, int>( "ShapeBorderWidthUnits", -1 ) );
265  mDataDefinedNames.insert( ShapeJoinStyle, QPair<QString, int>( "ShapeJoinStyle", -1 ) );
266 
267  // drop shadow
268  mDataDefinedNames.insert( ShadowDraw, QPair<QString, int>( "ShadowDraw", -1 ) );
269  mDataDefinedNames.insert( ShadowUnder, QPair<QString, int>( "ShadowUnder", -1 ) );
270  mDataDefinedNames.insert( ShadowOffsetAngle, QPair<QString, int>( "ShadowOffsetAngle", -1 ) );
271  mDataDefinedNames.insert( ShadowOffsetDist, QPair<QString, int>( "ShadowOffsetDist", -1 ) );
272  mDataDefinedNames.insert( ShadowOffsetUnits, QPair<QString, int>( "ShadowOffsetUnits", -1 ) );
273  mDataDefinedNames.insert( ShadowRadius, QPair<QString, int>( "ShadowRadius", -1 ) );
274  mDataDefinedNames.insert( ShadowRadiusUnits, QPair<QString, int>( "ShadowRadiusUnits", -1 ) );
275  mDataDefinedNames.insert( ShadowTransparency, QPair<QString, int>( "ShadowTransparency", -1 ) );
276  mDataDefinedNames.insert( ShadowScale, QPair<QString, int>( "ShadowScale", -1 ) );
277  mDataDefinedNames.insert( ShadowColor, QPair<QString, int>( "ShadowColor", -1 ) );
278  mDataDefinedNames.insert( ShadowBlendMode, QPair<QString, int>( "ShadowBlendMode", -1 ) );
279 
280  // placement
281  mDataDefinedNames.insert( CentroidWhole, QPair<QString, int>( "CentroidWhole", -1 ) );
282  mDataDefinedNames.insert( OffsetQuad, QPair<QString, int>( "OffsetQuad", -1 ) );
283  mDataDefinedNames.insert( OffsetXY, QPair<QString, int>( "OffsetXY", -1 ) );
284  mDataDefinedNames.insert( OffsetUnits, QPair<QString, int>( "OffsetUnits", -1 ) );
285  mDataDefinedNames.insert( LabelDistance, QPair<QString, int>( "LabelDistance", 13 ) );
286  mDataDefinedNames.insert( DistanceUnits, QPair<QString, int>( "DistanceUnits", -1 ) );
287  mDataDefinedNames.insert( OffsetRotation, QPair<QString, int>( "OffsetRotation", -1 ) );
288  mDataDefinedNames.insert( CurvedCharAngleInOut, QPair<QString, int>( "CurvedCharAngleInOut", -1 ) );
289  mDataDefinedNames.insert( RepeatDistance, QPair<QString, int>( "RepeatDistance", -1 ) );
290  mDataDefinedNames.insert( RepeatDistanceUnit, QPair<QString, int>( "RepeatDistanceUnit", -1 ) );
291  // (data defined only)
292  mDataDefinedNames.insert( PositionX, QPair<QString, int>( "PositionX", 9 ) );
293  mDataDefinedNames.insert( PositionY, QPair<QString, int>( "PositionY", 10 ) );
294  mDataDefinedNames.insert( Hali, QPair<QString, int>( "Hali", 11 ) );
295  mDataDefinedNames.insert( Vali, QPair<QString, int>( "Vali", 12 ) );
296  mDataDefinedNames.insert( Rotation, QPair<QString, int>( "Rotation", 14 ) );
297 
298  //rendering
299  mDataDefinedNames.insert( ScaleVisibility, QPair<QString, int>( "ScaleVisibility", -1 ) );
300  mDataDefinedNames.insert( MinScale, QPair<QString, int>( "MinScale", 16 ) );
301  mDataDefinedNames.insert( MaxScale, QPair<QString, int>( "MaxScale", 17 ) );
302  mDataDefinedNames.insert( FontLimitPixel, QPair<QString, int>( "FontLimitPixel", -1 ) );
303  mDataDefinedNames.insert( FontMinPixel, QPair<QString, int>( "FontMinPixel", -1 ) );
304  mDataDefinedNames.insert( FontMaxPixel, QPair<QString, int>( "FontMaxPixel", -1 ) );
305  // (data defined only)
306  mDataDefinedNames.insert( Show, QPair<QString, int>( "Show", 15 ) );
307  mDataDefinedNames.insert( AlwaysShow, QPair<QString, int>( "AlwaysShow", 20 ) );
308 
309  // temp stuff for when drawing label components (don't copy)
310  showingShadowRects = false;
311 }
312 
314 {
315  // copy only permanent stuff
316 
317  enabled = s.enabled;
318 
319  // text style
320  fieldName = s.fieldName;
322  textFont = s.textFont;
326  textColor = s.textColor;
328  blendMode = s.blendMode;
330  // font processing info
333 
334  // text formatting
335  wrapChar = s.wrapChar;
344  decimals = s.decimals;
345  plusSign = s.plusSign;
346 
347  // text buffer
357 
358  // placement
359  placement = s.placement;
364  xOffset = s.xOffset;
365  yOffset = s.yOffset;
368  dist = s.dist;
375  priority = s.priority;
379 
380  // rendering
382  scaleMin = s.scaleMin;
383  scaleMax = s.scaleMax;
389 
395  obstacle = s.obstacle;
396 
397  // shape background
398  shapeDraw = s.shapeDraw;
399  shapeType = s.shapeType;
402  shapeSize = s.shapeSize;
421 
422  // drop shadow
438 
439  // data defined
441  mDataDefinedNames = s.mDataDefinedNames;
442 
443  // scale factors
446 
447  ct = NULL;
448  extentGeom = NULL;
449  expression = NULL;
450 }
451 
452 
454 {
455  // pal layer is deleted internally in PAL
456 
457  delete ct;
458  delete expression;
459  delete extentGeom;
460 
461  // clear pointers to QgsDataDefined objects
462  dataDefinedProperties.clear();
463 }
464 
465 
467 {
468  QgsPalLayerSettings settings;
469  settings.readFromLayer( layer );
470  return settings;
471 }
472 
473 
475 {
476  if ( expression == NULL )
477  {
478  expression = new QgsExpression( fieldName );
479  }
480  return expression;
481 }
482 
483 static QColor _readColor( QgsVectorLayer* layer, QString property, QColor defaultColor = Qt::black, bool withAlpha = true )
484 {
485  int r = layer->customProperty( property + "R", QVariant( defaultColor.red() ) ).toInt();
486  int g = layer->customProperty( property + "G", QVariant( defaultColor.green() ) ).toInt();
487  int b = layer->customProperty( property + "B", QVariant( defaultColor.blue() ) ).toInt();
488  int a = withAlpha ? layer->customProperty( property + "A", QVariant( defaultColor.alpha() ) ).toInt() : 255;
489  return QColor( r, g, b, a );
490 }
491 
492 static void _writeColor( QgsVectorLayer* layer, QString property, QColor color, bool withAlpha = true )
493 {
494  layer->setCustomProperty( property + "R", color.red() );
495  layer->setCustomProperty( property + "G", color.green() );
496  layer->setCustomProperty( property + "B", color.blue() );
497  if ( withAlpha )
498  layer->setCustomProperty( property + "A", color.alpha() );
499 }
500 
501 static QgsPalLayerSettings::SizeUnit _decodeUnits( const QString& str )
502 {
503  if ( str.compare( "Point", Qt::CaseInsensitive ) == 0
504  || str.compare( "Points", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Points;
505  if ( str.compare( "MapUnit", Qt::CaseInsensitive ) == 0
506  || str.compare( "MapUnits", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::MapUnits;
507  if ( str.compare( "Percent", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Percent;
508  return QgsPalLayerSettings::MM; // "MM"
509 }
510 
511 static Qt::PenJoinStyle _decodePenJoinStyle( const QString& str )
512 {
513  if ( str.compare( "Miter", Qt::CaseInsensitive ) == 0 ) return Qt::MiterJoin;
514  if ( str.compare( "Round", Qt::CaseInsensitive ) == 0 ) return Qt::RoundJoin;
515  return Qt::BevelJoin; // "Bevel"
516 }
517 
518 void QgsPalLayerSettings::readDataDefinedPropertyMap( QgsVectorLayer* layer,
519  QMap < QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* > & propertyMap )
520 {
521  if ( !layer )
522  {
523  return;
524  }
525 
526  QMapIterator<QgsPalLayerSettings::DataDefinedProperties, QPair<QString, int> > i( mDataDefinedNames );
527  while ( i.hasNext() )
528  {
529  i.next();
530  readDataDefinedProperty( layer, i.key(), propertyMap );
531  }
532 }
533 
534 void QgsPalLayerSettings::writeDataDefinedPropertyMap( QgsVectorLayer* layer,
535  const QMap < QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* > & propertyMap )
536 {
537  if ( !layer )
538  {
539  return;
540  }
541 
542  QMapIterator<QgsPalLayerSettings::DataDefinedProperties, QPair<QString, int> > i( mDataDefinedNames );
543  while ( i.hasNext() )
544  {
545  i.next();
546  QString newPropertyName = "labeling/dataDefined/" + i.value().first;
547  QVariant propertyValue = QVariant();
548 
549  QMap< QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* >::const_iterator it = propertyMap.find( i.key() );
550  if ( it != propertyMap.constEnd() )
551  {
552  QgsDataDefined* dd = it.value();
553  if ( dd )
554  {
555  bool active = dd->isActive();
556  bool useExpr = dd->useExpression();
557  QString expr = dd->expressionString();
558  QString field = dd->field();
559 
560  bool defaultVals = ( !active && !useExpr && expr.isEmpty() && field.isEmpty() );
561 
562  if ( !defaultVals )
563  {
564  // TODO: update this when project settings for labeling are migrated to better XML layout
565  QStringList values;
566  values << ( active ? "1" : "0" );
567  values << ( useExpr ? "1" : "0" );
568  values << expr;
569  values << field;
570  if ( !values.isEmpty() )
571  {
572  propertyValue = QVariant( values.join( "~~" ) );
573  }
574  }
575  }
576  }
577 
578  if ( propertyValue.isValid() )
579  {
580  layer->setCustomProperty( newPropertyName, propertyValue );
581  }
582  else
583  {
584  // remove unused properties
585  layer->removeCustomProperty( newPropertyName );
586  }
587 
588  if ( layer->customProperty( newPropertyName, QVariant() ).isValid() && i.value().second > -1 )
589  {
590  // remove old-style field index-based property, if still present
591  layer->removeCustomProperty( QString( "labeling/dataDefinedProperty" ) + QString::number( i.value().second ) );
592  }
593  }
594 }
595 
596 void QgsPalLayerSettings::readDataDefinedProperty( QgsVectorLayer* layer,
598  QMap < QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* > & propertyMap )
599 {
600  QString newPropertyName = "labeling/dataDefined/" + mDataDefinedNames.value( p ).first;
601  QVariant newPropertyField = layer->customProperty( newPropertyName, QVariant() );
602 
603  QString ddString = QString();
604  if ( newPropertyField.isValid() )
605  {
606  ddString = newPropertyField.toString();
607  }
608  else // maybe working with old-style field index-based property (< QGIS 2.0)
609  {
610  int oldIndx = mDataDefinedNames.value( p ).second;
611 
612  if ( oldIndx < 0 ) // something went wrong and we are working with new-style
613  {
614  return;
615  }
616 
617  QString oldPropertyName = "labeling/dataDefinedProperty" + QString::number( oldIndx );
618  QVariant oldPropertyField = layer->customProperty( oldPropertyName, QVariant() );
619 
620  if ( !oldPropertyField.isValid() )
621  {
622  return;
623  }
624 
625  // switch from old-style field index- to name-based properties
626  bool conversionOk;
627  int indx = oldPropertyField.toInt( &conversionOk );
628 
629  if ( conversionOk )
630  {
631  // Fix to migrate from old-style vector api, where returned QMap keys possibly
632  // had 'holes' in sequence of field indices, e.g. 0,2,3
633  // QgsAttrPalIndexNameHash provides a means of access field name in sequences from
634  // providers that procuded holes (e.g. PostGIS skipped geom column), otherwise it is empty
635  QgsAttrPalIndexNameHash oldIndicesToNames = layer->dataProvider()->palAttributeIndexNames();
636 
637  if ( !oldIndicesToNames.isEmpty() )
638  {
639  ddString = oldIndicesToNames.value( indx );
640  }
641  else
642  {
643  QgsFields fields = layer->dataProvider()->fields();
644  if ( indx < fields.size() ) // in case field count has changed
645  {
646  ddString = fields.at( indx ).name();
647  }
648  }
649  }
650 
651  if ( !ddString.isEmpty() )
652  {
653  //upgrade any existing property to field name-based
654  layer->setCustomProperty( newPropertyName, QVariant( updateDataDefinedString( ddString ) ) );
655 
656  // fix for buffer drawing triggered off of just its data defined size in the past (<2.0)
657  if ( oldIndx == 7 ) // old bufferSize enum
658  {
659  bufferDraw = true;
660  layer->setCustomProperty( "labeling/bufferDraw", true );
661  }
662 
663  // fix for scale visibility limits triggered off of just its data defined values in the past (<2.0)
664  if ( oldIndx == 16 || oldIndx == 17 ) // old minScale and maxScale enums
665  {
666  scaleVisibility = true;
667  layer->setCustomProperty( "labeling/scaleVisibility", true );
668  }
669  }
670 
671  // remove old-style field index-based property
672  layer->removeCustomProperty( oldPropertyName );
673  }
674 
675  if ( !ddString.isEmpty() && ddString != QString( "0~~0~~~~" ) )
676  {
677  // TODO: update this when project settings for labeling are migrated to better XML layout
678  QString newStyleString = updateDataDefinedString( ddString );
679  QStringList ddv = newStyleString.split( "~~" );
680 
681  QgsDataDefined* dd = new QgsDataDefined( ddv.at( 0 ).toInt(), ddv.at( 1 ).toInt(), ddv.at( 2 ), ddv.at( 3 ) );
682  propertyMap.insert( p, dd );
683  }
684  else
685  {
686  // remove unused properties
687  layer->removeCustomProperty( newPropertyName );
688  }
689 }
690 
692 {
693  if ( layer->customProperty( "labeling" ).toString() != QString( "pal" ) )
694  {
695  // for polygons the "over point" (over centroid) placement is better than the default
696  // "around point" (around centroid) which is more suitable for points
697  if ( layer->geometryType() == QGis::Polygon )
699 
700  return; // there's no information available
701  }
702 
703  // NOTE: set defaults for newly added properties, for backwards compatibility
704 
705  enabled = layer->customProperty( "labeling/enabled" ).toBool();
706 
707  // text style
708  fieldName = layer->customProperty( "labeling/fieldName" ).toString();
709  isExpression = layer->customProperty( "labeling/isExpression" ).toBool();
710  QFont appFont = QApplication::font();
711  mTextFontFamily = layer->customProperty( "labeling/fontFamily", QVariant( appFont.family() ) ).toString();
712  QString fontFamily = mTextFontFamily;
714  {
715  // trigger to notify user about font family substitution (signal emitted in QgsVectorLayer::prepareLabelingAndDiagrams)
716  mTextFontFound = false;
717 
718  // TODO: update when pref for how to resolve missing family (use matching algorithm or just default font) is implemented
719  // currently only defaults to matching algorithm for resolving [foundry], if a font of similar family is found (default for QFont)
720 
721  // for now, do not use matching algorithm for substitution if family not found, substitute default instead
722  fontFamily = appFont.family();
723  }
724 
725  double fontSize = layer->customProperty( "labeling/fontSize" ).toDouble();
726  fontSizeInMapUnits = layer->customProperty( "labeling/fontSizeInMapUnits" ).toBool();
727  fontSizeMapUnitScale.minScale = layer->customProperty( "labeling/fontSizeMapUnitMinScale", 0.0 ).toDouble();
728  fontSizeMapUnitScale.maxScale = layer->customProperty( "labeling/fontSizeMapUnitMaxScale", 0.0 ).toDouble();
729  int fontWeight = layer->customProperty( "labeling/fontWeight" ).toInt();
730  bool fontItalic = layer->customProperty( "labeling/fontItalic" ).toBool();
731  textFont = QFont( fontFamily, fontSize, fontWeight, fontItalic );
732  textFont.setPointSizeF( fontSize ); //double precision needed because of map units
733  textNamedStyle = layer->customProperty( "labeling/namedStyle", QVariant( "" ) ).toString();
734  QgsFontUtils::updateFontViaStyle( textFont, textNamedStyle ); // must come after textFont.setPointSizeF()
735  textFont.setCapitalization(( QFont::Capitalization )layer->customProperty( "labeling/fontCapitals", QVariant( 0 ) ).toUInt() );
736  textFont.setUnderline( layer->customProperty( "labeling/fontUnderline" ).toBool() );
737  textFont.setStrikeOut( layer->customProperty( "labeling/fontStrikeout" ).toBool() );
738  textFont.setLetterSpacing( QFont::AbsoluteSpacing, layer->customProperty( "labeling/fontLetterSpacing", QVariant( 0.0 ) ).toDouble() );
739  textFont.setWordSpacing( layer->customProperty( "labeling/fontWordSpacing", QVariant( 0.0 ) ).toDouble() );
740  textColor = _readColor( layer, "labeling/textColor", Qt::black, false );
741  textTransp = layer->customProperty( "labeling/textTransp" ).toInt();
743  ( QgsMapRenderer::BlendMode )layer->customProperty( "labeling/blendMode", QVariant( QgsMapRenderer::BlendNormal ) ).toUInt() );
744  previewBkgrdColor = QColor( layer->customProperty( "labeling/previewBkgrdColor", QVariant( "#ffffff" ) ).toString() );
745 
746 
747  // text formatting
748  wrapChar = layer->customProperty( "labeling/wrapChar" ).toString();
749  multilineHeight = layer->customProperty( "labeling/multilineHeight", QVariant( 1.0 ) ).toDouble();
750  multilineAlign = ( MultiLineAlign )layer->customProperty( "labeling/multilineAlign", QVariant( MultiLeft ) ).toUInt();
751  addDirectionSymbol = layer->customProperty( "labeling/addDirectionSymbol" ).toBool();
752  leftDirectionSymbol = layer->customProperty( "labeling/leftDirectionSymbol", QVariant( "<" ) ).toString();
753  rightDirectionSymbol = layer->customProperty( "labeling/rightDirectionSymbol", QVariant( ">" ) ).toString();
754  reverseDirectionSymbol = layer->customProperty( "labeling/reverseDirectionSymbol" ).toBool();
755  placeDirectionSymbol = ( DirectionSymbols )layer->customProperty( "labeling/placeDirectionSymbol", QVariant( SymbolLeftRight ) ).toUInt();
756  formatNumbers = layer->customProperty( "labeling/formatNumbers" ).toBool();
757  decimals = layer->customProperty( "labeling/decimals" ).toInt();
758  plusSign = layer->customProperty( "labeling/plussign" ).toInt();
759 
760  // text buffer
761  double bufSize = layer->customProperty( "labeling/bufferSize", QVariant( 0.0 ) ).toDouble();
762 
763  // fix for buffer being keyed off of just its size in the past (<2.0)
764  QVariant drawBuffer = layer->customProperty( "labeling/bufferDraw", QVariant() );
765  if ( drawBuffer.isValid() )
766  {
767  bufferDraw = drawBuffer.toBool();
768  bufferSize = bufSize;
769  }
770  else if ( bufSize != 0.0 )
771  {
772  bufferDraw = true;
773  bufferSize = bufSize;
774  }
775  else
776  {
777  // keep bufferSize at new 1.0 default
778  bufferDraw = false;
779  }
780 
781  bufferSizeInMapUnits = layer->customProperty( "labeling/bufferSizeInMapUnits" ).toBool();
782  bufferSizeMapUnitScale.minScale = layer->customProperty( "labeling/bufferSizeMapUnitMinScale", 0.0 ).toDouble();
783  bufferSizeMapUnitScale.maxScale = layer->customProperty( "labeling/bufferSizeMapUnitMaxScale", 0.0 ).toDouble();
784  bufferColor = _readColor( layer, "labeling/bufferColor", Qt::white, false );
785  bufferTransp = layer->customProperty( "labeling/bufferTransp" ).toInt();
787  ( QgsMapRenderer::BlendMode )layer->customProperty( "labeling/bufferBlendMode", QVariant( QgsMapRenderer::BlendNormal ) ).toUInt() );
788  bufferJoinStyle = ( Qt::PenJoinStyle )layer->customProperty( "labeling/bufferJoinStyle", QVariant( Qt::BevelJoin ) ).toUInt();
789  bufferNoFill = layer->customProperty( "labeling/bufferNoFill", QVariant( false ) ).toBool();
790 
791  // background
792  shapeDraw = layer->customProperty( "labeling/shapeDraw", QVariant( false ) ).toBool();
793  shapeType = ( ShapeType )layer->customProperty( "labeling/shapeType", QVariant( ShapeRectangle ) ).toUInt();
794  shapeSVGFile = layer->customProperty( "labeling/shapeSVGFile", QVariant( "" ) ).toString();
795  shapeSizeType = ( SizeType )layer->customProperty( "labeling/shapeSizeType", QVariant( SizeBuffer ) ).toUInt();
796  shapeSize = QPointF( layer->customProperty( "labeling/shapeSizeX", QVariant( 0.0 ) ).toDouble(),
797  layer->customProperty( "labeling/shapeSizeY", QVariant( 0.0 ) ).toDouble() );
798  shapeSizeUnits = ( SizeUnit )layer->customProperty( "labeling/shapeSizeUnits", QVariant( MM ) ).toUInt();
799  shapeSizeMapUnitScale.minScale = layer->customProperty( "labeling/shapeSizeMapUnitMinScale", 0.0 ).toDouble();
800  shapeSizeMapUnitScale.maxScale = layer->customProperty( "labeling/shapeSizeMapUnitMaxScale", 0.0 ).toDouble();
801  shapeRotationType = ( RotationType )layer->customProperty( "labeling/shapeRotationType", QVariant( RotationSync ) ).toUInt();
802  shapeRotation = layer->customProperty( "labeling/shapeRotation", QVariant( 0.0 ) ).toDouble();
803  shapeOffset = QPointF( layer->customProperty( "labeling/shapeOffsetX", QVariant( 0.0 ) ).toDouble(),
804  layer->customProperty( "labeling/shapeOffsetY", QVariant( 0.0 ) ).toDouble() );
805  shapeOffsetUnits = ( SizeUnit )layer->customProperty( "labeling/shapeOffsetUnits", QVariant( MM ) ).toUInt();
806  shapeOffsetMapUnitScale.minScale = layer->customProperty( "labeling/shapeOffsetMapUnitMinScale", 0.0 ).toDouble();
807  shapeOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/shapeOffsetMapUnitMaxScale", 0.0 ).toDouble();
808  shapeRadii = QPointF( layer->customProperty( "labeling/shapeRadiiX", QVariant( 0.0 ) ).toDouble(),
809  layer->customProperty( "labeling/shapeRadiiY", QVariant( 0.0 ) ).toDouble() );
810  shapeRadiiUnits = ( SizeUnit )layer->customProperty( "labeling/shapeRadiiUnits", QVariant( MM ) ).toUInt();
811  shapeRadiiMapUnitScale.minScale = layer->customProperty( "labeling/shapeRaddiMapUnitMinScale", 0.0 ).toDouble();
812  shapeRadiiMapUnitScale.maxScale = layer->customProperty( "labeling/shapeRaddiMapUnitMaxScale", 0.0 ).toDouble();
813  shapeFillColor = _readColor( layer, "labeling/shapeFillColor", Qt::white, true );
814  shapeBorderColor = _readColor( layer, "labeling/shapeBorderColor", Qt::darkGray, true );
815  shapeBorderWidth = layer->customProperty( "labeling/shapeBorderWidth", QVariant( .0 ) ).toDouble();
816  shapeBorderWidthUnits = ( SizeUnit )layer->customProperty( "labeling/shapeBorderWidthUnits", QVariant( MM ) ).toUInt();
817  shapeBorderWidthMapUnitScale.minScale = layer->customProperty( "labeling/shapeBorderWidthMapUnitMinScale", 0.0 ).toDouble();
818  shapeBorderWidthMapUnitScale.maxScale = layer->customProperty( "labeling/shapeBorderWidthMapUnitMaxScale", 0.0 ).toDouble();
819  shapeJoinStyle = ( Qt::PenJoinStyle )layer->customProperty( "labeling/shapeJoinStyle", QVariant( Qt::BevelJoin ) ).toUInt();
820  shapeTransparency = layer->customProperty( "labeling/shapeTransparency", QVariant( 0 ) ).toInt();
822  ( QgsMapRenderer::BlendMode )layer->customProperty( "labeling/shapeBlendMode", QVariant( QgsMapRenderer::BlendNormal ) ).toUInt() );
823 
824  // drop shadow
825  shadowDraw = layer->customProperty( "labeling/shadowDraw", QVariant( false ) ).toBool();
826  shadowUnder = ( ShadowType )layer->customProperty( "labeling/shadowUnder", QVariant( ShadowLowest ) ).toUInt();//ShadowLowest;
827  shadowOffsetAngle = layer->customProperty( "labeling/shadowOffsetAngle", QVariant( 135 ) ).toInt();
828  shadowOffsetDist = layer->customProperty( "labeling/shadowOffsetDist", QVariant( 1.0 ) ).toDouble();
829  shadowOffsetUnits = ( SizeUnit )layer->customProperty( "labeling/shadowOffsetUnits", QVariant( MM ) ).toUInt();
830  shadowOffsetMapUnitScale.minScale = layer->customProperty( "labeling/shadowOffsetMapUnitMinScale", 0.0 ).toDouble();
831  shadowOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/shadowOffsetMapUnitMaxScale", 0.0 ).toDouble();
832  shadowOffsetGlobal = layer->customProperty( "labeling/shadowOffsetGlobal", QVariant( true ) ).toBool();
833  shadowRadius = layer->customProperty( "labeling/shadowRadius", QVariant( 1.5 ) ).toDouble();
834  shadowRadiusUnits = ( SizeUnit )layer->customProperty( "labeling/shadowRadiusUnits", QVariant( MM ) ).toUInt();
835  shadowRadiusMapUnitScale.minScale = layer->customProperty( "labeling/shadowRadiusMapUnitMinScale", 0.0 ).toDouble();
836  shadowRadiusMapUnitScale.maxScale = layer->customProperty( "labeling/shadowRadiusMapUnitMaxScale", 0.0 ).toDouble();
837  shadowRadiusAlphaOnly = layer->customProperty( "labeling/shadowRadiusAlphaOnly", QVariant( false ) ).toBool();
838  shadowTransparency = layer->customProperty( "labeling/shadowTransparency", QVariant( 30 ) ).toInt();
839  shadowScale = layer->customProperty( "labeling/shadowScale", QVariant( 100 ) ).toInt();
840  shadowColor = _readColor( layer, "labeling/shadowColor", Qt::black, false );
842  ( QgsMapRenderer::BlendMode )layer->customProperty( "labeling/shadowBlendMode", QVariant( QgsMapRenderer::BlendMultiply ) ).toUInt() );
843 
844  // placement
845  placement = ( Placement )layer->customProperty( "labeling/placement" ).toInt();
846  placementFlags = layer->customProperty( "labeling/placementFlags" ).toUInt();
847  centroidWhole = layer->customProperty( "labeling/centroidWhole", QVariant( false ) ).toBool();
848  centroidInside = layer->customProperty( "labeling/centroidInside", QVariant( false ) ).toBool();
849  dist = layer->customProperty( "labeling/dist" ).toDouble();
850  distInMapUnits = layer->customProperty( "labeling/distInMapUnits" ).toBool();
851  distMapUnitScale.minScale = layer->customProperty( "labeling/distMapUnitMinScale", 0.0 ).toDouble();
852  distMapUnitScale.maxScale = layer->customProperty( "labeling/distMapUnitMaxScale", 0.0 ).toDouble();
853  quadOffset = ( QuadrantPosition )layer->customProperty( "labeling/quadOffset", QVariant( QuadrantOver ) ).toUInt();
854  xOffset = layer->customProperty( "labeling/xOffset", QVariant( 0.0 ) ).toDouble();
855  yOffset = layer->customProperty( "labeling/yOffset", QVariant( 0.0 ) ).toDouble();
856  labelOffsetInMapUnits = layer->customProperty( "labeling/labelOffsetInMapUnits", QVariant( true ) ).toBool();
857  labelOffsetMapUnitScale.minScale = layer->customProperty( "labeling/labelOffsetMapUnitMinScale", 0.0 ).toDouble();
858  labelOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/labelOffsetMapUnitMaxScale", 0.0 ).toDouble();
859  angleOffset = layer->customProperty( "labeling/angleOffset", QVariant( 0.0 ) ).toDouble();
860  preserveRotation = layer->customProperty( "labeling/preserveRotation", QVariant( true ) ).toBool();
861  maxCurvedCharAngleIn = layer->customProperty( "labeling/maxCurvedCharAngleIn", QVariant( 20.0 ) ).toDouble();
862  maxCurvedCharAngleOut = layer->customProperty( "labeling/maxCurvedCharAngleOut", QVariant( -20.0 ) ).toDouble();
863  priority = layer->customProperty( "labeling/priority" ).toInt();
864  repeatDistance = layer->customProperty( "labeling/repeatDistance", 0.0 ).toDouble();
865  repeatDistanceUnit = ( SizeUnit ) layer->customProperty( "labeling/repeatDistanceUnit", QVariant( MM ) ).toUInt();
866  repeatDistanceMapUnitScale.minScale = layer->customProperty( "labeling/repeatDistanceMapUnitMinScale", 0.0 ).toDouble();
867  repeatDistanceMapUnitScale.maxScale = layer->customProperty( "labeling/repeatDistanceMapUnitMaxScale", 0.0 ).toDouble();
868 
869  // rendering
870  int scalemn = layer->customProperty( "labeling/scaleMin", QVariant( 0 ) ).toInt();
871  int scalemx = layer->customProperty( "labeling/scaleMax", QVariant( 0 ) ).toInt();
872 
873  // fix for scale visibility limits being keyed off of just its values in the past (<2.0)
874  QVariant scalevis = layer->customProperty( "labeling/scaleVisibility", QVariant() );
875  if ( scalevis.isValid() )
876  {
877  scaleVisibility = scalevis.toBool();
878  scaleMin = scalemn;
879  scaleMax = scalemx;
880  }
881  else if ( scalemn > 0 || scalemx > 0 )
882  {
883  scaleVisibility = true;
884  scaleMin = scalemn;
885  scaleMax = scalemx;
886  }
887  else
888  {
889  // keep scaleMin and scaleMax at new 1.0 defaults (1 and 10000000, were 0 and 0)
890  scaleVisibility = false;
891  }
892 
893 
894  fontLimitPixelSize = layer->customProperty( "labeling/fontLimitPixelSize", QVariant( false ) ).toBool();
895  fontMinPixelSize = layer->customProperty( "labeling/fontMinPixelSize", QVariant( 0 ) ).toInt();
896  fontMaxPixelSize = layer->customProperty( "labeling/fontMaxPixelSize", QVariant( 10000 ) ).toInt();
897  displayAll = layer->customProperty( "labeling/displayAll", QVariant( false ) ).toBool();
898  upsidedownLabels = ( UpsideDownLabels )layer->customProperty( "labeling/upsidedownLabels", QVariant( Upright ) ).toUInt();
899 
900  labelPerPart = layer->customProperty( "labeling/labelPerPart" ).toBool();
901  mergeLines = layer->customProperty( "labeling/mergeLines" ).toBool();
902  minFeatureSize = layer->customProperty( "labeling/minFeatureSize" ).toDouble();
903  limitNumLabels = layer->customProperty( "labeling/limitNumLabels", QVariant( false ) ).toBool();
904  maxNumLabels = layer->customProperty( "labeling/maxNumLabels", QVariant( 2000 ) ).toInt();
905  obstacle = layer->customProperty( "labeling/obstacle", QVariant( true ) ).toBool();
906 
907  readDataDefinedPropertyMap( layer, dataDefinedProperties );
908 }
909 
911 {
912  // this is a mark that labeling information is present
913  layer->setCustomProperty( "labeling", "pal" );
914 
915  layer->setCustomProperty( "labeling/enabled", enabled );
916 
917  // text style
918  layer->setCustomProperty( "labeling/fieldName", fieldName );
919  layer->setCustomProperty( "labeling/isExpression", isExpression );
920  layer->setCustomProperty( "labeling/fontFamily", textFont.family() );
921  layer->setCustomProperty( "labeling/namedStyle", textNamedStyle );
922  layer->setCustomProperty( "labeling/fontSize", textFont.pointSizeF() );
923  layer->setCustomProperty( "labeling/fontSizeInMapUnits", fontSizeInMapUnits );
924  layer->setCustomProperty( "labeling/fontSizeMapUnitMinScale", fontSizeMapUnitScale.minScale );
925  layer->setCustomProperty( "labeling/fontSizeMapUnitMaxScale", fontSizeMapUnitScale.maxScale );
926  layer->setCustomProperty( "labeling/fontWeight", textFont.weight() );
927  layer->setCustomProperty( "labeling/fontItalic", textFont.italic() );
928  layer->setCustomProperty( "labeling/fontBold", textFont.bold() );
929  layer->setCustomProperty( "labeling/fontStrikeout", textFont.strikeOut() );
930  layer->setCustomProperty( "labeling/fontUnderline", textFont.underline() );
931  _writeColor( layer, "labeling/textColor", textColor );
932  layer->setCustomProperty( "labeling/fontCapitals", ( unsigned int )textFont.capitalization() );
933  layer->setCustomProperty( "labeling/fontLetterSpacing", textFont.letterSpacing() );
934  layer->setCustomProperty( "labeling/fontWordSpacing", textFont.wordSpacing() );
935  layer->setCustomProperty( "labeling/textTransp", textTransp );
936  layer->setCustomProperty( "labeling/blendMode", QgsMapRenderer::getBlendModeEnum( blendMode ) );
937  layer->setCustomProperty( "labeling/previewBkgrdColor", previewBkgrdColor.name() );
938 
939  // text formatting
940  layer->setCustomProperty( "labeling/wrapChar", wrapChar );
941  layer->setCustomProperty( "labeling/multilineHeight", multilineHeight );
942  layer->setCustomProperty( "labeling/multilineAlign", ( unsigned int )multilineAlign );
943  layer->setCustomProperty( "labeling/addDirectionSymbol", addDirectionSymbol );
944  layer->setCustomProperty( "labeling/leftDirectionSymbol", leftDirectionSymbol );
945  layer->setCustomProperty( "labeling/rightDirectionSymbol", rightDirectionSymbol );
946  layer->setCustomProperty( "labeling/reverseDirectionSymbol", reverseDirectionSymbol );
947  layer->setCustomProperty( "labeling/placeDirectionSymbol", ( unsigned int )placeDirectionSymbol );
948  layer->setCustomProperty( "labeling/formatNumbers", formatNumbers );
949  layer->setCustomProperty( "labeling/decimals", decimals );
950  layer->setCustomProperty( "labeling/plussign", plusSign );
951 
952  // text buffer
953  layer->setCustomProperty( "labeling/bufferDraw", bufferDraw );
954  layer->setCustomProperty( "labeling/bufferSize", bufferSize );
955  layer->setCustomProperty( "labeling/bufferSizeInMapUnits", bufferSizeInMapUnits );
956  layer->setCustomProperty( "labeling/bufferSizeMapUnitMinScale", bufferSizeMapUnitScale.minScale );
957  layer->setCustomProperty( "labeling/bufferSizeMapUnitMaxScale", bufferSizeMapUnitScale.maxScale );
958  _writeColor( layer, "labeling/bufferColor", bufferColor );
959  layer->setCustomProperty( "labeling/bufferNoFill", bufferNoFill );
960  layer->setCustomProperty( "labeling/bufferTransp", bufferTransp );
961  layer->setCustomProperty( "labeling/bufferJoinStyle", ( unsigned int )bufferJoinStyle );
962  layer->setCustomProperty( "labeling/bufferBlendMode", QgsMapRenderer::getBlendModeEnum( bufferBlendMode ) );
963 
964  // background
965  layer->setCustomProperty( "labeling/shapeDraw", shapeDraw );
966  layer->setCustomProperty( "labeling/shapeType", ( unsigned int )shapeType );
967  layer->setCustomProperty( "labeling/shapeSVGFile", shapeSVGFile );
968  layer->setCustomProperty( "labeling/shapeSizeType", ( unsigned int )shapeSizeType );
969  layer->setCustomProperty( "labeling/shapeSizeX", shapeSize.x() );
970  layer->setCustomProperty( "labeling/shapeSizeY", shapeSize.y() );
971  layer->setCustomProperty( "labeling/shapeSizeUnits", ( unsigned int )shapeSizeUnits );
972  layer->setCustomProperty( "labeling/shapeSizeMapUnitMinScale", shapeSizeMapUnitScale.minScale );
973  layer->setCustomProperty( "labeling/shapeSizeMapUnitMaxScale", shapeSizeMapUnitScale.maxScale );
974  layer->setCustomProperty( "labeling/shapeRotationType", ( unsigned int )shapeRotationType );
975  layer->setCustomProperty( "labeling/shapeRotation", shapeRotation );
976  layer->setCustomProperty( "labeling/shapeOffsetX", shapeOffset.x() );
977  layer->setCustomProperty( "labeling/shapeOffsetY", shapeOffset.y() );
978  layer->setCustomProperty( "labeling/shapeOffsetUnits", ( unsigned int )shapeOffsetUnits );
979  layer->setCustomProperty( "labeling/shapeOffsetMapUnitMinScale", shapeOffsetMapUnitScale.minScale );
980  layer->setCustomProperty( "labeling/shapeOffsetMapUnitMaxScale", shapeOffsetMapUnitScale.maxScale );
981  layer->setCustomProperty( "labeling/shapeRadiiX", shapeRadii.x() );
982  layer->setCustomProperty( "labeling/shapeRadiiY", shapeRadii.y() );
983  layer->setCustomProperty( "labeling/shapeRadiiUnits", ( unsigned int )shapeRadiiUnits );
984  layer->setCustomProperty( "labeling/shapeRadiiMapUnitMinScale", shapeRadiiMapUnitScale.minScale );
985  layer->setCustomProperty( "labeling/shapeRadiiMapUnitMaxScale", shapeRadiiMapUnitScale.maxScale );
986  _writeColor( layer, "labeling/shapeFillColor", shapeFillColor, true );
987  _writeColor( layer, "labeling/shapeBorderColor", shapeBorderColor, true );
988  layer->setCustomProperty( "labeling/shapeBorderWidth", shapeBorderWidth );
989  layer->setCustomProperty( "labeling/shapeBorderWidthUnits", ( unsigned int )shapeBorderWidthUnits );
990  layer->setCustomProperty( "labeling/shapeBorderWidthMapUnitMinScale", shapeBorderWidthMapUnitScale.minScale );
991  layer->setCustomProperty( "labeling/shapeBorderWidthMapUnitMaxScale", shapeBorderWidthMapUnitScale.maxScale );
992  layer->setCustomProperty( "labeling/shapeJoinStyle", ( unsigned int )shapeJoinStyle );
993  layer->setCustomProperty( "labeling/shapeTransparency", shapeTransparency );
994  layer->setCustomProperty( "labeling/shapeBlendMode", QgsMapRenderer::getBlendModeEnum( shapeBlendMode ) );
995 
996  // drop shadow
997  layer->setCustomProperty( "labeling/shadowDraw", shadowDraw );
998  layer->setCustomProperty( "labeling/shadowUnder", ( unsigned int )shadowUnder );
999  layer->setCustomProperty( "labeling/shadowOffsetAngle", shadowOffsetAngle );
1000  layer->setCustomProperty( "labeling/shadowOffsetDist", shadowOffsetDist );
1001  layer->setCustomProperty( "labeling/shadowOffsetUnits", ( unsigned int )shadowOffsetUnits );
1002  layer->setCustomProperty( "labeling/shadowOffsetMapUnitMinScale", shadowOffsetMapUnitScale.minScale );
1003  layer->setCustomProperty( "labeling/shadowOffsetMapUnitMaxScale", shadowOffsetMapUnitScale.maxScale );
1004  layer->setCustomProperty( "labeling/shadowOffsetGlobal", shadowOffsetGlobal );
1005  layer->setCustomProperty( "labeling/shadowRadius", shadowRadius );
1006  layer->setCustomProperty( "labeling/shadowRadiusUnits", ( unsigned int )shadowRadiusUnits );
1007  layer->setCustomProperty( "labeling/shadowRadiusMapUnitMinScale", shadowRadiusMapUnitScale.minScale );
1008  layer->setCustomProperty( "labeling/shadowRadiusMapUnitMaxScale", shadowRadiusMapUnitScale.maxScale );
1009  layer->setCustomProperty( "labeling/shadowRadiusAlphaOnly", shadowRadiusAlphaOnly );
1010  layer->setCustomProperty( "labeling/shadowTransparency", shadowTransparency );
1011  layer->setCustomProperty( "labeling/shadowScale", shadowScale );
1012  _writeColor( layer, "labeling/shadowColor", shadowColor, false );
1013  layer->setCustomProperty( "labeling/shadowBlendMode", QgsMapRenderer::getBlendModeEnum( shadowBlendMode ) );
1014 
1015  // placement
1016  layer->setCustomProperty( "labeling/placement", placement );
1017  layer->setCustomProperty( "labeling/placementFlags", ( unsigned int )placementFlags );
1018  layer->setCustomProperty( "labeling/centroidWhole", centroidWhole );
1019  layer->setCustomProperty( "labeling/centroidInside", centroidInside );
1020  layer->setCustomProperty( "labeling/dist", dist );
1021  layer->setCustomProperty( "labeling/distInMapUnits", distInMapUnits );
1022  layer->setCustomProperty( "labeling/distMapUnitMinScale", distMapUnitScale.minScale );
1023  layer->setCustomProperty( "labeling/distMapUnitMaxScale", distMapUnitScale.maxScale );
1024  layer->setCustomProperty( "labeling/quadOffset", ( unsigned int )quadOffset );
1025  layer->setCustomProperty( "labeling/xOffset", xOffset );
1026  layer->setCustomProperty( "labeling/yOffset", yOffset );
1027  layer->setCustomProperty( "labeling/labelOffsetInMapUnits", labelOffsetInMapUnits );
1028  layer->setCustomProperty( "labeling/labelOffsetMapUnitMinScale", labelOffsetMapUnitScale.minScale );
1029  layer->setCustomProperty( "labeling/labelOffsetMapUnitMaxScale", labelOffsetMapUnitScale.maxScale );
1030  layer->setCustomProperty( "labeling/angleOffset", angleOffset );
1031  layer->setCustomProperty( "labeling/preserveRotation", preserveRotation );
1032  layer->setCustomProperty( "labeling/maxCurvedCharAngleIn", maxCurvedCharAngleIn );
1033  layer->setCustomProperty( "labeling/maxCurvedCharAngleOut", maxCurvedCharAngleOut );
1034  layer->setCustomProperty( "labeling/priority", priority );
1035  layer->setCustomProperty( "labeling/repeatDistance", repeatDistance );
1036  layer->setCustomProperty( "labeling/repeatDistanceUnit", repeatDistanceUnit );
1037  layer->setCustomProperty( "labeling/repeatDistanceMapUnitMinScale", repeatDistanceMapUnitScale.minScale );
1038  layer->setCustomProperty( "labeling/repeatDistanceMapUnitMaxScale", repeatDistanceMapUnitScale.maxScale );
1039 
1040  // rendering
1041  layer->setCustomProperty( "labeling/scaleVisibility", scaleVisibility );
1042  layer->setCustomProperty( "labeling/scaleMin", scaleMin );
1043  layer->setCustomProperty( "labeling/scaleMax", scaleMax );
1044  layer->setCustomProperty( "labeling/fontLimitPixelSize", fontLimitPixelSize );
1045  layer->setCustomProperty( "labeling/fontMinPixelSize", fontMinPixelSize );
1046  layer->setCustomProperty( "labeling/fontMaxPixelSize", fontMaxPixelSize );
1047  layer->setCustomProperty( "labeling/displayAll", displayAll );
1048  layer->setCustomProperty( "labeling/upsidedownLabels", ( unsigned int )upsidedownLabels );
1049 
1050  layer->setCustomProperty( "labeling/labelPerPart", labelPerPart );
1051  layer->setCustomProperty( "labeling/mergeLines", mergeLines );
1052  layer->setCustomProperty( "labeling/minFeatureSize", minFeatureSize );
1053  layer->setCustomProperty( "labeling/limitNumLabels", limitNumLabels );
1054  layer->setCustomProperty( "labeling/maxNumLabels", maxNumLabels );
1055  layer->setCustomProperty( "labeling/obstacle", obstacle );
1056 
1057  writeDataDefinedPropertyMap( layer, dataDefinedProperties );
1058 }
1059 
1061  bool active, bool useExpr, const QString& expr, const QString& field )
1062 {
1063  bool defaultVals = ( !active && !useExpr && expr.isEmpty() && field.isEmpty() );
1064 
1065  if ( dataDefinedProperties.contains( p ) )
1066  {
1067  QMap< QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* >::const_iterator it = dataDefinedProperties.find( p );
1068  if ( it != dataDefinedProperties.constEnd() )
1069  {
1070  QgsDataDefined* dd = it.value();
1071  dd->setActive( active );
1072  dd->setUseExpression( useExpr );
1073  dd->setExpressionString( expr );
1074  dd->setField( field );
1075  }
1076  }
1077  else if ( !defaultVals )
1078  {
1079  QgsDataDefined* dd = new QgsDataDefined( active, useExpr, expr, field );
1080  dataDefinedProperties.insert( p, dd );
1081  }
1082 }
1083 
1085 {
1086  QMap< DataDefinedProperties, QgsDataDefined* >::iterator it = dataDefinedProperties.find( p );
1087  if ( it != dataDefinedProperties.end() )
1088  {
1089  delete( it.value() );
1090  dataDefinedProperties.erase( it );
1091  }
1092 }
1093 
1094 QString QgsPalLayerSettings::updateDataDefinedString( const QString& value )
1095 {
1096  // TODO: update or remove this when project settings for labeling are migrated to better XML layout
1097  QString newValue = value;
1098  if ( !value.isEmpty() && !value.contains( "~~" ) )
1099  {
1100  QStringList values;
1101  values << "1"; // all old-style values are active if not empty
1102  values << "0";
1103  values << "";
1104  values << value; // all old-style values are only field names
1105  newValue = values.join( "~~" );
1106  }
1107 
1108  return newValue;
1109 }
1110 
1112 {
1113  QMap< QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* >::const_iterator it = dataDefinedProperties.find( p );
1114  if ( it != dataDefinedProperties.constEnd() )
1115  {
1116  return it.value();
1117  }
1118  return 0;
1119 }
1120 
1122 {
1123  QMap<QString, QString> map;
1124  QMap< QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* >::const_iterator it = dataDefinedProperties.find( p );
1125  if ( it != dataDefinedProperties.constEnd() )
1126  {
1127  return it.value()->toMap();
1128  }
1129  return map;
1130 }
1131 
1133 {
1134  if ( !dataDefinedProperties.contains( p ) )
1135  {
1136  return QVariant();
1137  }
1138 
1139  QgsDataDefined* dd = 0;
1140  QMap< DataDefinedProperties, QgsDataDefined* >::const_iterator it = dataDefinedProperties.find( p );
1141  if ( it != dataDefinedProperties.constEnd() )
1142  {
1143  dd = it.value();
1144  }
1145 
1146  if ( !dd )
1147  {
1148  return QVariant();
1149  }
1150 
1151  if ( !dd->isActive() )
1152  {
1153  return QVariant();
1154  }
1155 
1156  QVariant result = QVariant();
1157  bool useExpression = dd->useExpression();
1158  QString field = dd->field();
1159 
1160  //QgsDebugMsgLevel( QString( "isActive:" ) + isActive ? "1" : "0", 4 );
1161  //QgsDebugMsgLevel( QString( "useExpression:" ) + useExpression ? "1" : "0", 4 );
1162  //QgsDebugMsgLevel( QString( "expression:" ) + dd->expressionString(), 4 );
1163  //QgsDebugMsgLevel( QString( "field:" ) + field, 4 );
1164 
1165  if ( useExpression && dd->expressionIsPrepared() )
1166  {
1167  QgsExpression* expr = dd->expression();
1168  //QgsDebugMsgLevel( QString( "expr columns:" ) + expr->referencedColumns().join( "," ), 4 );
1169 
1170  result = expr->evaluate( &f );
1171  if ( expr->hasEvalError() )
1172  {
1173  QgsDebugMsgLevel( QString( "Evaluate error:" ) + expr->evalErrorString(), 4 );
1174  return QVariant();
1175  }
1176  }
1177  else if ( !useExpression && !field.isEmpty() )
1178  {
1179  // use direct attribute access instead of evaluating "field" expression (much faster)
1180  int indx = fields.indexFromName( field );
1181  if ( indx != -1 )
1182  {
1183  result = f.attribute( indx );
1184  }
1185  }
1186  return result;
1187 }
1188 
1190 {
1191  // null passed-around QVariant
1192  exprVal.clear();
1193 
1194  QVariant result = dataDefinedValue( p, *mCurFeat, *mCurFields );
1195 
1196  if ( result.isValid() ) // filter NULL values? i.e. && !result.isNull()
1197  {
1198  //QgsDebugMsgLevel( QString( "result type:" ) + QString( result.typeName() ), 4 );
1199  //QgsDebugMsgLevel( QString( "result string:" ) + result.toString(), 4 );
1200  exprVal = result;
1201  return true;
1202  }
1203 
1204  return false;
1205 }
1206 
1208 {
1209  bool isActive = false;
1210  QMap< DataDefinedProperties, QgsDataDefined* >::const_iterator it = dataDefinedProperties.find( p );
1211  if ( it != dataDefinedProperties.constEnd() )
1212  {
1213  isActive = it.value()->isActive();
1214  }
1215 
1216  return isActive;
1217 }
1218 
1220 {
1221  bool useExpression = false;
1222  QMap< DataDefinedProperties, QgsDataDefined* >::const_iterator it = dataDefinedProperties.find( p );
1223  if ( it != dataDefinedProperties.constEnd() )
1224  {
1225  useExpression = it.value()->useExpression();
1226  }
1227 
1228  return useExpression;
1229 }
1230 
1231 bool QgsPalLayerSettings::checkMinimumSizeMM( const QgsRenderContext& ct, QgsGeometry* geom, double minSize ) const
1232 {
1233  if ( minSize <= 0 )
1234  {
1235  return true;
1236  }
1237 
1238  if ( !geom )
1239  {
1240  return false;
1241  }
1242 
1243  QGis::GeometryType featureType = geom->type();
1244  if ( featureType == QGis::Point ) //minimum size does not apply to point features
1245  {
1246  return true;
1247  }
1248 
1249  double mapUnitsPerMM = ct.mapToPixel().mapUnitsPerPixel() * ct.scaleFactor();
1250  if ( featureType == QGis::Line )
1251  {
1252  double length = geom->length();
1253  if ( length >= 0.0 )
1254  {
1255  return ( length >= ( minSize * mapUnitsPerMM ) );
1256  }
1257  }
1258  else if ( featureType == QGis::Polygon )
1259  {
1260  double area = geom->area();
1261  if ( area >= 0.0 )
1262  {
1263  return ( sqrt( area ) >= ( minSize * mapUnitsPerMM ) );
1264  }
1265  }
1266  return true; //should never be reached. Return true in this case to label such geometries anyway.
1267 }
1268 
1269 void QgsPalLayerSettings::calculateLabelSize( const QFontMetricsF* fm, QString text, double& labelX, double& labelY, QgsFeature* f )
1270 {
1271  if ( !fm || !f )
1272  {
1273  return;
1274  }
1275 
1276  QString wrapchr = wrapChar;
1277  double multilineH = multilineHeight;
1278 
1279  bool addDirSymb = addDirectionSymbol;
1280  QString leftDirSymb = leftDirectionSymbol;
1281  QString rightDirSymb = rightDirectionSymbol;
1283 
1284  if ( f == mCurFeat ) // called internally, use any stored data defined values
1285  {
1286  if ( dataDefinedValues.contains( QgsPalLayerSettings::MultiLineWrapChar ) )
1287  {
1288  wrapchr = dataDefinedValues.value( QgsPalLayerSettings::MultiLineWrapChar ).toString();
1289  }
1290 
1291  if ( dataDefinedValues.contains( QgsPalLayerSettings::MultiLineHeight ) )
1292  {
1293  multilineH = dataDefinedValues.value( QgsPalLayerSettings::MultiLineHeight ).toDouble();
1294  }
1295 
1296  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbDraw ) )
1297  {
1298  addDirSymb = dataDefinedValues.value( QgsPalLayerSettings::DirSymbDraw ).toBool();
1299  }
1300 
1301  if ( addDirSymb )
1302  {
1303 
1304  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbLeft ) )
1305  {
1306  leftDirSymb = dataDefinedValues.value( QgsPalLayerSettings::DirSymbLeft ).toString();
1307  }
1308  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbRight ) )
1309  {
1310  rightDirSymb = dataDefinedValues.value( QgsPalLayerSettings::DirSymbRight ).toString();
1311  }
1312 
1313  if ( dataDefinedValues.contains( QgsPalLayerSettings::DirSymbPlacement ) )
1314  {
1315  placeDirSymb = ( QgsPalLayerSettings::DirectionSymbols )dataDefinedValues.value( QgsPalLayerSettings::DirSymbPlacement ).toInt();
1316  }
1317 
1318  }
1319 
1320  }
1321  else // called externally with passed-in feature, evaluate data defined
1322  {
1324  if ( exprVal.isValid() )
1325  {
1326  wrapchr = exprVal.toString();
1327  }
1328  exprVal.clear();
1330  if ( exprVal.isValid() )
1331  {
1332  bool ok;
1333  double size = exprVal.toDouble( &ok );
1334  if ( ok )
1335  {
1336  multilineH = size;
1337  }
1338  }
1339 
1340  exprVal.clear();
1342  if ( exprVal.isValid() )
1343  {
1344  addDirSymb = exprVal.toBool();
1345  }
1346 
1347  if ( addDirSymb ) // don't do extra evaluations if not adding a direction symbol
1348  {
1349  exprVal.clear();
1351  if ( exprVal.isValid() )
1352  {
1353  leftDirSymb = exprVal.toString();
1354  }
1355  exprVal.clear();
1357  if ( exprVal.isValid() )
1358  {
1359  rightDirSymb = exprVal.toString();
1360  }
1361  exprVal.clear();
1363  if ( exprVal.isValid() )
1364  {
1365  bool ok;
1366  int enmint = exprVal.toInt( &ok );
1367  if ( ok )
1368  {
1369  placeDirSymb = ( QgsPalLayerSettings::DirectionSymbols )enmint;
1370  }
1371  }
1372  }
1373 
1374  }
1375 
1376  if ( wrapchr.isEmpty() )
1377  {
1378  wrapchr = QString( "\n" ); // default to new line delimiter
1379  }
1380 
1381  //consider the space needed for the direction symbol
1382  if ( addDirSymb && placement == QgsPalLayerSettings::Line
1383  && ( !leftDirSymb.isEmpty() || !rightDirSymb.isEmpty() ) )
1384  {
1385  QString dirSym = leftDirSymb;
1386 
1387  if ( fm->width( rightDirSymb ) > fm->width( dirSym ) )
1388  dirSym = rightDirSymb;
1389 
1390  if ( placeDirSymb == QgsPalLayerSettings::SymbolLeftRight )
1391  {
1392  text.append( dirSym );
1393  }
1394  else
1395  {
1396  text.prepend( dirSym + wrapchr ); // SymbolAbove or SymbolBelow
1397  }
1398  }
1399 
1400  double w = 0.0, h = 0.0;
1401  QStringList multiLineSplit = text.split( wrapchr );
1402  int lines = multiLineSplit.size();
1403 
1404  double labelHeight = fm->ascent() + fm->descent(); // ignore +1 for baseline
1405 
1406  h += fm->height() + ( double )(( lines - 1 ) * labelHeight * multilineH );
1407  h /= rasterCompressFactor;
1408 
1409  for ( int i = 0; i < lines; ++i )
1410  {
1411  double width = fm->width( multiLineSplit.at( i ) );
1412  if ( width > w )
1413  {
1414  w = width;
1415  }
1416  }
1417  w /= rasterCompressFactor;
1418  QgsPoint ptSize = xform->toMapCoordinatesF( w, h );
1419 
1420  labelX = qAbs( ptSize.x() - ptZero.x() );
1421  labelY = qAbs( ptSize.y() - ptZero.y() );
1422 }
1423 
1424 void QgsPalLayerSettings::registerFeature( QgsFeature& f, const QgsRenderContext& context, QString dxfLayer )
1425 {
1426  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
1427  mCurFeat = &f;
1428 // mCurFields = &layer->pendingFields();
1429 
1430  // store data defined-derived values for later adding to QgsPalGeometry for use during rendering
1431  dataDefinedValues.clear();
1432 
1433  // data defined show label? defaults to show label if not 0
1435  {
1436  QgsDebugMsgLevel( QString( "exprVal Show:%1" ).arg( exprVal.toBool() ? "true" : "false" ), 4 );
1437  if ( !exprVal.toBool() )
1438  {
1439  return;
1440  }
1441  }
1442 
1443  // data defined scale visibility?
1444  bool useScaleVisibility = scaleVisibility;
1446  {
1447  QgsDebugMsgLevel( QString( "exprVal ScaleVisibility:%1" ).arg( exprVal.toBool() ? "true" : "false" ), 4 );
1448  useScaleVisibility = exprVal.toBool();
1449  }
1450 
1451  if ( useScaleVisibility )
1452  {
1453  // data defined min scale?
1454  double minScale = scaleMin;
1456  {
1457  QgsDebugMsgLevel( QString( "exprVal MinScale:%1" ).arg( exprVal.toDouble() ), 4 );
1458  bool conversionOk;
1459  double mins = exprVal.toDouble( &conversionOk );
1460  if ( conversionOk )
1461  {
1462  minScale = mins;
1463  }
1464  }
1465 
1466  // scales closer than 1:1
1467  if ( minScale < 0 )
1468  {
1469  minScale = 1 / qAbs( minScale );
1470  }
1471 
1472  if ( minScale != 0 && context.rendererScale() < minScale )
1473  {
1474  return;
1475  }
1476 
1477  // data defined max scale?
1478  double maxScale = scaleMax;
1480  {
1481  QgsDebugMsgLevel( QString( "exprVal MaxScale:%1" ).arg( exprVal.toDouble() ), 4 );
1482  bool conversionOk;
1483  double maxs = exprVal.toDouble( &conversionOk );
1484  if ( conversionOk )
1485  {
1486  maxScale = maxs;
1487  }
1488  }
1489 
1490  // scales closer than 1:1
1491  if ( maxScale < 0 )
1492  {
1493  maxScale = 1 / qAbs( maxScale );
1494  }
1495 
1496  if ( maxScale != 0 && context.rendererScale() > maxScale )
1497  {
1498  return;
1499  }
1500  }
1501 
1502  QFont labelFont = textFont;
1503  // labelFont will be added to label's QgsPalGeometry for use during label painting
1504 
1505  // data defined font units?
1508  {
1509  QString units = exprVal.toString().trimmed();
1510  QgsDebugMsgLevel( QString( "exprVal Font units:%1" ).arg( units ), 4 );
1511  if ( !units.isEmpty() )
1512  {
1513  fontunits = _decodeUnits( units );
1514  }
1515  }
1516 
1517  //data defined label size?
1518  double fontSize = labelFont.pointSizeF(); // font size doesn't have its own class data member
1520  {
1521  QgsDebugMsgLevel( QString( "exprVal Size:%1" ).arg( exprVal.toDouble() ), 4 );
1522  bool ok;
1523  double size = exprVal.toDouble( &ok );
1524  if ( ok )
1525  {
1526  fontSize = size;
1527  }
1528  }
1529  if ( fontSize <= 0.0 )
1530  {
1531  return;
1532  }
1533 
1534  int fontPixelSize = sizeToPixel( fontSize, context, fontunits, true, fontSizeMapUnitScale );
1535  // don't try to show font sizes less than 1 pixel (Qt complains)
1536  if ( fontPixelSize < 1 )
1537  {
1538  return;
1539  }
1540  labelFont.setPixelSize( fontPixelSize );
1541 
1542  // NOTE: labelFont now always has pixelSize set, so pointSize or pointSizeF might return -1
1543 
1544  // defined 'minimum/maximum pixel font size'?
1545  if ( fontunits == QgsPalLayerSettings::MapUnits )
1546  {
1547  bool useFontLimitPixelSize = fontLimitPixelSize;
1549  {
1550  QgsDebugMsgLevel( QString( "exprVal FontLimitPixel:%1" ).arg( exprVal.toBool() ? "true" : "false" ), 4 );
1551  useFontLimitPixelSize = exprVal.toBool();
1552  }
1553 
1554  if ( useFontLimitPixelSize )
1555  {
1556  int fontMinPixel = fontMinPixelSize;
1558  {
1559  bool ok;
1560  int sizeInt = exprVal.toInt( &ok );
1561  QgsDebugMsgLevel( QString( "exprVal FontMinPixel:%1" ).arg( sizeInt ), 4 );
1562  if ( ok )
1563  {
1564  fontMinPixel = sizeInt;
1565  }
1566  }
1567 
1568  int fontMaxPixel = fontMaxPixelSize;
1570  {
1571  bool ok;
1572  int sizeInt = exprVal.toInt( &ok );
1573  QgsDebugMsgLevel( QString( "exprVal FontMaxPixel:%1" ).arg( sizeInt ), 4 );
1574  if ( ok )
1575  {
1576  fontMaxPixel = sizeInt;
1577  }
1578  }
1579 
1580  if ( fontMinPixel > labelFont.pixelSize() || labelFont.pixelSize() > fontMaxPixel )
1581  {
1582  return;
1583  }
1584  }
1585  }
1586 
1587  // NOTE: the following parsing functions calculate and store any data defined values for later use in QgsPalLabeling::drawLabeling
1588  // this is done to provide clarity, and because such parsing is not directly related to PAL feature registration calculations
1589 
1590  // calculate rest of font attributes and store any data defined values
1591  // this is done here for later use in making label backgrounds part of collision management (when implemented)
1592  parseTextStyle( labelFont, fontunits, context );
1593  parseTextFormatting();
1594  parseTextBuffer();
1595  parseShapeBackground();
1596  parseDropShadow();
1597 
1598  QString labelText;
1599 
1600  // Check to see if we are a expression string.
1601  if ( isExpression )
1602  {
1604  if ( exp->hasParserError() )
1605  {
1606  QgsDebugMsgLevel( QString( "Expression parser error:%1" ).arg( exp->parserErrorString() ), 4 );
1607  return;
1608  }
1609  exp->setScale( context.rendererScale() );
1610 // QVariant result = exp->evaluate( &f, layer->pendingFields() );
1611  QVariant result = exp->evaluate( &f ); // expression prepared in QgsPalLabeling::prepareLayer()
1612  if ( exp->hasEvalError() )
1613  {
1614  QgsDebugMsgLevel( QString( "Expression parser eval error:%1" ).arg( exp->evalErrorString() ), 4 );
1615  return;
1616  }
1617  labelText = result.isNull() ? "" : result.toString();
1618  }
1619  else
1620  {
1621  const QVariant &v = f.attribute( fieldIndex );
1622  labelText = v.isNull() ? "" : v.toString();
1623  }
1624 
1625  // data defined format numbers?
1626  bool formatnum = formatNumbers;
1628  {
1629  formatnum = exprVal.toBool();
1630  QgsDebugMsgLevel( QString( "exprVal NumFormat:%1" ).arg( formatnum ? "true" : "false" ), 4 );
1631  }
1632 
1633  // format number if label text is coercible to a number
1634  if ( formatnum )
1635  {
1636  // data defined decimal places?
1637  int decimalPlaces = decimals;
1639  {
1640  bool ok;
1641  int dInt = exprVal.toInt( &ok );
1642  QgsDebugMsgLevel( QString( "exprVal NumDecimals:%1" ).arg( dInt ), 4 );
1643  if ( ok && dInt > 0 ) // needs to be positive
1644  {
1645  decimalPlaces = dInt;
1646  }
1647  }
1648 
1649  // data defined plus sign?
1650  bool signPlus = plusSign;
1652  {
1653  signPlus = exprVal.toBool();
1654  QgsDebugMsgLevel( QString( "exprVal NumPlusSign:%1" ).arg( signPlus ? "true" : "false" ), 4 );
1655  }
1656 
1657  QVariant textV( labelText );
1658  bool ok;
1659  double d = textV.toDouble( &ok );
1660  if ( ok )
1661  {
1662  QString numberFormat;
1663  if ( d > 0 && signPlus )
1664  {
1665  numberFormat.append( "+" );
1666  }
1667  numberFormat.append( "%1" );
1668  labelText = numberFormat.arg( d, 0, 'f', decimalPlaces );
1669  }
1670  }
1671 
1672 
1673  // NOTE: this should come AFTER any option that affects font metrics
1674  QFontMetricsF* labelFontMetrics = new QFontMetricsF( labelFont );
1675  double labelX, labelY; // will receive label size
1676  calculateLabelSize( labelFontMetrics, labelText, labelX, labelY, mCurFeat );
1677 
1678 
1679  // maximum angle between curved label characters (hardcoded defaults used in QGIS <2.0)
1680  //
1681  double maxcharanglein = 20.0; // range 20.0-60.0
1682  double maxcharangleout = -20.0; // range 20.0-95.0
1683 
1685  {
1686  maxcharanglein = maxCurvedCharAngleIn;
1687  maxcharangleout = maxCurvedCharAngleOut;
1688 
1689  //data defined maximum angle between curved label characters?
1691  {
1692  QString ptstr = exprVal.toString().trimmed();
1693  QgsDebugMsgLevel( QString( "exprVal CurvedCharAngleInOut:%1" ).arg( ptstr ), 4 );
1694 
1695  if ( !ptstr.isEmpty() )
1696  {
1697  QPointF maxcharanglePt = QgsSymbolLayerV2Utils::decodePoint( ptstr );
1698  maxcharanglein = qBound( 20.0, ( double )maxcharanglePt.x(), 60.0 );
1699  maxcharangleout = qBound( 20.0, ( double )maxcharanglePt.y(), 95.0 );
1700  }
1701  }
1702  // make sure maxcharangleout is always negative
1703  maxcharangleout = -( qAbs( maxcharangleout ) );
1704  }
1705 
1706  QgsGeometry* geom = f.geometry();
1707  if ( !geom )
1708  {
1709  return;
1710  }
1711 
1712  // reproject the geometry if necessary (but don't modify the features
1713  // geometry so that geometry based expression keep working)
1714  QScopedPointer<QgsGeometry> clonedGeometry;
1715  if ( ct )
1716  {
1717  geom = new QgsGeometry( *geom );
1718  clonedGeometry.reset( geom );
1719 
1720  try
1721  {
1722  geom->transform( *ct );
1723  }
1724  catch ( QgsCsException &cse )
1725  {
1726  Q_UNUSED( cse );
1727  QgsDebugMsgLevel( QString( "Ignoring feature %1 due transformation exception" ).arg( f.id() ), 4 );
1728  return;
1729  }
1730  }
1731 
1732  if ( !checkMinimumSizeMM( context, geom, minFeatureSize ) )
1733  {
1734  return;
1735  }
1736 
1737  // whether we're going to create a centroid for polygon
1738  bool centroidPoly = (( placement == QgsPalLayerSettings::AroundPoint
1740  && geom->type() == QGis::Polygon );
1741 
1742  // data defined centroid whole or clipped?
1743  bool wholeCentroid = centroidWhole;
1745  {
1746  QString str = exprVal.toString().trimmed();
1747  QgsDebugMsgLevel( QString( "exprVal CentroidWhole:%1" ).arg( str ), 4 );
1748 
1749  if ( !str.isEmpty() )
1750  {
1751  if ( str.compare( "Visible", Qt::CaseInsensitive ) == 0 )
1752  {
1753  wholeCentroid = false;
1754  }
1755  else if ( str.compare( "Whole", Qt::CaseInsensitive ) == 0 )
1756  {
1757  wholeCentroid = true;
1758  }
1759  }
1760  }
1761 
1762  if ( !geom->asGeos() )
1763  return; // there is something really wrong with the geometry
1764 
1765  // fix invalid polygons
1766  if ( geom->type() == QGis::Polygon && !geom->isGeosValid() )
1767  {
1768  QgsGeometry* bufferGeom = geom->buffer( 0, 0 );
1769  if ( !bufferGeom )
1770  {
1771  return;
1772  }
1773  geom = bufferGeom;
1774  clonedGeometry.reset( geom );
1775  }
1776 
1777  // CLIP the geometry if it is bigger than the extent
1778  // don't clip if centroid is requested for whole feature
1779  bool do_clip = false;
1780  if ( !centroidPoly || ( centroidPoly && !wholeCentroid ) )
1781  {
1782  do_clip = !extentGeom->contains( geom );
1783  if ( do_clip )
1784  {
1785  QgsGeometry* clipGeom = geom->intersection( extentGeom ); // creates new geometry
1786  if ( !clipGeom )
1787  {
1788  return;
1789  }
1790  geom = clipGeom;
1791  clonedGeometry.reset( geom );
1792  }
1793  }
1794 
1795  const GEOSGeometry* geos_geom = geom->asGeos();
1796 
1797  if ( geos_geom == NULL )
1798  return; // invalid geometry
1799 
1800  // likelihood exists label will be registered with PAL and may be drawn
1801  // check if max number of features to label (already registered with PAL) has been reached
1802  // Debug output at end of QgsPalLabeling::drawLabeling(), when deleting temp geometries
1803  if ( limitNumLabels )
1804  {
1805  if ( !maxNumLabels )
1806  {
1807  return;
1808  }
1810  if ( mFeatsRegPal >= maxNumLabels )
1811  {
1812  return;
1813  }
1814 
1815  int divNum = ( int )(( mFeaturesToLabel / maxNumLabels ) + 0.5 );
1816  if ( divNum && ( mFeatsRegPal == ( int )( mFeatsSendingToPal / divNum ) ) )
1817  {
1818  mFeatsSendingToPal += 1;
1819  if ( divNum && mFeatsSendingToPal % divNum )
1820  {
1821  return;
1822  }
1823  }
1824  }
1825 
1826  GEOSGeometry* geos_geom_clone;
1827  if ( GEOSGeomTypeId_r( QgsGeometry::getGEOSHandler(), geos_geom ) == GEOS_POLYGON && repeatDistance > 0 && placement == Line )
1828  {
1829  geos_geom_clone = GEOSBoundary_r( QgsGeometry::getGEOSHandler(), geos_geom );
1830  }
1831  else
1832  {
1833  geos_geom_clone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom );
1834  }
1835 
1836  //data defined position / alignment / rotation?
1837  bool dataDefinedPosition = false;
1838  bool labelIsPinned = false;
1839  bool layerDefinedRotation = false;
1840  bool dataDefinedRotation = false;
1841  double xPos = 0.0, yPos = 0.0, angle = 0.0;
1842  bool ddXPos = false, ddYPos = false;
1843  double quadOffsetX = 0.0, quadOffsetY = 0.0;
1844  double offsetX = 0.0, offsetY = 0.0;
1845 
1846  //data defined quadrant offset?
1847  QuadrantPosition quadOff = quadOffset;
1849  {
1850  bool ok;
1851  int quadInt = exprVal.toInt( &ok );
1852  QgsDebugMsgLevel( QString( "exprVal OffsetQuad:%1" ).arg( quadInt ), 4 );
1853  if ( ok && 0 <= quadInt && quadInt <= 8 )
1854  {
1855  quadOff = ( QuadrantPosition )quadInt;
1856  }
1857  }
1858 
1859  // adjust quadrant offset of labels
1860  switch ( quadOff )
1861  {
1862  case QuadrantAboveLeft:
1863  quadOffsetX = -1.0;
1864  quadOffsetY = 1.0;
1865  break;
1866  case QuadrantAbove:
1867  quadOffsetX = 0.0;
1868  quadOffsetY = 1.0;
1869  break;
1870  case QuadrantAboveRight:
1871  quadOffsetX = 1.0;
1872  quadOffsetY = 1.0;
1873  break;
1874  case QuadrantLeft:
1875  quadOffsetX = -1.0;
1876  quadOffsetY = 0.0;
1877  break;
1878  case QuadrantRight:
1879  quadOffsetX = 1.0;
1880  quadOffsetY = 0.0;
1881  break;
1882  case QuadrantBelowLeft:
1883  quadOffsetX = -1.0;
1884  quadOffsetY = -1.0;
1885  break;
1886  case QuadrantBelow:
1887  quadOffsetX = 0.0;
1888  quadOffsetY = -1.0;
1889  break;
1890  case QuadrantBelowRight:
1891  quadOffsetX = 1.0;
1892  quadOffsetY = -1.0;
1893  break;
1894  case QuadrantOver:
1895  default:
1896  break;
1897  }
1898 
1899  //data defined label offset?
1900  double xOff = xOffset;
1901  double yOff = yOffset;
1903  {
1904  QString ptstr = exprVal.toString().trimmed();
1905  QgsDebugMsgLevel( QString( "exprVal OffsetXY:%1" ).arg( ptstr ), 4 );
1906 
1907  if ( !ptstr.isEmpty() )
1908  {
1909  QPointF ddOffPt = QgsSymbolLayerV2Utils::decodePoint( ptstr );
1910  xOff = ddOffPt.x();
1911  yOff = ddOffPt.y();
1912  }
1913  }
1914 
1915  // data defined label offset units?
1916  bool offinmapunits = labelOffsetInMapUnits;
1918  {
1919  QString units = exprVal.toString().trimmed();
1920  QgsDebugMsgLevel( QString( "exprVal OffsetUnits:%1" ).arg( units ), 4 );
1921  if ( !units.isEmpty() )
1922  {
1923  offinmapunits = ( _decodeUnits( units ) == QgsPalLayerSettings::MapUnits );
1924  }
1925  }
1926 
1927  // adjust offset of labels to match chosen unit and map scale
1928  // offsets match those of symbology: -x = left, -y = up
1929  double mapUntsPerMM = labelOffsetMapUnitScale.computeMapUnitsPerPixel( context ) * context.scaleFactor();
1930  if ( xOff != 0 )
1931  {
1932  offsetX = xOff; // must be positive to match symbology offset direction
1933  if ( !offinmapunits )
1934  {
1935  offsetX *= mapUntsPerMM; //convert offset from mm to map units
1936  }
1937  }
1938  if ( yOff != 0 )
1939  {
1940  offsetY = -yOff; // must be negative to match symbology offset direction
1941  if ( !offinmapunits )
1942  {
1943  offsetY *= mapUntsPerMM; //convert offset from mm to map units
1944  }
1945  }
1946 
1947  // layer defined rotation?
1948  // only rotate non-pinned OverPoint placements until other placements are supported in pal::Feature
1949  if ( placement == QgsPalLayerSettings::OverPoint && angleOffset != 0 )
1950  {
1951  layerDefinedRotation = true;
1952  angle = angleOffset * M_PI / 180; // convert to radians
1953  }
1954 
1955  //data defined rotation?
1957  {
1958  bool ok;
1959  double rotD = exprVal.toDouble( &ok );
1960  QgsDebugMsgLevel( QString( "exprVal Rotation:%1" ).arg( rotD ), 4 );
1961  if ( ok )
1962  {
1963  dataDefinedRotation = true;
1964  angle = rotD * M_PI / 180.0;
1965  }
1966  }
1967 
1969  {
1970  if ( !exprVal.isNull() )
1971  xPos = exprVal.toDouble( &ddXPos );
1972  QgsDebugMsgLevel( QString( "exprVal PositionX:%1" ).arg( xPos ), 4 );
1973 
1975  {
1976  //data defined position. But field values could be NULL -> positions will be generated by PAL
1977  if ( !exprVal.isNull() )
1978  yPos = exprVal.toDouble( &ddYPos );
1979  QgsDebugMsgLevel( QString( "exprVal PositionY:%1" ).arg( yPos ), 4 );
1980 
1981  if ( ddXPos && ddYPos )
1982  {
1983  dataDefinedPosition = true;
1984  labelIsPinned = true;
1985  // layer rotation set, but don't rotate pinned labels unless data defined
1986  if ( layerDefinedRotation && !dataDefinedRotation )
1987  {
1988  angle = 0.0;
1989  }
1990 
1991  //x/y shift in case of alignment
1992  double xdiff = 0.0;
1993  double ydiff = 0.0;
1994 
1995  //horizontal alignment
1997  {
1998  QString haliString = exprVal.toString();
1999  QgsDebugMsgLevel( QString( "exprVal Hali:%1" ).arg( haliString ), 4 );
2000  if ( haliString.compare( "Center", Qt::CaseInsensitive ) == 0 )
2001  {
2002  xdiff -= labelX / 2.0;
2003  }
2004  else if ( haliString.compare( "Right", Qt::CaseInsensitive ) == 0 )
2005  {
2006  xdiff -= labelX;
2007  }
2008  }
2009 
2010  //vertical alignment
2012  {
2013  QString valiString = exprVal.toString();
2014  QgsDebugMsgLevel( QString( "exprVal Vali:%1" ).arg( valiString ), 4 );
2015 
2016  if ( valiString.compare( "Bottom", Qt::CaseInsensitive ) != 0 )
2017  {
2018  if ( valiString.compare( "Top", Qt::CaseInsensitive ) == 0 )
2019  {
2020  ydiff -= labelY;
2021  }
2022  else
2023  {
2024  double descentRatio = labelFontMetrics->descent() / labelFontMetrics->height();
2025  if ( valiString.compare( "Base", Qt::CaseInsensitive ) == 0 )
2026  {
2027  ydiff -= labelY * descentRatio;
2028  }
2029  else //'Cap' or 'Half'
2030  {
2031  double capHeightRatio = ( labelFontMetrics->boundingRect( 'H' ).height() + 1 + labelFontMetrics->descent() ) / labelFontMetrics->height();
2032  ydiff -= labelY * capHeightRatio;
2033  if ( valiString.compare( "Half", Qt::CaseInsensitive ) == 0 )
2034  {
2035  ydiff += labelY * ( capHeightRatio - descentRatio ) / 2.0;
2036  }
2037  }
2038  }
2039  }
2040  }
2041 
2042  if ( dataDefinedRotation )
2043  {
2044  //adjust xdiff and ydiff because the hali/vali point needs to be the rotation center
2045  double xd = xdiff * cos( angle ) - ydiff * sin( angle );
2046  double yd = xdiff * sin( angle ) + ydiff * cos( angle );
2047  xdiff = xd;
2048  ydiff = yd;
2049  }
2050 
2051  //project xPos and yPos from layer to map CRS
2052  double z = 0;
2053  if ( ct )
2054  {
2055  try
2056  {
2057  ct->transformInPlace( xPos, yPos, z );
2058  }
2059  catch ( QgsCsException &e )
2060  {
2061  Q_UNUSED( e );
2062  QgsDebugMsgLevel( QString( "Ignoring feature %1 due transformation exception on data-defined position" ).arg( f.id() ), 4 );
2063  return;
2064  }
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 #if QT_VERSION >= 0x040800
2103  QgsDebugMsgLevel( QString( "PAL font stored definedFont: %1, Style: %2" ).arg( labelFont.toString() ).arg( labelFont.styleName() ), 4 );
2104 #endif
2105  lbl->setDefinedFont( labelFont );
2106 
2107  // set repeat distance
2108  // data defined repeat distance?
2109  double repeatDist = repeatDistance;
2111  {
2112  bool ok;
2113  double distD = exprVal.toDouble( &ok );
2114  if ( ok )
2115  {
2116  repeatDist = distD;
2117  }
2118  }
2119 
2120  // data defined label-repeat distance units?
2121  bool repeatdistinmapunit = repeatDistanceUnit == QgsPalLayerSettings::MapUnits;
2123  {
2124  QString units = exprVal.toString().trimmed();
2125  QgsDebugMsgLevel( QString( "exprVal RepeatDistanceUnits:%1" ).arg( units ), 4 );
2126  if ( !units.isEmpty() )
2127  {
2128  repeatdistinmapunit = ( _decodeUnits( units ) == QgsPalLayerSettings::MapUnits );
2129  }
2130  }
2131 
2132  if ( repeatDist != 0 )
2133  {
2134  if ( repeatdistinmapunit ) //convert distance from mm/map units to pixels
2135  {
2136  repeatDist /= repeatDistanceMapUnitScale.computeMapUnitsPerPixel( context ) * context.scaleFactor();
2137  }
2138  else //mm
2139  {
2140  repeatDist *= vectorScaleFactor;
2141  }
2142  repeatDist *= qAbs( ptOne.x() - ptZero.x() );
2143  }
2144 
2145  // feature to the layer
2146  try
2147  {
2148  if ( !palLayer->registerFeature( lbl->strId(), lbl, labelX, labelY, labelText.toUtf8().constData(),
2149  xPos, yPos, dataDefinedPosition, angle, dataDefinedRotation,
2150  quadOffsetX, quadOffsetY, offsetX, offsetY, alwaysShow, repeatDist ) )
2151  return;
2152  }
2153  catch ( std::exception &e )
2154  {
2155  Q_UNUSED( e );
2156  QgsDebugMsgLevel( QString( "Ignoring feature %1 due PAL exception:" ).arg( f.id() ) + QString::fromLatin1( e.what() ), 4 );
2157  return;
2158  }
2159 
2160  // TODO: only for placement which needs character info
2161  pal::Feature* feat = palLayer->getFeature( lbl->strId() );
2162  // account for any data defined font metrics adjustments
2163  feat->setLabelInfo( lbl->info( labelFontMetrics, xform, rasterCompressFactor, maxcharanglein, maxcharangleout ) );
2164  delete labelFontMetrics;
2165 
2166  // TODO: allow layer-wide feature dist in PAL...?
2167 
2168  // data defined label-feature distance?
2169  double distance = dist;
2171  {
2172  bool ok;
2173  double distD = exprVal.toDouble( &ok );
2174  if ( ok )
2175  {
2176  distance = distD;
2177  }
2178  }
2179 
2180  // data defined label-feature distance units?
2181  bool distinmapunit = distInMapUnits;
2183  {
2184  QString units = exprVal.toString().trimmed();
2185  QgsDebugMsgLevel( QString( "exprVal DistanceUnits:%1" ).arg( units ), 4 );
2186  if ( !units.isEmpty() )
2187  {
2188  distinmapunit = ( _decodeUnits( units ) == QgsPalLayerSettings::MapUnits );
2189  }
2190  }
2191 
2192  if ( distance != 0 )
2193  {
2194  if ( distinmapunit ) //convert distance from mm/map units to pixels
2195  {
2196  distance /= distMapUnitScale.computeMapUnitsPerPixel( context );
2197  }
2198  else //mm
2199  {
2200  distance *= vectorScaleFactor;
2201  }
2202  feat->setDistLabel( qAbs( ptOne.x() - ptZero.x() )* distance );
2203  }
2204 
2205 
2206  //add parameters for data defined labeling to QgsPalGeometry
2207  QMap< DataDefinedProperties, QVariant >::const_iterator dIt = dataDefinedValues.constBegin();
2208  for ( ; dIt != dataDefinedValues.constEnd(); ++dIt )
2209  {
2210  lbl->addDataDefinedValue( dIt.key(), dIt.value() );
2211  }
2212 
2213  // set geometry's pinned property
2214  lbl->setIsPinned( labelIsPinned );
2215 }
2216 
2217 bool QgsPalLayerSettings::dataDefinedValEval( const QString& valType,
2219  QVariant& exprVal )
2220 {
2221  if ( dataDefinedEvaluate( p, exprVal ) )
2222  {
2223  QString dbgStr = QString( "exprVal %1:" ).arg( mDataDefinedNames.value( p ).first ) + "%1";
2224 
2225  if ( valType == QString( "bool" ) )
2226  {
2227  bool bol = exprVal.toBool();
2228  QgsDebugMsgLevel( dbgStr.arg( bol ? "true" : "false" ), 4 );
2229  dataDefinedValues.insert( p, QVariant( bol ) );
2230  return true;
2231  }
2232  if ( valType == QString( "int" ) )
2233  {
2234  bool ok;
2235  int size = exprVal.toInt( &ok );
2236  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2237 
2238  if ( ok )
2239  {
2240  dataDefinedValues.insert( p, QVariant( size ) );
2241  return true;
2242  }
2243  }
2244  if ( valType == QString( "intpos" ) )
2245  {
2246  bool ok;
2247  int size = exprVal.toInt( &ok );
2248  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2249 
2250  if ( ok && size > 0 )
2251  {
2252  dataDefinedValues.insert( p, QVariant( size ) );
2253  return true;
2254  }
2255  }
2256  if ( valType == QString( "double" ) )
2257  {
2258  bool ok;
2259  double size = exprVal.toDouble( &ok );
2260  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2261 
2262  if ( ok )
2263  {
2264  dataDefinedValues.insert( p, QVariant( size ) );
2265  return true;
2266  }
2267  }
2268  if ( valType == QString( "doublepos" ) )
2269  {
2270  bool ok;
2271  double size = exprVal.toDouble( &ok );
2272  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2273 
2274  if ( ok && size > 0.0 )
2275  {
2276  dataDefinedValues.insert( p, QVariant( size ) );
2277  return true;
2278  }
2279  }
2280  if ( valType == QString( "rotation180" ) )
2281  {
2282  bool ok;
2283  double rot = exprVal.toDouble( &ok );
2284  QgsDebugMsgLevel( dbgStr.arg( rot ), 4 );
2285  if ( ok )
2286  {
2287  if ( rot < -180.0 && rot >= -360 )
2288  {
2289  rot += 360;
2290  }
2291  if ( rot > 180.0 && rot <= 360 )
2292  {
2293  rot -= 360;
2294  }
2295  if ( rot >= -180 && rot <= 180 )
2296  {
2297  dataDefinedValues.insert( p, QVariant( rot ) );
2298  return true;
2299  }
2300  }
2301  }
2302  if ( valType == QString( "transp" ) )
2303  {
2304  bool ok;
2305  int size = exprVal.toInt( &ok );
2306  QgsDebugMsgLevel( dbgStr.arg( size ), 4 );
2307  if ( ok && size >= 0 && size <= 100 )
2308  {
2309  dataDefinedValues.insert( p, QVariant( size ) );
2310  return true;
2311  }
2312  }
2313  if ( valType == QString( "string" ) )
2314  {
2315  QString str = exprVal.toString(); // don't trim whitespace
2316  QgsDebugMsgLevel( dbgStr.arg( str ), 4 );
2317 
2318  dataDefinedValues.insert( p, QVariant( str ) ); // let it stay empty if it is
2319  return true;
2320  }
2321  if ( valType == QString( "units" ) )
2322  {
2323  QString unitstr = exprVal.toString().trimmed();
2324  QgsDebugMsgLevel( dbgStr.arg( unitstr ), 4 );
2325 
2326  if ( !unitstr.isEmpty() )
2327  {
2328  dataDefinedValues.insert( p, QVariant(( int )_decodeUnits( unitstr ) ) );
2329  return true;
2330  }
2331  }
2332  if ( valType == QString( "color" ) )
2333  {
2334  QString colorstr = exprVal.toString().trimmed();
2335  QgsDebugMsgLevel( dbgStr.arg( colorstr ), 4 );
2336  QColor color = QgsSymbolLayerV2Utils::decodeColor( colorstr );
2337 
2338  if ( color.isValid() )
2339  {
2340  dataDefinedValues.insert( p, QVariant( color ) );
2341  return true;
2342  }
2343  }
2344  if ( valType == QString( "joinstyle" ) )
2345  {
2346  QString joinstr = exprVal.toString().trimmed();
2347  QgsDebugMsgLevel( dbgStr.arg( joinstr ), 4 );
2348 
2349  if ( !joinstr.isEmpty() )
2350  {
2351  dataDefinedValues.insert( p, QVariant(( int )_decodePenJoinStyle( joinstr ) ) );
2352  return true;
2353  }
2354  }
2355  if ( valType == QString( "blendmode" ) )
2356  {
2357  QString blendstr = exprVal.toString().trimmed();
2358  QgsDebugMsgLevel( dbgStr.arg( blendstr ), 4 );
2359 
2360  if ( !blendstr.isEmpty() )
2361  {
2362  dataDefinedValues.insert( p, QVariant(( int )QgsSymbolLayerV2Utils::decodeBlendMode( blendstr ) ) );
2363  return true;
2364  }
2365  }
2366  if ( valType == QString( "pointf" ) )
2367  {
2368  QString ptstr = exprVal.toString().trimmed();
2369  QgsDebugMsgLevel( dbgStr.arg( ptstr ), 4 );
2370 
2371  if ( !ptstr.isEmpty() )
2372  {
2373  dataDefinedValues.insert( p, QVariant( QgsSymbolLayerV2Utils::decodePoint( ptstr ) ) );
2374  return true;
2375  }
2376  }
2377  }
2378  return false;
2379 }
2380 
2381 void QgsPalLayerSettings::parseTextStyle( QFont& labelFont,
2383  const QgsRenderContext& context )
2384 {
2385  // NOTE: labelFont already has pixelSize set, so pointSize or pointSizeF might return -1
2386 
2387  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2388 
2389  // Two ways to generate new data defined font:
2390  // 1) Family + [bold] + [italic] (named style is ignored and font is built off of base family)
2391  // 2) Family + named style (bold or italic is ignored)
2392 
2393  // data defined font family?
2394  QString ddFontFamily( "" );
2396  {
2397  QString family = exprVal.toString().trimmed();
2398  QgsDebugMsgLevel( QString( "exprVal Font family:%1" ).arg( family ), 4 );
2399 
2400  if ( labelFont.family() != family )
2401  {
2402  // testing for ddFontFamily in QFontDatabase.families() may be slow to do for every feature
2403  // (i.e. don't use QgsFontUtils::fontFamilyMatchOnSystem( family ) here)
2404  if ( QgsFontUtils::fontFamilyOnSystem( family ) )
2405  {
2406  ddFontFamily = family;
2407  }
2408  }
2409  }
2410 
2411  // data defined named font style?
2412  QString ddFontStyle( "" );
2414  {
2415  QString fontstyle = exprVal.toString().trimmed();
2416  QgsDebugMsgLevel( QString( "exprVal Font style:%1" ).arg( fontstyle ), 4 );
2417  ddFontStyle = fontstyle;
2418  }
2419 
2420  // data defined bold font style?
2421  bool ddBold = false;
2423  {
2424  bool bold = exprVal.toBool();
2425  QgsDebugMsgLevel( QString( "exprVal Font bold:%1" ).arg( bold ? "true" : "false" ), 4 );
2426  ddBold = bold;
2427  }
2428 
2429  // data defined italic font style?
2430  bool ddItalic = false;
2432  {
2433  bool italic = exprVal.toBool();
2434  QgsDebugMsgLevel( QString( "exprVal Font italic:%1" ).arg( italic ? "true" : "false" ), 4 );
2435  ddItalic = italic;
2436  }
2437 
2438  // TODO: update when pref for how to resolve missing family (use matching algorithm or just default font) is implemented
2439  // (currently defaults to what has been read in from layer settings)
2440  QFont newFont;
2441  QFont appFont = QApplication::font();
2442  bool newFontBuilt = false;
2443  if ( ddBold || ddItalic )
2444  {
2445  // new font needs built, since existing style needs removed
2446  newFont = QFont( !ddFontFamily.isEmpty() ? ddFontFamily : labelFont.family() );
2447  newFontBuilt = true;
2448  newFont.setBold( ddBold );
2449  newFont.setItalic( ddItalic );
2450  }
2451  else if ( !ddFontStyle.isEmpty()
2452  && ddFontStyle.compare( "Ignore", Qt::CaseInsensitive ) != 0 )
2453  {
2454  if ( !ddFontFamily.isEmpty() )
2455  {
2456  // both family and style are different, build font from database
2457  QFont styledfont = mFontDB.font( ddFontFamily, ddFontStyle, appFont.pointSize() );
2458  if ( appFont != styledfont )
2459  {
2460  newFont = styledfont;
2461  newFontBuilt = true;
2462  }
2463  }
2464 
2465  // update the font face style
2466  QgsFontUtils::updateFontViaStyle( newFontBuilt ? newFont : labelFont, ddFontStyle );
2467  }
2468  else if ( !ddFontFamily.isEmpty() )
2469  {
2470  if ( ddFontStyle.compare( "Ignore", Qt::CaseInsensitive ) != 0 )
2471  {
2472  // just family is different, build font from database
2473  QFont styledfont = mFontDB.font( ddFontFamily, textNamedStyle, appFont.pointSize() );
2474  if ( appFont != styledfont )
2475  {
2476  newFont = styledfont;
2477  newFontBuilt = true;
2478  }
2479  }
2480  else
2481  {
2482  newFont = QFont( ddFontFamily );
2483  newFontBuilt = true;
2484  }
2485  }
2486 
2487  if ( newFontBuilt )
2488  {
2489  // copy over existing font settings
2490  //newFont = newFont.resolve( labelFont ); // should work, but let's be sure what's being copied
2491  newFont.setPixelSize( labelFont.pixelSize() );
2492  newFont.setCapitalization( labelFont.capitalization() );
2493  newFont.setUnderline( labelFont.underline() );
2494  newFont.setStrikeOut( labelFont.strikeOut() );
2495  newFont.setWordSpacing( labelFont.wordSpacing() );
2496  newFont.setLetterSpacing( QFont::AbsoluteSpacing, labelFont.letterSpacing() );
2497 
2498  labelFont = newFont;
2499  }
2500 
2501  // data defined word spacing?
2502  double wordspace = labelFont.wordSpacing();
2504  {
2505  bool ok;
2506  double wspacing = exprVal.toDouble( &ok );
2507  QgsDebugMsgLevel( QString( "exprVal FontWordSpacing:%1" ).arg( wspacing ), 4 );
2508  if ( ok )
2509  {
2510  wordspace = wspacing;
2511  }
2512  }
2513  labelFont.setWordSpacing( sizeToPixel( wordspace, context, fontunits, false, fontSizeMapUnitScale ) );
2514 
2515  // data defined letter spacing?
2516  double letterspace = labelFont.letterSpacing();
2518  {
2519  bool ok;
2520  double lspacing = exprVal.toDouble( &ok );
2521  QgsDebugMsgLevel( QString( "exprVal FontLetterSpacing:%1" ).arg( lspacing ), 4 );
2522  if ( ok )
2523  {
2524  letterspace = lspacing;
2525  }
2526  }
2527  labelFont.setLetterSpacing( QFont::AbsoluteSpacing, sizeToPixel( letterspace, context, fontunits, false, fontSizeMapUnitScale ) );
2528 
2529  // data defined font capitalization?
2530  QFont::Capitalization fontcaps = labelFont.capitalization();
2532  {
2533  QString fcase = exprVal.toString().trimmed();
2534  QgsDebugMsgLevel( QString( "exprVal FontCase:%1" ).arg( fcase ), 4 );
2535 
2536  if ( !fcase.isEmpty() )
2537  {
2538  if ( fcase.compare( "NoChange", Qt::CaseInsensitive ) == 0 )
2539  {
2540  fontcaps = QFont::MixedCase;
2541  }
2542  else if ( fcase.compare( "Upper", Qt::CaseInsensitive ) == 0 )
2543  {
2544  fontcaps = QFont::AllUppercase;
2545  }
2546  else if ( fcase.compare( "Lower", Qt::CaseInsensitive ) == 0 )
2547  {
2548  fontcaps = QFont::AllLowercase;
2549  }
2550  else if ( fcase.compare( "Capitalize", Qt::CaseInsensitive ) == 0 )
2551  {
2552  fontcaps = QFont::Capitalize;
2553  }
2554 
2555  if ( fontcaps != labelFont.capitalization() )
2556  {
2557  labelFont.setCapitalization( fontcaps );
2558  }
2559  }
2560  }
2561 
2562  // data defined strikeout font style?
2564  {
2565  bool strikeout = exprVal.toBool();
2566  QgsDebugMsgLevel( QString( "exprVal Font strikeout:%1" ).arg( strikeout ? "true" : "false" ), 4 );
2567  labelFont.setStrikeOut( strikeout );
2568  }
2569 
2570  // data defined underline font style?
2572  {
2573  bool underline = exprVal.toBool();
2574  QgsDebugMsgLevel( QString( "exprVal Font underline:%1" ).arg( underline ? "true" : "false" ), 4 );
2575  labelFont.setUnderline( underline );
2576  }
2577 
2578  // pass the rest on to QgsPalLabeling::drawLabeling
2579 
2580  // data defined font color?
2581  dataDefinedValEval( "color", QgsPalLayerSettings::Color, exprVal );
2582 
2583  // data defined font transparency?
2584  dataDefinedValEval( "transp", QgsPalLayerSettings::FontTransp, exprVal );
2585 
2586  // data defined font blend mode?
2587  dataDefinedValEval( "blendmode", QgsPalLayerSettings::FontBlendMode, exprVal );
2588 
2589 }
2590 
2591 void QgsPalLayerSettings::parseTextBuffer()
2592 {
2593  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2594 
2595  // data defined draw buffer?
2596  bool drawBuffer = bufferDraw;
2597  if ( dataDefinedValEval( "bool", QgsPalLayerSettings::BufferDraw, exprVal ) )
2598  {
2599  drawBuffer = exprVal.toBool();
2600  }
2601 
2602  if ( !drawBuffer )
2603  {
2604  return;
2605  }
2606 
2607  // data defined buffer size?
2608  double bufrSize = bufferSize;
2609  if ( dataDefinedValEval( "doublepos", QgsPalLayerSettings::BufferSize, exprVal ) )
2610  {
2611  bufrSize = exprVal.toDouble();
2612  }
2613 
2614  // data defined buffer transparency?
2615  int bufTransp = bufferTransp;
2616  if ( dataDefinedValEval( "transp", QgsPalLayerSettings::BufferTransp, exprVal ) )
2617  {
2618  bufTransp = exprVal.toInt();
2619  }
2620 
2621  drawBuffer = ( drawBuffer && bufrSize > 0.0 && bufTransp < 100 );
2622 
2623  if ( !drawBuffer )
2624  {
2625  dataDefinedValues.insert( QgsPalLayerSettings::BufferDraw, QVariant( false ) ); // trigger value
2626  dataDefinedValues.remove( QgsPalLayerSettings::BufferSize );
2627  dataDefinedValues.remove( QgsPalLayerSettings::BufferTransp );
2628  return; // don't bother evaluating values that won't be used
2629  }
2630 
2631  // data defined buffer units?
2632  dataDefinedValEval( "units", QgsPalLayerSettings::BufferUnit, exprVal );
2633 
2634  // data defined buffer color?
2635  dataDefinedValEval( "color", QgsPalLayerSettings::BufferColor, exprVal );
2636 
2637  // data defined buffer pen join style?
2638  dataDefinedValEval( "joinstyle", QgsPalLayerSettings::BufferJoinStyle, exprVal );
2639 
2640  // data defined buffer blend mode?
2641  dataDefinedValEval( "blendmode", QgsPalLayerSettings::BufferBlendMode, exprVal );
2642 }
2643 
2644 void QgsPalLayerSettings::parseTextFormatting()
2645 {
2646  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2647 
2648  // data defined multiline wrap character?
2649  QString wrapchr = wrapChar;
2650  if ( dataDefinedValEval( "string", QgsPalLayerSettings::MultiLineWrapChar, exprVal ) )
2651  {
2652  wrapchr = exprVal.toString();
2653  }
2654 
2655  // data defined multiline height?
2656  dataDefinedValEval( "double", QgsPalLayerSettings::MultiLineHeight, exprVal );
2657 
2658  // data defined multiline text align?
2660  {
2661  QString str = exprVal.toString().trimmed();
2662  QgsDebugMsgLevel( QString( "exprVal MultiLineAlignment:%1" ).arg( str ), 4 );
2663 
2664  if ( !str.isEmpty() )
2665  {
2666  // "Left"
2668 
2669  if ( str.compare( "Center", Qt::CaseInsensitive ) == 0 )
2670  {
2672  }
2673  else if ( str.compare( "Right", Qt::CaseInsensitive ) == 0 )
2674  {
2675  aligntype = QgsPalLayerSettings::MultiRight;
2676  }
2677  dataDefinedValues.insert( QgsPalLayerSettings::MultiLineAlignment, QVariant(( int )aligntype ) );
2678  }
2679  }
2680 
2681  // data defined direction symbol?
2682  bool drawDirSymb = addDirectionSymbol;
2683  if ( dataDefinedValEval( "bool", QgsPalLayerSettings::DirSymbDraw, exprVal ) )
2684  {
2685  drawDirSymb = exprVal.toBool();
2686  }
2687 
2688  if ( drawDirSymb )
2689  {
2690  // data defined direction left symbol?
2691  dataDefinedValEval( "string", QgsPalLayerSettings::DirSymbLeft, exprVal );
2692 
2693  // data defined direction right symbol?
2694  dataDefinedValEval( "string", QgsPalLayerSettings::DirSymbRight, exprVal );
2695 
2696  // data defined direction symbol placement?
2698  {
2699  QString str = exprVal.toString().trimmed();
2700  QgsDebugMsgLevel( QString( "exprVal DirSymbPlacement:%1" ).arg( str ), 4 );
2701 
2702  if ( !str.isEmpty() )
2703  {
2704  // "LeftRight"
2706 
2707  if ( str.compare( "Above", Qt::CaseInsensitive ) == 0 )
2708  {
2710  }
2711  else if ( str.compare( "Below", Qt::CaseInsensitive ) == 0 )
2712  {
2714  }
2715  dataDefinedValues.insert( QgsPalLayerSettings::DirSymbPlacement, QVariant(( int )placetype ) );
2716  }
2717  }
2718 
2719  // data defined direction symbol reversed?
2720  dataDefinedValEval( "bool", QgsPalLayerSettings::DirSymbReverse, exprVal );
2721  }
2722 
2723  // formatting for numbers is inline with generation of base label text and not passed to label painting
2724 }
2725 
2726 void QgsPalLayerSettings::parseShapeBackground()
2727 {
2728  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2729 
2730  // data defined draw shape?
2731  bool drawShape = shapeDraw;
2732  if ( dataDefinedValEval( "bool", QgsPalLayerSettings::ShapeDraw, exprVal ) )
2733  {
2734  drawShape = exprVal.toBool();
2735  }
2736 
2737  if ( !drawShape )
2738  {
2739  return;
2740  }
2741 
2742  // data defined shape transparency?
2743  int shapeTransp = shapeTransparency;
2744  if ( dataDefinedValEval( "transp", QgsPalLayerSettings::ShapeTransparency, exprVal ) )
2745  {
2746  shapeTransp = exprVal.toInt();
2747  }
2748 
2749  drawShape = ( drawShape && shapeTransp < 100 ); // size is not taken into account (could be)
2750 
2751  if ( !drawShape )
2752  {
2753  dataDefinedValues.insert( QgsPalLayerSettings::ShapeDraw, QVariant( false ) ); // trigger value
2754  dataDefinedValues.remove( QgsPalLayerSettings::ShapeTransparency );
2755  return; // don't bother evaluating values that won't be used
2756  }
2757 
2758  // data defined shape kind?
2761  {
2762  QString skind = exprVal.toString().trimmed();
2763  QgsDebugMsgLevel( QString( "exprVal ShapeKind:%1" ).arg( skind ), 4 );
2764 
2765  if ( !skind.isEmpty() )
2766  {
2767  // "Rectangle"
2769 
2770  if ( skind.compare( "Square", Qt::CaseInsensitive ) == 0 )
2771  {
2773  }
2774  else if ( skind.compare( "Ellipse", Qt::CaseInsensitive ) == 0 )
2775  {
2777  }
2778  else if ( skind.compare( "Circle", Qt::CaseInsensitive ) == 0 )
2779  {
2781  }
2782  else if ( skind.compare( "SVG", Qt::CaseInsensitive ) == 0 )
2783  {
2785  }
2786  shapeKind = shpkind;
2787  dataDefinedValues.insert( QgsPalLayerSettings::ShapeKind, QVariant(( int )shpkind ) );
2788  }
2789  }
2790 
2791  // data defined shape SVG path?
2792  QString svgPath = shapeSVGFile;
2794  {
2795  QString svgfile = exprVal.toString().trimmed();
2796  QgsDebugMsgLevel( QString( "exprVal ShapeSVGFile:%1" ).arg( svgfile ), 4 );
2797 
2798  // '' empty paths are allowed
2799  svgPath = svgfile;
2800  dataDefinedValues.insert( QgsPalLayerSettings::ShapeSVGFile, QVariant( svgfile ) );
2801  }
2802 
2803  // data defined shape size type?
2806  {
2807  QString stype = exprVal.toString().trimmed();
2808  QgsDebugMsgLevel( QString( "exprVal ShapeSizeType:%1" ).arg( stype ), 4 );
2809 
2810  if ( !stype.isEmpty() )
2811  {
2812  // "Buffer"
2814 
2815  if ( stype.compare( "Fixed", Qt::CaseInsensitive ) == 0 )
2816  {
2818  }
2819  shpSizeType = sizType;
2820  dataDefinedValues.insert( QgsPalLayerSettings::ShapeSizeType, QVariant(( int )sizType ) );
2821  }
2822  }
2823 
2824  // data defined shape size X? (SVGs only use X for sizing)
2825  double ddShpSizeX = shapeSize.x();
2826  if ( dataDefinedValEval( "double", QgsPalLayerSettings::ShapeSizeX, exprVal ) )
2827  {
2828  ddShpSizeX = exprVal.toDouble();
2829  }
2830 
2831  // data defined shape size Y?
2832  double ddShpSizeY = shapeSize.y();
2833  if ( dataDefinedValEval( "double", QgsPalLayerSettings::ShapeSizeY, exprVal ) )
2834  {
2835  ddShpSizeY = exprVal.toDouble();
2836  }
2837 
2838  // don't continue under certain circumstances (e.g. size is fixed)
2839  bool skip = false;
2840  if ( shapeKind == QgsPalLayerSettings::ShapeSVG
2841  && ( svgPath.isEmpty()
2842  || ( !svgPath.isEmpty()
2843  && shpSizeType == QgsPalLayerSettings::SizeFixed
2844  && ddShpSizeX == 0.0 ) ) )
2845  {
2846  skip = true;
2847  }
2848  if ( shapeKind != QgsPalLayerSettings::ShapeSVG
2849  && shpSizeType == QgsPalLayerSettings::SizeFixed
2850  && ( ddShpSizeX == 0.0 || ddShpSizeY == 0.0 ) )
2851  {
2852  skip = true;
2853  }
2854 
2855  if ( skip )
2856  {
2857  dataDefinedValues.insert( QgsPalLayerSettings::ShapeDraw, QVariant( false ) ); // trigger value
2858  dataDefinedValues.remove( QgsPalLayerSettings::ShapeTransparency );
2859  dataDefinedValues.remove( QgsPalLayerSettings::ShapeKind );
2860  dataDefinedValues.remove( QgsPalLayerSettings::ShapeSVGFile );
2861  dataDefinedValues.remove( QgsPalLayerSettings::ShapeSizeX );
2862  dataDefinedValues.remove( QgsPalLayerSettings::ShapeSizeY );
2863  return; // don't bother evaluating values that won't be used
2864  }
2865 
2866  // data defined shape size units?
2867  dataDefinedValEval( "units", QgsPalLayerSettings::ShapeSizeUnits, exprVal );
2868 
2869  // data defined shape rotation type?
2871  {
2872  QString rotstr = exprVal.toString().trimmed();
2873  QgsDebugMsgLevel( QString( "exprVal ShapeRotationType:%1" ).arg( rotstr ), 4 );
2874 
2875  if ( !rotstr.isEmpty() )
2876  {
2877  // "Sync"
2879 
2880  if ( rotstr.compare( "Offset", Qt::CaseInsensitive ) == 0 )
2881  {
2883  }
2884  else if ( rotstr.compare( "Fixed", Qt::CaseInsensitive ) == 0 )
2885  {
2887  }
2888  dataDefinedValues.insert( QgsPalLayerSettings::ShapeRotationType, QVariant(( int )rottype ) );
2889  }
2890  }
2891 
2892  // data defined shape rotation?
2893  dataDefinedValEval( "rotation180", QgsPalLayerSettings::ShapeRotation, exprVal );
2894 
2895  // data defined shape offset?
2896  dataDefinedValEval( "pointf", QgsPalLayerSettings::ShapeOffset, exprVal );
2897 
2898  // data defined shape offset units?
2899  dataDefinedValEval( "units", QgsPalLayerSettings::ShapeOffsetUnits, exprVal );
2900 
2901  // data defined shape radii?
2902  dataDefinedValEval( "pointf", QgsPalLayerSettings::ShapeRadii, exprVal );
2903 
2904  // data defined shape radii units?
2905  dataDefinedValEval( "units", QgsPalLayerSettings::ShapeRadiiUnits, exprVal );
2906 
2907  // data defined shape blend mode?
2908  dataDefinedValEval( "blendmode", QgsPalLayerSettings::ShapeBlendMode, exprVal );
2909 
2910  // data defined shape fill color?
2911  dataDefinedValEval( "color", QgsPalLayerSettings::ShapeFillColor, exprVal );
2912 
2913  // data defined shape border color?
2914  dataDefinedValEval( "color", QgsPalLayerSettings::ShapeBorderColor, exprVal );
2915 
2916  // data defined shape border width?
2917  dataDefinedValEval( "doublepos", QgsPalLayerSettings::ShapeBorderWidth, exprVal );
2918 
2919  // data defined shape border width units?
2920  dataDefinedValEval( "units", QgsPalLayerSettings::ShapeBorderWidthUnits, exprVal );
2921 
2922  // data defined shape join style?
2923  dataDefinedValEval( "joinstyle", QgsPalLayerSettings::ShapeJoinStyle, exprVal );
2924 
2925 }
2926 
2927 void QgsPalLayerSettings::parseDropShadow()
2928 {
2929  QVariant exprVal; // value() is repeatedly nulled on data defined evaluation and replaced when successful
2930 
2931  // data defined draw shadow?
2932  bool drawShadow = shadowDraw;
2933  if ( dataDefinedValEval( "bool", QgsPalLayerSettings::ShadowDraw, exprVal ) )
2934  {
2935  drawShadow = exprVal.toBool();
2936  }
2937 
2938  if ( !drawShadow )
2939  {
2940  return;
2941  }
2942 
2943  // data defined shadow transparency?
2944  int shadowTransp = shadowTransparency;
2945  if ( dataDefinedValEval( "transp", QgsPalLayerSettings::ShadowTransparency, exprVal ) )
2946  {
2947  shadowTransp = exprVal.toInt();
2948  }
2949 
2950  // data defined shadow offset distance?
2951  double shadowOffDist = shadowOffsetDist;
2952  if ( dataDefinedValEval( "doublepos", QgsPalLayerSettings::ShadowOffsetDist, exprVal ) )
2953  {
2954  shadowOffDist = exprVal.toDouble();
2955  }
2956 
2957  // data defined shadow offset distance?
2958  double shadowRad = shadowRadius;
2959  if ( dataDefinedValEval( "doublepos", QgsPalLayerSettings::ShadowRadius, exprVal ) )
2960  {
2961  shadowRad = exprVal.toDouble();
2962  }
2963 
2964  drawShadow = ( drawShadow && shadowTransp < 100 && !( shadowOffDist == 0.0 && shadowRad == 0.0 ) );
2965 
2966  if ( !drawShadow )
2967  {
2968  dataDefinedValues.insert( QgsPalLayerSettings::ShadowDraw, QVariant( false ) ); // trigger value
2969  dataDefinedValues.remove( QgsPalLayerSettings::ShadowTransparency );
2970  dataDefinedValues.remove( QgsPalLayerSettings::ShadowOffsetDist );
2971  dataDefinedValues.remove( QgsPalLayerSettings::ShadowRadius );
2972  return; // don't bother evaluating values that won't be used
2973  }
2974 
2975  // data defined shadow under type?
2977  {
2978  QString str = exprVal.toString().trimmed();
2979  QgsDebugMsgLevel( QString( "exprVal ShadowUnder:%1" ).arg( str ), 4 );
2980 
2981  if ( !str.isEmpty() )
2982  {
2983  // "Lowest"
2985 
2986  if ( str.compare( "Text", Qt::CaseInsensitive ) == 0 )
2987  {
2989  }
2990  else if ( str.compare( "Buffer", Qt::CaseInsensitive ) == 0 )
2991  {
2993  }
2994  else if ( str.compare( "Background", Qt::CaseInsensitive ) == 0 )
2995  {
2997  }
2998  dataDefinedValues.insert( QgsPalLayerSettings::ShadowUnder, QVariant(( int )shdwtype ) );
2999  }
3000  }
3001 
3002  // data defined shadow offset angle?
3003  dataDefinedValEval( "rotation180", QgsPalLayerSettings::ShadowOffsetAngle, exprVal );
3004 
3005  // data defined shadow offset units?
3006  dataDefinedValEval( "units", QgsPalLayerSettings::ShadowOffsetUnits, exprVal );
3007 
3008  // data defined shadow radius?
3009  dataDefinedValEval( "double", QgsPalLayerSettings::ShadowRadius, exprVal );
3010 
3011  // data defined shadow radius units?
3012  dataDefinedValEval( "units", QgsPalLayerSettings::ShadowRadiusUnits, exprVal );
3013 
3014  // data defined shadow scale? ( gui bounds to 0-2000, no upper bound here )
3015  dataDefinedValEval( "intpos", QgsPalLayerSettings::ShadowScale, exprVal );
3016 
3017  // data defined shadow color?
3018  dataDefinedValEval( "color", QgsPalLayerSettings::ShadowColor, exprVal );
3019 
3020  // data defined shadow blend mode?
3021  dataDefinedValEval( "blendmode", QgsPalLayerSettings::ShadowBlendMode, exprVal );
3022 }
3023 
3024 int QgsPalLayerSettings::sizeToPixel( double size, const QgsRenderContext& c, SizeUnit unit, bool rasterfactor, const QgsMapUnitScale& mapUnitScale ) const
3025 {
3026  return ( int )( scaleToPixelContext( size, c, unit, rasterfactor, mapUnitScale ) + 0.5 );
3027 }
3028 
3029 double QgsPalLayerSettings::scaleToPixelContext( double size, const QgsRenderContext& c, SizeUnit unit, bool rasterfactor, const QgsMapUnitScale& mapUnitScale ) const
3030 {
3031  // if render context is that of device (i.e. not a scaled map), just return size
3032  double mapUnitsPerPixel = mapUnitScale.computeMapUnitsPerPixel( c );
3033 
3034  if ( unit == MapUnits && mapUnitsPerPixel > 0.0 )
3035  {
3036  size = size / mapUnitsPerPixel * ( rasterfactor ? c.rasterScaleFactor() : 1 );
3037  }
3038  else // e.g. in points or mm
3039  {
3040  double ptsTomm = ( unit == Points ? 0.352778 : 1 );
3041  size *= ptsTomm * c.scaleFactor() * ( rasterfactor ? c.rasterScaleFactor() : 1 );
3042  }
3043  return size;
3044 }
3045 
3046 // -------------
3047 
3049  : mMapSettings( NULL ), mPal( NULL )
3050  , mResults( 0 )
3051 {
3052 
3053  // find out engine defaults
3054  Pal p;
3055  mCandPoint = p.getPointP();
3056  mCandLine = p.getLineP();
3057  mCandPolygon = p.getPolyP();
3058 
3059  switch ( p.getSearch() )
3060  {
3061  case CHAIN: mSearch = Chain; break;
3062  case POPMUSIC_TABU: mSearch = Popmusic_Tabu; break;
3063  case POPMUSIC_CHAIN: mSearch = Popmusic_Chain; break;
3065  case FALP: mSearch = Falp; break;
3066  }
3067 
3068  mShowingCandidates = false;
3069  mShowingShadowRects = false;
3070  mShowingAllLabels = false;
3072  mDrawOutlineLabels = true;
3073 }
3074 
3076 {
3077  // make sure we've freed everything
3078  exit();
3079 
3081 
3082  delete mResults;
3083  mResults = 0;
3084 }
3085 
3087 {
3088  return staticWillUseLayer( layer );
3089 }
3090 
3091 bool QgsPalLabeling::staticWillUseLayer( const QString& layerID )
3092 {
3093  QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( layerID ) );
3094  if ( !layer )
3095  return false;
3096  return staticWillUseLayer( layer );
3097 }
3098 
3099 
3101 {
3102  // don't do QgsPalLayerSettings::readFromLayer( layer ) if not needed
3103  bool enabled = false;
3104  if ( layer->customProperty( "labeling" ).toString() == QString( "pal" ) )
3105  enabled = layer->customProperty( "labeling/enabled", QVariant( false ) ).toBool();
3106 
3107  return enabled;
3108 }
3109 
3110 
3112 {
3113  QHash<QString, QgsPalLayerSettings>::iterator lit;
3114  for ( lit = mActiveLayers.begin(); lit != mActiveLayers.end(); ++lit )
3115  {
3116  clearActiveLayer( lit.key() );
3117  }
3118  mActiveLayers.clear();
3119 }
3120 
3121 void QgsPalLabeling::clearActiveLayer( const QString &layerID )
3122 {
3123  QgsPalLayerSettings& lyr = mActiveLayers[layerID];
3124 
3125  // delete all QgsDataDefined objects (which also deletes their QgsExpression object)
3126  QMap< QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* >::iterator it = lyr.dataDefinedProperties.begin();
3127  for ( ; it != lyr.dataDefinedProperties.constEnd(); ++it )
3128  {
3129  delete( it.value() );
3130  it.value() = 0;
3131  }
3132  lyr.dataDefinedProperties.clear();
3133 }
3134 
3135 int QgsPalLabeling::prepareLayer( QgsVectorLayer* layer, QStringList& attrNames, QgsRenderContext& ctx )
3136 {
3137  Q_ASSERT( mMapSettings != NULL );
3138 
3139  if ( !willUseLayer( layer ) )
3140  {
3141  return 0;
3142  }
3143 
3144  QgsDebugMsgLevel( "PREPARE LAYER " + layer->id(), 4 );
3145 
3146  // start with a temporary settings class, find out labeling info
3147  QgsPalLayerSettings lyrTmp;
3148  lyrTmp.readFromLayer( layer );
3149 
3150  if ( lyrTmp.fieldName.isEmpty() )
3151  {
3152  return 0;
3153  }
3154 
3155  if ( lyrTmp.isExpression )
3156  {
3157  QgsExpression exp( lyrTmp.fieldName );
3158  if ( exp.hasEvalError() )
3159  {
3160  QgsDebugMsgLevel( "Prepare error:" + exp.evalErrorString(), 4 );
3161  return 0;
3162  }
3163  }
3164  else
3165  {
3166  // If we aren't an expression, we check to see if we can find the column.
3167  if ( layer->fieldNameIndex( lyrTmp.fieldName ) == -1 )
3168  {
3169  return 0;
3170  }
3171  }
3172 
3173  // add layer settings to the pallabeling hashtable: <QgsVectorLayer*, QgsPalLayerSettings>
3174  mActiveLayers.insert( layer->id(), lyrTmp );
3175  // start using the reference to the layer in hashtable instead of local instance
3176  QgsPalLayerSettings& lyr = mActiveLayers[layer->id()];
3177 
3178  lyr.mCurFields = &( layer->pendingFields() );
3179 
3180  // add field indices for label's text, from expression or field
3181  if ( lyr.isExpression )
3182  {
3183  // prepare expression for use in QgsPalLayerSettings::registerFeature()
3184  QgsExpression* exp = lyr.getLabelExpression();
3185  exp->prepare( layer->pendingFields() );
3186  if ( exp->hasEvalError() )
3187  {
3188  QgsDebugMsgLevel( "Prepare error:" + exp->evalErrorString(), 4 );
3189  }
3190  foreach ( QString name, exp->referencedColumns() )
3191  {
3192  QgsDebugMsgLevel( "REFERENCED COLUMN = " + name, 4 );
3193  attrNames.append( name );
3194  }
3195  }
3196  else
3197  {
3198  attrNames.append( lyr.fieldName );
3199  }
3200 
3201  // add field indices of data defined expression or field
3202  QMap< QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* >::const_iterator dIt = lyr.dataDefinedProperties.constBegin();
3203  for ( ; dIt != lyr.dataDefinedProperties.constEnd(); ++dIt )
3204  {
3205  QgsDataDefined* dd = dIt.value();
3206  if ( !dd->isActive() )
3207  {
3208  continue;
3209  }
3210 
3211  // NOTE: the following also prepares any expressions for later use
3212 
3213  // store parameters for data defined expressions
3214  QMap<QString, QVariant> exprParams;
3215  exprParams.insert( "scale", ctx.rendererScale() );
3216 
3217  dd->setExpressionParams( exprParams );
3218 
3219  // this will return columns for expressions or field name, depending upon what is set to be used
3220  QStringList cols = dd->referencedColumns( layer ); // <-- prepares any expressions, too
3221 
3222  //QgsDebugMsgLevel( QString( "Data defined referenced columns:" ) + cols.join( "," ), 4 );
3223  foreach ( QString name, cols )
3224  {
3225  attrNames.append( name );
3226  }
3227  }
3228 
3229  // how to place the labels
3230  Arrangement arrangement;
3231  switch ( lyr.placement )
3232  {
3233  case QgsPalLayerSettings::AroundPoint: arrangement = P_POINT; break;
3234  case QgsPalLayerSettings::OverPoint: arrangement = P_POINT_OVER; break;
3235  case QgsPalLayerSettings::Line: arrangement = P_LINE; break;
3236  case QgsPalLayerSettings::Curved: arrangement = P_CURVED; break;
3237  case QgsPalLayerSettings::Horizontal: arrangement = P_HORIZ; break;
3238  case QgsPalLayerSettings::Free: arrangement = P_FREE; break;
3239  default: Q_ASSERT( "unsupported placement" && 0 ); return 0;
3240  }
3241 
3242  // create the pal layer
3243  double priority = 1 - lyr.priority / 10.0; // convert 0..10 --> 1..0
3244  double min_scale = -1, max_scale = -1;
3245 
3246  // handled in QgsPalLayerSettings::registerFeature now
3247  //if ( lyr.scaleVisibility && !lyr.dataDefinedIsActive( QgsPalLayerSettings::ScaleVisibility ) )
3248  //{
3249  // min_scale = lyr.scaleMin;
3250  // max_scale = lyr.scaleMax;
3251  //}
3252 
3253  Layer* l = mPal->addLayer( layer->id().toUtf8().data(),
3254  min_scale, max_scale, arrangement,
3255  METER, priority, lyr.obstacle, true, true,
3256  lyr.displayAll );
3257 
3258  if ( lyr.placementFlags )
3260 
3261  // set label mode (label per feature is the default)
3262  l->setLabelMode( lyr.labelPerPart ? Layer::LabelPerFeaturePart : Layer::LabelPerFeature );
3263 
3264  // set whether adjacent lines should be merged
3266 
3267 
3268  // set whether location of centroid must be inside of polygons
3270 
3271  // set how to show upside-down labels
3272  Layer::UpsideDownLabels upsdnlabels;
3273  switch ( lyr.upsidedownLabels )
3274  {
3275  case QgsPalLayerSettings::Upright: upsdnlabels = Layer::Upright; break;
3276  case QgsPalLayerSettings::ShowDefined: upsdnlabels = Layer::ShowDefined; break;
3277  case QgsPalLayerSettings::ShowAll: upsdnlabels = Layer::ShowAll; break;
3278  default: Q_ASSERT( "unsupported upside-down label setting" && 0 ); return 0;
3279  }
3280  l->setUpsidedownLabels( upsdnlabels );
3281 
3282 // // fix for font size in map units causing font to show pointsize at small map scales
3283 // int pixelFontSize = lyr.sizeToPixel( lyr.textFont.pointSizeF(), ctx,
3284 // lyr.fontSizeInMapUnits ? QgsPalLayerSettings::MapUnits : QgsPalLayerSettings::Points,
3285 // true );
3286 
3287 // if ( pixelFontSize < 1 )
3288 // {
3289 // lyr.textFont.setPointSize( 1 );
3290 // lyr.textFont.setPixelSize( 1 );
3291 // }
3292 // else
3293 // {
3294 // lyr.textFont.setPixelSize( pixelFontSize );
3295 // }
3296 
3297 // // scale spacing sizes if using map units
3298 // if ( lyr.fontSizeInMapUnits )
3299 // {
3300 // double spacingPixelSize;
3301 // if ( lyr.textFont.wordSpacing() != 0 )
3302 // {
3303 // spacingPixelSize = lyr.textFont.wordSpacing() / ctx.mapToPixel().mapUnitsPerPixel() * ctx.rasterScaleFactor();
3304 // lyr.textFont.setWordSpacing( spacingPixelSize );
3305 // }
3306 
3307 // if ( lyr.textFont.letterSpacing() != 0 )
3308 // {
3309 // spacingPixelSize = lyr.textFont.letterSpacing() / ctx.mapToPixel().mapUnitsPerPixel() * ctx.rasterScaleFactor();
3310 // lyr.textFont.setLetterSpacing( QFont::AbsoluteSpacing, spacingPixelSize );
3311 // }
3312 // }
3313 
3314  //raster and vector scale factors
3315  lyr.vectorScaleFactor = ctx.scaleFactor();
3317 
3318  // save the pal layer to our layer context (with some additional info)
3319  lyr.palLayer = l;
3320  lyr.fieldIndex = layer->fieldNameIndex( lyr.fieldName );
3321 
3322  lyr.xform = &mMapSettings->mapToPixel();
3323  lyr.ct = 0;
3325  lyr.ct = new QgsCoordinateTransform( layer->crs(), mMapSettings->destinationCrs() );
3326  lyr.ptZero = lyr.xform->toMapCoordinates( 0, 0 );
3327  lyr.ptOne = lyr.xform->toMapCoordinates( 1, 0 );
3328 
3329  // rect for clipping
3331 
3332  lyr.mFeatsSendingToPal = 0;
3333 
3334  return 1; // init successful
3335 }
3336 
3338 {
3339  Layer* l = mPal->addLayer( layer->id().append( "d" ).toUtf8().data(), -1, -1, pal::Arrangement( s->placement ), METER, s->priority, s->obstacle, true, true );
3341 
3342  mActiveDiagramLayers.insert( layer->id(), *s );
3343  // initialize the local copy
3345 
3346  s2.palLayer = l;
3347  s2.ct = 0;
3349  s2.ct = new QgsCoordinateTransform( layer->crs(), mMapSettings->destinationCrs() );
3350 
3351  s2.xform = &mMapSettings->mapToPixel();
3352 
3353  s2.fields = layer->pendingFields();
3354 
3355  s2.renderer = layer->diagramRenderer()->clone();
3356 
3357  return 1;
3358 }
3359 
3360 void QgsPalLabeling::registerFeature( const QString& layerID, QgsFeature& f, const QgsRenderContext& context, QString dxfLayer )
3361 {
3362  QgsPalLayerSettings& lyr = mActiveLayers[layerID];
3363  lyr.registerFeature( f, context, dxfLayer );
3364 }
3365 
3366 void QgsPalLabeling::registerDiagramFeature( const QString& layerID, QgsFeature& feat, const QgsRenderContext& context )
3367 {
3368  //get diagram layer settings, diagram renderer
3369  QHash<QString, QgsDiagramLayerSettings>::iterator layerIt = mActiveDiagramLayers.find( layerID );
3370  if ( layerIt == mActiveDiagramLayers.constEnd() )
3371  {
3372  return;
3373  }
3374 
3375  //convert geom to geos
3376  QgsGeometry* geom = feat.geometry();
3377 
3378  if ( layerIt.value().ct && staticWillUseLayer( layerID ) ) // reproject the geometry if feature not already transformed for labeling
3379  {
3380  geom->transform( *( layerIt.value().ct ) );
3381  }
3382 
3383  const GEOSGeometry* geos_geom = geom->asGeos();
3384  if ( geos_geom == 0 )
3385  {
3386  return; // invalid geometry
3387  }
3388 
3389  //create PALGeometry with diagram = true
3390  QgsPalGeometry* lbl = new QgsPalGeometry( feat.id(), "", GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom ) );
3391  lbl->setIsDiagram( true );
3392 
3393  // record the created geometry - it will be deleted at the end.
3394  layerIt.value().geometries.append( lbl );
3395 
3396  double diagramWidth = 0;
3397  double diagramHeight = 0;
3398  QgsDiagramRendererV2* dr = layerIt.value().renderer;
3399  if ( dr )
3400  {
3401  QSizeF diagSize = dr->sizeMapUnits( feat, context );
3402  if ( diagSize.isValid() )
3403  {
3404  diagramWidth = diagSize.width();
3405  diagramHeight = diagSize.height();
3406  }
3407 
3408  //append the diagram attributes to lbl
3409  lbl->setDiagramAttributes( feat.attributes() );
3410  }
3411 
3412  // feature to the layer
3413  int ddColX = layerIt.value().xPosColumn;
3414  int ddColY = layerIt.value().yPosColumn;
3415  double ddPosX = 0.0;
3416  double ddPosY = 0.0;
3417  bool ddPos = ( ddColX >= 0 && ddColY >= 0 );
3418  if ( ddPos )
3419  {
3420  bool posXOk, posYOk;
3421  //data defined diagram position is always centered
3422  ddPosX = feat.attribute( ddColX ).toDouble( &posXOk ) - diagramWidth / 2.0;
3423  ddPosY = feat.attribute( ddColY ).toDouble( &posYOk ) - diagramHeight / 2.0;
3424  if ( !posXOk || !posYOk )
3425  {
3426  ddPos = false;
3427  }
3428  else
3429  {
3430  const QgsCoordinateTransform* ct = layerIt.value().ct;
3431  if ( ct )
3432  {
3433  double z = 0;
3434  ct->transformInPlace( ddPosX, ddPosY, z );
3435  }
3436  }
3437  }
3438 
3439  try
3440  {
3441  if ( !layerIt.value().palLayer->registerFeature( lbl->strId(), lbl, diagramWidth, diagramHeight, "", ddPosX, ddPosY, ddPos ) )
3442  {
3443  return;
3444  }
3445  }
3446  catch ( std::exception &e )
3447  {
3448  Q_UNUSED( e );
3449  QgsDebugMsgLevel( QString( "Ignoring feature %1 due PAL exception:" ).arg( feat.id() ) + QString::fromLatin1( e.what() ), 4 );
3450  return;
3451  }
3452 
3453  pal::Feature* palFeat = layerIt.value().palLayer->getFeature( lbl->strId() );
3454  QgsPoint ptZero = layerIt.value().xform->toMapCoordinates( 0, 0 );
3455  QgsPoint ptOne = layerIt.value().xform->toMapCoordinates( 1, 0 );
3456  palFeat->setDistLabel( qAbs( ptOne.x() - ptZero.x() ) * layerIt.value().dist );
3457 }
3458 
3459 
3461 {
3462  init( mr->mapSettings() );
3463 }
3464 
3465 void QgsPalLabeling::init( const QgsMapSettings& mapSettings )
3466 {
3467  mMapSettings = &mapSettings;
3468 
3469  // delete if exists already
3470  if ( mPal )
3471  delete mPal;
3472 
3473  mPal = new Pal;
3474 
3475  SearchMethod s;
3476  switch ( mSearch )
3477  {
3478  default:
3479  case Chain: s = CHAIN; break;
3480  case Popmusic_Tabu: s = POPMUSIC_TABU; break;
3481  case Popmusic_Chain: s = POPMUSIC_CHAIN; break;
3482  case Popmusic_Tabu_Chain: s = POPMUSIC_TABU_CHAIN; break;
3483  case Falp: s = FALP; break;
3484  }
3485  mPal->setSearch( s );
3486 
3487  // set number of candidates generated per feature
3489  mPal->setLineP( mCandLine );
3491 
3493 
3494  clearActiveLayers(); // free any previous QgsDataDefined objects
3495  mActiveDiagramLayers.clear();
3496 }
3497 
3499 {
3500  delete mPal;
3501  mPal = NULL;
3502  mMapSettings = NULL;
3503 }
3504 
3505 QgsPalLayerSettings& QgsPalLabeling::layer( const QString& layerName )
3506 {
3507  QHash<QString, QgsPalLayerSettings>::iterator lit;
3508  for ( lit = mActiveLayers.begin(); lit != mActiveLayers.end(); ++lit )
3509  {
3510  if ( lit.key() == layerName )
3511  {
3512  return lit.value();
3513  }
3514  }
3515  return mInvalidLayerSettings;
3516 }
3517 
3519  const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant >& ddValues )
3520 {
3521  //font color
3522  if ( ddValues.contains( QgsPalLayerSettings::Color ) )
3523  {
3524  QVariant ddColor = ddValues.value( QgsPalLayerSettings::Color );
3525  tmpLyr.textColor = ddColor.value<QColor>();
3526  }
3527 
3528  //font transparency
3529  if ( ddValues.contains( QgsPalLayerSettings::FontTransp ) )
3530  {
3531  tmpLyr.textTransp = ddValues.value( QgsPalLayerSettings::FontTransp ).toInt();
3532  }
3533 
3534  tmpLyr.textColor.setAlphaF(( 100.0 - ( double )( tmpLyr.textTransp ) ) / 100.0 );
3535 
3536  //font blend mode
3537  if ( ddValues.contains( QgsPalLayerSettings::FontBlendMode ) )
3538  {
3539  tmpLyr.blendMode = ( QPainter::CompositionMode )ddValues.value( QgsPalLayerSettings::FontBlendMode ).toInt();
3540  }
3541 }
3542 
3544  const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant >& ddValues )
3545 {
3546  if ( ddValues.contains( QgsPalLayerSettings::MultiLineWrapChar ) )
3547  {
3548  tmpLyr.wrapChar = ddValues.value( QgsPalLayerSettings::MultiLineWrapChar ).toString();
3549  }
3550 
3551  if ( !tmpLyr.wrapChar.isEmpty() )
3552  {
3553 
3554  if ( ddValues.contains( QgsPalLayerSettings::MultiLineHeight ) )
3555  {
3556  tmpLyr.multilineHeight = ddValues.value( QgsPalLayerSettings::MultiLineHeight ).toDouble();
3557  }
3558 
3559  if ( ddValues.contains( QgsPalLayerSettings::MultiLineAlignment ) )
3560  {
3562  }
3563 
3564  }
3565 
3566  if ( ddValues.contains( QgsPalLayerSettings::DirSymbDraw ) )
3567  {
3568  tmpLyr.addDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbDraw ).toBool();
3569  }
3570 
3571  if ( tmpLyr.addDirectionSymbol )
3572  {
3573 
3574  if ( ddValues.contains( QgsPalLayerSettings::DirSymbLeft ) )
3575  {
3576  tmpLyr.leftDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbLeft ).toString();
3577  }
3578  if ( ddValues.contains( QgsPalLayerSettings::DirSymbRight ) )
3579  {
3580  tmpLyr.rightDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbRight ).toString();
3581  }
3582 
3583  if ( ddValues.contains( QgsPalLayerSettings::DirSymbPlacement ) )
3584  {
3586  }
3587 
3588  if ( ddValues.contains( QgsPalLayerSettings::DirSymbReverse ) )
3589  {
3590  tmpLyr.reverseDirectionSymbol = ddValues.value( QgsPalLayerSettings::DirSymbReverse ).toBool();
3591  }
3592 
3593  }
3594 }
3595 
3597  const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant >& ddValues )
3598 {
3599  //buffer draw
3600  if ( ddValues.contains( QgsPalLayerSettings::BufferDraw ) )
3601  {
3602  tmpLyr.bufferDraw = ddValues.value( QgsPalLayerSettings::BufferDraw ).toBool();
3603  }
3604 
3605  if ( !tmpLyr.bufferDraw )
3606  {
3607  // tmpLyr.bufferSize > 0.0 && tmpLyr.bufferTransp < 100 figured in during evaluation
3608  return; // don't continue looking for unused values
3609  }
3610 
3611  //buffer size
3612  if ( ddValues.contains( QgsPalLayerSettings::BufferSize ) )
3613  {
3614  tmpLyr.bufferSize = ddValues.value( QgsPalLayerSettings::BufferSize ).toDouble();
3615  }
3616 
3617  //buffer transparency
3618  if ( ddValues.contains( QgsPalLayerSettings::BufferTransp ) )
3619  {
3620  tmpLyr.bufferTransp = ddValues.value( QgsPalLayerSettings::BufferTransp ).toInt();
3621  }
3622 
3623  //buffer size units
3624  if ( ddValues.contains( QgsPalLayerSettings::BufferUnit ) )
3625  {
3627  tmpLyr.bufferSizeInMapUnits = ( bufunit == QgsPalLayerSettings::MapUnits );
3628  }
3629 
3630  //buffer color
3631  if ( ddValues.contains( QgsPalLayerSettings::BufferColor ) )
3632  {
3633  QVariant ddColor = ddValues.value( QgsPalLayerSettings::BufferColor );
3634  tmpLyr.bufferColor = ddColor.value<QColor>();
3635  }
3636 
3637  // apply any transparency
3638  tmpLyr.bufferColor.setAlphaF(( 100.0 - ( double )( tmpLyr.bufferTransp ) ) / 100.0 );
3639 
3640  //buffer pen join style
3641  if ( ddValues.contains( QgsPalLayerSettings::BufferJoinStyle ) )
3642  {
3643  tmpLyr.bufferJoinStyle = ( Qt::PenJoinStyle )ddValues.value( QgsPalLayerSettings::BufferJoinStyle ).toInt();
3644  }
3645 
3646  //buffer blend mode
3647  if ( ddValues.contains( QgsPalLayerSettings::BufferBlendMode ) )
3648  {
3649  tmpLyr.bufferBlendMode = ( QPainter::CompositionMode )ddValues.value( QgsPalLayerSettings::BufferBlendMode ).toInt();
3650  }
3651 }
3652 
3654  const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant >& ddValues )
3655 {
3656  //shape draw
3657  if ( ddValues.contains( QgsPalLayerSettings::ShapeDraw ) )
3658  {
3659  tmpLyr.shapeDraw = ddValues.value( QgsPalLayerSettings::ShapeDraw ).toBool();
3660  }
3661 
3662  if ( !tmpLyr.shapeDraw )
3663  {
3664  return; // don't continue looking for unused values
3665  }
3666 
3667  if ( ddValues.contains( QgsPalLayerSettings::ShapeKind ) )
3668  {
3669  tmpLyr.shapeType = ( QgsPalLayerSettings::ShapeType )ddValues.value( QgsPalLayerSettings::ShapeKind ).toInt();
3670  }
3671 
3672  if ( ddValues.contains( QgsPalLayerSettings::ShapeSVGFile ) )
3673  {
3674  tmpLyr.shapeSVGFile = ddValues.value( QgsPalLayerSettings::ShapeSVGFile ).toString();
3675  }
3676 
3677  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeType ) )
3678  {
3680  }
3681 
3682  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeX ) )
3683  {
3684  tmpLyr.shapeSize.setX( ddValues.value( QgsPalLayerSettings::ShapeSizeX ).toDouble() );
3685  }
3686  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeY ) )
3687  {
3688  tmpLyr.shapeSize.setY( ddValues.value( QgsPalLayerSettings::ShapeSizeY ).toDouble() );
3689  }
3690 
3691  if ( ddValues.contains( QgsPalLayerSettings::ShapeSizeUnits ) )
3692  {
3694  }
3695 
3696  if ( ddValues.contains( QgsPalLayerSettings::ShapeRotationType ) )
3697  {
3699  }
3700 
3701  if ( ddValues.contains( QgsPalLayerSettings::ShapeRotation ) )
3702  {
3703  tmpLyr.shapeRotation = ddValues.value( QgsPalLayerSettings::ShapeRotation ).toDouble();
3704  }
3705 
3706  if ( ddValues.contains( QgsPalLayerSettings::ShapeOffset ) )
3707  {
3708  tmpLyr.shapeOffset = ddValues.value( QgsPalLayerSettings::ShapeOffset ).toPointF();
3709  }
3710 
3711  if ( ddValues.contains( QgsPalLayerSettings::ShapeOffsetUnits ) )
3712  {
3714  }
3715 
3716  if ( ddValues.contains( QgsPalLayerSettings::ShapeRadii ) )
3717  {
3718  tmpLyr.shapeRadii = ddValues.value( QgsPalLayerSettings::ShapeRadii ).toPointF();
3719  }
3720 
3721  if ( ddValues.contains( QgsPalLayerSettings::ShapeRadiiUnits ) )
3722  {
3724  }
3725 
3726  if ( ddValues.contains( QgsPalLayerSettings::ShapeTransparency ) )
3727  {
3728  tmpLyr.shapeTransparency = ddValues.value( QgsPalLayerSettings::ShapeTransparency ).toInt();
3729  }
3730 
3731  if ( ddValues.contains( QgsPalLayerSettings::ShapeBlendMode ) )
3732  {
3733  tmpLyr.shapeBlendMode = ( QPainter::CompositionMode )ddValues.value( QgsPalLayerSettings::ShapeBlendMode ).toInt();
3734  }
3735 
3736  if ( ddValues.contains( QgsPalLayerSettings::ShapeFillColor ) )
3737  {
3738  QVariant ddColor = ddValues.value( QgsPalLayerSettings::ShapeFillColor );
3739  tmpLyr.shapeFillColor = ddColor.value<QColor>();
3740  }
3741 
3742  if ( ddValues.contains( QgsPalLayerSettings::ShapeBorderColor ) )
3743  {
3744  QVariant ddColor = ddValues.value( QgsPalLayerSettings::ShapeBorderColor );
3745  tmpLyr.shapeBorderColor = ddColor.value<QColor>();
3746  }
3747 
3748  if ( ddValues.contains( QgsPalLayerSettings::ShapeBorderWidth ) )
3749  {
3750  tmpLyr.shapeBorderWidth = ddValues.value( QgsPalLayerSettings::ShapeBorderWidth ).toDouble();
3751  }
3752 
3753  if ( ddValues.contains( QgsPalLayerSettings::ShapeBorderWidthUnits ) )
3754  {
3756  }
3757 
3758  if ( ddValues.contains( QgsPalLayerSettings::ShapeJoinStyle ) )
3759  {
3760  tmpLyr.shapeJoinStyle = ( Qt::PenJoinStyle )ddValues.value( QgsPalLayerSettings::ShapeJoinStyle ).toInt();
3761  }
3762 }
3763 
3765  const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant >& ddValues )
3766 {
3767  //shadow draw
3768  if ( ddValues.contains( QgsPalLayerSettings::ShadowDraw ) )
3769  {
3770  tmpLyr.shadowDraw = ddValues.value( QgsPalLayerSettings::ShadowDraw ).toBool();
3771  }
3772 
3773  if ( !tmpLyr.shadowDraw )
3774  {
3775  return; // don't continue looking for unused values
3776  }
3777 
3778  if ( ddValues.contains( QgsPalLayerSettings::ShadowUnder ) )
3779  {
3781  }
3782 
3783  if ( ddValues.contains( QgsPalLayerSettings::ShadowOffsetAngle ) )
3784  {
3785  tmpLyr.shadowOffsetAngle = ddValues.value( QgsPalLayerSettings::ShadowOffsetAngle ).toInt();
3786  }
3787 
3788  if ( ddValues.contains( QgsPalLayerSettings::ShadowOffsetDist ) )
3789  {
3790  tmpLyr.shadowOffsetDist = ddValues.value( QgsPalLayerSettings::ShadowOffsetDist ).toDouble();
3791  }
3792 
3793  if ( ddValues.contains( QgsPalLayerSettings::ShadowOffsetUnits ) )
3794  {
3796  }
3797 
3798  if ( ddValues.contains( QgsPalLayerSettings::ShadowRadius ) )
3799  {
3800  tmpLyr.shadowRadius = ddValues.value( QgsPalLayerSettings::ShadowRadius ).toDouble();
3801  }
3802 
3803  if ( ddValues.contains( QgsPalLayerSettings::ShadowRadiusUnits ) )
3804  {
3806  }
3807 
3808  if ( ddValues.contains( QgsPalLayerSettings::ShadowTransparency ) )
3809  {
3810  tmpLyr.shadowTransparency = ddValues.value( QgsPalLayerSettings::ShadowTransparency ).toInt();
3811  }
3812 
3813  if ( ddValues.contains( QgsPalLayerSettings::ShadowScale ) )
3814  {
3815  tmpLyr.shadowScale = ddValues.value( QgsPalLayerSettings::ShadowScale ).toInt();
3816  }
3817 
3818  if ( ddValues.contains( QgsPalLayerSettings::ShadowColor ) )
3819  {
3820  QVariant ddColor = ddValues.value( QgsPalLayerSettings::ShadowColor );
3821  tmpLyr.shadowColor = ddColor.value<QColor>();
3822  }
3823 
3824  if ( ddValues.contains( QgsPalLayerSettings::ShadowBlendMode ) )
3825  {
3826  tmpLyr.shadowBlendMode = ( QPainter::CompositionMode )ddValues.value( QgsPalLayerSettings::ShadowBlendMode ).toInt();
3827  }
3828 }
3829 
3830 
3831 // helper function for checking for job cancellation within PAL
3832 static bool _palIsCancelled( void* ctx )
3833 {
3834  return (( QgsRenderContext* ) ctx )->renderingStopped();
3835 }
3836 
3838 {
3839  Q_ASSERT( mMapSettings != NULL );
3840  QPainter* painter = context.painter();
3841  QgsRectangle extent = context.extent();
3842 
3844 
3845  delete mResults;
3847 
3848  QTime t;
3849  t.start();
3850 
3851  // do the labeling itself
3852  double scale = mMapSettings->scale(); // scale denominator
3853  QgsRectangle r = extent;
3854  double bbox[] = { r.xMinimum(), r.yMinimum(), r.xMaximum(), r.yMaximum() };
3855 
3856  std::list<LabelPosition*>* labels;
3857  pal::Problem* problem;
3858  try
3859  {
3860  problem = mPal->extractProblem( scale, bbox );
3861  }
3862  catch ( std::exception& e )
3863  {
3864  Q_UNUSED( e );
3865  QgsDebugMsgLevel( "PAL EXCEPTION :-( " + QString::fromLatin1( e.what() ), 4 );
3866  //mActiveLayers.clear(); // clean up
3867  return;
3868  }
3869 
3870  if ( context.renderingStopped() )
3871  return; // it has been cancelled
3872 
3873  const QgsMapToPixel& xform = mMapSettings->mapToPixel();
3874 
3875  // draw rectangles with all candidates
3876  // this is done before actual solution of the problem
3877  // before number of candidates gets reduced
3878  mCandidates.clear();
3879  if ( mShowingCandidates && problem )
3880  {
3881  painter->setPen( QColor( 0, 0, 0, 64 ) );
3882  painter->setBrush( Qt::NoBrush );
3883  for ( int i = 0; i < problem->getNumFeatures(); i++ )
3884  {
3885  for ( int j = 0; j < problem->getFeatureCandidateCount( i ); j++ )
3886  {
3887  pal::LabelPosition* lp = problem->getFeatureCandidate( i, j );
3888 
3889  drawLabelCandidateRect( lp, painter, &xform );
3890  }
3891  }
3892  }
3893 
3894  // find the solution
3895  labels = mPal->solveProblem( problem, mShowingAllLabels );
3896 
3897  QgsDebugMsgLevel( QString( "LABELING work: %1 ms ... labels# %2" ).arg( t.elapsed() ).arg( labels->size() ), 4 );
3898  t.restart();
3899 
3900  if ( context.renderingStopped() )
3901  {
3902  delete problem;
3903  delete labels;
3905  return;
3906  }
3907 
3908  painter->setRenderHint( QPainter::Antialiasing );
3909 
3910  // draw the labels
3911  std::list<LabelPosition*>::iterator it = labels->begin();
3912  for ( ; it != labels->end(); ++it )
3913  {
3914  if ( context.renderingStopped() )
3915  break;
3916 
3917  QgsPalGeometry* palGeometry = dynamic_cast< QgsPalGeometry* >(( *it )->getFeaturePart()->getUserGeometry() );
3918  if ( !palGeometry )
3919  {
3920  continue;
3921  }
3922 
3923  //layer names
3924  QString layerName = QString::fromUtf8(( *it )->getLayerName() );
3925  if ( palGeometry->isDiagram() )
3926  {
3927  QgsFeature feature;
3928  //render diagram
3929  QHash<QString, QgsDiagramLayerSettings>::iterator dit = mActiveDiagramLayers.begin();
3930  for ( dit = mActiveDiagramLayers.begin(); dit != mActiveDiagramLayers.end(); ++dit )
3931  {
3932  if ( QString( dit.key() + "d" ) == layerName )
3933  {
3934  feature.setFields( &dit.value().fields );
3935  palGeometry->feature( feature );
3936  QgsPoint outPt = xform.transform(( *it )->getX(), ( *it )->getY() );
3937  dit.value().renderer->renderDiagram( feature, context, QPointF( outPt.x(), outPt.y() ) );
3938  }
3939  }
3940 
3941  //insert into label search tree to manipulate position interactively
3942  if ( mResults->mLabelSearchTree )
3943  {
3944  //for diagrams, remove the additional 'd' at the end of the layer id
3945  QString layerId = layerName;
3946  layerId.chop( 1 );
3947  mResults->mLabelSearchTree->insertLabel( *it, QString( palGeometry->strId() ).toInt(), QString( "" ), layerId, QFont(), true, false );
3948  }
3949  continue;
3950  }
3951 
3952  const QgsPalLayerSettings& lyr = layer( layerName );
3953 
3954  // Copy to temp, editable layer settings
3955  // these settings will be changed by any data defined values, then used for rendering label components
3956  // settings may be adjusted during rendering of components
3957  QgsPalLayerSettings tmpLyr( lyr );
3958 
3959  // apply any previously applied data defined settings for the label
3960  const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant >& ddValues = palGeometry->dataDefinedValues();
3961 
3962  //font
3963  QFont dFont = palGeometry->definedFont();
3964  // following debug is >= Qt 4.8 only ( because of QFont::styleName() )
3965 #if QT_VERSION >= 0x040800
3966  QgsDebugMsgLevel( QString( "PAL font tmpLyr: %1, Style: %2" ).arg( tmpLyr.textFont.toString() ).arg( QFontInfo( tmpLyr.textFont ).styleName() ), 4 );
3967  QgsDebugMsgLevel( QString( "PAL font definedFont: %1, Style: %2" ).arg( dFont.toString() ).arg( dFont.styleName() ), 4 );
3968 #endif
3969  tmpLyr.textFont = dFont;
3970 
3971  // update tmpLyr with any data defined text style values
3972  dataDefinedTextStyle( tmpLyr, ddValues );
3973 
3974  // update tmpLyr with any data defined text buffer values
3975  dataDefinedTextBuffer( tmpLyr, ddValues );
3976 
3977  // update tmpLyr with any data defined text formatting values
3978  dataDefinedTextFormatting( tmpLyr, ddValues );
3979 
3980  // update tmpLyr with any data defined shape background values
3981  dataDefinedShapeBackground( tmpLyr, ddValues );
3982 
3983  // update tmpLyr with any data defined drop shadow values
3984  dataDefinedDropShadow( tmpLyr, ddValues );
3985 
3986 
3988 
3989  // Render the components of a label in reverse order
3990  // (backgrounds -> text)
3991 
3992  if ( tmpLyr.shadowDraw && tmpLyr.shadowUnder == QgsPalLayerSettings::ShadowLowest )
3993  {
3994  if ( tmpLyr.shapeDraw )
3995  {
3997  }
3998  else if ( tmpLyr.bufferDraw )
3999  {
4001  }
4002  else
4003  {
4005  }
4006  }
4007 
4008  if ( tmpLyr.shapeDraw )
4009  {
4010  drawLabel( *it, context, tmpLyr, LabelShape );
4011  }
4012 
4013  if ( tmpLyr.bufferDraw )
4014  {
4015  drawLabel( *it, context, tmpLyr, LabelBuffer );
4016  }
4017 
4018  drawLabel( *it, context, tmpLyr, LabelText );
4019 
4020  if ( mResults->mLabelSearchTree )
4021  {
4022  QString labeltext = (( QgsPalGeometry* )( *it )->getFeaturePart()->getUserGeometry() )->text();
4023  mResults->mLabelSearchTree->insertLabel( *it, QString( palGeometry->strId() ).toInt(), layerName, labeltext, dFont, false, palGeometry->isPinned() );
4024  }
4025  }
4026 
4027  // Reset composition mode for further drawing operations
4028  painter->setCompositionMode( QPainter::CompositionMode_SourceOver );
4029 
4030  QgsDebugMsgLevel( QString( "LABELING draw: %1 ms" ).arg( t.elapsed() ), 4 );
4031 
4032  delete problem;
4033  delete labels;
4035 }
4036 
4038 {
4039  // delete all allocated geometries for features
4040  QHash<QString, QgsPalLayerSettings>::iterator lit;
4041  for ( lit = mActiveLayers.begin(); lit != mActiveLayers.end(); ++lit )
4042  {
4043  QgsPalLayerSettings& lyr = lit.value();
4044  for ( QList<QgsPalGeometry*>::iterator git = lyr.geometries.begin(); git != lyr.geometries.end(); ++git )
4045  delete *git;
4046  if ( lyr.limitNumLabels )
4047  {
4048  QgsDebugMsgLevel( QString( "mFeaturesToLabel: %1" ).arg( lyr.mFeaturesToLabel ), 4 );
4049  QgsDebugMsgLevel( QString( "maxNumLabels: %1" ).arg( lyr.maxNumLabels ), 4 );
4050  QgsDebugMsgLevel( QString( "mFeatsSendingToPal: %1" ).arg( lyr.mFeatsSendingToPal ), 4 );
4051  QgsDebugMsgLevel( QString( "mFeatsRegPal: %1" ).arg( lyr.geometries.count() ), 4 );
4052  }
4053  lyr.geometries.clear();
4054  }
4055 
4056  //delete all allocated geometries for diagrams
4057  QHash<QString, QgsDiagramLayerSettings>::iterator dIt = mActiveDiagramLayers.begin();
4058  for ( ; dIt != mActiveDiagramLayers.end(); ++dIt )
4059  {
4060  QgsDiagramLayerSettings& dls = dIt.value();
4061  for ( QList<QgsPalGeometry*>::iterator git = dls.geometries.begin(); git != dls.geometries.end(); ++git )
4062  {
4063  delete *git;
4064  }
4065  dls.geometries.clear();
4066  }
4067 }
4068 
4069 QList<QgsLabelPosition> QgsPalLabeling::labelsAtPosition( const QgsPoint& p )
4070 {
4071  return mResults ? mResults->labelsAtPosition( p ) : QList<QgsLabelPosition>();
4072 }
4073 
4074 QList<QgsLabelPosition> QgsPalLabeling::labelsWithinRect( const QgsRectangle& r )
4075 {
4076  return mResults ? mResults->labelsWithinRect( r ) : QList<QgsLabelPosition>();
4077 }
4078 
4080 {
4081  if ( mResults )
4082  {
4084  mResults = 0;
4085  return tmp; // ownership passed to the caller
4086  }
4087  else
4088  return 0;
4089 }
4090 
4091 void QgsPalLabeling::numCandidatePositions( int& candPoint, int& candLine, int& candPolygon )
4092 {
4093  candPoint = mCandPoint;
4094  candLine = mCandLine;
4095  candPolygon = mCandPolygon;
4096 }
4097 
4098 void QgsPalLabeling::setNumCandidatePositions( int candPoint, int candLine, int candPolygon )
4099 {
4100  mCandPoint = candPoint;
4101  mCandLine = candLine;
4102  mCandPolygon = candPolygon;
4103 }
4104 
4106 {
4107  mSearch = s;
4108 }
4109 
4111 {
4112  return mSearch;
4113 }
4114 
4116 {
4117  QgsPoint outPt = xform->transform( lp->getX(), lp->getY() );
4118  QgsPoint outPt2 = xform->transform( lp->getX() + lp->getWidth(), lp->getY() + lp->getHeight() );
4119 
4120  painter->save();
4121  painter->translate( QPointF( outPt.x(), outPt.y() ) );
4122  painter->rotate( -lp->getAlpha() * 180 / M_PI );
4123  QRectF rect( 0, 0, outPt2.x() - outPt.x(), outPt2.y() - outPt.y() );
4124  painter->drawRect( rect );
4125  painter->restore();
4126 
4127  // save the rect
4128  rect.moveTo( outPt.x(), outPt.y() );
4129  mCandidates.append( QgsLabelCandidate( rect, lp->getCost() * 1000 ) );
4130 
4131  // show all parts of the multipart label
4132  if ( lp->getNextPart() )
4133  drawLabelCandidateRect( lp->getNextPart(), painter, xform );
4134 }
4135 
4136 void QgsPalLabeling::drawLabel( pal::LabelPosition* label, QgsRenderContext& context, QgsPalLayerSettings& tmpLyr, DrawLabelType drawType, double dpiRatio )
4137 {
4138  // NOTE: this is repeatedly called for multi-part labels
4139  QPainter* painter = context.painter();
4140  const QgsMapToPixel* xform = &context.mapToPixel();
4141 
4142  QgsLabelComponent component;
4143  component.setDpiRatio( dpiRatio );
4144 
4145  QgsPoint outPt = xform->transform( label->getX(), label->getY() );
4146 // QgsPoint outPt2 = xform->transform( label->getX() + label->getWidth(), label->getY() + label->getHeight() );
4147 // QRectF labelRect( 0, 0, outPt2.x() - outPt.x(), outPt2.y() - outPt.y() );
4148 
4149  component.setOrigin( outPt );
4150  component.setRotation( label->getAlpha() );
4151 
4152  if ( drawType == QgsPalLabeling::LabelShape )
4153  {
4154  // get rotated label's center point
4155  QgsPoint centerPt( outPt );
4156  QgsPoint outPt2 = xform->transform( label->getX() + label->getWidth() / 2,
4157  label->getY() + label->getHeight() / 2 );
4158 
4159  double xc = outPt2.x() - outPt.x();
4160  double yc = outPt2.y() - outPt.y();
4161 
4162  double angle = -label->getAlpha();
4163  double xd = xc * cos( angle ) - yc * sin( angle );
4164  double yd = xc * sin( angle ) + yc * cos( angle );
4165 
4166  centerPt.setX( centerPt.x() + xd );
4167  centerPt.setY( centerPt.y() + yd );
4168 
4169  component.setCenter( centerPt );
4170  component.setSize( QgsPoint( label->getWidth(), label->getHeight() ) );
4171 
4172  drawLabelBackground( context, component, tmpLyr );
4173  }
4174 
4175  if ( drawType == QgsPalLabeling::LabelBuffer
4176  || drawType == QgsPalLabeling::LabelText )
4177  {
4178 
4179  // TODO: optimize access :)
4180  QString text = (( QgsPalGeometry* )label->getFeaturePart()->getUserGeometry() )->text();
4181  QString txt = ( label->getPartId() == -1 ? text : QString( text[label->getPartId()] ) );
4182  QFontMetricsF* labelfm = (( QgsPalGeometry* )label->getFeaturePart()->getUserGeometry() )->getLabelFontMetrics();
4183 
4184  QString wrapchr = !tmpLyr.wrapChar.isEmpty() ? tmpLyr.wrapChar : QString( "\n" );
4185 
4186  //add the direction symbol if needed
4187  if ( !txt.isEmpty() && tmpLyr.placement == QgsPalLayerSettings::Line &&
4188  tmpLyr.addDirectionSymbol )
4189  {
4190  bool prependSymb = false;
4191  QString symb = tmpLyr.rightDirectionSymbol;
4192 
4193  if ( label->getReversed() )
4194  {
4195  prependSymb = true;
4196  symb = tmpLyr.leftDirectionSymbol;
4197  }
4198 
4199  if ( tmpLyr.reverseDirectionSymbol )
4200  {
4201  if ( symb == tmpLyr.rightDirectionSymbol )
4202  {
4203  prependSymb = true;
4204  symb = tmpLyr.leftDirectionSymbol;
4205  }
4206  else
4207  {
4208  prependSymb = false;
4209  symb = tmpLyr.rightDirectionSymbol;
4210  }
4211  }
4212 
4214  {
4215  prependSymb = true;
4216  symb = symb + wrapchr;
4217  }
4219  {
4220  prependSymb = false;
4221  symb = wrapchr + symb;
4222  }
4223 
4224  if ( prependSymb )
4225  {
4226  txt.prepend( symb );
4227  }
4228  else
4229  {
4230  txt.append( symb );
4231  }
4232  }
4233 
4234  //QgsDebugMsgLevel( "drawLabel " + txt, 4 );
4235 
4236  QStringList multiLineList = txt.split( wrapchr );
4237  int lines = multiLineList.size();
4238 
4239  double labelWidest = 0.0;
4240  for ( int i = 0; i < lines; ++i )
4241  {
4242  double labelWidth = labelfm->width( multiLineList.at( i ) );
4243  if ( labelWidth > labelWidest )
4244  {
4245  labelWidest = labelWidth;
4246  }
4247  }
4248 
4249  double labelHeight = labelfm->ascent() + labelfm->descent(); // ignore +1 for baseline
4250  // double labelHighest = labelfm->height() + ( double )(( lines - 1 ) * labelHeight * tmpLyr.multilineHeight );
4251 
4252  // needed to move bottom of text's descender to within bottom edge of label
4253  double ascentOffset = 0.25 * labelfm->ascent(); // labelfm->descent() is not enough
4254 
4255  for ( int i = 0; i < lines; ++i )
4256  {
4257  painter->save();
4258  painter->translate( QPointF( outPt.x(), outPt.y() ) );
4259  painter->rotate( -label->getAlpha() * 180 / M_PI );
4260 
4261  // scale down painter: the font size has been multiplied by raster scale factor
4262  // to workaround a Qt font scaling bug with small font sizes
4263  painter->scale( 1.0 / tmpLyr.rasterCompressFactor, 1.0 / tmpLyr.rasterCompressFactor );
4264 
4265  // figure x offset for horizontal alignment of multiple lines
4266  double xMultiLineOffset = 0.0;
4267  double labelWidth = labelfm->width( multiLineList.at( i ) );
4268  if ( lines > 1 && tmpLyr.multilineAlign != QgsPalLayerSettings::MultiLeft )
4269  {
4270  double labelWidthDiff = labelWidest - labelWidth;
4272  {
4273  labelWidthDiff /= 2;
4274  }
4275  xMultiLineOffset = labelWidthDiff;
4276  //QgsDebugMsgLevel( QString( "xMultiLineOffset: %1" ).arg( xMultiLineOffset ), 4 );
4277  }
4278 
4279  double yMultiLineOffset = ( lines - 1 - i ) * labelHeight * tmpLyr.multilineHeight;
4280  painter->translate( QPointF( xMultiLineOffset, - ascentOffset - yMultiLineOffset ) );
4281 
4282  component.setText( multiLineList.at( i ) );
4283  component.setSize( QgsPoint( labelWidth, labelHeight ) );
4284  component.setOffset( QgsPoint( 0.0, -ascentOffset ) );
4285  component.setRotation( -component.rotation() * 180 / M_PI );
4286  component.setRotationOffset( 0.0 );
4287 
4288  if ( drawType == QgsPalLabeling::LabelBuffer )
4289  {
4290  // draw label's buffer
4291  drawLabelBuffer( context, component, tmpLyr );
4292  }
4293  else
4294  {
4295  // draw label's text, QPainterPath method
4296  QPainterPath path;
4297  path.addText( 0, 0, tmpLyr.textFont, component.text() );
4298 
4299  // store text's drawing in QPicture for drop shadow call
4300  QPicture textPict;
4301  QPainter textp;
4302  textp.begin( &textPict );
4303  textp.setPen( Qt::NoPen );
4304  textp.setBrush( tmpLyr.textColor );
4305  textp.drawPath( path );
4306  // TODO: why are some font settings lost on drawPicture() when using drawText() inside QPicture?
4307  // e.g. some capitalization options, but not others
4308  //textp.setFont( tmpLyr.textFont );
4309  //textp.setPen( tmpLyr.textColor );
4310  //textp.drawText( 0, 0, component.text() );
4311  textp.end();
4312 
4313  if ( tmpLyr.shadowDraw && tmpLyr.shadowUnder == QgsPalLayerSettings::ShadowText )
4314  {
4315  component.setPicture( &textPict );
4316  component.setPictureBuffer( 0.0 ); // no pen width to deal with
4317  component.setOrigin( QgsPoint( 0.0, 0.0 ) );
4318 
4319  drawLabelShadow( context, component, tmpLyr );
4320  }
4321 
4322  // paint the text
4323  if ( context.useAdvancedEffects() )
4324  {
4325  painter->setCompositionMode( tmpLyr.blendMode );
4326  }
4327 
4328  // scale for any print output or image saving @ specific dpi
4329  painter->scale( component.dpiRatio(), component.dpiRatio() );
4330 
4331  if ( mDrawOutlineLabels )
4332  {
4333  // draw outlined text
4334  _fixQPictureDPI( painter );
4335  painter->drawPicture( 0, 0, textPict );
4336  }
4337  else
4338  {
4339  // draw text as text (for SVG and PDF exports)
4340  painter->setFont( tmpLyr.textFont );
4341  painter->setPen( tmpLyr.textColor );
4342  painter->setRenderHint( QPainter::TextAntialiasing );
4343  painter->drawText( 0, 0, component.text() );
4344  }
4345  }
4346  painter->restore();
4347  }
4348  }
4349 
4350  // NOTE: this used to be within above multi-line loop block, at end. (a mistake since 2010? [LS])
4351  if ( label->getNextPart() )
4352  drawLabel( label->getNextPart(), context, tmpLyr, drawType, dpiRatio );
4353 }
4354 
4356  QgsLabelComponent component,
4357  const QgsPalLayerSettings& tmpLyr )
4358 {
4359  QPainter* p = context.painter();
4360 
4361  double penSize = tmpLyr.scaleToPixelContext( tmpLyr.bufferSize, context,
4363 
4364  QPainterPath path;
4365  path.addText( 0, 0, tmpLyr.textFont, component.text() );
4366  QPen pen( tmpLyr.bufferColor );
4367  pen.setWidthF( penSize );
4368  pen.setJoinStyle( tmpLyr.bufferJoinStyle );
4369  QColor tmpColor( tmpLyr.bufferColor );
4370  // honor pref for whether to fill buffer interior
4371  if ( tmpLyr.bufferNoFill )
4372  {
4373  tmpColor.setAlpha( 0 );
4374  }
4375 
4376  // store buffer's drawing in QPicture for drop shadow call
4377  QPicture buffPict;
4378  QPainter buffp;
4379  buffp.begin( &buffPict );
4380  buffp.setPen( pen );
4381  buffp.setBrush( tmpColor );
4382  buffp.drawPath( path );
4383  buffp.end();
4384 
4385  if ( tmpLyr.shadowDraw && tmpLyr.shadowUnder == QgsPalLayerSettings::ShadowBuffer )
4386  {
4387  component.setOrigin( QgsPoint( 0.0, 0.0 ) );
4388  component.setPicture( &buffPict );
4389  component.setPictureBuffer( penSize / 2.0 );
4390 
4391  drawLabelShadow( context, component, tmpLyr );
4392  }
4393 
4394  p->save();
4395  if ( context.useAdvancedEffects() )
4396  {
4397  p->setCompositionMode( tmpLyr.bufferBlendMode );
4398  }
4399 // p->setPen( pen );
4400 // p->setBrush( tmpColor );
4401 // p->drawPath( path );
4402 
4403  // scale for any print output or image saving @ specific dpi
4404  p->scale( component.dpiRatio(), component.dpiRatio() );
4405  _fixQPictureDPI( p );
4406  p->drawPicture( 0, 0, buffPict );
4407  p->restore();
4408 }
4409 
4411  QgsLabelComponent component,
4412  const QgsPalLayerSettings& tmpLyr )
4413 {
4414  QPainter* p = context.painter();
4415  double labelWidth = component.size().x(), labelHeight = component.size().y();
4416  //QgsDebugMsgLevel( QString( "Background label rotation: %1" ).arg( component.rotation() ), 4 );
4417 
4418  // shared calculations between shapes and SVG
4419 
4420  // configure angles, set component rotation and rotationOffset
4422  {
4423  component.setRotation( -( component.rotation() * 180 / M_PI ) ); // RotationSync
4424  component.setRotationOffset(
4426  }
4427  else // RotationFixed
4428  {
4429  component.setRotation( 0.0 ); // don't use label's rotation
4430  component.setRotationOffset( tmpLyr.shapeRotation );
4431  }
4432 
4433  // mm to map units conversion factor
4434  double mmToMapUnits = tmpLyr.shapeSizeMapUnitScale.computeMapUnitsPerPixel( context ) * context.scaleFactor();
4435 
4436  // TODO: the following label-buffered generated shapes and SVG symbols should be moved into marker symbology classes
4437 
4438  if ( tmpLyr.shapeType == QgsPalLayerSettings::ShapeSVG )
4439  {
4440  // all calculations done in shapeSizeUnits, which are then passed to symbology class for painting
4441 
4442  if ( tmpLyr.shapeSVGFile.isEmpty() )
4443  return;
4444 
4445  double sizeOut = 0.0;
4446  // only one size used for SVG sizing/scaling (no use of shapeSize.y() or Y field in gui)
4448  {
4449  sizeOut = tmpLyr.shapeSize.x();
4450  }
4451  else if ( tmpLyr.shapeSizeType == QgsPalLayerSettings::SizeBuffer )
4452  {
4453  // add buffer to greatest dimension of label
4454  if ( labelWidth >= labelHeight )
4455  sizeOut = labelWidth;
4456  else if ( labelHeight > labelWidth )
4457  sizeOut = labelHeight;
4458 
4459  // label size in map units, convert to shapeSizeUnits, if different
4460  if ( tmpLyr.shapeSizeUnits == QgsPalLayerSettings::MM )
4461  {
4462  sizeOut /= mmToMapUnits;
4463  }
4464 
4465  // add buffer
4466  sizeOut += tmpLyr.shapeSize.x() * 2;
4467  }
4468 
4469  // don't bother rendering symbols smaller than 1x1 pixels in size
4470  // TODO: add option to not show any svgs under/over a certian size
4471  if ( tmpLyr.scaleToPixelContext( sizeOut, context, tmpLyr.shapeSizeUnits, false, tmpLyr.shapeSizeMapUnitScale ) < 1.0 )
4472  return;
4473 
4474  QgsStringMap map; // for SVG symbology marker
4475  map["name"] = QgsSymbolLayerV2Utils::symbolNameToPath( tmpLyr.shapeSVGFile.trimmed() );
4476  map["size"] = QString::number( sizeOut );
4477  map["size_unit"] = QgsSymbolLayerV2Utils::encodeOutputUnit(
4479  map["angle"] = QString::number( 0.0 ); // angle is handled by this local painter
4480 
4481  // offset is handled by this local painter
4482  // TODO: see why the marker renderer doesn't seem to translate offset *after* applying rotation
4483  //map["offset"] = QgsSymbolLayerV2Utils::encodePoint( tmpLyr.shapeOffset );
4484  //map["offset_unit"] = QgsSymbolLayerV2Utils::encodeOutputUnit(
4485  // tmpLyr.shapeOffsetUnits == QgsPalLayerSettings::MapUnits ? QgsSymbolV2::MapUnit : QgsSymbolV2::MM );
4486 
4487  map["fill"] = tmpLyr.shapeFillColor.name();
4488  map["outline"] = tmpLyr.shapeBorderColor.name();
4489  map["outline-width"] = QString::number( tmpLyr.shapeBorderWidth );
4490 
4491  // TODO: fix overriding SVG symbol's border width/units in QgsSvgCache
4492  // currently broken, fall back to symbol's
4493  //map["outline_width_unit"] = QgsSymbolLayerV2Utils::encodeOutputUnit(
4494  // tmpLyr.shapeBorderWidthUnits == QgsPalLayerSettings::MapUnits ? QgsSymbolV2::MapUnit : QgsSymbolV2::MM );
4495 
4496  if ( tmpLyr.shadowDraw && tmpLyr.shadowUnder == QgsPalLayerSettings::ShadowShape )
4497  {
4498  // configure SVG shadow specs
4499  QgsStringMap shdwmap( map );
4500  shdwmap["fill"] = tmpLyr.shadowColor.name();
4501  shdwmap["outline"] = tmpLyr.shadowColor.name();
4502  shdwmap["size"] = QString::number( sizeOut * tmpLyr.rasterCompressFactor );
4503 
4504  // store SVG's drawing in QPicture for drop shadow call
4505  QPicture svgPict;
4506  QPainter svgp;
4507  svgp.begin( &svgPict );
4508 
4509  // draw shadow symbol
4510 
4511  // clone current render context map unit/mm conversion factors, but not
4512  // other map canvas parameters, then substitute this painter for use in symbology painting
4513  // NOTE: this is because the shadow needs to be scaled correctly for output to map canvas,
4514  // but will be created relative to the SVG's computed size, not the current map canvas
4515  QgsRenderContext shdwContext;
4516  shdwContext.setMapToPixel( context.mapToPixel() );
4517  shdwContext.setScaleFactor( context.scaleFactor() );
4518  shdwContext.setPainter( &svgp );
4519 
4520  QgsSymbolLayerV2* symShdwL = QgsSvgMarkerSymbolLayerV2::create( shdwmap );
4521  QgsSvgMarkerSymbolLayerV2* svgShdwM = static_cast<QgsSvgMarkerSymbolLayerV2*>( symShdwL );
4522  QgsSymbolV2RenderContext svgShdwContext( shdwContext, QgsSymbolV2::Mixed,
4523  ( 100.0 - ( double )( tmpLyr.shapeTransparency ) ) / 100.0 );
4524 
4525  double svgSize = tmpLyr.scaleToPixelContext( sizeOut, context, tmpLyr.shapeSizeUnits, true, tmpLyr.shapeSizeMapUnitScale );
4526  svgShdwM->renderPoint( QPointF( svgSize / 2, -svgSize / 2 ), svgShdwContext );
4527  svgp.end();
4528 
4529  component.setPicture( &svgPict );
4530  // TODO: when SVG symbol's border width/units is fixed in QgsSvgCache, adjust for it here
4531  component.setPictureBuffer( 0.0 );
4532 
4533  component.setSize( QgsPoint( svgSize, svgSize ) );
4534  component.setOffset( QgsPoint( 0.0, 0.0 ) );
4535 
4536  // rotate about origin center of SVG
4537  p->save();
4538  p->translate( component.center().x(), component.center().y() );
4539  p->rotate( component.rotation() );
4540  p->scale( 1.0 / tmpLyr.rasterCompressFactor, 1.0 / tmpLyr.rasterCompressFactor );
4541  double xoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.x(), context, tmpLyr.shapeOffsetUnits, true, tmpLyr.shapeOffsetMapUnitScale );
4542  double yoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.y(), context, tmpLyr.shapeOffsetUnits, true, tmpLyr.shapeOffsetMapUnitScale );
4543  p->translate( QPointF( xoff, yoff ) );
4544  p->rotate( component.rotationOffset() );
4545  p->translate( -svgSize / 2, svgSize / 2 );
4546 
4547  drawLabelShadow( context, component, tmpLyr );
4548  p->restore();
4549 
4550  delete svgShdwM;
4551  svgShdwM = 0;
4552  }
4553 
4554  // draw the actual symbol
4556  QgsSvgMarkerSymbolLayerV2* svgM = static_cast<QgsSvgMarkerSymbolLayerV2*>( symL );
4557  QgsSymbolV2RenderContext svgContext( context, QgsSymbolV2::Mixed,
4558  ( 100.0 - ( double )( tmpLyr.shapeTransparency ) ) / 100.0 );
4559 
4560  p->save();
4561  if ( context.useAdvancedEffects() )
4562  {
4563  p->setCompositionMode( tmpLyr.shapeBlendMode );
4564  }
4565  p->translate( component.center().x(), component.center().y() );
4566  p->rotate( component.rotation() );
4567  double xoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.x(), context, tmpLyr.shapeOffsetUnits, false, tmpLyr.shapeOffsetMapUnitScale );
4568  double yoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.y(), context, tmpLyr.shapeOffsetUnits, false, tmpLyr.shapeOffsetMapUnitScale );
4569  p->translate( QPointF( xoff, yoff ) );
4570  p->rotate( component.rotationOffset() );
4571  svgM->renderPoint( QPointF( 0, 0 ), svgContext );
4572  p->setCompositionMode( QPainter::CompositionMode_SourceOver ); // just to be sure
4573  p->restore();
4574 
4575  delete svgM;
4576  svgM = 0;
4577 
4578  }
4579  else // Generated Shapes
4580  {
4581  // all calculations done in shapeSizeUnits
4582 
4583  double w = labelWidth / ( tmpLyr.shapeSizeUnits == QgsPalLayerSettings::MM ? mmToMapUnits : 1 );
4584  double h = labelHeight / ( tmpLyr.shapeSizeUnits == QgsPalLayerSettings::MM ? mmToMapUnits : 1 );
4585 
4586  double xsize = tmpLyr.shapeSize.x();
4587  double ysize = tmpLyr.shapeSize.y();
4588 
4590  {
4591  w = xsize;
4592  h = ysize;
4593  }
4594  else if ( tmpLyr.shapeSizeType == QgsPalLayerSettings::SizeBuffer )
4595  {
4597  {
4598  if ( w > h )
4599  h = w;
4600  else if ( h > w )
4601  w = h;
4602  }
4603  else if ( tmpLyr.shapeType == QgsPalLayerSettings::ShapeCircle )
4604  {
4605  // start with label bound by circle
4606  h = sqrt( pow( w, 2 ) + pow( h, 2 ) );
4607  w = h;
4608  }
4609  else if ( tmpLyr.shapeType == QgsPalLayerSettings::ShapeEllipse )
4610  {
4611  // start with label bound by ellipse
4612  h = h / sqrt( 2.0 ) * 2;
4613  w = w / sqrt( 2.0 ) * 2;
4614  }
4615 
4616  w += xsize * 2;
4617  h += ysize * 2;
4618  }
4619 
4620  // convert everything over to map pixels from here on
4621  w = tmpLyr.scaleToPixelContext( w, context, tmpLyr.shapeSizeUnits, true, tmpLyr.shapeSizeMapUnitScale );
4622  h = tmpLyr.scaleToPixelContext( h, context, tmpLyr.shapeSizeUnits, true, tmpLyr.shapeSizeMapUnitScale );
4623 
4624  // offsets match those of symbology: -x = left, -y = up
4625  QRectF rect( -w / 2.0, - h / 2.0, w, h );
4626 
4627  if ( rect.isNull() )
4628  return;
4629 
4630  p->save();
4631  p->translate( QPointF( component.center().x(), component.center().y() ) );
4632  p->rotate( component.rotation() );
4633  double xoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.x(), context, tmpLyr.shapeOffsetUnits, false, tmpLyr.shapeOffsetMapUnitScale );
4634  double yoff = tmpLyr.scaleToPixelContext( tmpLyr.shapeOffset.y(), context, tmpLyr.shapeOffsetUnits, false, tmpLyr.shapeOffsetMapUnitScale );
4635  p->translate( QPointF( xoff, yoff ) );
4636  p->rotate( component.rotationOffset() );
4637 
4638  double penSize = tmpLyr.scaleToPixelContext( tmpLyr.shapeBorderWidth, context, tmpLyr.shapeBorderWidthUnits, true, tmpLyr.shapeBorderWidthMapUnitScale );
4639 
4640  QPen pen;
4641  if ( tmpLyr.shapeBorderWidth > 0 )
4642  {
4643  pen.setColor( tmpLyr.shapeBorderColor );
4644  pen.setWidthF( penSize );
4646  pen.setJoinStyle( tmpLyr.shapeJoinStyle );
4647  }
4648  else
4649  {
4650  pen = Qt::NoPen;
4651  }
4652 
4653  // store painting in QPicture for shadow drawing
4654  QPicture shapePict;
4655  QPainter shapep;
4656  shapep.begin( &shapePict );
4657  shapep.setPen( pen );
4658  shapep.setBrush( tmpLyr.shapeFillColor );
4659 
4662  {
4664  {
4665  shapep.drawRoundedRect( rect, tmpLyr.shapeRadii.x(), tmpLyr.shapeRadii.y(), Qt::RelativeSize );
4666  }
4667  else
4668  {
4669  double xRadius = tmpLyr.scaleToPixelContext( tmpLyr.shapeRadii.x(), context, tmpLyr.shapeRadiiUnits, true, tmpLyr.shapeRadiiMapUnitScale );
4670  double yRadius = tmpLyr.scaleToPixelContext( tmpLyr.shapeRadii.y(), context, tmpLyr.shapeRadiiUnits, true, tmpLyr.shapeRadiiMapUnitScale );
4671  shapep.drawRoundedRect( rect, xRadius, yRadius );
4672  }
4673  }
4674  else if ( tmpLyr.shapeType == QgsPalLayerSettings::ShapeEllipse
4676  {
4677  shapep.drawEllipse( rect );
4678  }
4679  shapep.end();
4680 
4681  p->scale( 1.0 / tmpLyr.rasterCompressFactor, 1.0 / tmpLyr.rasterCompressFactor );
4682 
4683  if ( tmpLyr.shadowDraw && tmpLyr.shadowUnder == QgsPalLayerSettings::ShadowShape )
4684  {
4685  component.setPicture( &shapePict );
4686  component.setPictureBuffer( penSize / 2.0 );
4687 
4688  component.setSize( QgsPoint( rect.width(), rect.height() ) );
4689  component.setOffset( QgsPoint( rect.width() / 2, -rect.height() / 2 ) );
4690  drawLabelShadow( context, component, tmpLyr );
4691  }
4692 
4693  p->setOpacity(( 100.0 - ( double )( tmpLyr.shapeTransparency ) ) / 100.0 );
4694  if ( context.useAdvancedEffects() )
4695  {
4696  p->setCompositionMode( tmpLyr.shapeBlendMode );
4697  }
4698 
4699  // scale for any print output or image saving @ specific dpi
4700  p->scale( component.dpiRatio(), component.dpiRatio() );
4701  _fixQPictureDPI( p );
4702  p->drawPicture( 0, 0, shapePict );
4703  p->restore();
4704  }
4705 }
4706 
4708  QgsLabelComponent component,
4709  const QgsPalLayerSettings& tmpLyr )
4710 {
4711  // incoming component sizes should be multiplied by rasterCompressFactor, as
4712  // this allows shadows to be created at paint device dpi (e.g. high resolution),
4713  // then scale device painter by 1.0 / rasterCompressFactor for output
4714 
4715  QPainter* p = context.painter();
4716  double componentWidth = component.size().x(), componentHeight = component.size().y();
4717  double xOffset = component.offset().x(), yOffset = component.offset().y();
4718  double pictbuffer = component.pictureBuffer();
4719 
4720  // generate pixmap representation of label component drawing
4721  bool mapUnits = ( tmpLyr.shadowRadiusUnits == QgsPalLayerSettings::MapUnits );
4722  double radius = tmpLyr.scaleToPixelContext( tmpLyr.shadowRadius, context, tmpLyr.shadowRadiusUnits, !mapUnits, tmpLyr.shadowRadiusMapUnitScale );
4723  radius /= ( mapUnits ? tmpLyr.vectorScaleFactor / component.dpiRatio() : 1 );
4724  radius = ( int )( radius + 0.5 );
4725 
4726  // TODO: add labeling gui option to adjust blurBufferClippingScale to minimize pixels, or
4727  // to ensure shadow isn't clipped too tight. (Or, find a better method of buffering)
4728  double blurBufferClippingScale = 3.75;
4729  int blurbuffer = ( radius > 17 ? 16 : radius ) * blurBufferClippingScale;
4730 
4731  QImage blurImg( componentWidth + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ),
4732  componentHeight + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ),
4733  QImage::Format_ARGB32_Premultiplied );
4734 
4735  // TODO: add labeling gui option to not show any shadows under/over a certian size
4736  // keep very small QImages from causing paint device issues, i.e. must be at least > 1
4737  int minBlurImgSize = 1;
4738  // max limitation on QgsSvgCache is 10,000 for screen, which will probably be reasonable for future caching here, too
4739  // 4 x QgsSvgCache limit for output to print/image at higher dpi
4740  // TODO: should it be higher, scale with dpi, or have no limit? Needs testing with very large labels rendered at high dpi output
4741  int maxBlurImgSize = 40000;
4742  if ( blurImg.isNull()
4743  || ( blurImg.width() < minBlurImgSize || blurImg.height() < minBlurImgSize )
4744  || ( blurImg.width() > maxBlurImgSize || blurImg.height() > maxBlurImgSize ) )
4745  return;
4746 
4747  blurImg.fill( QColor( Qt::transparent ).rgba() );
4748  QPainter pictp;
4749  if ( !pictp.begin( &blurImg ) )
4750  return;
4751  pictp.setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform );
4752  QPointF imgOffset( blurbuffer + pictbuffer + xOffset,
4753  blurbuffer + pictbuffer + componentHeight + yOffset );
4754 
4755  pictp.drawPicture( imgOffset,
4756  *component.picture() );
4757 
4758  // overlay shadow color
4759  pictp.setCompositionMode( QPainter::CompositionMode_SourceIn );
4760  pictp.fillRect( blurImg.rect(), tmpLyr.shadowColor );
4761  pictp.end();
4762 
4763  // blur the QImage in-place
4764  if ( tmpLyr.shadowRadius > 0.0 && radius > 0 )
4765  {
4766  QgsSymbolLayerV2Utils::blurImageInPlace( blurImg, blurImg.rect(), radius, tmpLyr.shadowRadiusAlphaOnly );
4767  }
4768 
4769  if ( tmpLyr.showingShadowRects ) // engine setting, not per layer
4770  {
4771  // debug rect for QImage shadow registration and clipping visualization
4772  QPainter picti;
4773  picti.begin( &blurImg );
4774  picti.setBrush( Qt::Dense7Pattern );
4775  QPen imgPen( QColor( 0, 0, 255, 255 ) );
4776  imgPen.setWidth( 1 );
4777  picti.setPen( imgPen );
4778  picti.setOpacity( 0.1 );
4779  picti.drawRect( 0, 0, blurImg.width(), blurImg.height() );
4780  picti.end();
4781  }
4782 
4783  double offsetDist = tmpLyr.scaleToPixelContext( tmpLyr.shadowOffsetDist, context, tmpLyr.shadowOffsetUnits, true, tmpLyr.shadowOffsetMapUnitScale );
4784  double angleRad = tmpLyr.shadowOffsetAngle * M_PI / 180; // to radians
4785  if ( tmpLyr.shadowOffsetGlobal )
4786  {
4787  // TODO: check for differences in rotation origin and cw/ccw direction,
4788  // when this shadow function is used for something other than labels
4789 
4790  // it's 0-->cw-->360 for labels
4791  //QgsDebugMsgLevel( QString( "Shadow aggregated label rotation (degrees): %1" ).arg( component.rotation() + component.rotationOffset() ), 4 );
4792  angleRad -= ( component.rotation() * M_PI / 180 + component.rotationOffset() * M_PI / 180 );
4793  }
4794 
4795  QPointF transPt( -offsetDist * cos( angleRad + M_PI / 2 ),
4796  -offsetDist * sin( angleRad + M_PI / 2 ) );
4797 
4798  p->save();
4799  p->setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform );
4800  if ( context.useAdvancedEffects() )
4801  {
4802  p->setCompositionMode( tmpLyr.shadowBlendMode );
4803  }
4804  p->setOpacity(( 100.0 - ( double )( tmpLyr.shadowTransparency ) ) / 100.0 );
4805 
4806  double scale = ( double )tmpLyr.shadowScale / 100.0;
4807  // TODO: scale from center/center, left/center or left/top, instead of default left/bottom?
4808  p->scale( scale, scale );
4809  if ( component.useOrigin() )
4810  {
4811  p->translate( component.origin().x(), component.origin().y() );
4812  }
4813  p->translate( transPt );
4814  p->translate( -imgOffset.x(),
4815  -imgOffset.y() );
4816  p->drawImage( 0, 0, blurImg );
4817  p->restore();
4818 
4819  // debug rects
4820  if ( tmpLyr.showingShadowRects ) // engine setting, not per layer
4821  {
4822  // draw debug rect for QImage painting registration
4823  p->save();
4824  p->setBrush( Qt::NoBrush );
4825  QPen imgPen( QColor( 255, 0, 0, 10 ) );
4826  imgPen.setWidth( 2 );
4827  imgPen.setStyle( Qt::DashLine );
4828  p->setPen( imgPen );
4829  p->scale( scale, scale );
4830  if ( component.useOrigin() )
4831  {
4832  p->translate( component.origin().x(), component.origin().y() );
4833  }
4834  p->translate( transPt );
4835  p->translate( -imgOffset.x(),
4836  -imgOffset.y() );
4837  p->drawRect( 0, 0, blurImg.width(), blurImg.height() );
4838  p->restore();
4839 
4840  // draw debug rect for passed in component dimensions
4841  p->save();
4842  p->setBrush( Qt::NoBrush );
4843  QPen componentRectPen( QColor( 0, 255, 0, 70 ) );
4844  componentRectPen.setWidth( 1 );
4845  if ( component.useOrigin() )
4846  {
4847  p->translate( component.origin().x(), component.origin().y() );
4848  }
4849  p->setPen( componentRectPen );
4850  p->drawRect( QRect( -xOffset, -componentHeight - yOffset, componentWidth, componentHeight ) );
4851  p->restore();
4852  }
4853 }
4854 
4856 {
4857  // start with engine defaults for new project, or project that has no saved settings
4858  Pal p;
4859  bool saved = false;
4861  "PAL", "/SearchMethod", ( int )p.getSearch(), &saved ) );
4863  "PAL", "/CandidatesPoint", p.getPointP(), &saved );
4865  "PAL", "/CandidatesLine", p.getLineP(), &saved );
4867  "PAL", "/CandidatesPolygon", p.getPolyP(), &saved );
4869  "PAL", "/ShowingCandidates", false, &saved );
4871  "PAL", "/ShowingShadowRects", false, &saved );
4873  "PAL", "/ShowingAllLabels", false, &saved );
4875  "PAL", "/ShowingPartialsLabels", p.getShowPartial(), &saved );
4877  "PAL", "/DrawOutlineLabels", true, &saved );
4878 }
4879 
4881 {
4882  QgsProject::instance()->writeEntry( "PAL", "/SearchMethod", ( int )mSearch );
4883  QgsProject::instance()->writeEntry( "PAL", "/CandidatesPoint", mCandPoint );
4884  QgsProject::instance()->writeEntry( "PAL", "/CandidatesLine", mCandLine );
4885  QgsProject::instance()->writeEntry( "PAL", "/CandidatesPolygon", mCandPolygon );
4886  QgsProject::instance()->writeEntry( "PAL", "/ShowingCandidates", mShowingCandidates );
4887  QgsProject::instance()->writeEntry( "PAL", "/ShowingShadowRects", mShowingShadowRects );
4888  QgsProject::instance()->writeEntry( "PAL", "/ShowingAllLabels", mShowingAllLabels );
4889  QgsProject::instance()->writeEntry( "PAL", "/ShowingPartialsLabels", mShowingPartialsLabels );
4890  QgsProject::instance()->writeEntry( "PAL", "/DrawOutlineLabels", mDrawOutlineLabels );
4891 }
4892 
4894 {
4895  QgsProject::instance()->removeEntry( "PAL", "/SearchMethod" );
4896  QgsProject::instance()->removeEntry( "PAL", "/CandidatesPoint" );
4897  QgsProject::instance()->removeEntry( "PAL", "/CandidatesLine" );
4898  QgsProject::instance()->removeEntry( "PAL", "/CandidatesPolygon" );
4899  QgsProject::instance()->removeEntry( "PAL", "/ShowingCandidates" );
4900  QgsProject::instance()->removeEntry( "PAL", "/ShowingShadowRects" );
4901  QgsProject::instance()->removeEntry( "PAL", "/ShowingAllLabels" );
4902  QgsProject::instance()->removeEntry( "PAL", "/ShowingPartialsLabels" );
4903  QgsProject::instance()->removeEntry( "PAL", "/DrawOutlineLabels" );
4904 }
4905 
4907 {
4908  QgsPalLabeling* lbl = new QgsPalLabeling();
4914  return lbl;
4915 }
4916 
4917 
4919 {
4920  mLabelSearchTree = new QgsLabelSearchTree();
4921 }
4922 
4924 {
4925  delete mLabelSearchTree;
4926  mLabelSearchTree = NULL;
4927 }
4928 
4929 QList<QgsLabelPosition> QgsLabelingResults::labelsAtPosition( const QgsPoint& p ) const
4930 {
4931  QList<QgsLabelPosition> positions;
4932 
4933  QList<QgsLabelPosition*> positionPointers;
4934  if ( mLabelSearchTree )
4935  {
4936  mLabelSearchTree->label( p, positionPointers );
4937  QList<QgsLabelPosition*>::const_iterator pointerIt = positionPointers.constBegin();
4938  for ( ; pointerIt != positionPointers.constEnd(); ++pointerIt )
4939  {
4940  positions.push_back( QgsLabelPosition( **pointerIt ) );
4941  }
4942  }
4943 
4944  return positions;
4945 }
4946 
4947 QList<QgsLabelPosition> QgsLabelingResults::labelsWithinRect( const QgsRectangle& r ) const
4948 {
4949  QList<QgsLabelPosition> positions;
4950 
4951  QList<QgsLabelPosition*> positionPointers;
4952  if ( mLabelSearchTree )
4953  {
4954  mLabelSearchTree->labelsInRect( r, positionPointers );
4955  QList<QgsLabelPosition*>::const_iterator pointerIt = positionPointers.constBegin();
4956  for ( ; pointerIt != positionPointers.constEnd(); ++pointerIt )
4957  {
4958  positions.push_back( QgsLabelPosition( **pointerIt ) );
4959  }
4960  }
4961 
4962  return positions;
4963 }
const QgsMapSettings & mapSettings()
bridge to QgsMapSettings
QgsFeatureId id() const
Get the feature id for this feature.
Definition: qgsfeature.cpp:100
static QString encodeOutputUnit(QgsSymbolV2::OutputUnit unit)
static void _fixQPictureDPI(QPainter *p)
void calculateLabelSize(const QFontMetricsF *fm, QString text, double &labelX, double &labelY, QgsFeature *f=0)
Class for parsing and evaluation of expressions (formerly called "search strings").
Definition: qgsexpression.h:87
QgsPalLayerSettings & layer(const QString &layerName)
returns PAL layer settings for a registered layer
const QString & name() const
Gets the name of the field.
Definition: qgsfield.cpp:59
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
void setRotationOffset(double rotation)
void setActive(bool active)
FeaturePart * getFeaturePart()
return the feature corresponding to this labelposition
A rectangle specified with double values.
Definition: qgsrectangle.h:35
virtual Q_DECL_DEPRECATED QList< QgsLabelPosition > labelsWithinRect(const QgsRectangle &r)
return infos about labels within a given (map) rectangle
double getCost() const
get the position geographical cost
void label(const QgsPoint &p, QList< QgsLabelPosition * > &posList) const
Returns label position(s) at a given point.
bool hasParserError() const
Returns true if an error occurred when parsing the input expression.
Definition: qgsexpression.h:94
void dataDefinedShapeBackground(QgsPalLayerSettings &tmpLyr, const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &ddValues)
std::list< LabelPosition * > * solveProblem(Problem *prob, bool displayAll)
Definition: pal.cpp:867
bool dataDefinedIsActive(QgsPalLayerSettings::DataDefinedProperties p) const
Whether data definition is active.
QgsMapUnitScale shapeSizeMapUnitScale
void dataDefinedTextStyle(QgsPalLayerSettings &tmpLyr, const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &ddValues)
A container class for data source field mapping or expression.
QgsMapUnitScale shadowRadiusMapUnitScale
virtual void drawLabel(pal::LabelPosition *label, QgsRenderContext &context, QgsPalLayerSettings &tmpLyr, DrawLabelType drawType, double dpiRatio=1.0)
drawLabel
pal::Layer * palLayer
double scale() const
Return the calculated scale of the map.
double length()
get length of geometry using GEOS
const QgsMapSettings * mMapSettings
pal::Pal * mPal
void addDataDefinedValue(QgsPalLayerSettings::DataDefinedProperties p, QVariant v)
int getFeatureCandidateCount(int i)
Definition: problem.h:184
void setNumCandidatePositions(int candPoint, int candLine, int candPolygon)
void registerFeature(QgsFeature &f, const QgsRenderContext &context, QString dxfLayer)
void setDxfLayer(QString dxfLayer)
QgsExpression * expression()
const QgsPoint & offset()
QVariant evaluate(const QgsFeature *f=NULL)
Evaluate the feature and return the result.
double getWidth() const
QgsLabelingResults * takeResults()
Return pointer to recently computed results (in drawLabeling()) and pass the ownership of results to ...
QString field() const
A class to query the labeling structure at a given point (small wraper around pal RTree class) ...
bool prepare(const QgsFields &fields)
Get the expression ready for evaluation - find out column indexes.
double yMaximum() const
Get the y maximum value (top side of rectangle)
Definition: qgsrectangle.h:188
virtual void clearActiveLayer(const QString &layerID)
clears data defined objects from PAL layer settings for a registered layer
void setSearchMethod(Search s)
virtual Q_DECL_DEPRECATED void init(QgsMapRenderer *mr)
called when we're going to start with rendering
void loadEngineSettings()
load/save engine settings to project file
QPainter::CompositionMode bufferBlendMode
A layer of spacial entites.
Definition: layer.h:65
double rendererScale() const
double rotationOffset() const
is the best but slowest
Definition: pal.h:83
QgsMapUnitScale shadowOffsetMapUnitScale
void setPointP(int point_p)
set # candidates to generate for points features Higher the value is, longer Pal::labeller will spend...
Definition: pal.cpp:885
QgsGeometry * geometry() const
Get the geometry object associated with this feature.
Definition: qgsfeature.cpp:112
double computeMapUnitsPerPixel(const QgsRenderContext &c) const
QgsPoint transform(const QgsPoint &p) const
void setCustomProperty(const QString &key, const QVariant &value)
Set a custom property for layer.
void setPolyP(int poly_p)
set maximum # candidates to generate for polygon features Higher the value is, longer Pal::labeller w...
Definition: pal.cpp:897
bool mShowingPartialsLabels
QuadrantPosition quadOffset
QgsRectangle visibleExtent() const
Return the actual extent derived from requested extent that takes takes output image size into accoun...
virtual Q_DECL_DEPRECATED QList< QgsLabelPosition > labelsAtPosition(const QgsPoint &p)
return infos about labels at a given (map) position
Pal main class.
Definition: pal.h:126
void numCandidatePositions(int &candPoint, int &candLine, int &candPolygon)
QGis::GeometryType type()
Returns type of the vector.
static bool _palIsCancelled(void *ctx)
UpsideDownLabels
Definition: layer.h:78
bool hasCrsTransformEnabled() const
returns true if projections are enabled for this layer set
static QPointF decodePoint(QString str)
Container of fields for a vector layer.
Definition: qgsfield.h:172
static QgsPalLayerSettings fromLayer(QgsVectorLayer *layer)
void readFromLayer(QgsVectorLayer *layer)
void setUpsidedownLabels(UpsideDownLabels ud)
Definition: layer.h:296
static QColor decodeColor(QString str)
QString expressionString() const
GeometryType
Definition: qgis.h:155
const QgsRectangle & extent() const
const QgsMapToPixel & mapToPixel() const
virtual void exit()
called when we're done with rendering
void dataDefinedDropShadow(QgsPalLayerSettings &tmpLyr, const QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > &ddValues)
QVariant dataDefinedValue(QgsPalLayerSettings::DataDefinedProperties p, QgsFeature &f, const QgsFields &fields) const
Get data defined property value from expression string or attribute field name.
void setIsDiagram(bool d)
QgsMapUnitScale repeatDistanceMapUnitScale
MultiLineAlign multilineAlign
const QgsField & at(int i) const
Get field at particular index (must be in range 0..N-1)
Definition: qgsfield.h:227
void setOffset(QgsPoint point)
void removeDataDefinedProperty(QgsPalLayerSettings::DataDefinedProperties p)
Set a property to static instead data defined.
double scaleFactor() const
static QgsSymbolLayerV2 * create(const QgsStringMap &properties=QgsStringMap())
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:113
virtual int addDiagramLayer(QgsVectorLayer *layer, const QgsDiagramLayerSettings *s)
adds a diagram layer to the labeling engine
double dpiRatio() const
double area()
get area of geometry using GEOS
A non GUI class for rendering a map layer set onto a QPainter.
bool readBoolEntry(const QString &scope, const QString &key, bool def=false, bool *ok=0) const
Problem * extractProblem(double scale, double bbox[4])
Definition: pal.cpp:840