QGIS API Documentation
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( nullptr )
32  , mLabelingEngineV2( nullptr )
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 = nullptr;
47 
48  delete mLabelingEngineV2;
49  mLabelingEngineV2 = nullptr;
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 = nullptr;
81 
82  delete mLabelingEngineV2;
83  mLabelingEngineV2 = nullptr;
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 nullptr;
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  logRenderingTime( mLayerJobs );
204 
205  // final cleanup
206  cleanupJobs( mLayerJobs );
207 
208  emit finished();
209 }
210 
211 
213 {
214  try
215  {
216  self->doRender();
217  }
218  catch ( QgsException & e )
219  {
220  Q_UNUSED( e );
221  QgsDebugMsg( "Caught unhandled QgsException: " + e.what() );
222  }
223  catch ( std::exception & e )
224  {
225  Q_UNUSED( e );
226  QgsDebugMsg( "Caught unhandled std::exception: " + QString::fromAscii( e.what() ) );
227  }
228  catch ( ... )
229  {
230  QgsDebugMsg( "Caught unhandled unknown exception" );
231  }
232 }
233 
235 {
236  QgsDebugMsg( "Starting to render layer stack." );
237  QTime renderTime;
238  renderTime.start();
239 
240  for ( LayerRenderJobs::iterator it = mLayerJobs.begin(); it != mLayerJobs.end(); ++it )
241  {
242  LayerRenderJob& job = *it;
243 
244  if ( job.context.renderingStopped() )
245  break;
246 
247  if ( job.context.useAdvancedEffects() )
248  {
249  // Set the QPainter composition mode so that this layer is rendered using
250  // the desired blending mode
251  mPainter->setCompositionMode( job.blendMode );
252  }
253 
254  if ( !job.cached )
255  {
256  QTime layerTime;
257  layerTime.start();
258 
259  job.renderer->render();
260 
261  job.renderingTime = layerTime.elapsed();
262  }
263 
264  if ( job.img )
265  {
266  // If we flattened this layer for alternate blend modes, composite it now
267  mPainter->drawImage( 0, 0, *job.img );
268  }
269 
270  }
271 
272  QgsDebugMsg( "Done rendering map layers" );
273 
274  if ( mSettings.testFlag( QgsMapSettings::DrawLabeling ) && !mLabelingRenderContext.renderingStopped() )
275  drawLabeling( mSettings, mLabelingRenderContext, mLabelingEngine, mLabelingEngineV2, mPainter );
276 
277  QgsDebugMsg( "Rendering completed in (seconds): " + QString( "%1" ).arg( renderTime.elapsed() / 1000.0 ) );
278 }
279 
280 
281 void QgsMapRendererJob::drawLabeling( const QgsMapSettings& settings, QgsRenderContext& renderContext, QgsPalLabeling* labelingEngine, QgsLabelingEngineV2* labelingEngine2, QPainter* painter )
282 {
283  QgsDebugMsg( "Draw labeling start" );
284 
285  QTime t;
286  t.start();
287 
288  // Reset the composition mode before rendering the labels
289  painter->setCompositionMode( QPainter::CompositionMode_SourceOver );
290 
291  // TODO: this is not ideal - we could override rendering stopped flag that has been set in meanwhile
292  renderContext = QgsRenderContext::fromMapSettings( settings );
293  renderContext.setPainter( painter );
294  renderContext.setLabelingEngine( labelingEngine );
295 
296 #if !defined(QGIS_DISABLE_DEPRECATED)
297  // old labeling - to be removed at some point...
298  drawOldLabeling( settings, renderContext );
299 #endif
300  drawNewLabeling( settings, renderContext, labelingEngine );
301 
302  if ( labelingEngine2 )
303  {
304  // set correct extent
305  renderContext.setExtent( settings.visibleExtent() );
306  renderContext.setCoordinateTransform( nullptr );
307 
308  labelingEngine2->run( renderContext );
309  }
310 
311  QgsDebugMsg( QString( "Draw labeling took (seconds): %1" ).arg( t.elapsed() / 1000. ) );
312 }
313 
314 
316 {
317  // render all labels for vector layers in the stack, starting at the base
318  QListIterator<QString> li( settings.layers() );
319  li.toBack();
320  while ( li.hasPrevious() )
321  {
322  if ( renderContext.renderingStopped() )
323  {
324  break;
325  }
326 
327  QString layerId = li.previous();
328 
330 
331  if ( !ml || ( ml->type() != QgsMapLayer::VectorLayer ) )
332  continue;
333 
334  // only make labels if the layer is visible
335  // after scale dep viewing settings are checked
336  if ( !ml->isInScaleRange( settings.scale() ) )
337  continue;
338 
339  const QgsCoordinateTransform* ct = nullptr;
340  QgsRectangle r1 = settings.visibleExtent(), r2;
341 
342  if ( settings.hasCrsTransformEnabled() )
343  {
344  ct = settings.layerTransform( ml );
345  if ( ct )
346  reprojectToLayerExtent( ml, ct, r1, r2 );
347  }
348 
349  renderContext.setCoordinateTransform( ct );
350  renderContext.setExtent( r1 );
351 
352  ml->drawLabels( renderContext );
353  }
354 }
355 
356 
357 void QgsMapRendererJob::drawNewLabeling( const QgsMapSettings& settings, QgsRenderContext& renderContext, QgsPalLabeling* labelingEngine )
358 {
359  if ( labelingEngine && !renderContext.renderingStopped() )
360  {
361  // set correct extent
362  renderContext.setExtent( settings.visibleExtent() );
363  renderContext.setCoordinateTransform( nullptr );
364 
365  labelingEngine->drawLabeling( renderContext );
366  labelingEngine->exit();
367  }
368 }
369 
371 {
373  for ( ; it != mGeometryCaches.constEnd(); ++it )
374  {
375  const QgsGeometryCache& cache = it.value();
376  if ( QgsVectorLayer* vl = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( it.key() ) ) )
377  * vl->cache() = cache;
378  }
380 }
381 
382 
384 {
385  if ( ml->type() == QgsMapLayer::VectorLayer )
386  {
387  QgsVectorLayer* vl = qobject_cast<QgsVectorLayer *>( ml );
388  if ( vl->rendererV2() && vl->rendererV2()->forceRasterRender() )
389  {
390  //raster rendering is forced for this layer
391  return true;
392  }
394  (( vl->blendMode() != QPainter::CompositionMode_SourceOver )
395  || ( vl->featureBlendMode() != QPainter::CompositionMode_SourceOver )
396  || ( vl->layerTransparency() != 0 ) ) )
397  {
398  //layer properties require rasterisation
399  return true;
400  }
401  }
402 
403  return false;
404 }
405 
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.
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&#39;s CRS to destination CRS.
void updateLayerGeometryCaches()
called when rendering has finished to update all layers&#39; geometry caches
#define QgsDebugMsg(str)
Definition: qgslogger.h:33
void loadEngineSettings()
load/save engine settings to project file
void logRenderingTime(const LayerRenderJobs &jobs)
static bool reprojectToLayerExtent(const QgsMapLayer *ml, const QgsCoordinateTransform *ct, QgsRectangle &extent, QgsRectangle &r2)
Convenience function to project an extent into the layer source CRS, but also split it into two exten...
QMap< QString, QgsGeometryCache > mGeometryCaches
map of geometry caches
const_iterator constBegin() const
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.
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 isInScaleRange(double scale) const
Tests whether the layer should be visible at the specified scale.
QSize outputSize() const
Return the size of the resulting map image.
int exec(QFlags< QEventLoop::ProcessEventsFlag > flags)
bool renderingStopped() const
static void staticRender(QgsMapRendererCustomPainterJob *self)
virtual void drawLabeling(QgsRenderContext &context) override
called when the map is drawn and labels should be placed
const_iterator constEnd() const
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)
const Key key(const T &value) const
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:36
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)
int renderingTime
time it took to render the layer in ms (it is -1 if not rendered or still rendering) ...
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
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.
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.
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&#39;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&#39;re done with rendering
Structure keeping low-level rendering job information.
const T value(const Key &key) const
virtual bool isActive() const override
Tell whether the rendering job is currently running in background.