QGIS API Documentation  2.14.4-Essen
qgscomposition.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgscomposition.cpp
3  -------------------
4  begin : January 2005
5  copyright : (C) 2005 by Radim Blazek
6  email : blazek@itc.it
7  ***************************************************************************/
8 /***************************************************************************
9  * *
10  * This program is free software; you can redistribute it and/or modify *
11  * it under the terms of the GNU General Public License as published by *
12  * the Free Software Foundation; either version 2 of the License, or *
13  * (at your option) any later version. *
14  * *
15  ***************************************************************************/
16 
17 #include "qgscomposition.h"
18 #include "qgscomposerutils.h"
19 #include "qgscomposerarrow.h"
20 #include "qgscomposerframe.h"
21 #include "qgscomposerhtml.h"
22 #include "qgscomposerlabel.h"
23 #include "qgscomposerlegend.h"
24 #include "qgscomposermap.h"
25 #include "qgscomposermapoverview.h"
27 #include "qgscomposeritemgroup.h"
28 #include "qgscomposerpicture.h"
29 #include "qgscomposerscalebar.h"
30 #include "qgscomposershape.h"
31 #include "qgscomposermodel.h"
37 #include "qgspaintenginehack.h"
38 #include "qgspaperitem.h"
39 #include "qgsproject.h"
40 #include "qgsgeometry.h"
41 #include "qgsvectorlayer.h"
42 #include "qgsvectordataprovider.h"
43 #include "qgsexpression.h"
44 #include "qgssymbolv2.h"
45 #include "qgssymbollayerv2utils.h"
46 #include "qgsdatadefined.h"
47 #include "qgslogger.h"
48 
49 #include <QDomDocument>
50 #include <QDomElement>
51 #include <QGraphicsRectItem>
52 #include <QGraphicsView>
53 #include <QPainter>
54 #include <QPrinter>
55 #include <QSettings>
56 #include <QDir>
57 
58 #include <limits>
59 
61  : QGraphicsScene( nullptr )
62  , mMapRenderer( mapRenderer )
63  , mMapSettings( mapRenderer->mapSettings() )
64  , mAtlasComposition( this )
65 {
66  init();
67 }
68 
70  : QGraphicsScene( nullptr )
71  , mMapRenderer( nullptr )
72  , mMapSettings( mapSettings )
73  , mAtlasComposition( this )
74 {
75  init();
76 }
77 
79 {
80  // these members should be ideally in constructor's initialization list, but now we have two constructors...
81  mPlotStyle = QgsComposition::Preview;
82  mPageWidth = 297;
83  mPageHeight = 210;
84  mSpaceBetweenPages = 10;
85  mPageStyleSymbol = nullptr;
86  mPrintAsRaster = false;
87  mGenerateWorldFile = false;
88  mWorldFileMap = nullptr;
89  mUseAdvancedEffects = true;
90  mSnapToGrid = false;
91  mGridVisible = false;
92  mPagesVisible = true;
93  mSnapGridResolution = 0;
94  mSnapGridOffsetX = 0;
95  mSnapGridOffsetY = 0;
96  mAlignmentSnap = true;
97  mGuidesVisible = true;
98  mSmartGuides = true;
99  mSnapTolerance = 0;
100  mBoundingBoxesVisible = true;
101  mSelectionHandles = nullptr;
102  mActiveItemCommand = nullptr;
103  mActiveMultiFrameCommand = nullptr;
104  mAtlasMode = QgsComposition::AtlasOff;
105  mPreventCursorChange = false;
106  mItemsModel = nullptr;
107  mUndoStack = new QUndoStack();
108 
109  mResizeToContentsMarginTop = 0;
110  mResizeToContentsMarginRight = 0;
111  mResizeToContentsMarginBottom = 0;
112  mResizeToContentsMarginLeft = 0;
113 
114  //data defined strings
115  mDataDefinedNames.insert( QgsComposerObject::PresetPaperSize, QString( "dataDefinedPaperSize" ) );
116  mDataDefinedNames.insert( QgsComposerObject::PaperWidth, QString( "dataDefinedPaperWidth" ) );
117  mDataDefinedNames.insert( QgsComposerObject::PaperHeight, QString( "dataDefinedPaperHeight" ) );
118  mDataDefinedNames.insert( QgsComposerObject::NumPages, QString( "dataDefinedNumPages" ) );
119  mDataDefinedNames.insert( QgsComposerObject::PaperOrientation, QString( "dataDefinedPaperOrientation" ) );
120 
121  //connect to atlas toggling on/off and coverage layer and feature changes
122  //to update data defined values
123  connect( &mAtlasComposition, SIGNAL( toggled( bool ) ), this, SLOT( refreshDataDefinedProperty() ) );
124  connect( &mAtlasComposition, SIGNAL( coverageLayerChanged( QgsVectorLayer* ) ), this, SLOT( refreshDataDefinedProperty() ) );
125  connect( &mAtlasComposition, SIGNAL( featureChanged( QgsFeature* ) ), this, SLOT( refreshDataDefinedProperty() ) );
126  //also, refreshing composition triggers a recalculation of data defined properties
127  connect( this, SIGNAL( refreshItemsTriggered() ), this, SLOT( refreshDataDefinedProperty() ) );
128  //toggling atlas or changing coverage layer requires data defined expressions to be reprepared
129  connect( &mAtlasComposition, SIGNAL( toggled( bool ) ), this, SLOT( prepareAllDataDefinedExpressions() ) );
130  connect( &mAtlasComposition, SIGNAL( coverageLayerChanged( QgsVectorLayer* ) ), this, SLOT( prepareAllDataDefinedExpressions() ) );
131 
132  setBackgroundBrush( QColor( 215, 215, 215 ) );
133  createDefaultPageStyleSymbol();
134 
135  addPaperItem();
136 
137  updateBounds();
138 
139  //add mouse selection handles to composition, and initially hide
140  mSelectionHandles = new QgsComposerMouseHandles( this );
141  addItem( mSelectionHandles );
142  mSelectionHandles->hide();
143  mSelectionHandles->setZValue( 500 );
144 
145  mPrintResolution = 300; //hardcoded default
146 
147  //load default composition settings
148  loadDefaults();
149  loadSettings();
150 
151  mItemsModel = new QgsComposerModel( this );
152 }
153 
154 
155 /*
156 QgsComposition::QgsComposition()
157  : QGraphicsScene( 0 )
158  , mMapRenderer( 0 )
159  , mPlotStyle( QgsComposition::Preview )
160  , mPageWidth( 297 )
161  , mPageHeight( 210 )
162  , mSpaceBetweenPages( 10 )
163  , mPageStyleSymbol( 0 )
164  , mPrintAsRaster( false )
165  , mGenerateWorldFile( false )
166  , mWorldFileMap( 0 )
167  , mUseAdvancedEffects( true )
168  , mSnapToGrid( false )
169  , mGridVisible( false )
170  , mSnapGridResolution( 0 )
171  , mSnapGridTolerance( 0 )
172  , mSnapGridOffsetX( 0 )
173  , mSnapGridOffsetY( 0 )
174  , mAlignmentSnap( true )
175  , mGuidesVisible( true )
176  , mSmartGuides( true )
177  , mAlignmentSnapTolerance( 0 )
178  , mSelectionHandles( 0 )
179  , mActiveItemCommand( 0 )
180  , mActiveMultiFrameCommand( 0 )
181  , mAtlasComposition( this )
182  , mAtlasMode( QgsComposition::AtlasOff )
183  , mPreventCursorChange( false )
184  , mItemsModel( 0 )
185 {
186  //load default composition settings
187  loadDefaults();
188  loadSettings();
189  mItemsModel = new QgsComposerModel( this );
190 }*/
191 
193 {
194  removePaperItems();
195  deleteAndRemoveMultiFrames();
196 
197  // make sure that all composer items are removed before
198  // this class is deconstructed - to avoid segfaults
199  // when composer items access in destructor composition that isn't valid anymore
200  QList<QGraphicsItem*> itemList = items();
201  qDeleteAll( itemList );
202 
203  // clear pointers to QgsDataDefined objects
204  qDeleteAll( mDataDefinedProperties );
205  mDataDefinedProperties.clear();
206 
207  //order is important here - we need to delete model last so that all items have already
208  //been deleted. Deleting the undo stack will also delete any items which have been
209  //removed from the scene, so this needs to be done before deleting the model
210  delete mUndoStack;
211 
212  delete mActiveItemCommand;
213  delete mActiveMultiFrameCommand;
214  delete mPageStyleSymbol;
215  delete mItemsModel;
216 }
217 
218 void QgsComposition::loadDefaults()
219 {
220  QSettings settings;
221  mSnapGridResolution = settings.value( "/Composer/defaultSnapGridResolution", 10.0 ).toDouble();
222  mSnapGridOffsetX = settings.value( "/Composer/defaultSnapGridOffsetX", 0 ).toDouble();
223  mSnapGridOffsetY = settings.value( "/Composer/defaultSnapGridOffsetY", 0 ).toDouble();
224  mSnapTolerance = settings.value( "/Composer/defaultSnapTolerancePixels", 5 ).toInt();
225 }
226 
228 {
229  setSceneRect( compositionBounds( false, 0.05 ) );
230 }
231 
233 {
234  emit refreshItemsTriggered();
235  //force a redraw on all maps
237  composerItems( maps );
239  for ( ; mapIt != maps.end(); ++mapIt )
240  {
241  ( *mapIt )->cache();
242  ( *mapIt )->update();
243  }
244 }
245 
247 {
249  if ( item )
250  {
251  item->setSelected( true );
252  emit selectedItemChanged( item );
253  }
254 }
255 
257 {
258  //we can't use QGraphicsScene::clearSelection, as that emits no signals
259  //and we don't know which items are being unselected
260  //accordingly, we can't inform the composition model of selection changes
261  //instead, do the clear selection manually...
262  QList<QGraphicsItem *> selectedItemList = selectedItems();
263  QList<QGraphicsItem *>::iterator itemIter = selectedItemList.begin();
264 
265  for ( ; itemIter != selectedItemList.end(); ++itemIter )
266  {
267  QgsComposerItem* composerItem = dynamic_cast<QgsComposerItem *>( *itemIter );
268  if ( composerItem )
269  {
270  composerItem->setSelected( false );
271  }
272  }
273 }
274 
276 {
277  const QgsExpressionContext* evalContext = context;
279  if ( !evalContext )
280  {
281  scopedContext.reset( createExpressionContext() );
282  evalContext = scopedContext.data();
283  }
284 
285  //updates data defined properties and redraws composition to match
286  if ( property == QgsComposerObject::NumPages || property == QgsComposerObject::AllProperties )
287  {
288  setNumPages( numPages() );
289  }
290  if ( property == QgsComposerObject::PaperWidth || property == QgsComposerObject::PaperHeight ||
293  {
294  refreshPageSize( evalContext );
295  }
296 }
297 
298 QRectF QgsComposition::compositionBounds( bool ignorePages, double margin ) const
299 {
300  //start with an empty rectangle
301  QRectF bounds;
302 
303  //add all QgsComposerItems and QgsPaperItems which are in the composition
304  QList<QGraphicsItem *> itemList = items();
305  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
306  for ( ; itemIt != itemList.end(); ++itemIt )
307  {
308  const QgsComposerItem* composerItem = dynamic_cast<const QgsComposerItem *>( *itemIt );
309  const QgsPaperItem* paperItem = dynamic_cast<const QgsPaperItem*>( *itemIt );
310  if (( composerItem && ( !paperItem || !ignorePages ) ) )
311  {
312  //expand bounds with current item's bounds
313  if ( bounds.isValid() )
314  bounds = bounds.united(( *itemIt )->sceneBoundingRect() );
315  else
316  bounds = ( *itemIt )->sceneBoundingRect();
317  }
318  }
319 
320  if ( bounds.isValid() && margin > 0.0 )
321  {
322  //finally, expand bounds out by specified margin of page size
323  bounds.adjust( -mPageWidth * margin, -mPageWidth * margin, mPageWidth * margin, mPageWidth * margin );
324  }
325 
326  return bounds;
327 }
328 
329 QRectF QgsComposition::pageItemBounds( int pageNumber, bool visibleOnly ) const
330 {
331  //start with an empty rectangle
332  QRectF bounds;
333 
334  //add all QgsComposerItems on page
335  QList<QGraphicsItem *> itemList = items();
336  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
337  for ( ; itemIt != itemList.end(); ++itemIt )
338  {
339  const QgsComposerItem* composerItem = dynamic_cast<const QgsComposerItem *>( *itemIt );
340  const QgsPaperItem* paperItem = dynamic_cast<const QgsPaperItem*>( *itemIt );
341  if ( composerItem && !paperItem && itemPageNumber( composerItem ) == pageNumber )
342  {
343  if ( visibleOnly && !composerItem->isVisible() )
344  continue;
345 
346  //expand bounds with current item's bounds
347  if ( bounds.isValid() )
348  bounds = bounds.united(( *itemIt )->sceneBoundingRect() );
349  else
350  bounds = ( *itemIt )->sceneBoundingRect();
351  }
352  }
353 
354  return bounds;
355 }
356 
357 void QgsComposition::setPaperSize( const double width, const double height, bool keepRelativeItemPosition )
358 {
359  if ( qgsDoubleNear( width, mPageWidth ) && qgsDoubleNear( height, mPageHeight ) )
360  {
361  return;
362  }
363 
364  if ( keepRelativeItemPosition )
365  {
366  //update item positions
367  QList<QGraphicsItem *> itemList = items();
368  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
369  for ( ; itemIt != itemList.end(); ++itemIt )
370  {
371  QgsComposerItem* composerItem = dynamic_cast<QgsComposerItem *>( *itemIt );
372  if ( composerItem )
373  {
374  composerItem->updatePagePos( width, height );
375  }
376  }
377  }
378 
379  //update guide positions and size
381  QList< QGraphicsLineItem* >::iterator guideIt = guides->begin();
382  double totalHeight = ( height + spaceBetweenPages() ) * ( numPages() - 1 ) + height;
383  for ( ; guideIt != guides->end(); ++guideIt )
384  {
385  QLineF line = ( *guideIt )->line();
386  if ( qgsDoubleNear( line.dx(), 0. ) )
387  {
388  //vertical line, change height of line
389  ( *guideIt )->setLine( line.x1(), 0, line.x1(), totalHeight );
390  }
391  else
392  {
393  //horizontal line
394  if ( keepRelativeItemPosition )
395  {
396  //move to new vertical position and change width of line
397  QPointF curPagePos = positionOnPage( line.p1() );
398  int curPage = pageNumberForPoint( line.p1() ) - 1;
399  double newY = curPage * ( height + spaceBetweenPages() ) + curPagePos.y();
400  ( *guideIt )->setLine( 0, newY, width, newY );
401  }
402  else
403  {
404  //just resize guide to new page size
405  ( *guideIt )->setLine( 0, line.y1(), width, line.y1() );
406  }
407  }
408  }
409 
410  mPageWidth = width;
411  mPageHeight = height;
412  double currentY = 0;
413  for ( int i = 0; i < mPages.size(); ++i )
414  {
415  mPages.at( i )->setSceneRect( QRectF( 0, currentY, width, height ) );
416  currentY += ( height + mSpaceBetweenPages );
417  }
418  QgsProject::instance()->dirty( true );
419  updateBounds();
420  emit paperSizeChanged();
421 }
422 
424 {
425  return mPageHeight;
426 }
427 
429 {
430  return mPageWidth;
431 }
432 
433 void QgsComposition::resizePageToContents( double marginTop, double marginRight, double marginBottom, double marginLeft )
434 {
435  //calculate current bounds
436  QRectF bounds = compositionBounds( true, 0.0 );
437 
438  setNumPages( 1 );
439  double newWidth = bounds.width() + marginLeft + marginRight;
440  double newHeight = bounds.height() + marginTop + marginBottom;
441  setPaperSize( newWidth, newHeight, false );
442 
443  //also move all items so that top-left of bounds is at marginLeft, marginTop
444  double diffX = marginLeft - bounds.left();
445  double diffY = marginTop - bounds.top();
446 
447  QList<QGraphicsItem *> itemList = items();
448  Q_FOREACH ( QGraphicsItem* item, itemList )
449  {
450  QgsComposerItem* composerItem = dynamic_cast<QgsComposerItem *>( item );
451  if ( composerItem )
452  {
453  const QgsPaperItem* paperItem = dynamic_cast<const QgsPaperItem*>( item );
454 
455  if ( !paperItem )
456  composerItem->move( diffX, diffY );
457  }
458  }
459 
460  //also move guides
461  Q_FOREACH ( QGraphicsLineItem* guide, mSnapLines )
462  {
463  QLineF line = guide->line();
464  if ( qgsDoubleNear( line.dx(), 0.0 ) )
465  {
466  //vertical line
467  guide->setLine( line.x1() + diffX, 0, line.x1() + diffX, newHeight );
468  }
469  else
470  {
471  //horizontal line
472  guide->setLine( 0, line.y1() + diffY, newWidth, line.y1() + diffY );
473  }
474  }
475 }
476 
477 void QgsComposition::setResizeToContentsMargins( double marginTop, double marginRight, double marginBottom, double marginLeft )
478 {
479  mResizeToContentsMarginTop = marginTop;
480  mResizeToContentsMarginRight = marginRight;
481  mResizeToContentsMarginBottom = marginBottom;
482  mResizeToContentsMarginLeft = marginLeft;
483 }
484 
485 void QgsComposition::resizeToContentsMargins( double& marginTop, double& marginRight, double& marginBottom, double& marginLeft ) const
486 {
487  marginTop = mResizeToContentsMarginTop;
488  marginRight = mResizeToContentsMarginRight;
489  marginBottom = mResizeToContentsMarginBottom;
490  marginLeft = mResizeToContentsMarginLeft;
491 }
492 
494 {
495  int currentPages = numPages();
496  int desiredPages = pages;
497 
498  //data defined num pages set?
499  QVariant exprVal;
501  if ( dataDefinedEvaluate( QgsComposerObject::NumPages, exprVal, *context.data(), &mDataDefinedProperties ) )
502  {
503  bool ok = false;
504  int pagesD = exprVal.toInt( &ok );
505  QgsDebugMsg( QString( "exprVal NumPages:%1" ).arg( pagesD ) );
506  if ( ok )
507  {
508  desiredPages = pagesD;
509  }
510  }
511 
512  int diff = desiredPages - currentPages;
513  if ( diff >= 0 )
514  {
515  for ( int i = 0; i < diff; ++i )
516  {
517  addPaperItem();
518  }
519  }
520  else
521  {
522  diff = -diff;
523  for ( int i = 0; i < diff; ++i )
524  {
525  delete mPages.last();
526  mPages.removeLast();
527  }
528  }
529 
530  //update vertical guide height
532  QList< QGraphicsLineItem* >::iterator guideIt = guides->begin();
533  double totalHeight = ( mPageHeight + spaceBetweenPages() ) * ( pages - 1 ) + mPageHeight;
534  for ( ; guideIt != guides->end(); ++guideIt )
535  {
536  QLineF line = ( *guideIt )->line();
537  if ( qgsDoubleNear( line.dx(), 0.0 ) )
538  {
539  //vertical line, change height of line
540  ( *guideIt )->setLine( line.x1(), 0, line.x1(), totalHeight );
541  }
542  }
543 
544  QgsProject::instance()->dirty( true );
545  updateBounds();
546 
547  emit nPagesChanged();
548 }
549 
551 {
552  return mPages.size();
553 }
554 
555 bool QgsComposition::pageIsEmpty( const int page ) const
556 {
557  //get all items on page
559  //composerItemsOnPage uses 0-based page numbering
560  composerItemsOnPage( items, page - 1 );
561 
562  //loop through and check for non-paper items
564  for ( ; itemIt != items.constEnd(); ++itemIt )
565  {
566  //is item a paper item?
567  QgsPaperItem* paper = dynamic_cast<QgsPaperItem*>( *itemIt );
568  if ( !paper )
569  {
570  //item is not a paper item, so we have other items on the page
571  return false;
572  }
573  }
574  //no non-paper items
575  return true;
576 }
577 
578 bool QgsComposition::shouldExportPage( const int page ) const
579 {
580  if ( page > numPages() || page < 1 )
581  {
582  //page number out of range
583  return false;
584  }
585 
586  //check all frame items on page
588  //composerItemsOnPage uses 0 based page numbering
589  composerItemsOnPage( frames, page - 1 );
591  for ( ; frameIt != frames.constEnd(); ++frameIt )
592  {
593  if (( *frameIt )->hidePageIfEmpty() && ( *frameIt )->isEmpty() )
594  {
595  //frame is set to hide page if empty, and frame is empty, so we don't want to export this page
596  return false;
597  }
598  }
599  return true;
600 }
601 
603 {
604  delete mPageStyleSymbol;
605  mPageStyleSymbol = static_cast<QgsFillSymbolV2*>( symbol->clone() );
606  QgsProject::instance()->dirty( true );
607 }
608 
609 void QgsComposition::createDefaultPageStyleSymbol()
610 {
611  delete mPageStyleSymbol;
612  QgsStringMap properties;
613  properties.insert( "color", "white" );
614  properties.insert( "style", "solid" );
615  properties.insert( "style_border", "no" );
616  properties.insert( "joinstyle", "miter" );
617  mPageStyleSymbol = QgsFillSymbolV2::createSimple( properties );
618 }
619 
621 {
622  double y;
623  if ( position.y() > ( mPages.size() - 1 ) * ( paperHeight() + spaceBetweenPages() ) )
624  {
625  //y coordinate is greater then the end of the last page, so return distance between
626  //top of last page and y coordinate
627  y = position.y() - ( mPages.size() - 1 ) * ( paperHeight() + spaceBetweenPages() );
628  }
629  else
630  {
631  //y coordinate is less then the end of the last page
632  y = fmod( position.y(), ( paperHeight() + spaceBetweenPages() ) );
633  }
634  return QPointF( position.x(), y );
635 }
636 
638 {
639  int pageNumber = qFloor( position.y() / ( paperHeight() + spaceBetweenPages() ) ) + 1;
640  pageNumber = pageNumber < 1 ? 1 : pageNumber;
641  pageNumber = pageNumber > mPages.size() ? mPages.size() : pageNumber;
642  return pageNumber;
643 }
644 
646 {
647  emit statusMsgChanged( message );
648 }
649 
650 QgsComposerItem* QgsComposition::composerItemAt( QPointF position, bool ignoreLocked ) const
651 {
652  return composerItemAt( position, nullptr, ignoreLocked );
653 }
654 
655 QgsComposerItem* QgsComposition::composerItemAt( QPointF position, const QgsComposerItem* belowItem, const bool ignoreLocked ) const
656 {
657  //get a list of items which intersect the specified position, in descending z order
658  QList<QGraphicsItem*> itemList;
659  itemList = items( position, Qt::IntersectsItemShape, Qt::DescendingOrder );
660  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
661 
662  bool foundBelowItem = false;
663  for ( ; itemIt != itemList.end(); ++itemIt )
664  {
665  QgsComposerItem* composerItem = dynamic_cast<QgsComposerItem *>( *itemIt );
666  QgsPaperItem* paperItem = dynamic_cast<QgsPaperItem*>( *itemIt );
667  if ( composerItem && !paperItem )
668  {
669  // If we are not checking for a an item below a specified item, or if we've
670  // already found that item, then we've found our target
671  if (( ! belowItem || foundBelowItem ) && ( !ignoreLocked || !composerItem->positionLock() ) )
672  {
673  return composerItem;
674  }
675  else
676  {
677  if ( composerItem == belowItem )
678  {
679  //Target item is next in list
680  foundBelowItem = true;
681  }
682  }
683  }
684  }
685  return nullptr;
686 }
687 
689 {
690  return position.y() / ( paperHeight() + spaceBetweenPages() );
691 }
692 
694 {
695  return pageNumberAt( QPointF( item->pos().x(), item->pos().y() ) );
696 }
697 
699 {
700  QList<QgsComposerItem*> composerItemList;
701 
702  QList<QGraphicsItem *> graphicsItemList = selectedItems();
703  QList<QGraphicsItem *>::iterator itemIter = graphicsItemList.begin();
704 
705  for ( ; itemIter != graphicsItemList.end(); ++itemIter )
706  {
707  QgsComposerItem* composerItem = dynamic_cast<QgsComposerItem *>( *itemIter );
708  if ( composerItem && ( includeLockedItems || !composerItem->positionLock() ) )
709  {
710  composerItemList.push_back( composerItem );
711  }
712  }
713 
714  return composerItemList;
715 }
716 
718 {
719  QList<const QgsComposerMap*> resultList;
720 
721  QList<QGraphicsItem *> itemList = items();
722  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
723  for ( ; itemIt != itemList.end(); ++itemIt )
724  {
725  const QgsComposerMap* composerMap = dynamic_cast<const QgsComposerMap *>( *itemIt );
726  if ( composerMap )
727  {
728  resultList.push_back( composerMap );
729  }
730  }
731 
732  return resultList;
733 }
734 
736 {
737  QList<QGraphicsItem *> itemList = items();
738  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
739  for ( ; itemIt != itemList.end(); ++itemIt )
740  {
741  const QgsComposerMap* composerMap = dynamic_cast<const QgsComposerMap *>( *itemIt );
742  if ( composerMap )
743  {
744  if ( composerMap->id() == id )
745  {
746  return composerMap;
747  }
748  }
749  }
750  return nullptr;
751 }
752 
754 {
755  // an html item will be a composer frame and if it is we can try to get
756  // its multiframe parent and then try to cast that to a composer html
757  const QgsComposerFrame* composerFrame =
758  dynamic_cast<const QgsComposerFrame *>( item );
759  if ( composerFrame )
760  {
761  const QgsComposerMultiFrame * mypMultiFrame = composerFrame->multiFrame();
762  const QgsComposerHtml* composerHtml =
763  dynamic_cast<const QgsComposerHtml *>( mypMultiFrame );
764  if ( composerHtml )
765  {
766  return composerHtml;
767  }
768  }
769  return nullptr;
770 }
771 
773 {
774  QList<QGraphicsItem *> itemList = items();
775  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
776  for ( ; itemIt != itemList.end(); ++itemIt )
777  {
778  const QgsComposerItem* mypItem = dynamic_cast<const QgsComposerItem *>( *itemIt );
779  if ( mypItem )
780  {
781  if ( mypItem->id() == theId )
782  {
783  return mypItem;
784  }
785  }
786  }
787  return nullptr;
788 }
789 
790 #if 0
791 const QgsComposerItem* QgsComposition::getComposerItemByUuid( QString theUuid, bool inAllComposers ) const
792 {
793  //This does not work since it seems impossible to get the QgisApp::instance() from here... Is there a workaround ?
795 
796  if ( inAllComposers )
797  {
798  composers = QgisApp::instance()->printComposers();
799  }
800  else
801  {
802  composers.insert( this )
803  }
804 
806  for ( ; it != composers.constEnd(); ++it )
807  {
808  QList<QGraphicsItem *> itemList = ( *it )->items();
809  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
810  for ( ; itemIt != itemList.end(); ++itemIt )
811  {
812  const QgsComposerItem* mypItem = dynamic_cast<const QgsComposerItem *>( *itemIt );
813  if ( mypItem )
814  {
815  if ( mypItem->uuid() == theUuid )
816  {
817  return mypItem;
818  }
819  }
820  }
821  }
822 
823  return 0;
824 }
825 #endif
826 
828 {
829  QList<QGraphicsItem *> itemList = items();
830  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
831  for ( ; itemIt != itemList.end(); ++itemIt )
832  {
833  const QgsComposerItem* mypItem = dynamic_cast<const QgsComposerItem *>( *itemIt );
834  if ( mypItem )
835  {
836  if ( mypItem->uuid() == theUuid )
837  {
838  return mypItem;
839  }
840  }
841  }
842 
843  return nullptr;
844 }
845 
847 {
848  mPrintResolution = dpi;
849  emit printResolutionChanged();
850  QgsProject::instance()->dirty( true );
851 }
852 
853 void QgsComposition::setUseAdvancedEffects( const bool effectsEnabled )
854 {
855  mUseAdvancedEffects = effectsEnabled;
856 
857  //toggle effects for all composer items
858  QList<QGraphicsItem*> itemList = items();
860  for ( ; itemIt != itemList.constEnd(); ++itemIt )
861  {
862  QgsComposerItem* composerItem = dynamic_cast<QgsComposerItem*>( *itemIt );
863  if ( composerItem )
864  {
865  composerItem->setEffectsEnabled( effectsEnabled );
866  }
867  }
868 }
869 
870 int QgsComposition::pixelFontSize( double pointSize ) const
871 {
872  return qRound( QgsComposerUtils::pointsToMM( pointSize ) ); //round to nearest mm
873 }
874 
875 double QgsComposition::pointFontSize( int pixelSize ) const
876 {
877  return QgsComposerUtils::mmToPoints( pixelSize );
878 }
879 
881 {
882  if ( composerElem.isNull() )
883  {
884  return false;
885  }
886 
887  QDomElement compositionElem = doc.createElement( "Composition" );
888  compositionElem.setAttribute( "paperWidth", QString::number( mPageWidth ) );
889  compositionElem.setAttribute( "paperHeight", QString::number( mPageHeight ) );
890  compositionElem.setAttribute( "numPages", mPages.size() );
891 
892  QDomElement pageStyleElem = QgsSymbolLayerV2Utils::saveSymbol( QString(), mPageStyleSymbol, doc );
893  compositionElem.appendChild( pageStyleElem );
894 
895  //snapping
896  if ( mSnapToGrid )
897  {
898  compositionElem.setAttribute( "snapping", "1" );
899  }
900  else
901  {
902  compositionElem.setAttribute( "snapping", "0" );
903  }
904  if ( mGridVisible )
905  {
906  compositionElem.setAttribute( "gridVisible", "1" );
907  }
908  else
909  {
910  compositionElem.setAttribute( "gridVisible", "0" );
911  }
912  compositionElem.setAttribute( "snapGridResolution", QString::number( mSnapGridResolution ) );
913  compositionElem.setAttribute( "snapGridOffsetX", QString::number( mSnapGridOffsetX ) );
914  compositionElem.setAttribute( "snapGridOffsetY", QString::number( mSnapGridOffsetY ) );
915 
916  compositionElem.setAttribute( "showPages", mPagesVisible );
917 
918  //custom snap lines
920  for ( ; snapLineIt != mSnapLines.constEnd(); ++snapLineIt )
921  {
922  QDomElement snapLineElem = doc.createElement( "SnapLine" );
923  QLineF line = ( *snapLineIt )->line();
924  snapLineElem.setAttribute( "x1", QString::number( line.x1() ) );
925  snapLineElem.setAttribute( "y1", QString::number( line.y1() ) );
926  snapLineElem.setAttribute( "x2", QString::number( line.x2() ) );
927  snapLineElem.setAttribute( "y2", QString::number( line.y2() ) );
928  compositionElem.appendChild( snapLineElem );
929  }
930 
931  compositionElem.setAttribute( "printResolution", mPrintResolution );
932  compositionElem.setAttribute( "printAsRaster", mPrintAsRaster );
933 
934  compositionElem.setAttribute( "generateWorldFile", mGenerateWorldFile ? 1 : 0 );
935  if ( mGenerateWorldFile && mWorldFileMap )
936  {
937  compositionElem.setAttribute( "worldFileMap", mWorldFileMap->id() );
938  }
939 
940  compositionElem.setAttribute( "alignmentSnap", mAlignmentSnap ? 1 : 0 );
941  compositionElem.setAttribute( "guidesVisible", mGuidesVisible ? 1 : 0 );
942  compositionElem.setAttribute( "smartGuides", mSmartGuides ? 1 : 0 );
943  compositionElem.setAttribute( "snapTolerancePixels", mSnapTolerance );
944 
945  compositionElem.setAttribute( "resizeToContentsMarginTop", mResizeToContentsMarginTop );
946  compositionElem.setAttribute( "resizeToContentsMarginRight", mResizeToContentsMarginRight );
947  compositionElem.setAttribute( "resizeToContentsMarginBottom", mResizeToContentsMarginBottom );
948  compositionElem.setAttribute( "resizeToContentsMarginLeft", mResizeToContentsMarginLeft );
949 
950  //save items except paper items and frame items (they are saved with the corresponding multiframe)
951  QList<QGraphicsItem*> itemList = items();
953  for ( ; itemIt != itemList.constEnd(); ++itemIt )
954  {
955  const QgsComposerItem* composerItem = dynamic_cast<const QgsComposerItem*>( *itemIt );
956  if ( composerItem )
957  {
958  if ( composerItem->type() != QgsComposerItem::ComposerPaper && composerItem->type() != QgsComposerItem::ComposerFrame )
959  {
960  composerItem->writeXML( compositionElem, doc );
961  }
962  }
963  }
964 
965  //save multiframes
966  QSet<QgsComposerMultiFrame*>::const_iterator multiFrameIt = mMultiFrames.constBegin();
967  for ( ; multiFrameIt != mMultiFrames.constEnd(); ++multiFrameIt )
968  {
969  ( *multiFrameIt )->writeXML( compositionElem, doc );
970  }
971  composerElem.appendChild( compositionElem );
972 
973  //data defined properties
974  QgsComposerUtils::writeDataDefinedPropertyMap( compositionElem, doc, &mDataDefinedNames, &mDataDefinedProperties );
975 
976  //custom properties
977  mCustomProperties.writeXml( compositionElem, doc );
978 
979  return true;
980 }
981 
982 bool QgsComposition::readXML( const QDomElement& compositionElem, const QDomDocument& doc )
983 {
984  Q_UNUSED( doc );
985  if ( compositionElem.isNull() )
986  {
987  return false;
988  }
989 
990  //create pages
991  bool widthConversionOk, heightConversionOk;
992  mPageWidth = compositionElem.attribute( "paperWidth" ).toDouble( &widthConversionOk );
993  mPageHeight = compositionElem.attribute( "paperHeight" ).toDouble( &heightConversionOk );
994  emit paperSizeChanged();
995  int numPages = compositionElem.attribute( "numPages", "1" ).toInt();
996 
997  QDomElement pageStyleSymbolElem = compositionElem.firstChildElement( "symbol" );
998  if ( !pageStyleSymbolElem.isNull() )
999  {
1000  delete mPageStyleSymbol;
1001  mPageStyleSymbol = QgsSymbolLayerV2Utils::loadSymbol<QgsFillSymbolV2>( pageStyleSymbolElem );
1002  }
1003 
1004  if ( widthConversionOk && heightConversionOk )
1005  {
1006  removePaperItems();
1007  for ( int i = 0; i < numPages; ++i )
1008  {
1009  addPaperItem();
1010  }
1011  }
1012 
1013  //snapping
1014  mSnapToGrid = compositionElem.attribute( "snapping", "0" ).toInt() == 0 ? false : true;
1015  mGridVisible = compositionElem.attribute( "gridVisible", "0" ).toInt() == 0 ? false : true;
1016 
1017  mSnapGridResolution = compositionElem.attribute( "snapGridResolution" ).toDouble();
1018  mSnapGridOffsetX = compositionElem.attribute( "snapGridOffsetX" ).toDouble();
1019  mSnapGridOffsetY = compositionElem.attribute( "snapGridOffsetY" ).toDouble();
1020 
1021  mAlignmentSnap = compositionElem.attribute( "alignmentSnap", "1" ).toInt() == 0 ? false : true;
1022  mGuidesVisible = compositionElem.attribute( "guidesVisible", "1" ).toInt() == 0 ? false : true;
1023  mSmartGuides = compositionElem.attribute( "smartGuides", "1" ).toInt() == 0 ? false : true;
1024  mSnapTolerance = compositionElem.attribute( "snapTolerancePixels", "10" ).toInt();
1025 
1026  mResizeToContentsMarginTop = compositionElem.attribute( "resizeToContentsMarginTop", "0" ).toDouble();
1027  mResizeToContentsMarginRight = compositionElem.attribute( "resizeToContentsMarginRight", "0" ).toDouble();
1028  mResizeToContentsMarginBottom = compositionElem.attribute( "resizeToContentsMarginBottom", "0" ).toDouble();
1029  mResizeToContentsMarginLeft = compositionElem.attribute( "resizeToContentsMarginLeft", "0" ).toDouble();
1030 
1031  //custom snap lines
1032  QDomNodeList snapLineNodes = compositionElem.elementsByTagName( "SnapLine" );
1033  for ( int i = 0; i < snapLineNodes.size(); ++i )
1034  {
1035  QDomElement snapLineElem = snapLineNodes.at( i ).toElement();
1036  QGraphicsLineItem* snapItem = addSnapLine();
1037  double x1 = snapLineElem.attribute( "x1" ).toDouble();
1038  double y1 = snapLineElem.attribute( "y1" ).toDouble();
1039  double x2 = snapLineElem.attribute( "x2" ).toDouble();
1040  double y2 = snapLineElem.attribute( "y2" ).toDouble();
1041  snapItem->setLine( x1, y1, x2, y2 );
1042  }
1043 
1044  mPagesVisible = ( compositionElem.attribute( "showPages", "1" ) != "0" );
1045  mPrintAsRaster = compositionElem.attribute( "printAsRaster" ).toInt();
1046  mPrintResolution = compositionElem.attribute( "printResolution", "300" ).toInt();
1047 
1048  mGenerateWorldFile = compositionElem.attribute( "generateWorldFile", "0" ).toInt() == 1 ? true : false;
1049 
1050  //data defined properties
1051  QgsComposerUtils::readDataDefinedPropertyMap( compositionElem, &mDataDefinedNames, &mDataDefinedProperties );
1052 
1053  //custom properties
1054  mCustomProperties.readXml( compositionElem );
1055 
1056  updatePaperItems();
1057 
1058  updateBounds();
1059 
1060  return true;
1061 }
1062 
1063 bool QgsComposition::loadFromTemplate( const QDomDocument& doc, QMap<QString, QString>* substitutionMap, bool addUndoCommands, const bool clearComposition )
1064 {
1065  if ( clearComposition )
1066  {
1067  deleteAndRemoveMultiFrames();
1068 
1069  //delete all non paper items and emit itemRemoved signal
1070  QList<QGraphicsItem *> itemList = items();
1071  QList<QGraphicsItem *>::iterator itemIter = itemList.begin();
1072  for ( ; itemIter != itemList.end(); ++itemIter )
1073  {
1074  QgsComposerItem* cItem = dynamic_cast<QgsComposerItem*>( *itemIter );
1075  QgsPaperItem* pItem = dynamic_cast<QgsPaperItem*>( *itemIter );
1076  if ( cItem && !pItem )
1077  {
1078  removeItem( cItem );
1079  emit itemRemoved( cItem );
1080  delete cItem;
1081  }
1082  }
1083  mItemsModel->clear();
1084 
1085  removePaperItems();
1086  mUndoStack->clear();
1087  }
1088 
1089  QDomDocument importDoc;
1090  if ( substitutionMap )
1091  {
1092  QString xmlString = doc.toString();
1093  QMap<QString, QString>::const_iterator sIt = substitutionMap->constBegin();
1094  for ( ; sIt != substitutionMap->constEnd(); ++sIt )
1095  {
1096  xmlString = xmlString.replace( '[' + sIt.key() + ']', encodeStringForXML( sIt.value() ) );
1097  }
1098 
1099  QString errorMsg;
1100  int errorLine, errorColumn;
1101  if ( !importDoc.setContent( xmlString, &errorMsg, &errorLine, &errorColumn ) )
1102  {
1103  return false;
1104  }
1105  }
1106  else
1107  {
1108  importDoc = doc;
1109  }
1110 
1111  //read general settings
1112  QDomElement atlasElem;
1113  if ( clearComposition )
1114  {
1115  QDomElement compositionElem = importDoc.documentElement().firstChildElement( "Composition" );
1116  if ( compositionElem.isNull() )
1117  {
1118  return false;
1119  }
1120 
1121  bool ok = readXML( compositionElem, importDoc );
1122  if ( !ok )
1123  {
1124  return false;
1125  }
1126 
1127  // read atlas parameters - must be done before adding items
1128  atlasElem = importDoc.documentElement().firstChildElement( "Atlas" );
1129  atlasComposition().readXML( atlasElem, importDoc );
1130  }
1131 
1132  // remove all uuid attributes since we don't want duplicates UUIDS
1133  QDomNodeList composerItemsNodes = importDoc.elementsByTagName( "ComposerItem" );
1134  for ( int i = 0; i < composerItemsNodes.count(); ++i )
1135  {
1136  QDomNode composerItemNode = composerItemsNodes.at( i );
1137  if ( composerItemNode.isElement() )
1138  {
1139  composerItemNode.toElement().setAttribute( "templateUuid", composerItemNode.toElement().attribute( "uuid" ) );
1140  composerItemNode.toElement().removeAttribute( "uuid" );
1141  }
1142  }
1143 
1144  //addItemsFromXML
1145  addItemsFromXML( importDoc.documentElement(), importDoc, nullptr, addUndoCommands, nullptr );
1146 
1147  //read atlas map parameters (for pre 2.2 templates)
1148  //this can only be done after items have been added
1149  if ( clearComposition )
1150  {
1151  atlasComposition().readXMLMapSettings( atlasElem, importDoc );
1152  }
1153  return true;
1154 }
1155 
1156 QPointF QgsComposition::minPointFromXml( const QDomElement& elem ) const
1157 {
1158  double minX = std::numeric_limits<double>::max();
1159  double minY = std::numeric_limits<double>::max();
1160  QDomNodeList composerItemList = elem.elementsByTagName( "ComposerItem" );
1161  for ( int i = 0; i < composerItemList.size(); ++i )
1162  {
1163  QDomElement currentComposerItemElem = composerItemList.at( i ).toElement();
1164  double x, y;
1165  bool xOk, yOk;
1166  x = currentComposerItemElem.attribute( "x" ).toDouble( &xOk );
1167  y = currentComposerItemElem.attribute( "y" ).toDouble( &yOk );
1168  if ( !xOk || !yOk )
1169  {
1170  continue;
1171  }
1172  minX = qMin( minX, x );
1173  minY = qMin( minY, y );
1174  }
1175  if ( minX < std::numeric_limits<double>::max() )
1176  {
1177  return QPointF( minX, minY );
1178  }
1179  else
1180  {
1181  return QPointF( 0, 0 );
1182  }
1183 }
1184 
1186  bool addUndoCommands, QPointF* pos, bool pasteInPlace )
1187 {
1188  QPointF* pasteInPlacePt = nullptr;
1189 
1190  //if we are adding items to a composition which already contains items, we need to make sure
1191  //these items are placed at the top of the composition and that zValues are not duplicated
1192  //so, calculate an offset which needs to be added to the zValue of created items
1193  int zOrderOffset = mItemsModel->zOrderListSize();
1194 
1195  QPointF pasteShiftPos;
1196  QgsComposerItem* lastPastedItem = nullptr;
1197  if ( pos )
1198  {
1199  //If we are placing items relative to a certain point, then calculate how much we need
1200  //to shift the items by so that they are placed at this point
1201  //First, calculate the minimum position from the xml
1202  QPointF minItemPos = minPointFromXml( elem );
1203  //next, calculate how much each item needs to be shifted from its original position
1204  //so that it's placed at the correct relative position
1205  pasteShiftPos = *pos - minItemPos;
1206 
1207  //since we are pasting items, clear the existing selection
1208  setAllUnselected();
1209 
1210  if ( pasteInPlace )
1211  {
1212  pasteInPlacePt = new QPointF( 0, pageNumberAt( *pos ) * ( mPageHeight + mSpaceBetweenPages ) );
1213  }
1214  }
1215  QDomNodeList composerLabelList = elem.elementsByTagName( "ComposerLabel" );
1216  for ( int i = 0; i < composerLabelList.size(); ++i )
1217  {
1218  QDomElement currentComposerLabelElem = composerLabelList.at( i ).toElement();
1219  QgsComposerLabel* newLabel = new QgsComposerLabel( this );
1220  newLabel->readXML( currentComposerLabelElem, doc );
1221  if ( pos )
1222  {
1223  if ( pasteInPlacePt )
1224  {
1225  newLabel->setItemPosition( newLabel->pos().x(), fmod( newLabel->pos().y(), ( paperHeight() + spaceBetweenPages() ) ) );
1226  newLabel->move( pasteInPlacePt->x(), pasteInPlacePt->y() );
1227  }
1228  else
1229  {
1230  newLabel->move( pasteShiftPos.x(), pasteShiftPos.y() );
1231  }
1232  newLabel->setSelected( true );
1233  lastPastedItem = newLabel;
1234  }
1235  addComposerLabel( newLabel );
1236  newLabel->setZValue( newLabel->zValue() + zOrderOffset );
1237  if ( addUndoCommands )
1238  {
1239  pushAddRemoveCommand( newLabel, tr( "Label added" ) );
1240  }
1241  }
1242  // map
1243  QDomNodeList composerMapList = elem.elementsByTagName( "ComposerMap" );
1244  for ( int i = 0; i < composerMapList.size(); ++i )
1245  {
1246  QDomElement currentComposerMapElem = composerMapList.at( i ).toElement();
1247  QgsComposerMap* newMap = new QgsComposerMap( this );
1248 
1249  if ( mapsToRestore )
1250  {
1251  newMap->setUpdatesEnabled( false );
1252  }
1253 
1254  newMap->readXML( currentComposerMapElem, doc );
1255  newMap->assignFreeId();
1256 
1257  if ( mapsToRestore )
1258  {
1259  mapsToRestore->insert( newMap, static_cast< int >( newMap->previewMode() ) );
1261  newMap->setUpdatesEnabled( true );
1262  }
1263  addComposerMap( newMap, false );
1264  newMap->setZValue( newMap->zValue() + zOrderOffset );
1265  if ( pos )
1266  {
1267  if ( pasteInPlace )
1268  {
1269  newMap->setItemPosition( newMap->pos().x(), fmod( newMap->pos().y(), ( paperHeight() + spaceBetweenPages() ) ) );
1270  newMap->move( pasteInPlacePt->x(), pasteInPlacePt->y() );
1271  }
1272  else
1273  {
1274  newMap->move( pasteShiftPos.x(), pasteShiftPos.y() );
1275  }
1276  newMap->setSelected( true );
1277  lastPastedItem = newMap;
1278  }
1279 
1280  if ( addUndoCommands )
1281  {
1282  pushAddRemoveCommand( newMap, tr( "Map added" ) );
1283  }
1284  }
1285  //now that all map items have been created, re-connect overview map signals
1287  composerItems( maps );
1288  for ( QList<QgsComposerMap*>::iterator mit = maps.begin(); mit != maps.end(); ++mit )
1289  {
1290  QgsComposerMap* map = ( *mit );
1291  if ( map )
1292  {
1293  QList<QgsComposerMapOverview* > overviews = map->overviews()->asList();
1294  QList<QgsComposerMapOverview* >::iterator overviewIt = overviews.begin();
1295  for ( ; overviewIt != overviews.end(); ++overviewIt )
1296  {
1297  ( *overviewIt )->connectSignals();
1298  }
1299  }
1300  }
1301 
1302  // arrow
1303  QDomNodeList composerArrowList = elem.elementsByTagName( "ComposerArrow" );
1304  for ( int i = 0; i < composerArrowList.size(); ++i )
1305  {
1306  QDomElement currentComposerArrowElem = composerArrowList.at( i ).toElement();
1307  QgsComposerArrow* newArrow = new QgsComposerArrow( this );
1308  newArrow->readXML( currentComposerArrowElem, doc );
1309  if ( pos )
1310  {
1311  if ( pasteInPlace )
1312  {
1313  newArrow->setItemPosition( newArrow->pos().x(), fmod( newArrow->pos().y(), ( paperHeight() + spaceBetweenPages() ) ) );
1314  newArrow->move( pasteInPlacePt->x(), pasteInPlacePt->y() );
1315  }
1316  else
1317  {
1318  newArrow->move( pasteShiftPos.x(), pasteShiftPos.y() );
1319  }
1320  newArrow->setSelected( true );
1321  lastPastedItem = newArrow;
1322  }
1323  addComposerArrow( newArrow );
1324  newArrow->setZValue( newArrow->zValue() + zOrderOffset );
1325  if ( addUndoCommands )
1326  {
1327  pushAddRemoveCommand( newArrow, tr( "Arrow added" ) );
1328  }
1329  }
1330  // scalebar
1331  QDomNodeList composerScaleBarList = elem.elementsByTagName( "ComposerScaleBar" );
1332  for ( int i = 0; i < composerScaleBarList.size(); ++i )
1333  {
1334  QDomElement currentComposerScaleBarElem = composerScaleBarList.at( i ).toElement();
1335  QgsComposerScaleBar* newScaleBar = new QgsComposerScaleBar( this );
1336  newScaleBar->readXML( currentComposerScaleBarElem, doc );
1337  if ( pos )
1338  {
1339  if ( pasteInPlace )
1340  {
1341  newScaleBar->setItemPosition( newScaleBar->pos().x(), fmod( newScaleBar->pos().y(), ( paperHeight() + spaceBetweenPages() ) ) );
1342  newScaleBar->move( pasteInPlacePt->x(), pasteInPlacePt->y() );
1343  }
1344  else
1345  {
1346  newScaleBar->move( pasteShiftPos.x(), pasteShiftPos.y() );
1347  }
1348  newScaleBar->setSelected( true );
1349  lastPastedItem = newScaleBar;
1350  }
1351  addComposerScaleBar( newScaleBar );
1352  newScaleBar->setZValue( newScaleBar->zValue() + zOrderOffset );
1353  if ( addUndoCommands )
1354  {
1355  pushAddRemoveCommand( newScaleBar, tr( "Scale bar added" ) );
1356  }
1357  }
1358  // shape
1359  QDomNodeList composerShapeList = elem.elementsByTagName( "ComposerShape" );
1360  for ( int i = 0; i < composerShapeList.size(); ++i )
1361  {
1362  QDomElement currentComposerShapeElem = composerShapeList.at( i ).toElement();
1363  QgsComposerShape* newShape = new QgsComposerShape( this );
1364  newShape->readXML( currentComposerShapeElem, doc );
1365  //new shapes should default to symbol v2
1366  newShape->setUseSymbolV2( true );
1367  if ( pos )
1368  {
1369  if ( pasteInPlace )
1370  {
1371  newShape->setItemPosition( newShape->pos().x(), fmod( newShape->pos().y(), ( paperHeight() + spaceBetweenPages() ) ) );
1372  newShape->move( pasteInPlacePt->x(), pasteInPlacePt->y() );
1373  }
1374  else
1375  {
1376  newShape->move( pasteShiftPos.x(), pasteShiftPos.y() );
1377  }
1378  newShape->setSelected( true );
1379  lastPastedItem = newShape;
1380  }
1381  addComposerShape( newShape );
1382  newShape->setZValue( newShape->zValue() + zOrderOffset );
1383  if ( addUndoCommands )
1384  {
1385  pushAddRemoveCommand( newShape, tr( "Shape added" ) );
1386  }
1387  }
1388  // picture
1389  QDomNodeList composerPictureList = elem.elementsByTagName( "ComposerPicture" );
1390  for ( int i = 0; i < composerPictureList.size(); ++i )
1391  {
1392  QDomElement currentComposerPictureElem = composerPictureList.at( i ).toElement();
1393  QgsComposerPicture* newPicture = new QgsComposerPicture( this );
1394  newPicture->readXML( currentComposerPictureElem, doc );
1395  if ( pos )
1396  {
1397  if ( pasteInPlace )
1398  {
1399  newPicture->setItemPosition( newPicture->pos().x(), fmod( newPicture->pos().y(), ( paperHeight() + spaceBetweenPages() ) ) );
1400  newPicture->move( pasteInPlacePt->x(), pasteInPlacePt->y() );
1401  }
1402  else
1403  {
1404  newPicture->move( pasteShiftPos.x(), pasteShiftPos.y() );
1405  }
1406  newPicture->setSelected( true );
1407  lastPastedItem = newPicture;
1408  }
1409  addComposerPicture( newPicture );
1410  newPicture->setZValue( newPicture->zValue() + zOrderOffset );
1411  if ( addUndoCommands )
1412  {
1413  pushAddRemoveCommand( newPicture, tr( "Picture added" ) );
1414  }
1415  }
1416  // legend
1417  QDomNodeList composerLegendList = elem.elementsByTagName( "ComposerLegend" );
1418  for ( int i = 0; i < composerLegendList.size(); ++i )
1419  {
1420  QDomElement currentComposerLegendElem = composerLegendList.at( i ).toElement();
1421  QgsComposerLegend* newLegend = new QgsComposerLegend( this );
1422  newLegend->readXML( currentComposerLegendElem, doc );
1423  if ( pos )
1424  {
1425  if ( pasteInPlace )
1426  {
1427  newLegend->setItemPosition( newLegend->pos().x(), fmod( newLegend->pos().y(), ( paperHeight() + spaceBetweenPages() ) ) );
1428  newLegend->move( pasteInPlacePt->x(), pasteInPlacePt->y() );
1429  }
1430  else
1431  {
1432  newLegend->move( pasteShiftPos.x(), pasteShiftPos.y() );
1433  }
1434  newLegend->setSelected( true );
1435  lastPastedItem = newLegend;
1436  }
1437  addComposerLegend( newLegend );
1438  newLegend->setZValue( newLegend->zValue() + zOrderOffset );
1439  if ( addUndoCommands )
1440  {
1441  pushAddRemoveCommand( newLegend, tr( "Legend added" ) );
1442  }
1443  }
1444  // table
1445  QDomNodeList composerTableList = elem.elementsByTagName( "ComposerAttributeTable" );
1446  for ( int i = 0; i < composerTableList.size(); ++i )
1447  {
1448  QDomElement currentComposerTableElem = composerTableList.at( i ).toElement();
1449  QgsComposerAttributeTable* newTable = new QgsComposerAttributeTable( this );
1450  newTable->readXML( currentComposerTableElem, doc );
1451  if ( pos )
1452  {
1453  if ( pasteInPlace )
1454  {
1455  newTable->setItemPosition( newTable->pos().x(), fmod( newTable->pos().y(), ( paperHeight() + spaceBetweenPages() ) ) );
1456  newTable->move( pasteInPlacePt->x(), pasteInPlacePt->y() );
1457  }
1458  else
1459  {
1460  newTable->move( pasteShiftPos.x(), pasteShiftPos.y() );
1461  }
1462  newTable->setSelected( true );
1463  lastPastedItem = newTable;
1464  }
1465  addComposerTable( newTable );
1466  newTable->setZValue( newTable->zValue() + zOrderOffset );
1467  if ( addUndoCommands )
1468  {
1469  pushAddRemoveCommand( newTable, tr( "Table added" ) );
1470  }
1471  }
1472  // html
1473  //TODO - fix this. pasting multiframe frame items has no effect
1474  QDomNodeList composerHtmlList = elem.elementsByTagName( "ComposerHtml" );
1475  for ( int i = 0; i < composerHtmlList.size(); ++i )
1476  {
1477  QDomElement currentHtmlElem = composerHtmlList.at( i ).toElement();
1478  QgsComposerHtml* newHtml = new QgsComposerHtml( this, false );
1479  newHtml->readXML( currentHtmlElem, doc );
1480  newHtml->setCreateUndoCommands( true );
1481  this->addMultiFrame( newHtml );
1482 
1483  //offset z values for frames
1484  //TODO - fix this after fixing html item paste
1485  /*for ( int frameIdx = 0; frameIdx < newHtml->frameCount(); ++frameIdx )
1486  {
1487  QgsComposerFrame * frame = newHtml->frame( frameIdx );
1488  frame->setZValue( frame->zValue() + zOrderOffset );
1489  }*/
1490  }
1491  QDomNodeList composerAttributeTableV2List = elem.elementsByTagName( "ComposerAttributeTableV2" );
1492  for ( int i = 0; i < composerAttributeTableV2List.size(); ++i )
1493  {
1494  QDomElement currentTableElem = composerAttributeTableV2List.at( i ).toElement();
1495  QgsComposerAttributeTableV2* newTable = new QgsComposerAttributeTableV2( this, false );
1496  newTable->readXML( currentTableElem, doc );
1497  newTable->setCreateUndoCommands( true );
1498  this->addMultiFrame( newTable );
1499 
1500  //offset z values for frames
1501  //TODO - fix this after fixing html item paste
1502  /*for ( int frameIdx = 0; frameIdx < newHtml->frameCount(); ++frameIdx )
1503  {
1504  QgsComposerFrame * frame = newHtml->frame( frameIdx );
1505  frame->setZValue( frame->zValue() + zOrderOffset );
1506  }*/
1507  }
1508 
1509  // groups (must be last as it references uuids of above items)
1510  //TODO - pasted groups lose group properties, since the uuids of group items
1511  //changes
1512  QDomNodeList groupList = elem.elementsByTagName( "ComposerItemGroup" );
1513  for ( int i = 0; i < groupList.size(); ++i )
1514  {
1515  QDomElement groupElem = groupList.at( i ).toElement();
1516  QgsComposerItemGroup *newGroup = new QgsComposerItemGroup( this );
1517  newGroup->readXML( groupElem, doc );
1518  addItem( newGroup );
1519  if ( addUndoCommands )
1520  {
1521  pushAddRemoveCommand( newGroup, tr( "Group added" ) );
1522  }
1523  }
1524 
1525  //Since this function adds items grouped by type, and each item is added to end of
1526  //z order list in turn, it will now be inconsistent with the actual order of items in the scene.
1527  //Make sure z order list matches the actual order of items in the scene.
1528  mItemsModel->rebuildZList();
1529 
1530  if ( lastPastedItem )
1531  {
1532  emit selectedItemChanged( lastPastedItem );
1533  }
1534 
1535  delete pasteInPlacePt;
1536  pasteInPlacePt = nullptr;
1537 
1538 }
1539 
1541 {
1542  if ( !item )
1543  {
1544  return;
1545  }
1546 
1547  //model handles changes to z list
1548  mItemsModel->addItemAtTop( item );
1549 }
1550 
1552 {
1553  if ( !item )
1554  {
1555  return;
1556  }
1557 
1558  //model handles changes to z list
1559  mItemsModel->removeItem( item );
1560 }
1561 
1563 {
1565  QList<QgsComposerItem*>::iterator it = selectedItems.begin();
1566  bool itemsRaised = false;
1567  for ( ; it != selectedItems.end(); ++it )
1568  {
1569  itemsRaised = itemsRaised | raiseItem( *it );
1570  }
1571 
1572  if ( !itemsRaised )
1573  {
1574  //no change
1575  return;
1576  }
1577 
1578  //update all positions
1579  updateZValues();
1580  update();
1581 }
1582 
1584 {
1585  //model handles reordering items
1586  return mItemsModel->reorderItemUp( item );
1587 }
1588 
1590 {
1591  return mItemsModel->getComposerItemAbove( item );
1592 }
1593 
1595 {
1596  return mItemsModel->getComposerItemBelow( item );
1597 }
1598 
1600 {
1601  QgsComposerItem* previousSelectedItem = nullptr;
1603  if ( !selectedItems.isEmpty() )
1604  {
1605  previousSelectedItem = selectedItems.at( 0 );
1606  }
1607 
1608  if ( !previousSelectedItem )
1609  {
1610  return;
1611  }
1612 
1613  //select item with target z value
1614  QgsComposerItem* selectedItem = nullptr;
1615  switch ( direction )
1616  {
1618  selectedItem = getComposerItemBelow( previousSelectedItem );
1619  break;
1621  selectedItem = getComposerItemAbove( previousSelectedItem );
1622  break;
1623  }
1624 
1625  if ( !selectedItem )
1626  {
1627  return;
1628  }
1629 
1630  //ok, found a good target item
1631  setAllUnselected();
1632  selectedItem->setSelected( true );
1633  emit selectedItemChanged( selectedItem );
1634 }
1635 
1637 {
1639  QList<QgsComposerItem*>::iterator it = selectedItems.begin();
1640  bool itemsLowered = false;
1641  for ( ; it != selectedItems.end(); ++it )
1642  {
1643  itemsLowered = itemsLowered | lowerItem( *it );
1644  }
1645 
1646  if ( !itemsLowered )
1647  {
1648  //no change
1649  return;
1650  }
1651 
1652  //update all positions
1653  updateZValues();
1654  update();
1655 }
1656 
1658 {
1659  //model handles reordering items
1660  return mItemsModel->reorderItemDown( item );
1661 }
1662 
1664 {
1666  QList<QgsComposerItem*>::iterator it = selectedItems.begin();
1667  bool itemsRaised = false;
1668  for ( ; it != selectedItems.end(); ++it )
1669  {
1670  itemsRaised = itemsRaised | moveItemToTop( *it );
1671  }
1672 
1673  if ( !itemsRaised )
1674  {
1675  //no change
1676  return;
1677  }
1678 
1679  //update all positions
1680  updateZValues();
1681  update();
1682 }
1683 
1685 {
1686  //model handles reordering items
1687  return mItemsModel->reorderItemToTop( item );
1688 }
1689 
1691 {
1693  QList<QgsComposerItem*>::iterator it = selectedItems.begin();
1694  bool itemsLowered = false;
1695  for ( ; it != selectedItems.end(); ++it )
1696  {
1697  itemsLowered = itemsLowered | moveItemToBottom( *it );
1698  }
1699 
1700  if ( !itemsLowered )
1701  {
1702  //no change
1703  return;
1704  }
1705 
1706  //update all positions
1707  updateZValues();
1708  update();
1709 }
1710 
1712 {
1713  //model handles reordering items
1714  return mItemsModel->reorderItemToBottom( item );
1715 }
1716 
1718 {
1720  if ( selectedItems.size() < 2 )
1721  {
1722  return;
1723  }
1724 
1725  QRectF selectedItemBBox;
1726  if ( boundingRectOfSelectedItems( selectedItemBBox ) != 0 )
1727  {
1728  return;
1729  }
1730 
1731  double minXCoordinate = selectedItemBBox.left();
1732 
1733  //align items left to minimum x coordinate
1734  QUndoCommand* parentCommand = new QUndoCommand( tr( "Aligned items left" ) );
1735  QList<QgsComposerItem*>::iterator align_it = selectedItems.begin();
1736  for ( ; align_it != selectedItems.end(); ++align_it )
1737  {
1738  QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand );
1739  subcommand->savePreviousState();
1740  ( *align_it )->setPos( minXCoordinate, ( *align_it )->pos().y() );
1741  subcommand->saveAfterState();
1742  }
1743  mUndoStack->push( parentCommand );
1744  QgsProject::instance()->dirty( true );
1745 }
1746 
1748 {
1750  if ( selectedItems.size() < 2 )
1751  {
1752  return;
1753  }
1754 
1755  QRectF selectedItemBBox;
1756  if ( boundingRectOfSelectedItems( selectedItemBBox ) != 0 )
1757  {
1758  return;
1759  }
1760 
1761  double averageXCoord = ( selectedItemBBox.left() + selectedItemBBox.right() ) / 2.0;
1762 
1763  //place items
1764  QUndoCommand* parentCommand = new QUndoCommand( tr( "Aligned items horizontal center" ) );
1765  QList<QgsComposerItem*>::iterator align_it = selectedItems.begin();
1766  for ( ; align_it != selectedItems.end(); ++align_it )
1767  {
1768  QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand );
1769  subcommand->savePreviousState();
1770  ( *align_it )->setPos( averageXCoord - ( *align_it )->rect().width() / 2.0, ( *align_it )->pos().y() );
1771  subcommand->saveAfterState();
1772  }
1773  mUndoStack->push( parentCommand );
1774  QgsProject::instance()->dirty( true );
1775 }
1776 
1778 {
1780  if ( selectedItems.size() < 2 )
1781  {
1782  return;
1783  }
1784 
1785  QRectF selectedItemBBox;
1786  if ( boundingRectOfSelectedItems( selectedItemBBox ) != 0 )
1787  {
1788  return;
1789  }
1790 
1791  double maxXCoordinate = selectedItemBBox.right();
1792 
1793  //align items right to maximum x coordinate
1794  QUndoCommand* parentCommand = new QUndoCommand( tr( "Aligned items right" ) );
1795  QList<QgsComposerItem*>::iterator align_it = selectedItems.begin();
1796  for ( ; align_it != selectedItems.end(); ++align_it )
1797  {
1798  QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand );
1799  subcommand->savePreviousState();
1800  ( *align_it )->setPos( maxXCoordinate - ( *align_it )->rect().width(), ( *align_it )->pos().y() );
1801  subcommand->saveAfterState();
1802  }
1803  mUndoStack->push( parentCommand );
1804  QgsProject::instance()->dirty( true );
1805 }
1806 
1808 {
1810  if ( selectedItems.size() < 2 )
1811  {
1812  return;
1813  }
1814 
1815  QRectF selectedItemBBox;
1816  if ( boundingRectOfSelectedItems( selectedItemBBox ) != 0 )
1817  {
1818  return;
1819  }
1820 
1821  double minYCoordinate = selectedItemBBox.top();
1822 
1823  QUndoCommand* parentCommand = new QUndoCommand( tr( "Aligned items top" ) );
1824  QList<QgsComposerItem*>::iterator align_it = selectedItems.begin();
1825  for ( ; align_it != selectedItems.end(); ++align_it )
1826  {
1827  QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand );
1828  subcommand->savePreviousState();
1829  ( *align_it )->setPos(( *align_it )->pos().x(), minYCoordinate );
1830  subcommand->saveAfterState();
1831  }
1832  mUndoStack->push( parentCommand );
1833  QgsProject::instance()->dirty( true );
1834 }
1835 
1837 {
1839  if ( selectedItems.size() < 2 )
1840  {
1841  return;
1842  }
1843 
1844  QRectF selectedItemBBox;
1845  if ( boundingRectOfSelectedItems( selectedItemBBox ) != 0 )
1846  {
1847  return;
1848  }
1849 
1850  double averageYCoord = ( selectedItemBBox.top() + selectedItemBBox.bottom() ) / 2.0;
1851  QUndoCommand* parentCommand = new QUndoCommand( tr( "Aligned items vertical center" ) );
1852  QList<QgsComposerItem*>::iterator align_it = selectedItems.begin();
1853  for ( ; align_it != selectedItems.end(); ++align_it )
1854  {
1855  QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand );
1856  subcommand->savePreviousState();
1857  ( *align_it )->setPos(( *align_it )->pos().x(), averageYCoord - ( *align_it )->rect().height() / 2 );
1858  subcommand->saveAfterState();
1859  }
1860  mUndoStack->push( parentCommand );
1861  QgsProject::instance()->dirty( true );
1862 }
1863 
1865 {
1867  if ( selectedItems.size() < 2 )
1868  {
1869  return;
1870  }
1871 
1872  QRectF selectedItemBBox;
1873  if ( boundingRectOfSelectedItems( selectedItemBBox ) != 0 )
1874  {
1875  return;
1876  }
1877 
1878  double maxYCoord = selectedItemBBox.bottom();
1879  QUndoCommand* parentCommand = new QUndoCommand( tr( "Aligned items bottom" ) );
1880  QList<QgsComposerItem*>::iterator align_it = selectedItems.begin();
1881  for ( ; align_it != selectedItems.end(); ++align_it )
1882  {
1883  QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand );
1884  subcommand->savePreviousState();
1885  ( *align_it )->setPos(( *align_it )->pos().x(), maxYCoord - ( *align_it )->rect().height() );
1886  subcommand->saveAfterState();
1887  }
1888  mUndoStack->push( parentCommand );
1889  QgsProject::instance()->dirty( true );
1890 }
1891 
1893 {
1894  QUndoCommand* parentCommand = new QUndoCommand( tr( "Items locked" ) );
1896  QList<QgsComposerItem*>::iterator itemIter = selectionList.begin();
1897  for ( ; itemIter != selectionList.end(); ++itemIter )
1898  {
1899  QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *itemIter, "", parentCommand );
1900  subcommand->savePreviousState();
1901  ( *itemIter )->setPositionLock( true );
1902  subcommand->saveAfterState();
1903  }
1904 
1905  setAllUnselected();
1906  mUndoStack->push( parentCommand );
1907  QgsProject::instance()->dirty( true );
1908 }
1909 
1911 {
1912  //unlock all items in composer
1913 
1914  QUndoCommand* parentCommand = new QUndoCommand( tr( "Items unlocked" ) );
1915 
1916  //first, clear the selection
1917  setAllUnselected();
1918 
1919  QList<QGraphicsItem *> itemList = items();
1920  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
1921  for ( ; itemIt != itemList.end(); ++itemIt )
1922  {
1923  QgsComposerItem* mypItem = dynamic_cast<QgsComposerItem *>( *itemIt );
1924  if ( mypItem && mypItem->positionLock() )
1925  {
1926  QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( mypItem, "", parentCommand );
1927  subcommand->savePreviousState();
1928  mypItem->setPositionLock( false );
1929  //select unlocked items, same behaviour as illustrator
1930  mypItem->setSelected( true );
1931  emit selectedItemChanged( mypItem );
1932  subcommand->saveAfterState();
1933  }
1934  }
1935  mUndoStack->push( parentCommand );
1936  QgsProject::instance()->dirty( true );
1937 }
1938 
1940 {
1941  if ( items.size() < 2 )
1942  {
1943  //not enough items for a group
1944  return nullptr;
1945  }
1946 
1947  QgsComposerItemGroup* itemGroup = new QgsComposerItemGroup( this );
1948  QgsDebugMsg( QString( "itemgroup created with %1 items (%2 to be added)" ) .arg( itemGroup->items().size() ).arg( items.size() ) );
1949 
1950  QList<QgsComposerItem*>::iterator itemIter = items.begin();
1951  for ( ; itemIter != items.end(); ++itemIter )
1952  {
1953  itemGroup->addItem( *itemIter );
1954  QgsDebugMsg( QString( "itemgroup now has %1" )
1955  .arg( itemGroup->items().size() ) );
1956  }
1957 
1958  addItem( itemGroup );
1959 
1961  QObject::connect( c, SIGNAL( itemRemoved( QgsComposerItem* ) ), this, SIGNAL( itemRemoved( QgsComposerItem* ) ) );
1962  QObject::connect( c, SIGNAL( itemAdded( QgsComposerItem* ) ), this, SLOT( sendItemAddedSignal( QgsComposerItem* ) ) );
1963 
1964  undoStack()->push( c );
1965  QgsProject::instance()->setDirty( true );
1966  //QgsDebugMsg( QString( "itemgroup after pushAddRemove has %1" ) .arg( itemGroup->items().size() ) );
1967 
1968  emit composerItemGroupAdded( itemGroup );
1969 
1970  return itemGroup;
1971 }
1972 
1974 {
1975  QList<QgsComposerItem *> ungroupedItems;
1976  if ( !group )
1977  {
1978  return ungroupedItems;
1979  }
1980 
1981  // group ownership transferred to QgsGroupUngroupItemsCommand
1982  // Call this before removing group items so it can keep note
1983  // of contents
1985  QObject::connect( c, SIGNAL( itemRemoved( QgsComposerItem* ) ), this, SIGNAL( itemRemoved( QgsComposerItem* ) ) );
1986  QObject::connect( c, SIGNAL( itemAdded( QgsComposerItem* ) ), this, SLOT( sendItemAddedSignal( QgsComposerItem* ) ) );
1987 
1988  undoStack()->push( c );
1989  QgsProject::instance()->setDirty( true );
1990 
1991 
1992  QSet<QgsComposerItem*> groupedItems = group->items();
1993  QSet<QgsComposerItem*>::iterator itemIt = groupedItems.begin();
1994  for ( ; itemIt != groupedItems.end(); ++itemIt )
1995  {
1996  ungroupedItems << ( *itemIt );
1997  }
1998 
1999  group->removeItems();
2000 
2001  // note: emits itemRemoved
2002  removeComposerItem( group, false, false );
2003 
2004  return ungroupedItems;
2005 }
2006 
2007 void QgsComposition::updateZValues( const bool addUndoCommands )
2008 {
2009  int counter = mItemsModel->zOrderListSize();
2011  QgsComposerItem* currentItem = nullptr;
2012 
2013  QUndoCommand* parentCommand = nullptr;
2014  if ( addUndoCommands )
2015  {
2016  parentCommand = new QUndoCommand( tr( "Item z-order changed" ) );
2017  }
2018  for ( ; it != mItemsModel->zOrderList()->constEnd(); ++it )
2019  {
2020  currentItem = *it;
2021  if ( currentItem )
2022  {
2023  QgsComposerItemCommand* subcommand = nullptr;
2024  if ( addUndoCommands )
2025  {
2026  subcommand = new QgsComposerItemCommand( *it, "", parentCommand );
2027  subcommand->savePreviousState();
2028  }
2029  currentItem->setZValue( counter );
2030  if ( addUndoCommands )
2031  {
2032  subcommand->saveAfterState();
2033  }
2034  }
2035  --counter;
2036  }
2037  if ( addUndoCommands )
2038  {
2039  mUndoStack->push( parentCommand );
2040  QgsProject::instance()->dirty( true );
2041  }
2042 }
2043 
2045 {
2046  //model handles changes to item z order list
2047  mItemsModel->rebuildZList();
2048 
2049  //Finally, rebuild the zValue of all items to remove any duplicate zValues and make sure there's
2050  //no missing zValues.
2051  updateZValues( false );
2052 }
2053 
2055 {
2056  if ( !mSnapToGrid || mSnapGridResolution <= 0 || !graphicsView() )
2057  {
2058  return scenePoint;
2059  }
2060 
2061  //y offset to current page
2062  int pageNr = static_cast< int >( scenePoint.y() / ( mPageHeight + mSpaceBetweenPages ) );
2063  double yOffset = pageNr * ( mPageHeight + mSpaceBetweenPages );
2064  double yPage = scenePoint.y() - yOffset; //y-coordinate relative to current page
2065 
2066  //snap x coordinate
2067  int xRatio = static_cast< int >(( scenePoint.x() - mSnapGridOffsetX ) / mSnapGridResolution + 0.5 );
2068  int yRatio = static_cast< int >(( yPage - mSnapGridOffsetY ) / mSnapGridResolution + 0.5 );
2069 
2070  double xSnapped = xRatio * mSnapGridResolution + mSnapGridOffsetX;
2071  double ySnapped = yRatio * mSnapGridResolution + mSnapGridOffsetY + yOffset;
2072 
2073  //convert snap tolerance from pixels to mm
2074  double viewScaleFactor = graphicsView()->transform().m11();
2075  double alignThreshold = mSnapTolerance / viewScaleFactor;
2076 
2077  if ( fabs( xSnapped - scenePoint.x() ) > alignThreshold )
2078  {
2079  //snap distance is outside of tolerance
2080  xSnapped = scenePoint.x();
2081  }
2082  if ( fabs( ySnapped - scenePoint.y() ) > alignThreshold )
2083  {
2084  //snap distance is outside of tolerance
2085  ySnapped = scenePoint.y();
2086  }
2087 
2088  return QPointF( xSnapped, ySnapped );
2089 }
2090 
2092 {
2093  QGraphicsLineItem* item = new QGraphicsLineItem();
2094  QPen linePen( Qt::SolidLine );
2095  linePen.setColor( Qt::red );
2096  // use a pen width of 0, since this activates a cosmetic pen
2097  // which doesn't scale with the composer and keeps a constant size
2098  linePen.setWidthF( 0 );
2099  item->setPen( linePen );
2100  item->setZValue( 100 );
2101  item->setVisible( mGuidesVisible );
2102  addItem( item );
2103  mSnapLines.push_back( item );
2104  return item;
2105 }
2106 
2108 {
2109  removeItem( line );
2110  mSnapLines.removeAll( line );
2111  delete line;
2112 }
2113 
2115 {
2116  Q_FOREACH ( QGraphicsLineItem* line, mSnapLines )
2117  {
2118  removeItem( line );
2119  delete( line );
2120  }
2121  mSnapLines.clear();
2122 }
2123 
2124 void QgsComposition::setSnapLinesVisible( const bool visible )
2125 {
2126  mGuidesVisible = visible;
2127  Q_FOREACH ( QGraphicsLineItem* line, mSnapLines )
2128  {
2129  line->setVisible( visible );
2130  }
2131 }
2132 
2134 {
2135  mPagesVisible = visible;
2136  update();
2137 }
2138 
2139 QGraphicsLineItem* QgsComposition::nearestSnapLine( const bool horizontal, const double x, const double y, const double tolerance,
2141 {
2142  double minSqrDist = DBL_MAX;
2143  QGraphicsLineItem* item = nullptr;
2144  double currentXCoord = 0;
2145  double currentYCoord = 0;
2146  double currentSqrDist = 0;
2147  double sqrTolerance = tolerance * tolerance;
2148 
2149  snappedItems.clear();
2150 
2152  for ( ; it != mSnapLines.constEnd(); ++it )
2153  {
2154  bool itemHorizontal = qgsDoubleNear(( *it )->line().y2() - ( *it )->line().y1(), 0 );
2155  if ( horizontal && itemHorizontal )
2156  {
2157  currentYCoord = ( *it )->line().y1();
2158  currentSqrDist = ( y - currentYCoord ) * ( y - currentYCoord );
2159  }
2160  else if ( !horizontal && !itemHorizontal )
2161  {
2162  currentXCoord = ( *it )->line().x1();
2163  currentSqrDist = ( x - currentXCoord ) * ( x - currentXCoord );
2164  }
2165  else
2166  {
2167  continue;
2168  }
2169 
2170  if ( currentSqrDist < minSqrDist && currentSqrDist < sqrTolerance )
2171  {
2172  item = *it;
2173  minSqrDist = currentSqrDist;
2174  }
2175  }
2176 
2177  double itemTolerance = 0.0000001;
2178  if ( item )
2179  {
2180  //go through all the items to find items snapped to this snap line
2181  QList<QGraphicsItem *> itemList = items();
2182  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
2183  for ( ; itemIt != itemList.end(); ++itemIt )
2184  {
2185  QgsComposerItem* currentItem = dynamic_cast<QgsComposerItem*>( *itemIt );
2186  if ( !currentItem || currentItem->type() == QgsComposerItem::ComposerPaper )
2187  {
2188  continue;
2189  }
2190 
2191  if ( horizontal )
2192  {
2193  if ( qgsDoubleNear( currentYCoord, currentItem->pos().y() + currentItem->rect().top(), itemTolerance ) )
2194  {
2195  snappedItems.append( qMakePair( currentItem, QgsComposerItem::UpperMiddle ) );
2196  }
2197  else if ( qgsDoubleNear( currentYCoord, currentItem->pos().y() + currentItem->rect().center().y(), itemTolerance ) )
2198  {
2199  snappedItems.append( qMakePair( currentItem, QgsComposerItem::Middle ) );
2200  }
2201  else if ( qgsDoubleNear( currentYCoord, currentItem->pos().y() + currentItem->rect().bottom(), itemTolerance ) )
2202  {
2203  snappedItems.append( qMakePair( currentItem, QgsComposerItem::LowerMiddle ) );
2204  }
2205  }
2206  else
2207  {
2208  if ( qgsDoubleNear( currentXCoord, currentItem->pos().x(), itemTolerance ) )
2209  {
2210  snappedItems.append( qMakePair( currentItem, QgsComposerItem::MiddleLeft ) );
2211  }
2212  else if ( qgsDoubleNear( currentXCoord, currentItem->pos().x() + currentItem->rect().center().x(), itemTolerance ) )
2213  {
2214  snappedItems.append( qMakePair( currentItem, QgsComposerItem::Middle ) );
2215  }
2216  else if ( qgsDoubleNear( currentXCoord, currentItem->pos().x() + currentItem->rect().width(), itemTolerance ) )
2217  {
2218  snappedItems.append( qMakePair( currentItem, QgsComposerItem::MiddleRight ) );
2219  }
2220  }
2221  }
2222  }
2223 
2224  return item;
2225 }
2226 
2227 int QgsComposition::boundingRectOfSelectedItems( QRectF& bRect )
2228 {
2230  if ( selectedItems.size() < 1 )
2231  {
2232  return 1;
2233  }
2234 
2235  //set the box to the first item
2236  QgsComposerItem* currentItem = selectedItems.at( 0 );
2237  double minX = currentItem->pos().x();
2238  double minY = currentItem->pos().y();
2239  double maxX = minX + currentItem->rect().width();
2240  double maxY = minY + currentItem->rect().height();
2241 
2242  double currentMinX, currentMinY, currentMaxX, currentMaxY;
2243 
2244  for ( int i = 1; i < selectedItems.size(); ++i )
2245  {
2246  currentItem = selectedItems.at( i );
2247  currentMinX = currentItem->pos().x();
2248  currentMinY = currentItem->pos().y();
2249  currentMaxX = currentMinX + currentItem->rect().width();
2250  currentMaxY = currentMinY + currentItem->rect().height();
2251 
2252  if ( currentMinX < minX )
2253  minX = currentMinX;
2254  if ( currentMaxX > maxX )
2255  maxX = currentMaxX;
2256  if ( currentMinY < minY )
2257  minY = currentMinY;
2258  if ( currentMaxY > maxY )
2259  maxY = currentMaxY;
2260  }
2261 
2262  bRect.setTopLeft( QPointF( minX, minY ) );
2263  bRect.setBottomRight( QPointF( maxX, maxY ) );
2264  return 0;
2265 }
2266 
2268 {
2269  mSnapToGrid = b;
2270  updatePaperItems();
2271 }
2272 
2274 {
2275  mGridVisible = b;
2276  updatePaperItems();
2277 }
2278 
2280 {
2281  mSnapGridResolution = r;
2282  updatePaperItems();
2283 }
2284 
2285 void QgsComposition::setSnapGridOffsetX( const double offset )
2286 {
2287  mSnapGridOffsetX = offset;
2288  updatePaperItems();
2289 }
2290 
2291 void QgsComposition::setSnapGridOffsetY( const double offset )
2292 {
2293  mSnapGridOffsetY = offset;
2294  updatePaperItems();
2295 }
2296 
2298 {
2299  mGridPen = p;
2300  //make sure grid is drawn using a zero-width cosmetic pen
2301  mGridPen.setWidthF( 0 );
2302  updatePaperItems();
2303 }
2304 
2306 {
2307  mGridStyle = s;
2308  updatePaperItems();
2309 }
2310 
2311 void QgsComposition::setBoundingBoxesVisible( const bool boundsVisible )
2312 {
2313  mBoundingBoxesVisible = boundsVisible;
2314 
2315  if ( mSelectionHandles )
2316  {
2317  mSelectionHandles->update();
2318  }
2319 }
2320 
2322 {
2323  //load new composer setting values
2324  loadSettings();
2325  //update any paper items to reflect new settings
2326  updatePaperItems();
2327 }
2328 
2329 void QgsComposition::loadSettings()
2330 {
2331  //read grid style, grid color and pen width from settings
2332  QSettings s;
2333 
2334  QString gridStyleString;
2335  gridStyleString = s.value( "/Composer/gridStyle", "Dots" ).toString();
2336 
2337  int gridRed, gridGreen, gridBlue, gridAlpha;
2338  gridRed = s.value( "/Composer/gridRed", 190 ).toInt();
2339  gridGreen = s.value( "/Composer/gridGreen", 190 ).toInt();
2340  gridBlue = s.value( "/Composer/gridBlue", 190 ).toInt();
2341  gridAlpha = s.value( "/Composer/gridAlpha", 100 ).toInt();
2342  QColor gridColor = QColor( gridRed, gridGreen, gridBlue, gridAlpha );
2343 
2344  mGridPen.setColor( gridColor );
2345  mGridPen.setWidthF( 0 );
2346 
2347  if ( gridStyleString == "Dots" )
2348  {
2349  mGridStyle = Dots;
2350  }
2351  else if ( gridStyleString == "Crosses" )
2352  {
2353  mGridStyle = Crosses;
2354  }
2355  else
2356  {
2357  mGridStyle = Solid;
2358  }
2359 }
2360 
2362 {
2363  delete mActiveItemCommand;
2364  if ( !item )
2365  {
2366  mActiveItemCommand = nullptr;
2367  return;
2368  }
2369 
2371  {
2372  mActiveItemCommand = new QgsComposerItemCommand( item, commandText );
2373  }
2374  else
2375  {
2376  mActiveItemCommand = new QgsComposerMergeCommand( c, item, commandText );
2377  }
2378  mActiveItemCommand->savePreviousState();
2379 }
2380 
2382 {
2383  if ( mActiveItemCommand )
2384  {
2385  mActiveItemCommand->saveAfterState();
2386  if ( mActiveItemCommand->containsChange() ) //protect against empty commands
2387  {
2388  mUndoStack->push( mActiveItemCommand );
2389  QgsProject::instance()->dirty( true );
2390  }
2391  else
2392  {
2393  delete mActiveItemCommand;
2394  }
2395  mActiveItemCommand = nullptr;
2396  }
2397 }
2398 
2400 {
2401  delete mActiveItemCommand;
2402  mActiveItemCommand = nullptr;
2403 }
2404 
2406 {
2407  delete mActiveMultiFrameCommand;
2408 
2409  if ( !multiFrame )
2410  {
2411  mActiveMultiFrameCommand = nullptr;
2412  return;
2413  }
2414 
2416  {
2417  mActiveMultiFrameCommand = new QgsComposerMultiFrameCommand( multiFrame, text );
2418  }
2419  else
2420  {
2421  mActiveMultiFrameCommand = new QgsComposerMultiFrameMergeCommand( c, multiFrame, text );
2422  }
2423  mActiveMultiFrameCommand->savePreviousState();
2424 }
2425 
2427 {
2428  if ( mActiveMultiFrameCommand )
2429  {
2430  mActiveMultiFrameCommand->saveAfterState();
2431  if ( mActiveMultiFrameCommand->containsChange() )
2432  {
2433  mUndoStack->push( mActiveMultiFrameCommand );
2434  QgsProject::instance()->dirty( true );
2435  }
2436  else
2437  {
2438  delete mActiveMultiFrameCommand;
2439  }
2440  mActiveMultiFrameCommand = nullptr;
2441  }
2442 }
2443 
2445 {
2446  delete mActiveMultiFrameCommand;
2447  mActiveMultiFrameCommand = nullptr;
2448 }
2449 
2451 {
2452  mMultiFrames.insert( multiFrame );
2453 
2454  updateBounds();
2455 }
2456 
2458 {
2459  mMultiFrames.remove( multiFrame );
2460 
2461  updateBounds();
2462 }
2463 
2465 {
2466  addItem( arrow );
2467 
2468  updateBounds();
2469  connect( arrow, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2470 
2471  emit composerArrowAdded( arrow );
2472 }
2473 
2475 {
2476  addItem( label );
2477 
2478  updateBounds();
2479  connect( label, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2480 
2481  emit composerLabelAdded( label );
2482 }
2483 
2484 void QgsComposition::addComposerMap( QgsComposerMap* map, const bool setDefaultPreviewStyle )
2485 {
2486  addItem( map );
2487  if ( setDefaultPreviewStyle )
2488  {
2489  //set default preview mode to cache. Must be done here between adding composer map to scene and emiting signal
2491  }
2492 
2493  if ( map->previewMode() != QgsComposerMap::Rectangle )
2494  {
2495  map->cache();
2496  }
2497 
2498  updateBounds();
2499  connect( map, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2500 
2501  emit composerMapAdded( map );
2502 }
2503 
2505 {
2506  addItem( scaleBar );
2507 
2508  updateBounds();
2509  connect( scaleBar, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2510 
2511  emit composerScaleBarAdded( scaleBar );
2512 }
2513 
2515 {
2516  addItem( legend );
2517 
2518  updateBounds();
2519  connect( legend, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2520 
2521  emit composerLegendAdded( legend );
2522 }
2523 
2525 {
2526  addItem( picture );
2527 
2528  updateBounds();
2529  connect( picture, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2530 
2531  emit composerPictureAdded( picture );
2532 }
2533 
2535 {
2536  addItem( shape );
2537 
2538  updateBounds();
2539  connect( shape, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2540 
2541  emit composerShapeAdded( shape );
2542 }
2543 
2545 {
2546  addItem( table );
2547 
2548  updateBounds();
2549  connect( table, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2550 
2551  emit composerTableAdded( table );
2552 }
2553 
2555 {
2556  addItem( frame );
2557 
2558  updateBounds();
2559  connect( frame, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2560 
2561  emit composerHtmlFrameAdded( html, frame );
2562 }
2563 
2565 {
2566  addItem( frame );
2567 
2568  updateBounds();
2569  connect( frame, SIGNAL( sizeChanged() ), this, SLOT( updateBounds() ) );
2570 
2571  emit composerTableFrameAdded( table, frame );
2572 }
2573 
2574 /* public */
2575 void QgsComposition::removeComposerItem( QgsComposerItem* item, const bool createCommand, const bool removeGroupItems )
2576 {
2577  QgsComposerMap* map = dynamic_cast<QgsComposerMap *>( item );
2578 
2579  if ( !map || !map->isDrawing() ) //don't delete a composer map while it draws
2580  {
2581  mItemsModel->setItemRemoved( item );
2582  removeItem( item );
2583  emit itemRemoved( item );
2584 
2585  QgsDebugMsg( QString( "removeComposerItem called, createCommand:%1 removeGroupItems:%2" )
2586  .arg( createCommand ).arg( removeGroupItems ) );
2587 
2588  QgsComposerItemGroup* itemGroup = dynamic_cast<QgsComposerItemGroup*>( item );
2589  if ( itemGroup && removeGroupItems )
2590  {
2591  QgsDebugMsg( QString( "itemGroup && removeGroupItems" ) );
2592 
2593  // Takes ownership of itemGroup
2594  QgsAddRemoveItemCommand* parentCommand = new QgsAddRemoveItemCommand(
2595  QgsAddRemoveItemCommand::Removed, itemGroup, this,
2596  tr( "Remove item group" ) );
2597  connectAddRemoveCommandSignals( parentCommand );
2598 
2599  //add add/remove item command for every item in the group
2600  QSet<QgsComposerItem*> groupedItems = itemGroup->items();
2601  QgsDebugMsg( QString( "itemGroup contains %1 items" ) .arg( groupedItems.size() ) );
2602  QSet<QgsComposerItem*>::iterator it = groupedItems.begin();
2603  for ( ; it != groupedItems.end(); ++it )
2604  {
2605  mItemsModel->setItemRemoved( *it );
2606  removeItem( *it );
2607  QgsAddRemoveItemCommand* subcommand = new QgsAddRemoveItemCommand( QgsAddRemoveItemCommand::Removed, *it, this, "", parentCommand );
2608  connectAddRemoveCommandSignals( subcommand );
2609  emit itemRemoved( *it );
2610  }
2611 
2612  undoStack()->push( parentCommand );
2613  }
2614  else
2615  {
2616  bool frameItem = ( item->type() == QgsComposerItem::ComposerFrame );
2617  QgsComposerMultiFrame* multiFrame = nullptr;
2618  if ( createCommand )
2619  {
2620  if ( frameItem ) //multiframe tracks item changes
2621  {
2622  multiFrame = static_cast<QgsComposerFrame*>( item )->multiFrame();
2623  item->beginItemCommand( tr( "Frame deleted" ) );
2624  item->endItemCommand();
2625  }
2626  else
2627  {
2628  pushAddRemoveCommand( item, tr( "Item deleted" ), QgsAddRemoveItemCommand::Removed );
2629  }
2630  }
2631 
2632  //check if there are frames left. If not, remove the multi frame
2633  if ( frameItem && multiFrame )
2634  {
2635  if ( multiFrame->frameCount() < 1 )
2636  {
2637  removeMultiFrame( multiFrame );
2638  if ( createCommand )
2639  {
2641  multiFrame, this, tr( "Multiframe removed" ) );
2642  undoStack()->push( command );
2643  }
2644  else
2645  {
2646  delete multiFrame;
2647  }
2648  }
2649  }
2650  }
2651  }
2652 
2653  updateBounds();
2654 }
2655 
2657 {
2658  QgsAddRemoveItemCommand* c = new QgsAddRemoveItemCommand( state, item, this, text );
2659  connectAddRemoveCommandSignals( c );
2660  undoStack()->push( c );
2661  QgsProject::instance()->dirty( true );
2662 }
2663 
2664 void QgsComposition::connectAddRemoveCommandSignals( QgsAddRemoveItemCommand* c )
2665 {
2666  if ( !c )
2667  {
2668  return;
2669  }
2670 
2671  QObject::connect( c, SIGNAL( itemRemoved( QgsComposerItem* ) ), this, SIGNAL( itemRemoved( QgsComposerItem* ) ) );
2672  QObject::connect( c, SIGNAL( itemAdded( QgsComposerItem* ) ), this, SLOT( sendItemAddedSignal( QgsComposerItem* ) ) );
2673 }
2674 
2676 {
2677  //cast and send proper signal
2678  item->setSelected( true );
2679  QgsComposerArrow* arrow = dynamic_cast<QgsComposerArrow*>( item );
2680  if ( arrow )
2681  {
2682  emit composerArrowAdded( arrow );
2683  emit selectedItemChanged( arrow );
2684  return;
2685  }
2686  QgsComposerLabel* label = dynamic_cast<QgsComposerLabel*>( item );
2687  if ( label )
2688  {
2689  emit composerLabelAdded( label );
2690  emit selectedItemChanged( label );
2691  return;
2692  }
2693  QgsComposerMap* map = dynamic_cast<QgsComposerMap*>( item );
2694  if ( map )
2695  {
2696  emit composerMapAdded( map );
2697  emit selectedItemChanged( map );
2698  return;
2699  }
2700  QgsComposerScaleBar* scalebar = dynamic_cast<QgsComposerScaleBar*>( item );
2701  if ( scalebar )
2702  {
2703  emit composerScaleBarAdded( scalebar );
2704  emit selectedItemChanged( scalebar );
2705  return;
2706  }
2707  QgsComposerLegend* legend = dynamic_cast<QgsComposerLegend*>( item );
2708  if ( legend )
2709  {
2710  emit composerLegendAdded( legend );
2711  emit selectedItemChanged( legend );
2712  return;
2713  }
2714  QgsComposerPicture* picture = dynamic_cast<QgsComposerPicture*>( item );
2715  if ( picture )
2716  {
2717  emit composerPictureAdded( picture );
2718  emit selectedItemChanged( picture );
2719  return;
2720  }
2721  QgsComposerShape* shape = dynamic_cast<QgsComposerShape*>( item );
2722  if ( shape )
2723  {
2724  emit composerShapeAdded( shape );
2725  emit selectedItemChanged( shape );
2726  return;
2727  }
2728  QgsComposerAttributeTable* table = dynamic_cast<QgsComposerAttributeTable*>( item );
2729  if ( table )
2730  {
2731  emit composerTableAdded( table );
2732  emit selectedItemChanged( table );
2733  return;
2734  }
2735  QgsComposerFrame* frame = dynamic_cast<QgsComposerFrame*>( item );
2736  if ( frame )
2737  {
2738  //emit composerFrameAdded( multiframe, frame, );
2739  QgsComposerMultiFrame* mf = frame->multiFrame();
2740  QgsComposerHtml* html = dynamic_cast<QgsComposerHtml*>( mf );
2741  if ( html )
2742  {
2743  emit composerHtmlFrameAdded( html, frame );
2744  }
2745  QgsComposerAttributeTableV2* table = dynamic_cast<QgsComposerAttributeTableV2*>( mf );
2746  if ( table )
2747  {
2748  emit composerTableFrameAdded( table, frame );
2749  }
2750  emit selectedItemChanged( frame );
2751  return;
2752  }
2753  QgsComposerItemGroup* group = dynamic_cast<QgsComposerItemGroup*>( item );
2754  if ( group )
2755  {
2756  emit composerItemGroupAdded( group );
2757  }
2758 }
2759 
2760 void QgsComposition::updatePaperItems()
2761 {
2762  Q_FOREACH ( QgsPaperItem* page, mPages )
2763  {
2764  page->update();
2765  }
2766 }
2767 
2768 void QgsComposition::addPaperItem()
2769 {
2770  double paperHeight = this->paperHeight();
2771  double paperWidth = this->paperWidth();
2772  double currentY = paperHeight * mPages.size() + mPages.size() * mSpaceBetweenPages; //add 10mm visible space between pages
2773  QgsPaperItem* paperItem = new QgsPaperItem( 0, currentY, paperWidth, paperHeight, this ); //default size A4
2774  paperItem->setBrush( Qt::white );
2775  addItem( paperItem );
2776  paperItem->setZValue( 0 );
2777  mPages.push_back( paperItem );
2778 }
2779 
2780 void QgsComposition::removePaperItems()
2781 {
2782  qDeleteAll( mPages );
2783  mPages.clear();
2784 }
2785 
2786 void QgsComposition::deleteAndRemoveMultiFrames()
2787 {
2788  qDeleteAll( mMultiFrames );
2789  mMultiFrames.clear();
2790 }
2791 
2792 void QgsComposition::beginPrintAsPDF( QPrinter& printer, const QString& file )
2793 {
2794  printer.setOutputFileName( file );
2795  // setOutputFormat should come after setOutputFileName, which auto-sets format to QPrinter::PdfFormat.
2796  // [LS] This should be QPrinter::NativeFormat for Mac, otherwise fonts are not embed-able
2797  // and text is not searchable; however, there are several bugs with <= Qt 4.8.5, 5.1.1, 5.2.0:
2798  // https://bugreports.qt-project.org/browse/QTBUG-10094 - PDF font embedding fails
2799  // https://bugreports.qt-project.org/browse/QTBUG-33583 - PDF output converts text to outline
2800  // Also an issue with PDF paper size using QPrinter::NativeFormat on Mac (always outputs portrait letter-size)
2801  printer.setOutputFormat( QPrinter::PdfFormat );
2802 
2803  refreshPageSize();
2804  //must set orientation to portrait before setting paper size, otherwise size will be flipped
2805  //for landscape sized outputs (#11352)
2806  printer.setOrientation( QPrinter::Portrait );
2807  printer.setPaperSize( QSizeF( paperWidth(), paperHeight() ), QPrinter::Millimeter );
2808 
2809  // TODO: add option for this in Composer
2810  // May not work on Windows or non-X11 Linux. Works fine on Mac using QPrinter::NativeFormat
2811  //printer.setFontEmbeddingEnabled( true );
2812 
2814 }
2815 
2817 {
2818  QPrinter printer;
2819  beginPrintAsPDF( printer, file );
2820  return print( printer );
2821 }
2822 
2823 void QgsComposition::doPrint( QPrinter& printer, QPainter& p, bool startNewPage )
2824 {
2825  if ( ddPageSizeActive() )
2826  {
2827  //set the page size again so that data defined page size takes effect
2828  refreshPageSize();
2829  //must set orientation to portrait before setting paper size, otherwise size will be flipped
2830  //for landscape sized outputs (#11352)
2831  printer.setOrientation( QPrinter::Portrait );
2832  printer.setPaperSize( QSizeF( paperWidth(), paperHeight() ), QPrinter::Millimeter );
2833  }
2834 
2835  //QgsComposition starts page numbering at 0
2836  int fromPage = ( printer.fromPage() < 1 ) ? 0 : printer.fromPage() - 1;
2837  int toPage = ( printer.toPage() < 1 ) ? numPages() - 1 : printer.toPage() - 1;
2838 
2839  bool pageExported = false;
2840  if ( mPrintAsRaster )
2841  {
2842  for ( int i = fromPage; i <= toPage; ++i )
2843  {
2844  if ( !shouldExportPage( i + 1 ) )
2845  {
2846  continue;
2847  }
2848  if (( pageExported && i > fromPage ) || startNewPage )
2849  {
2850  printer.newPage();
2851  }
2852 
2853  QImage image = printPageAsRaster( i );
2854  if ( !image.isNull() )
2855  {
2856  QRectF targetArea( 0, 0, image.width(), image.height() );
2857  p.drawImage( targetArea, image, targetArea );
2858  }
2859  pageExported = true;
2860  }
2861  }
2862 
2863  if ( !mPrintAsRaster )
2864  {
2865  for ( int i = fromPage; i <= toPage; ++i )
2866  {
2867  if ( !shouldExportPage( i + 1 ) )
2868  {
2869  continue;
2870  }
2871  if (( pageExported && i > fromPage ) || startNewPage )
2872  {
2873  printer.newPage();
2874  }
2875  renderPage( &p, i );
2876  pageExported = true;
2877  }
2878  }
2879 }
2880 
2881 void QgsComposition::beginPrint( QPrinter &printer, const bool evaluateDDPageSize )
2882 {
2883  //set resolution based on composer setting
2884  printer.setFullPage( true );
2885  printer.setColorMode( QPrinter::Color );
2886 
2887  //set user-defined resolution
2888  printer.setResolution( printResolution() );
2889 
2890  if ( evaluateDDPageSize && ddPageSizeActive() )
2891  {
2892  //set data defined page size
2893  refreshPageSize();
2894  //must set orientation to portrait before setting paper size, otherwise size will be flipped
2895  //for landscape sized outputs (#11352)
2896  printer.setOrientation( QPrinter::Portrait );
2897  printer.setPaperSize( QSizeF( paperWidth(), paperHeight() ), QPrinter::Millimeter );
2898  }
2899 }
2900 
2901 bool QgsComposition::print( QPrinter &printer, const bool evaluateDDPageSize )
2902 {
2903  beginPrint( printer, evaluateDDPageSize );
2904  QPainter p;
2905  bool ready = p.begin( &printer );
2906  if ( !ready )
2907  {
2908  //error beginning print
2909  return false;
2910  }
2911  doPrint( printer, p );
2912  p.end();
2913  return true;
2914 }
2915 
2916 QImage QgsComposition::printPageAsRaster( int page, QSize imageSize, int dpi )
2917 {
2918  int resolution = mPrintResolution;
2919  if ( imageSize.isValid() )
2920  {
2921  //output size in pixels specified, calculate resolution using average of
2922  //derived x/y dpi
2923  resolution = ( imageSize.width() / mPageWidth
2924  + imageSize.height() / mPageHeight ) / 2.0 * 25.4;
2925  }
2926  else if ( dpi > 0 )
2927  {
2928  //dpi overridden by function parameters
2929  resolution = dpi;
2930  }
2931 
2932  int width = imageSize.isValid() ? imageSize.width()
2933  : static_cast< int >( resolution * mPageWidth / 25.4 );
2934  int height = imageSize.isValid() ? imageSize.height()
2935  : static_cast< int >( resolution * mPageHeight / 25.4 );
2936 
2937  QImage image( QSize( width, height ), QImage::Format_ARGB32 );
2938  if ( !image.isNull() )
2939  {
2940  image.setDotsPerMeterX( resolution / 25.4 * 1000 );
2941  image.setDotsPerMeterY( resolution / 25.4 * 1000 );
2942  image.fill( 0 );
2943  QPainter imagePainter( &image );
2944  renderPage( &imagePainter, page );
2945  if ( !imagePainter.isActive() ) return QImage();
2946  }
2947  return image;
2948 }
2949 
2950 QImage QgsComposition::renderRectAsRaster( const QRectF& rect, QSize imageSize, int dpi )
2951 {
2952  int resolution = mPrintResolution;
2953  if ( imageSize.isValid() )
2954  {
2955  //output size in pixels specified, calculate resolution using average of
2956  //derived x/y dpi
2957  resolution = ( imageSize.width() / rect.width()
2958  + imageSize.height() / rect.height() ) / 2.0 * 25.4;
2959  }
2960  else if ( dpi > 0 )
2961  {
2962  //dpi overridden by function parameters
2963  resolution = dpi;
2964  }
2965 
2966  int width = imageSize.isValid() ? imageSize.width()
2967  : static_cast< int >( resolution * rect.width() / 25.4 );
2968  int height = imageSize.isValid() ? imageSize.height()
2969  : static_cast< int >( resolution * rect.height() / 25.4 );
2970 
2971  QImage image( QSize( width, height ), QImage::Format_ARGB32 );
2972  if ( !image.isNull() )
2973  {
2974  image.setDotsPerMeterX( resolution / 25.4 * 1000 );
2975  image.setDotsPerMeterY( resolution / 25.4 * 1000 );
2976  image.fill( Qt::transparent );
2977  QPainter imagePainter( &image );
2978  renderRect( &imagePainter, rect );
2979  if ( !imagePainter.isActive() ) return QImage();
2980  }
2981  return image;
2982 }
2983 
2985 {
2986  if ( mPages.size() <= page )
2987  {
2988  return;
2989  }
2990 
2991  QgsPaperItem* paperItem = mPages.at( page );
2992  if ( !paperItem )
2993  {
2994  return;
2995  }
2996 
2997  QRectF paperRect = QRectF( paperItem->pos().x(), paperItem->pos().y(), paperItem->rect().width(), paperItem->rect().height() );
2998  renderRect( p, paperRect );
2999 }
3000 
3002 {
3003  QPaintDevice* paintDevice = p->device();
3004  if ( !paintDevice )
3005  {
3006  return;
3007  }
3008 
3009  QgsComposition::PlotStyle savedPlotStyle = mPlotStyle;
3010  mPlotStyle = QgsComposition::Print;
3011 
3012  setSnapLinesVisible( false );
3013  //hide background before rendering
3014  setBackgroundBrush( Qt::NoBrush );
3015  render( p, QRectF( 0, 0, paintDevice->width(), paintDevice->height() ), rect );
3016  //show background after rendering
3017  setBackgroundBrush( QColor( 215, 215, 215 ) );
3018  setSnapLinesVisible( true );
3019 
3020  mPlotStyle = savedPlotStyle;
3021 }
3022 
3023 QString QgsComposition::encodeStringForXML( const QString& str )
3024 {
3025  QString modifiedStr( str );
3026  modifiedStr.replace( '&', "&amp;" );
3027  modifiedStr.replace( '\"', "&quot;" );
3028  modifiedStr.replace( '\'', "&apos;" );
3029  modifiedStr.replace( '<', "&lt;" );
3030  modifiedStr.replace( '>', "&gt;" );
3031  return modifiedStr;
3032 }
3033 
3034 QGraphicsView *QgsComposition::graphicsView() const
3035 {
3036  //try to find current view attached to composition
3037  QList<QGraphicsView*> viewList = views();
3038  if ( !viewList.isEmpty() )
3039  {
3040  return viewList.at( 0 );
3041  }
3042 
3043  //no view attached to composition
3044  return nullptr;
3045 }
3046 
3047 void QgsComposition::computeWorldFileParameters( double& a, double& b, double& c, double& d, double& e, double& f ) const
3048 {
3049  if ( !mWorldFileMap )
3050  {
3051  return;
3052  }
3053 
3054  int pageNumber = mWorldFileMap->page() - 1;
3055  double pageY = pageNumber * ( mPageHeight + mSpaceBetweenPages );
3056  QRectF pageRect( 0, pageY, mPageWidth, mPageHeight );
3057  computeWorldFileParameters( pageRect, a, b, c, d, e, f );
3058 }
3059 
3060 void QgsComposition::computeWorldFileParameters( const QRectF& exportRegion, double& a, double& b, double& c, double& d, double& e, double& f ) const
3061 {
3062  // World file parameters : affine transformation parameters from pixel coordinates to map coordinates
3063 
3064  if ( !mWorldFileMap )
3065  {
3066  return;
3067  }
3068 
3069  double destinationHeight = exportRegion.height();
3070  double destinationWidth = exportRegion.width();
3071 
3072  QRectF mapItemSceneRect = mWorldFileMap->mapRectToScene( mWorldFileMap->rect() );
3073  QgsRectangle mapExtent = *mWorldFileMap->currentMapExtent();
3074 
3075  double alpha = mWorldFileMap->mapRotation() / 180 * M_PI;
3076 
3077  double xRatio = mapExtent.width() / mapItemSceneRect.width();
3078  double yRatio = mapExtent.height() / mapItemSceneRect.height();
3079 
3080  double xCenter = mapExtent.center().x();
3081  double yCenter = mapExtent.center().y();
3082 
3083  // get the extent (in map units) for the region
3084  QPointF mapItemPos = mWorldFileMap->pos();
3085  //adjust item position so it is relative to export region
3086  mapItemPos.rx() -= exportRegion.left();
3087  mapItemPos.ry() -= exportRegion.top();
3088 
3089  double xmin = mapExtent.xMinimum() - mapItemPos.x() * xRatio;
3090  double ymax = mapExtent.yMaximum() + mapItemPos.y() * yRatio;
3091  QgsRectangle paperExtent( xmin, ymax - destinationHeight * yRatio, xmin + destinationWidth * xRatio, ymax );
3092 
3093  double X0 = paperExtent.xMinimum();
3094  double Y0 = paperExtent.yMinimum();
3095 
3096  int widthPx = static_cast< int >( printResolution() * destinationWidth / 25.4 );
3097  int heightPx = static_cast< int >( printResolution() * destinationHeight / 25.4 );
3098 
3099  double Ww = paperExtent.width() / widthPx;
3100  double Hh = paperExtent.height() / heightPx;
3101 
3102  // scaling matrix
3103  double s[6];
3104  s[0] = Ww;
3105  s[1] = 0;
3106  s[2] = X0;
3107  s[3] = 0;
3108  s[4] = -Hh;
3109  s[5] = Y0 + paperExtent.height();
3110 
3111  // rotation matrix
3112  double r[6];
3113  r[0] = cos( alpha );
3114  r[1] = -sin( alpha );
3115  r[2] = xCenter * ( 1 - cos( alpha ) ) + yCenter * sin( alpha );
3116  r[3] = sin( alpha );
3117  r[4] = cos( alpha );
3118  r[5] = - xCenter * sin( alpha ) + yCenter * ( 1 - cos( alpha ) );
3119 
3120  // result = rotation x scaling = rotation(scaling(X))
3121  a = r[0] * s[0] + r[1] * s[3];
3122  b = r[0] * s[1] + r[1] * s[4];
3123  c = r[0] * s[2] + r[1] * s[5] + r[2];
3124  d = r[3] * s[0] + r[4] * s[3];
3125  e = r[3] * s[1] + r[4] * s[4];
3126  f = r[3] * s[2] + r[4] * s[5] + r[5];
3127 }
3128 
3130 {
3131  mAtlasMode = mode;
3132 
3133  if ( mode == QgsComposition::AtlasOff )
3134  {
3135  mAtlasComposition.endRender();
3136  }
3137  else
3138  {
3139  bool atlasHasFeatures = mAtlasComposition.beginRender();
3140  if ( ! atlasHasFeatures )
3141  {
3142  mAtlasMode = QgsComposition::AtlasOff;
3143  mAtlasComposition.endRender();
3144  return false;
3145  }
3146  }
3147 
3148  update();
3149  return true;
3150 }
3151 
3152 bool QgsComposition::ddPageSizeActive() const
3153 {
3154  //check if any data defined page settings are active
3155  return dataDefinedActive( QgsComposerObject::PresetPaperSize, &mDataDefinedProperties ) ||
3156  dataDefinedActive( QgsComposerObject::PaperWidth, &mDataDefinedProperties ) ||
3157  dataDefinedActive( QgsComposerObject::PaperHeight, &mDataDefinedProperties ) ||
3158  dataDefinedActive( QgsComposerObject::PaperOrientation, &mDataDefinedProperties );
3159 }
3160 
3161 void QgsComposition::refreshPageSize( const QgsExpressionContext* context )
3162 {
3163  const QgsExpressionContext* evalContext = context;
3165  if ( !evalContext )
3166  {
3167  scopedContext.reset( createExpressionContext() );
3168  evalContext = scopedContext.data();
3169  }
3170 
3171  double pageWidth = mPageWidth;
3172  double pageHeight = mPageHeight;
3173 
3174  QVariant exprVal;
3175  //in order of precedence - first consider predefined page size
3176  if ( dataDefinedEvaluate( QgsComposerObject::PresetPaperSize, exprVal, *evalContext, &mDataDefinedProperties ) )
3177  {
3178  QString presetString = exprVal.toString().trimmed();
3179  QgsDebugMsg( QString( "exprVal Paper Preset size :%1" ).arg( presetString ) );
3180  double widthD = 0;
3181  double heightD = 0;
3182  if ( QgsComposerUtils::decodePresetPaperSize( presetString, widthD, heightD ) )
3183  {
3184  pageWidth = widthD;
3185  pageHeight = heightD;
3186  }
3187  }
3188 
3189  //which is overwritten by data defined width/height
3190  if ( dataDefinedEvaluate( QgsComposerObject::PaperWidth, exprVal, *evalContext, &mDataDefinedProperties ) )
3191  {
3192  bool ok;
3193  double widthD = exprVal.toDouble( &ok );
3194  QgsDebugMsg( QString( "exprVal Paper Width:%1" ).arg( widthD ) );
3195  if ( ok )
3196  {
3197  pageWidth = widthD;
3198  }
3199  }
3200  if ( dataDefinedEvaluate( QgsComposerObject::PaperHeight, exprVal, *evalContext, &mDataDefinedProperties ) )
3201  {
3202  bool ok;
3203  double heightD = exprVal.toDouble( &ok );
3204  QgsDebugMsg( QString( "exprVal Paper Height:%1" ).arg( heightD ) );
3205  if ( ok )
3206  {
3207  pageHeight = heightD;
3208  }
3209  }
3210 
3211  //which is finally overwritten by data defined orientation
3212  if ( dataDefinedEvaluate( QgsComposerObject::PaperOrientation, exprVal, *evalContext, &mDataDefinedProperties ) )
3213  {
3214  bool ok;
3215  QString orientationString = exprVal.toString().trimmed();
3216  QgsComposition::PaperOrientation orientation = QgsComposerUtils::decodePaperOrientation( orientationString, ok );
3217  QgsDebugMsg( QString( "exprVal Paper Orientation:%1" ).arg( orientationString ) );
3218  if ( ok )
3219  {
3220  double heightD, widthD;
3221  if ( orientation == QgsComposition::Portrait )
3222  {
3223  heightD = qMax( pageHeight, pageWidth );
3224  widthD = qMin( pageHeight, pageWidth );
3225  }
3226  else
3227  {
3228  heightD = qMin( pageHeight, pageWidth );
3229  widthD = qMax( pageHeight, pageWidth );
3230  }
3231  pageWidth = widthD;
3232  pageHeight = heightD;
3233  }
3234  }
3235 
3236  setPaperSize( pageWidth, pageHeight );
3237 }
3238 
3240 {
3241  if ( property == QgsComposerObject::AllProperties || property == QgsComposerObject::NoProperty )
3242  {
3243  //invalid property
3244  return nullptr;
3245  }
3246 
3247  //find matching QgsDataDefined for property
3249  if ( it != mDataDefinedProperties.constEnd() )
3250  {
3251  return it.value();
3252  }
3253 
3254  //not found
3255  return nullptr;
3256 }
3257 
3258 void QgsComposition::setDataDefinedProperty( const QgsComposerObject::DataDefinedProperty property, bool active, bool useExpression, const QString &expression, const QString &field )
3259 {
3260  if ( property == QgsComposerObject::AllProperties || property == QgsComposerObject::NoProperty )
3261  {
3262  //invalid property
3263  return;
3264  }
3265 
3266  bool defaultVals = ( !active && !useExpression && expression.isEmpty() && field.isEmpty() );
3267 
3268  if ( mDataDefinedProperties.contains( property ) )
3269  {
3271  if ( it != mDataDefinedProperties.constEnd() )
3272  {
3273  QgsDataDefined* dd = it.value();
3274  dd->setActive( active );
3275  dd->setExpressionString( expression );
3276  dd->setField( field );
3277  dd->setUseExpression( useExpression );
3278  }
3279  }
3280  else if ( !defaultVals )
3281  {
3282  QgsDataDefined* dd = new QgsDataDefined( active, useExpression, expression, field );
3283  mDataDefinedProperties.insert( property, dd );
3284  }
3285 }
3286 
3287 void QgsComposition::setCustomProperty( const QString& key, const QVariant& value )
3288 {
3289  mCustomProperties.setValue( key, value );
3290 }
3291 
3292 QVariant QgsComposition::customProperty( const QString& key, const QVariant& defaultValue ) const
3293 {
3294  return mCustomProperties.value( key, defaultValue );
3295 }
3296 
3298 {
3299  mCustomProperties.remove( key );
3300 }
3301 
3303 {
3304  return mCustomProperties.keys();
3305 }
3306 
3307 bool QgsComposition::dataDefinedEvaluate( QgsComposerObject::DataDefinedProperty property, QVariant &expressionValue,
3308  const QgsExpressionContext& context,
3310 {
3312  {
3313  //invalid property
3314  return false;
3315  }
3316 
3317  //null passed-around QVariant
3318  expressionValue.clear();
3319 
3320  //get fields and feature from atlas
3321  QgsFeature currentFeature;
3322  QgsFields layerFields;
3323  bool useFeature = false;
3324  if ( mAtlasComposition.enabled() )
3325  {
3326  QgsVectorLayer* atlasLayer = mAtlasComposition.coverageLayer();
3327  if ( atlasLayer )
3328  {
3329  layerFields = atlasLayer->fields();
3330  }
3331  if ( mAtlasMode != QgsComposition::AtlasOff )
3332  {
3333  useFeature = true;
3334  currentFeature = mAtlasComposition.feature();
3335  }
3336  }
3337 
3338  //evaluate data defined property using current atlas context
3339  QVariant result = dataDefinedValue( property, useFeature ? &currentFeature : nullptr, layerFields, context, dataDefinedProperties );
3340 
3341  if ( result.isValid() )
3342  {
3343  expressionValue = result;
3344  return true;
3345  }
3346 
3347  return false;
3348 }
3349 
3350 bool QgsComposition::dataDefinedActive( const QgsComposerObject::DataDefinedProperty property, const QMap<QgsComposerObject::DataDefinedProperty, QgsDataDefined *> *dataDefinedProperties ) const
3351 {
3353  {
3354  //invalid property
3355  return false;
3356  }
3357  if ( !dataDefinedProperties->contains( property ) )
3358  {
3359  //missing property
3360  return false;
3361  }
3362 
3363  QgsDataDefined* dd = nullptr;
3365  if ( it != dataDefinedProperties->constEnd() )
3366  {
3367  dd = it.value();
3368  }
3369 
3370  if ( !dd )
3371  {
3372  return false;
3373  }
3374 
3375  //found the data defined property, return whether it is active
3376  return dd->isActive();
3377 }
3378 
3379 QVariant QgsComposition::dataDefinedValue( QgsComposerObject::DataDefinedProperty property, const QgsFeature *feature, const QgsFields& fields, const QgsExpressionContext& context, QMap<QgsComposerObject::DataDefinedProperty, QgsDataDefined *> *dataDefinedProperties ) const
3380 {
3382  {
3383  //invalid property
3384  return QVariant();
3385  }
3386  if ( !dataDefinedProperties->contains( property ) )
3387  {
3388  //missing property
3389  return QVariant();
3390  }
3391 
3392  QgsDataDefined* dd = nullptr;
3394  if ( it != dataDefinedProperties->constEnd() )
3395  {
3396  dd = it.value();
3397  }
3398 
3399  if ( !dd )
3400  {
3401  return QVariant();
3402  }
3403 
3404  if ( !dd->isActive() )
3405  {
3406  return QVariant();
3407  }
3408 
3409  QVariant result = QVariant();
3410  bool useExpression = dd->useExpression();
3411  QString field = dd->field();
3412 
3413  if ( !dd->expressionIsPrepared() )
3414  {
3415  prepareDataDefinedExpression( dd, dataDefinedProperties, context );
3416  }
3417 
3418  if ( useExpression && dd->expressionIsPrepared() )
3419  {
3420  QgsExpression* expr = dd->expression();
3421 
3422  result = expr->evaluate( &context );
3423  if ( expr->hasEvalError() )
3424  {
3425  QgsDebugMsgLevel( QString( "Evaluate error:" ) + expr->evalErrorString(), 4 );
3426  return QVariant();
3427  }
3428  }
3429  else if ( !useExpression && !field.isEmpty() )
3430  {
3431  if ( !feature )
3432  {
3433  return QVariant();
3434  }
3435  // use direct attribute access instead of evaluating "field" expression (much faster)
3436  int indx = fields.indexFromName( field );
3437  if ( indx != -1 )
3438  {
3439  result = feature->attribute( indx );
3440  }
3441  }
3442  return result;
3443 }
3444 
3445 void QgsComposition::prepareDataDefinedExpression( QgsDataDefined *dd, QMap<QgsComposerObject::DataDefinedProperty, QgsDataDefined *> *dataDefinedProperties,
3446  const QgsExpressionContext& context ) const
3447 {
3448  //if specific QgsDataDefined passed, prepare it
3449  //otherwise prepare all QgsDataDefineds
3450  if ( dd )
3451  {
3452  dd->prepareExpression( context );
3453  }
3454  else
3455  {
3457  for ( ; it != dataDefinedProperties->constEnd(); ++it )
3458  {
3459  it.value()->prepareExpression( context );
3460  }
3461  }
3462 }
3463 
3465 {
3466  QgsExpressionContext* context = new QgsExpressionContext();
3470  if ( mAtlasComposition.enabled() )
3471  {
3472  context->appendScope( QgsExpressionContextUtils::atlasScope( &mAtlasComposition ) );
3473  }
3474  return context;
3475 }
3476 
3477 void QgsComposition::prepareAllDataDefinedExpressions()
3478 {
3480  prepareDataDefinedExpression( nullptr, &mDataDefinedProperties, *context.data() );
3481 }
3482 
3483 void QgsComposition::relativeResizeRect( QRectF& rectToResize, const QRectF& boundsBefore, const QRectF& boundsAfter )
3484 {
3485  QgsComposerUtils::relativeResizeRect( rectToResize, boundsBefore, boundsAfter );
3486 }
3487 
3488 double QgsComposition::relativePosition( double position, double beforeMin, double beforeMax, double afterMin, double afterMax )
3489 {
3490  return QgsComposerUtils::relativePosition( position, beforeMin, beforeMax, afterMin, afterMax );
3491 }
bool positionLock() const
Returns whether position lock for mouse drags is enabled returns true if item is locked for mouse mov...
Class for parsing and evaluation of expressions (formerly called "search strings").
void beginPrint(QPrinter &printer, const bool evaluateDDPageSize=false)
Prepare the printer for printing.
static void relativeResizeRect(QRectF &rectToResize, const QRectF &boundsBefore, const QRectF &boundsAfter)
Resizes a QRectF relative to a resized bounding rectangle.
Item representing the paper.
Definition: qgspaperitem.h:40
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
void clear()
void composerItemGroupAdded(QgsComposerItemGroup *group)
Is emitted when a new item group has been added to the view.
A scale bar item that can be added to a map composition.
QUndoStack * undoStack()
Returns pointer to undo/redo command storage.
QDomNodeList elementsByTagName(const QString &tagname) const
void unlockAllItems()
Unlock all items.
void setActive(bool active)
bool readXML(const QDomElement &itemElem, const QDomDocument &doc) override
Sets state from Dom document.
A rectangle specified with double values.
Definition: qgsrectangle.h:35
double paperWidth() const
Width of paper item.
bool isValid() const
void setDotsPerMeterX(int x)
void setDotsPerMeterY(int y)
bool writeXML(QDomElement &composerElem, QDomDocument &doc)
Writes settings to xml (paper dimension)
virtual bool writeXML(QDomElement &elem, QDomDocument &doc) const
Stores item state in DOM element.
void setAllUnselected()
Clears any selected items in the composition.
int pageNumberAt(QPointF position) const
Returns the page number (0-based) given a coordinate.
QgsComposerItem * getComposerItemAbove(QgsComposerItem *item) const
Finds the next composer item above an item.
bool readXML(const QDomElement &itemElem, const QDomDocument &doc) override
Sets state from Dom document.
int width() const
A container class for data source field mapping or expression.
bool end()
bool contains(const Key &key) const
Q_DECL_DEPRECATED QVariant evaluate(const QgsFeature *f)
Evaluate the feature and return the result.
An item that draws an arrow between to points.
QLineF line() const
QgsComposerMapOverviewStack * overviews()
Returns the map item&#39;s overview stack, which is used to control how overviews are drawn over the map&#39;...
void render(QPainter *painter, const QRectF &target, const QRectF &source, Qt::AspectRatioMode aspectRatioMode)
void setResolution(int dpi)
QDomNode appendChild(const QDomNode &newChild)
void addItemToZList(QgsComposerItem *item)
Adds item to z list.
void addItemsFromXML(const QDomElement &elem, const QDomDocument &doc, QMap< QgsComposerMap *, int > *mapsToRestore=nullptr, bool addUndoCommands=false, QPointF *pos=nullptr, bool pasteInPlace=false)
Add items from XML representation to the graphics scene (for project file reading, pasting items from clipboard)
void readXml(const QDomNode &parentNode, const QString &keyStartsWith=QString())
Read store contents from XML.
void composerArrowAdded(QgsComposerArrow *arrow)
Is emitted when new composer arrow has been added to the view.
void setBoundingBoxesVisible(const bool boundsVisible)
Sets whether selection bounding boxes should be shown in the composition.
void push_back(const T &value)
QList< QGraphicsItem * > selectedItems() const
void setPageStyleSymbol(QgsFillSymbolV2 *symbol)
Note: added in version 2.1.
static QgsExpressionContextScope * atlasScope(const QgsAtlasComposition *atlas)
Creates a new scope which contains variables and functions relating to a QgsAtlasComposition.
void assignFreeId()
Sets mId to a number not yet used in the composition.
void statusMsgChanged(const QString &message)
Is emitted when the composition has an updated status bar message for the composer window...
void setOutputFileName(const QString &fileName)
QString field() const
Get the field which this QgsDataDefined represents.
QString attribute(const QString &name, const QString &defValue) const
virtual void beginItemCommand(const QString &text)
QPointF snapPointToGrid(QPointF scenePoint) const
Snaps a scene coordinate point to grid.
void computeWorldFileParameters(double &a, double &b, double &c, double &d, double &e, double &f) const
Compute world file parameters.
void setResizeToContentsMargins(double marginTop, double marginRight, double marginBottom, double marginLeft)
Sets the resize to contents margins.
double yMaximum() const
Get the y maximum value (top side of rectangle)
Definition: qgsrectangle.h:197
GridStyle
Style to draw the snapping grid.
#define QgsDebugMsg(str)
Definition: qgslogger.h:33
QgsFields fields() const
Returns the list of fields of this layer.
QList< QGraphicsItem * > items() const
void alignSelectedItemsTop()
void clear()
int size() const
void rebuildZList()
Rebuilds the z-order list, based on the current stacking of items in the composition.
QString toString(int indent) const
void composerPictureAdded(QgsComposerPicture *picture)
Is emitted when a new composer picture has been added.
const QgsMapSettings & mapSettings() const
Return setting of QGIS map canvas.
static double relativePosition(const double position, const double beforeMin, const double beforeMax, const double afterMin, const double afterMax)
Returns a scaled position given a before and after range.
QgsDataDefined * dataDefinedProperty(const QgsComposerObject::DataDefinedProperty property)
Returns a reference to the data defined settings for one of the composition&#39;s data defined properties...
void removeItems() override
Removes the items but does not delete them.
bool isElement() const
static QgsFillSymbolV2 * createSimple(const QgsStringMap &properties)
Create a fill symbol with one symbol layer: SimpleFill with specified properties. ...
void cache()
Create cache image.
int zOrderListSize() const
Returns the size of the z-order list, which includes items which may have been removed from the compo...
const_iterator constBegin() const
const T & at(int i) const
QgsComposerItemGroup * groupItems(QList< QgsComposerItem * > items)
Creates a new group from a list of composer items and adds it to the composition. ...
static void readDataDefinedPropertyMap(const QDomElement &itemElem, QMap< QgsComposerObject::DataDefinedProperty, QString > *dataDefinedNames, QMap< QgsComposerObject::DataDefinedProperty, QgsDataDefined * > *dataDefinedProperties)
Reads all data defined properties from xml.
QList< const QgsComposerMap * > composerMapItems() const
Returns pointers to all composer maps in the scene.
void addComposerScaleBar(QgsComposerScaleBar *scaleBar)
Adds scale bar to the graphics scene and advices composer to create a widget for it (through signal) ...
A item that forms part of a map composition.
void setBackgroundBrush(const QBrush &brush)
void setSelectedItem(QgsComposerItem *item)
Clears any selected items and sets an item as the current selection.
void setPagesVisible(bool visible)
Sets whether the page items should be visible in the composition.
void pushAddRemoveCommand(QgsComposerItem *item, const QString &text, const QgsAddRemoveItemCommand::State state=QgsAddRemoveItemCommand::Added)
Convenience function to create a QgsAddRemoveItemCommand, connect its signals and push it to the undo...
void removeItemFromZList(QgsComposerItem *item)
Removes item from z list.
static QDomElement saveSymbol(const QString &symbolName, QgsSymbolV2 *symbol, QDomDocument &doc)
bool enabled() const
Returns whether the atlas generation is enabled.
void setSceneRect(const QRectF &rect)
QgsExpression * expression()
void updateBounds()
Updates the scene bounds of the composition.
Container of fields for a vector layer.
Definition: qgsfield.h:187
A container for grouping several QgsComposerItems.
void resizeToContentsMargins(double &marginTop, double &marginRight, double &marginBottom, double &marginLeft) const
Returns the resize to contents margins.
void paperSizeChanged()
void sendItemAddedSignal(QgsComposerItem *item)
Casts object to the proper subclass type and calls corresponding itemAdded signal.
qreal top() const
QgsFeature feature() const
Returns the current atlas feature.
virtual void setSelected(bool s)
Set selected, selected item should be highlighted.
void savePreviousState()
Saves current item state as previous state.
const QgsComposerItem * getComposerItemByUuid(const QString &theUuid) const
Returns a composer item given its unique identifier.
const_iterator constFind(const Key &key) const
A composer command that merges together with other commands having the same context (=id)...
QDomElement documentElement() const
bool moveItemToBottom(QgsComposerItem *item)
void setCreateUndoCommands(bool enabled)
Sets whether undo commands should be created for interactions with the multiframe.
bool isNull() const
QVariant customProperty(const QString &key, const QVariant &defaultValue=QVariant()) const
Read a custom property from the composition.
const_iterator insert(const T &value)
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:187
void beginPrintAsPDF(QPrinter &printer, const QString &file)
Prepare the printer for printing in a PDF.
A non GUI class for rendering a map layer set onto a QPainter.
qreal height() const
QRectF mapRectToScene(const QRectF &rect) const
void composerScaleBarAdded(QgsComposerScaleBar *scalebar)
Is emitted when new composer scale bar has been added.
void setDirty(bool b)
Set project as dirty (modified).
Definition: qgsproject.cpp:415
void moveSelectedItemsToBottom()
void clear()
static void writeDataDefinedPropertyMap(QDomElement &itemElem, QDomDocument &doc, const QMap< QgsComposerObject::DataDefinedProperty, QString > *dataDefinedNames, const QMap< QgsComposerObject::DataDefinedProperty, QgsDataDefined * > *dataDefinedProperties)
Writes data defined properties to xml.
bool reorderItemDown(QgsComposerItem *item)
Moves an item down the z-order list.
void alignSelectedItemsHCenter()
double toDouble(bool *ok) const
double spaceBetweenPages() const
Returns the vertical space between pages in a composer view.
void doPrint(QPrinter &printer, QPainter &painter, bool startNewPage=false)
Print on a preconfigured printer.
void setPaperSize(double width, double height, bool keepRelativeItemPosition=true)
Changes size of paper item.
void setStatusMessage(const QString &message)
Sets the status bar message for the composer window.
QString tr(const char *sourceText, const char *disambiguation, int n)
void remove(const QString &key)
Remove a key (entry) from the store.
void composerMapAdded(QgsComposerMap *map)
Is emitted when new composer map has been added to the view.
int numPages() const
Returns the number of pages in the composition.
qreal left() const
void adjust(qreal dx1, qreal dy1, qreal dx2, qreal dy2)
bool qgsDoubleNear(double a, double b, double epsilon=4 *DBL_EPSILON)
Definition: qgis.h:285
virtual bool readXML(const QDomElement &itemElem, const QDomDocument &doc, bool ignoreFrames=false) override
Reads the properties specific to an attribute table from xml.
void update(const QRectF &rect)
static Q_DECL_DEPRECATED double relativePosition(double position, double beforeMin, double beforeMax, double afterMin, double afterMax)
Returns a scaled position given a before and after range.
void setGridVisible(const bool b)
void alignSelectedItemsVCenter()
bool shouldExportPage(const int page) const
Returns whether a specified page number should be included in exports of the composition.
double x() const
Get the x value of the point.
Definition: qgspoint.h:128
qreal dx() const
A table that displays attributes from a vector layer.
DataDefinedProperty
Data defined properties for different item types.
void composerItemsOnPage(QList< T * > &itemList, const int pageNumber) const
Return composer items of a specific type on a specified page.
void endRender()
Ends the rendering.
int size() const
QRectF pageItemBounds(int pageNumber, bool visibleOnly=false) const
Returns the bounding box of the items contained on a specified page.
A composer class that displays svg files or raster format (jpg, png, ...)
void readXML(const QDomElement &elem, const QDomDocument &doc)
Reads general atlas settings from xml.
QSet< QgsComposerItem * > items()
void reset(T *other)
bool isDrawing() const
True if a draw is already in progress.
void composerLegendAdded(QgsComposerLegend *legend)
Is emitted when a new composer legend has been added.
void setCustomProperty(const QString &key, const QVariant &value)
Set a custom property for the composition.
void setItemPosition(double x, double y, ItemPositionMode itemPoint=UpperLeft, int page=-1)
Moves the item to a new position (in canvas coordinates)
The QgsMapSettings class contains configuration for rendering of the map.
QList< QgsComposerItem * > * zOrderList()
Returns the item z-order list.
int width() const
double ANALYSIS_EXPORT max(double x, double y)
Returns the maximum of two doubles or the first argument if both are equal.
QDomElement toElement() const
void addComposerShape(QgsComposerShape *shape)
Adds a composer shape to the graphics scene and advices composer to create a widget for it (through s...
void setGridPen(const QPen &p)
QVariant value(const QString &key, const QVariant &defaultValue=QVariant()) const
Return value for the given key. If the key is not stored, default value will be used.
bool readXML(const QDomElement &itemElem, const QDomDocument &doc) override
Reads the properties specific to an attribute table from xml.
qreal bottom() const
void setUseExpression(bool use)
Controls if the field or the expression part is active.
QgsComposerItem * getComposerItemBelow(QgsComposerItem *item) const
QTransform transform() const
QString uuid() const
Get item identification name.
qreal zValue() const
qreal y1() const
qreal y2() const
QPointF pos() const
void setNumPages(const int pages)
Sets the number of pages for the composition.
int count() const
qreal x1() const
qreal x2() const
QString number(int n, int base)
void refreshItemsTriggered()
Is emitted when item in the composition must be refreshed.
qreal x() const
qreal y() const
QPointF p1() const
bool beginRender()
Begins the rendering.
void setValue(const QString &key, const QVariant &value)
Add an entry to the store. If the entry with the keys exists already, it will be overwritten.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context...
void setSnapLinesVisible(const bool visible)
Hides / shows custom snap lines.
int itemPageNumber(const QgsComposerItem *) const
Returns on which page number (0-based) is displayed an item.
QVariant property(const char *name) const
int toInt(bool *ok) const
double yMinimum() const
Get the y minimum value (bottom side of rectangle)
Definition: qgsrectangle.h:202
void removeItem(QGraphicsItem *item)
void cancelCommand()
Deletes current command.
void fill(uint pixelValue)
void setSnapGridOffsetX(const double offset)
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:34
bool containsChange() const
Returns true if previous state and after state are valid and different.
void setUseSymbolV2(bool useSymbolV2)
Controls whether the shape should be drawn using a QgsFillSymbolV2.
void endCommand()
Saves end state of item and pushes command to the undo history.
void itemRemoved(QgsComposerItem *)
Is emitted when a composer item has been removed from the scene.
int printResolution() const
void updatePagePos(double newPageWidth, double newPageHeight)
Moves the item so that it retains its relative position on the page when the paper size changes...
int width() const
void setAttribute(const QString &name, const QString &value)
void setField(const QString &field)
Set the field name which this QgsDataDefined represents.
void clear()
Clears all items from z-order list and resets the model.
QList< QGraphicsView * > views() const
void removeSnapLine(QGraphicsLineItem *line)
Remove custom snap line (and delete the object)
qreal m11() const
void addItem(QgsComposerItem *item) override
Adds an item to the group.
int toInt(bool *ok, int base) const
bool isEmpty() const
void alignSelectedItemsRight()
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QDomNodeList elementsByTagName(const QString &tagname) const
QStringList keys() const
Return list of stored keys.
Abstract base class for composer items with the ability to distribute the content to several frames (...
bool isEmpty() const
void resizePageToContents(double marginTop=0.0, double marginRight=0.0, double marginBottom=0.0, double marginLeft=0.0)
Resizes the composition page to fit the current contents of the composition.
int removeAll(const T &value)
QString trimmed() const
const_iterator constEnd() const
void refreshDataDefinedProperty(const QgsComposerObject::DataDefinedProperty property=QgsComposerObject::AllProperties, const QgsExpressionContext *context=nullptr)
Refreshes a data defined property for the composition by reevaluating the property&#39;s value and redraw...
void setLine(const QLineF &line)
void addComposerTableFrame(QgsComposerAttributeTableV2 *table, QgsComposerFrame *frame)
Adds composer tablev2 frame and advises composer to create a widget for it (through signal) ...
#define M_PI
QPaintDevice * device() const
QList< QgsComposerItem * > ungroupItems(QgsComposerItemGroup *group)
Ungroups items by removing them from an item group and removing the group from the composition...
void cancelMultiFrameCommand()
Deletes current multi frame command.
void setWidthF(qreal width)
void removeComposerItem(QgsComposerItem *item, const bool createCommand=true, const bool removeGroupItems=true)
Remove item from the graphics scene.
QPointF center() const
QRectF compositionBounds(bool ignorePages=false, double margin=0.0) const
Calculates the bounds of all non-gui items in the composition.
const_iterator constEnd() const
void removeCustomProperty(const QString &key)
Remove a custom property from the composition.
bool loadFromTemplate(const QDomDocument &doc, QMap< QString, QString > *substitutionMap=nullptr, bool addUndoCommands=false, const bool clearComposition=true)
Load a template document.
bool readXML(const QDomElement &itemElem, const QDomDocument &doc) override
Sets state from Dom document.
QRectF united(const QRectF &rectangle) const
void setPaperSize(PaperSize newPaperSize)
void moveSelectedItemsToTop()
bool readXML(const QDomElement &itemElem, const QDomDocument &doc) override
Sets state from Dom document.
int frameCount() const
Returns the number of frames associated with this multiframe.
void setColor(const QColor &color)
QImage printPageAsRaster(int page, QSize imageSize=QSize(), int dpi=0)
Renders a composer page to an image.
QStringList customProperties() const
Return list of keys stored in custom properties for composition.
A composer command that merges together with other commands having the same context (=id) for multi f...
double mapRotation(QgsComposerObject::PropertyValueType valueType=QgsComposerObject::EvaluatedValue) const
Returns the rotation used for drawing the map within the composer item.
void setSnapGridResolution(const double r)
bool pageIsEmpty(const int page) const
Returns whether a page is empty, ie, it contains no items except for the background paper item...
virtual QPaintEngine * paintEngine() const
void setPen(const QPen &pen)
const QgsComposerItem * getComposerItemById(const QString &theId) const
Returns a composer item given its text identifier.
void removeMultiFrame(QgsComposerMultiFrame *multiFrame)
Removes multi frame (but does not delete it)
Object representing map window.
Frame item for a composer multiframe item.
bool readXML(const QDomElement &compositionElem, const QDomDocument &doc)
Reads settings from xml file.
A composer command class for grouping / ungrouping composer items.
bool useExpression() const
Returns if the field or the expression part is active.
int indexFromName(const QString &name) const
Look up field&#39;s index from name. Returns -1 on error.
Definition: qgsfield.cpp:424
bool isActive() const
T * data() const
iterator end()
bool readXML(const QDomElement &itemElem, const QDomDocument &doc) override
Sets state from Dom document.
QgsExpressionContext * createExpressionContext() const
Creates an expression context relating to the compositions&#39;s current state.
void refreshItems()
Forces items in the composition to refresh.
qreal right() const
void setUpdatesEnabled(bool enabled)
Sets whether updates to the composer map are enabled.
iterator begin()
void clear()
QgsComposerItem * getComposerItemAbove(QgsComposerItem *item) const
Q_DECL_DEPRECATED int pixelFontSize(double pointSize) const
Returns the mm font size for a font that has point size set.
void setFullPage(bool fp)
PreviewMode previewMode() const
virtual QgsFillSymbolV2 * clone() const override
void setLine(qreal x1, qreal y1, qreal x2, qreal y2)
void nPagesChanged()
void removeItem(QgsComposerItem *item)
Removes an item from the z-order list.
bool readXML(const QDomElement &itemElem, const QDomDocument &doc) override
Sets state from Dom document.
void setTopLeft(const QPointF &position)
void updateSettings()
Refreshes the composition when composer related options change.
void saveAfterState()
Saves current item state as after state.
const_iterator constBegin() const
static bool decodePresetPaperSize(const QString &presetString, double &width, double &height)
Decodes a string representing a preset page size.
bool setAtlasMode(const QgsComposition::AtlasMode mode)
Sets the current atlas mode of the composition.
bool isNull() const
int pageNumberForPoint(QPointF position) const
Returns the page number corresponding to a point in the composition.
bool newPage()
void setPositionLock(const bool lock)
Locks / unlocks the item position for mouse drags.
void setOrientation(Orientation orientation)
void setPrintResolution(const int dpi)
bool print(QPrinter &printer, const bool evaluateDDPageSize=false)
Convenience function that prepares the printer and prints.
void composerTableAdded(QgsComposerAttributeTable *table)
Is emitted when a new composer table has been added.
const Key key(const T &value) const
QList< QgsPaperItem * > pages()
Return pages in the correct order.
void refreshZList()
Rebuilds the z order list by adding any item which are present in the composition but missing from th...
int id() const
Get identification number.
bool isValid() const
void composerShapeAdded(QgsComposerShape *shape)
Is emitted when a new composer shape has been added.
bool exportAsPDF(const QString &file)
Convenience function that prepares the printer for printing in PDF and prints.
void lockSelectedItems()
Lock the selected items.
QString & replace(int position, int n, QChar after)
void setGridStyle(const GridStyle s)
A composer command class for adding / removing composer items.
void selectNextByZOrder(const ZValueDirection direction)
QVariant value(const QString &key, const QVariant &defaultValue) const
bool isVisible() const
void clearSnapLines()
Removes all snap lines.
A table class that displays a vector attribute table.
bool reorderItemUp(QgsComposerItem *item)
Moves an item up the z-order list.
void drawImage(const QRectF &target, const QImage &image, const QRectF &source, QFlags< Qt::ImageConversionFlag > flags)
qreal width() const
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
Definition: qgsfeature.cpp:271
QgsComposerItem * getComposerItemBelow(QgsComposerItem *item) const
Finds the next composer item below an item.
bool remove(const T &value)
Undo command to undo/redo all composer item related changes.
bool readXML(const QDomElement &itemElem, const QDomDocument &doc) override
Sets state from Dom document.
void setDataDefinedProperty(const QgsComposerObject::DataDefinedProperty property, bool active, bool useExpression, const QString &expression, const QString &field)
Sets parameters for a data defined property for the composition.
A composer items that draws common shapes (ellipse, triangle, rectangle)
void writeXml(QDomNode &parentNode, QDomDocument &doc) const
Write store contents to XML.
virtual void endItemCommand()
void readXMLMapSettings(const QDomElement &elem, const QDomDocument &doc)
Reads old (pre 2.2) map related atlas settings from xml.
QPointF positionOnPage(QPointF position) const
Returns the position within a page of a point in the composition.
Q_DECL_DEPRECATED bool prepareExpression(QgsVectorLayer *layer)
Prepares the expression using a vector layer.
bool expressionIsPrepared() const
Returns whether the data defined object&#39;s expression is prepared.
void addComposerHtmlFrame(QgsComposerHtml *html, QgsComposerFrame *frame)
Adds composer html frame and advises composer to create a widget for it (through signal) ...
iterator end()
QgsComposerItem * composerItemAt(QPointF position, const bool ignoreLocked=false) const
Returns the topmost composer item at a specified position.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
QList< QgsComposerMapOverview * > asList() const
Returns a list of QgsComposerMapOverviews contained by the stack.
AtlasMode
Composition atlas modes.
static QgsProject * instance()
access to canonical QgsProject instance
Definition: qgsproject.cpp:381
QDomElement firstChildElement(const QString &tagName) const
void addComposerMap(QgsComposerMap *map, const bool setDefaultPreviewStyle=true)
Adds map to the graphics scene and advices composer to create a widget for it (through signal) ...
T & last()
void alignSelectedItemsBottom()
static void fixEngineFlags(QPaintEngine *engine)
void update(qreal x, qreal y, qreal w, qreal h)
void renderRect(QPainter *p, const QRectF &rect)
Renders a portion of the composition to a paint device.
void alignSelectedItemsLeft()
int height() const
QGraphicsLineItem * nearestSnapLine(const bool horizontal, const double x, const double y, const double tolerance, QList< QPair< QgsComposerItem *, QgsComposerItem::ItemPositionMode > > &snappedItems) const
Get nearest snap line.
qreal & rx()
qreal & ry()
void removeLast()
double paperHeight() const
Height of paper item.
static double pointsToMM(const double pointSize)
Returns the size in mm corresponding to a font point size.
int page() const
Gets the page the item is currently on.
void selectedItemChanged(QgsComposerItem *selected)
Is emitted when selected item changed.
void renderPage(QPainter *p, int page)
Renders a full page to a paint device.
void setVisible(bool visible)
double y() const
Get the y value of the point.
Definition: qgspoint.h:136
QImage renderRectAsRaster(const QRectF &rect, QSize imageSize=QSize(), int dpi=0)
Renders a portion of the composition to an image.
A label that can be placed onto a map composition.
void setUseAdvancedEffects(const bool effectsEnabled)
Used to enable or disable advanced effects such as blend modes in a composition.
bool isValid() const
void setEffectsEnabled(const bool effectsEnabled)
Sets whether effects (eg blend modes) are enabled for the item.
void composerLabelAdded(QgsComposerLabel *label)
Is emitted when new composer label has been added to the view.
qreal height() const
int height() const
void addComposerPicture(QgsComposerPicture *picture)
Adds picture to the graphics scene and advices composer to create a widget for it (through signal) ...
QgsAtlasComposition & atlasComposition()
double toDouble(bool *ok) const
void composerHtmlFrameAdded(QgsComposerHtml *html, QgsComposerFrame *frame)
Is emitted when a new composer html has been added to the view.
iterator insert(const Key &key, const T &value)
static Q_DECL_DEPRECATED void relativeResizeRect(QRectF &rectToResize, const QRectF &boundsBefore, const QRectF &boundsAfter)
Resizes a QRectF relative to the change from boundsBefore to boundsAfter.
void addComposerTable(QgsComposerAttributeTable *table)
Adds a composer table to the graphics scene and advices composer to create a widget for it (through s...
void removeAttribute(const QString &name)
Handles drawing of selection outlines and mouse handles.
void composerTableFrameAdded(QgsComposerAttributeTableV2 *table, QgsComposerFrame *frame)
Is emitted when a new composer table frame has been added to the view.
Q_DECL_DEPRECATED const QgsComposerHtml * getComposerHtmlByItem(QgsComposerItem *item) const
Returns the composer html with specified id (a string as named in the composer user interface item pr...
QgsVectorLayer * coverageLayer() const
Returns the coverage layer used for the atlas features.
void setItemRemoved(QgsComposerItem *item)
Marks an item as removed from the composition.
bool readXML(const QDomElement &itemElem, const QDomDocument &doc) override
Sets state from DOM document.
static QgsExpressionContextScope * projectScope()
Creates a new scope which contains variables and functions relating to the current QGIS project...
void setBrush(const QBrush &brush)
friend class QgsComposerModel
int size() const
int height() const
bool readXML(const QDomElement &itemElem, const QDomDocument &doc, bool ignoreFrames=false) override
Reads multiframe state information from a DOM element.
const_iterator constEnd() const
Q_DECL_DEPRECATED double pointFontSize(int pixelSize) const
Does the inverse calculation and returns points for mm.
int fromPage() const
QGraphicsLineItem * addSnapLine()
Add a custom snap line (can be horizontal or vertical)
QDomElement createElement(const QString &tagName)
void clear()
void composerItems(QList< T * > &itemList)
Return composer items of a specific type.
const_iterator constBegin() const
void printResolutionChanged()
Is emitted when the compositions print resolution changes.
void setColorMode(ColorMode newColorMode)
PlotStyle
Plot type.
void addItem(QGraphicsItem *item)
const QgsComposerMap * getComposerMapById(const int id) const
Returns the composer map with specified id.
void setPreviewMode(PreviewMode m)
double width() const
Width of the rectangle.
Definition: qgsrectangle.h:207
bool raiseItem(QgsComposerItem *item)
bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
QgsComposerMultiFrame * multiFrame() const
Returns the parent multiframe for the frame.
void setSnapToGridEnabled(const bool b)
bool reorderItemToTop(QgsComposerItem *item)
Moves an item to the top of the z-order list.
void setOutputFormat(OutputFormat format)
Represents a vector layer which manages a vector based data sets.
bool begin(QPaintDevice *device)
void setBottomRight(const QPointF &position)
void move(double dx, double dy)
Moves item in canvas coordinates.
A legend that can be placed onto a map composition.
void addComposerLabel(QgsComposerLabel *label)
Adds label to the graphics scene and advices composer to create a widget for it (through signal) ...
double xMinimum() const
Get the x minimum value (left side of rectangle)
Definition: qgsrectangle.h:192
QString toString() const
void setZValue(qreal z)
void addMultiFrame(QgsComposerMultiFrame *multiFrame)
Adds multiframe.
void addItemAtTop(QgsComposerItem *item)
Adds an item to the top of the composition z stack.
QgsPoint center() const
Center point of the rectangle.
Definition: qgsrectangle.h:217
const QgsRectangle * currentMapExtent() const
Returns a pointer to the current map extent, which is either the original user specified extent or th...
QString evalErrorString() const
Returns evaluation error.
void setExpressionString(const QString &expr)
Sets the expression for this QgsDataDefined.
bool isActive() const
iterator find(const Key &key)
iterator begin()
bool lowerItem(QgsComposerItem *item)
void addComposerArrow(QgsComposerArrow *arrow)
Adds an arrow item to the graphics scene and advices composer to create a widget for it (through sign...
bool reorderItemToBottom(QgsComposerItem *item)
Moves an item to the bottom of the z-order list.
bool moveItemToTop(QgsComposerItem *item)
void addComposerLegend(QgsComposerLegend *legend)
Adds legend to the graphics scene and advices composer to create a widget for it (through signal) ...
bool containsChange() const
Returns true if previous state and after state are valid and different.
Q_DECL_DEPRECATED QgsComposition(QgsMapRenderer *mapRenderer)
static QgsComposition::PaperOrientation decodePaperOrientation(const QString &orientationString, bool &ok)
Decodes a string representing a paper orientation.
void push(QUndoCommand *cmd)
double height() const
Height of the rectangle.
Definition: qgsrectangle.h:212
virtual int type() const override
Return correct graphics item type.
qreal width() const
bool setContent(const QByteArray &data, bool namespaceProcessing, QString *errorMsg, int *errorLine, int *errorColumn)
QDomNode at(int index) const
QRectF rect() const
int toPage() const
void setSnapGridOffsetY(const double offset)
const T value(const Key &key) const
void beginCommand(QgsComposerItem *item, const QString &commandText, const QgsComposerMergeCommand::Context c=QgsComposerMergeCommand::Unknown)
Allocates new item command and saves initial state in it.
QList< QgsComposerItem * > selectedComposerItems(const bool includeLockedItems=true)
Returns list of selected composer items.
void dirty(bool b)
Definition: qgsproject.cpp:410
static QgsExpressionContextScope * compositionScope(const QgsComposition *composition)
Creates a new scope which contains variables and functions relating to a QgsComposition.
QList< QGraphicsLineItem * > * snapLines()
Returns pointer to snap lines collection.
void beginMultiFrameCommand(QgsComposerMultiFrame *multiFrame, const QString &text, const QgsComposerMultiFrameMergeCommand::Context c=QgsComposerMultiFrameMergeCommand::Unknown)
static double mmToPoints(const double mmSize)
Returns the size in mm corresponding to a font point size.
QString id() const
Get item&#39;s id (which is not necessarly unique)