QGIS API Documentation  2.12.0-Lyon
qgsmaprenderercustompainterjob.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsmaprenderercustompainterjob.cpp
3  --------------------------------------
4  Date : December 2013
5  Copyright : (C) 2013 by Martin Dobias
6  Email : wonder dot sk at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
17 
18 #include "qgslabelingenginev2.h"
19 #include "qgslogger.h"
20 #include "qgsmaplayerregistry.h"
21 #include "qgsmaplayerrenderer.h"
22 #include "qgspallabeling.h"
23 #include "qgsvectorlayer.h"
24 #include "qgsrendererv2.h"
25 
26 #define LABELING_V2
27 
29  : QgsMapRendererJob( settings )
30  , mPainter( painter )
31  , mLabelingEngine( 0 )
32  , mLabelingEngineV2( 0 )
33  , mActive( false )
34  , mRenderSynchronously( false )
35 {
36  QgsDebugMsg( "QPAINTER construct" );
37 }
38 
40 {
41  QgsDebugMsg( "QPAINTER destruct" );
42  Q_ASSERT( !mFutureWatcher.isRunning() );
43  //cancel();
44 
45  delete mLabelingEngine;
46  mLabelingEngine = 0;
47 
48  delete mLabelingEngineV2;
49  mLabelingEngineV2 = 0;
50 }
51 
53 {
54  if ( isActive() )
55  return;
56 
58 
59  mActive = true;
60 
61  mErrors.clear();
62 
63  QgsDebugMsg( "QPAINTER run!" );
64 
65  QgsDebugMsg( "Preparing list of layer jobs for rendering" );
66  QTime prepareTime;
67  prepareTime.start();
68 
69  // clear the background
71 
72  mPainter->setRenderHint( QPainter::Antialiasing, mSettings.testFlag( QgsMapSettings::Antialiasing ) );
73 
74  QPaintDevice* thePaintDevice = mPainter->device();
75 
76  QString errMsg = QString( "pre-set DPI not equal to painter's DPI (%1 vs %2)" ).arg( thePaintDevice->logicalDpiX() ).arg( mSettings.outputDpi() );
77  Q_ASSERT_X( thePaintDevice->logicalDpiX() == mSettings.outputDpi(), "Job::startRender()", errMsg.toAscii().data() );
78 
79  delete mLabelingEngine;
80  mLabelingEngine = 0;
81 
82  delete mLabelingEngineV2;
83  mLabelingEngineV2 = 0;
84 
86  {
87 #ifdef LABELING_V2
88  mLabelingEngineV2 = new QgsLabelingEngineV2();
89  mLabelingEngineV2->readSettingsFromProject();
90  mLabelingEngineV2->setMapSettings( mSettings );
91 #else
92  mLabelingEngine = new QgsPalLabeling;
93  mLabelingEngine->loadEngineSettings();
94  mLabelingEngine->init( mSettings );
95 #endif
96  }
97 
98  mLayerJobs = prepareJobs( mPainter, mLabelingEngine, mLabelingEngineV2 );
99 
100  QgsDebugMsg( "Rendering prepared in (seconds): " + QString( "%1" ).arg( prepareTime.elapsed() / 1000.0 ) );
101 
102  if ( mRenderSynchronously )
103  {
104  // do the rendering right now!
105  doRender();
106  return;
107  }
108 
109  // now we are ready to start rendering!
110  connect( &mFutureWatcher, SIGNAL( finished() ), SLOT( futureFinished() ) );
111 
112  mFuture = QtConcurrent::run( staticRender, this );
113  mFutureWatcher.setFuture( mFuture );
114 }
115 
116 
118 {
119  if ( !isActive() )
120  {
121  QgsDebugMsg( "QPAINTER not running!" );
122  return;
123  }
124 
125  QgsDebugMsg( "QPAINTER cancelling" );
126  disconnect( &mFutureWatcher, SIGNAL( finished() ), this, SLOT( futureFinished() ) );
127 
128  mLabelingRenderContext.setRenderingStopped( true );
129  for ( LayerRenderJobs::iterator it = mLayerJobs.begin(); it != mLayerJobs.end(); ++it )
130  {
131  it->context.setRenderingStopped( true );
132  }
133 
134  QTime t;
135  t.start();
136 
137  mFutureWatcher.waitForFinished();
138 
139  QgsDebugMsg( QString( "QPAINER cancel waited %1 ms" ).arg( t.elapsed() / 1000.0 ) );
140 
141  futureFinished();
142 
143  QgsDebugMsg( "QPAINTER cancelled" );
144 }
145 
147 {
148  if ( !isActive() )
149  return;
150 
151  disconnect( &mFutureWatcher, SIGNAL( finished() ), this, SLOT( futureFinished() ) );
152 
153  QTime t;
154  t.start();
155 
156  mFutureWatcher.waitForFinished();
157 
158  QgsDebugMsg( QString( "waitForFinished: %1 ms" ).arg( t.elapsed() / 1000.0 ) );
159 
160  futureFinished();
161 }
162 
164 {
165  return mActive;
166 }
167 
168 
170 {
171  if ( mLabelingEngine )
172  return mLabelingEngine->takeResults();
173  else if ( mLabelingEngineV2 )
174  return mLabelingEngineV2->takeResults();
175  else
176  return 0;
177 }
178 
179 
181 {
182  QEventLoop loop;
183  connect( &mFutureWatcher, SIGNAL( finished() ), &loop, SLOT( quit() ) );
184  loop.exec( flags );
185 }
186 
187 
189 {
190  mRenderSynchronously = true;
191  start();
192  futureFinished();
193  mRenderSynchronously = false;
194 }
195 
196 
198 {
199  mActive = false;
201  QgsDebugMsg( "QPAINTER futureFinished" );
202 
203  // final cleanup
204  cleanupJobs( mLayerJobs );
205 
206  emit finished();
207 }
208 
209 
211 {
212  try
213  {
214  self->doRender();
215  }
216  catch ( QgsException & e )
217  {
218  QgsDebugMsg( "Caught unhandled QgsException: " + e.what() );
219  }
220  catch ( std::exception & e )
221  {
222  QgsDebugMsg( "Caught unhandled std::exception: " + QString::fromAscii( e.what() ) );
223  }
224  catch ( ... )
225  {
226  QgsDebugMsg( "Caught unhandled unknown exception" );
227  }
228 }
229 
231 {
232  QgsDebugMsg( "Starting to render layer stack." );
233  QTime renderTime;
234  renderTime.start();
235 
236  for ( LayerRenderJobs::iterator it = mLayerJobs.begin(); it != mLayerJobs.end(); ++it )
237  {
238  LayerRenderJob& job = *it;
239 
240  if ( job.context.renderingStopped() )
241  break;
242 
243  if ( job.context.useAdvancedEffects() )
244  {
245  // Set the QPainter composition mode so that this layer is rendered using
246  // the desired blending mode
247  mPainter->setCompositionMode( job.blendMode );
248  }
249 
250  if ( !job.cached )
251  job.renderer->render();
252 
253  if ( job.img )
254  {
255  // If we flattened this layer for alternate blend modes, composite it now
256  mPainter->drawImage( 0, 0, *job.img );
257  }
258 
259  }
260 
261  QgsDebugMsg( "Done rendering map layers" );
262 
263  if ( mSettings.testFlag( QgsMapSettings::DrawLabeling ) && !mLabelingRenderContext.renderingStopped() )
264  drawLabeling( mSettings, mLabelingRenderContext, mLabelingEngine, mLabelingEngineV2, mPainter );
265 
266  QgsDebugMsg( "Rendering completed in (seconds): " + QString( "%1" ).arg( renderTime.elapsed() / 1000.0 ) );
267 }
268 
269 
270 void QgsMapRendererJob::drawLabeling( const QgsMapSettings& settings, QgsRenderContext& renderContext, QgsPalLabeling* labelingEngine, QgsLabelingEngineV2* labelingEngine2, QPainter* painter )
271 {
272  QgsDebugMsg( "Draw labeling start" );
273 
274  QTime t;
275  t.start();
276 
277  // Reset the composition mode before rendering the labels
278  painter->setCompositionMode( QPainter::CompositionMode_SourceOver );
279 
280  // TODO: this is not ideal - we could override rendering stopped flag that has been set in meanwhile
281  renderContext = QgsRenderContext::fromMapSettings( settings );
282  renderContext.setPainter( painter );
283  renderContext.setLabelingEngine( labelingEngine );
284 
285  // old labeling - to be removed at some point...
286  drawOldLabeling( settings, renderContext );
287 
288  drawNewLabeling( settings, renderContext, labelingEngine );
289 
290  if ( labelingEngine2 )
291  {
292  // set correct extent
293  renderContext.setExtent( settings.visibleExtent() );
294  renderContext.setCoordinateTransform( NULL );
295 
296  labelingEngine2->run( renderContext );
297  }
298 
299  QgsDebugMsg( QString( "Draw labeling took (seconds): %1" ).arg( t.elapsed() / 1000. ) );
300 }
301 
302 
304 {
305  // render all labels for vector layers in the stack, starting at the base
306  QListIterator<QString> li( settings.layers() );
307  li.toBack();
308  while ( li.hasPrevious() )
309  {
310  if ( renderContext.renderingStopped() )
311  {
312  break;
313  }
314 
315  QString layerId = li.previous();
316 
318 
319  if ( !ml || ( ml->type() != QgsMapLayer::VectorLayer ) )
320  continue;
321 
322  // only make labels if the layer is visible
323  // after scale dep viewing settings are checked
324  if ( ml->hasScaleBasedVisibility() && ( settings.scale() < ml->minimumScale() || settings.scale() > ml->maximumScale() ) )
325  continue;
326 
327  const QgsCoordinateTransform* ct = 0;
328  QgsRectangle r1 = settings.visibleExtent(), r2;
329 
330  if ( settings.hasCrsTransformEnabled() )
331  {
332  ct = settings.layerTransform( ml );
333  if ( ct )
334  reprojectToLayerExtent( ct, ml->crs().geographicFlag(), r1, r2 );
335  }
336 
337  renderContext.setCoordinateTransform( ct );
338  renderContext.setExtent( r1 );
339 
340  ml->drawLabels( renderContext );
341  }
342 }
343 
344 
345 void QgsMapRendererJob::drawNewLabeling( const QgsMapSettings& settings, QgsRenderContext& renderContext, QgsPalLabeling* labelingEngine )
346 {
347  if ( labelingEngine && !renderContext.renderingStopped() )
348  {
349  // set correct extent
350  renderContext.setExtent( settings.visibleExtent() );
351  renderContext.setCoordinateTransform( NULL );
352 
353  labelingEngine->drawLabeling( renderContext );
354  labelingEngine->exit();
355  }
356 }
357 
359 {
360  Q_FOREACH ( const QString& id, mGeometryCaches.keys() )
361  {
362  const QgsGeometryCache& cache = mGeometryCaches[id];
363  if ( QgsVectorLayer* vl = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( id ) ) )
364  * vl->cache() = cache;
365  }
367 }
368 
369 
371 {
372  if ( ml->type() == QgsMapLayer::VectorLayer )
373  {
374  QgsVectorLayer* vl = qobject_cast<QgsVectorLayer *>( ml );
375  if ( vl->rendererV2() && vl->rendererV2()->forceRasterRender() )
376  {
377  //raster rendering is forced for this layer
378  return true;
379  }
381  (( vl->blendMode() != QPainter::CompositionMode_SourceOver )
382  || ( vl->featureBlendMode() != QPainter::CompositionMode_SourceOver )
383  || ( vl->layerTransparency() != 0 ) ) )
384  {
385  //layer properties require rasterisation
386  return true;
387  }
388  }
389 
390  return false;
391 }
392 
QgsMapRendererCustomPainterJob(const QgsMapSettings &settings, QPainter *painter)
void clear()
QString fromAscii(const char *str, int size)
void finished()
emitted when asynchronous rendering is finished (or canceled).
static void drawNewLabeling(const QgsMapSettings &settings, QgsRenderContext &renderContext, QgsPalLabeling *labelingEngine)
void setRenderingStopped(bool stopped)
A rectangle specified with double values.
Definition: qgsrectangle.h:35
Base class for all map layer types.
Definition: qgsmaplayer.h:49
Job implementation that renders everything sequentially using a custom painter.
QgsMapLayer::LayerType type() const
Get the type of the layer.
Definition: qgsmaplayer.cpp:94
int width() const
Abstract base class for map rendering implementations.
virtual void drawLabels(QgsRenderContext &rendererContext)
Draw labels.
double scale() const
Return the calculated scale of the map.
void fillRect(const QRectF &rectangle, const QBrush &brush)
void setCompositionMode(CompositionMode mode)
void setRenderHint(RenderHint hint, bool on)
void cleanupJobs(LayerRenderJobs &jobs)
QgsLabelingResults * takeResults()
Return pointer to recently computed results (in drawLabeling()) and pass the ownership of results to ...
const QgsCoordinateTransform * layerTransform(QgsMapLayer *layer) const
Return coordinate transform from layer's CRS to destination CRS.
void updateLayerGeometryCaches()
called when rendering has finished to update all layers' geometry caches
#define QgsDebugMsg(str)
Definition: qgslogger.h:33
void loadEngineSettings()
load/save engine settings to project file
QMap< QString, QgsGeometryCache > mGeometryCaches
map of geometry caches
float minimumScale() const
Returns the minimum scale denominator at which the layer is visible.
QgsRectangle visibleExtent() const
Return the actual extent derived from requested extent that takes takes output image size into accoun...
The QgsLabelingEngineV2 class provides map labeling functionality.
bool hasCrsTransformEnabled() const
returns true if projections are enabled for this layer set
virtual void cancel() override
Stop the rendering job - does not return until the job has terminated.
void readSettingsFromProject()
Read configuration of the labeling engine from the current project file.
void clear()
Enable layer transparency and blending effects.
bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method)
void setExtent(const QgsRectangle &extent)
Enable drawing of labels on top of the map.
QgsMapLayer * mapLayer(const QString &theLayerId)
Retrieve a pointer to a loaded layer by id.
The QgsMapSettings class contains configuration for rendering of the map.
void setCoordinateTransform(const QgsCoordinateTransform *t)
Sets coordinate transformation.
bool useAdvancedEffects() const
Returns true if advanced effects such as blend modes such be used.
QList< Key > keys() const
QgsFeatureRendererV2 * rendererV2()
Return renderer V2.
int elapsed() const
int outputDpi() const
Return DPI used for conversion between real world units (e.g.
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
bool forceRasterRender() const
Returns whether the renderer must render as a raster.
virtual void start() override
Start the rendering job and immediately return.
QPainter::CompositionMode featureBlendMode() const
Returns the current blending mode for features.
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
QSize outputSize() const
Return the size of the resulting map image.
int exec(QFlags< QEventLoop::ProcessEventsFlag > flags)
bool renderingStopped() const
float maximumScale() const
Returns the maximum scale denominator at which the layer is visible.
static void staticRender(QgsMapRendererCustomPainterJob *self)
virtual void drawLabeling(QgsRenderContext &context) override
called when the map is drawn and labels should be placed
Enable anti-aliasin for map rendering.
QPaintDevice * device() const
void setPainter(QPainter *p)
QFuture< T > run(Function function,...)
void setFuture(const QFuture< T > &future)
QgsMapSettings mSettings
int logicalDpiX() const
iterator end()
QColor backgroundColor() const
Get the background color of the map.
void setMapSettings(const QgsMapSettings &mapSettings)
Associate map settings instance.
void run(QgsRenderContext &context)
compute the labeling with given map settings and providers
bool testFlag(Flag flag) const
Check whether a particular flag is enabled.
int layerTransparency() const
Returns the current transparency for the vector layer.
static void drawOldLabeling(const QgsMapSettings &settings, QgsRenderContext &renderContext)
bool isRunning() const
void waitForFinished()
static void drawLabeling(const QgsMapSettings &settings, QgsRenderContext &renderContext, QgsPalLabeling *labelingEngine, QgsLabelingEngineV2 *labelingEngine2, QPainter *painter)
QString what() const
Definition: qgsexception.h:35
typedef ProcessEventsFlags
Contains information about the context of a rendering operation.
virtual bool render()=0
Do the rendering (based on data stored in the class)
static QgsMapLayerRegistry * instance()
Returns the instance pointer, creating the object on the first call.
void drawImage(const QRectF &target, const QImage &image, const QRectF &source, QFlags< Qt::ImageConversionFlag > flags)
LayerRenderJobs prepareJobs(QPainter *painter, QgsPalLabeling *labelingEngine, QgsLabelingEngineV2 *labelingEngine2)
static QgsRenderContext fromMapSettings(const QgsMapSettings &mapSettings)
create initialized QgsRenderContext instance from given QgsMapSettings
void setLabelingEngine(QgsLabelingEngineInterface *iface)
int height() const
QgsMapLayerRenderer * renderer
Class for doing transforms between two map coordinate systems.
char * data()
QgsRenderContext context
const QgsCoordinateReferenceSystem & crs() const
Returns layer's spatial reference system.
QStringList layers() const
Get list of layer IDs for map rendering The layers are stored in the reverse order of how they are re...
void start()
Class that stores computed placement from labeling engine.
static bool reprojectToLayerExtent(const QgsCoordinateTransform *ct, bool layerCrsGeographic, QgsRectangle &extent, QgsRectangle &r2)
Convenience function to project an extent into the layer source CRS, but also split it into two exten...
virtual QgsLabelingResults * takeLabelingResults() override
Get pointer to internal labeling engine (in order to get access to the results)
QPainter::CompositionMode blendMode
bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
virtual void waitForFinished() override
Block until the job has finished.
Represents a vector layer which manages a vector based data sets.
bool geographicFlag() const
Get this Geographic? flag.
QString arg(qlonglong a, int fieldWidth, int base, const QChar &fillChar) const
bool needTemporaryImage(QgsMapLayer *ml)
void waitForFinishedWithEventLoop(const QEventLoop::ProcessEventsFlags &flags=QEventLoop::AllEvents)
Wait for the job to be finished - and keep the thread's event loop running while waiting.
Defines a qgis exception class.
Definition: qgsexception.h:25
void renderSynchronously()
Render the map synchronously in this thread.
QgsLabelingResults * takeResults()
Return pointer to recently computed results and pass the ownership of results to the caller...
iterator begin()
QByteArray toAscii() const
virtual void exit() override
called when we're done with rendering
Structure keeping low-level rendering job information.
virtual bool isActive() const override
Tell whether the rendering job is currently running in background.