QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgslayoutitemhtml.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgslayoutitemhtml.cpp
3 ------------------------------------------------------------
4 begin : October 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson 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
16#include "qgslayoutitemhtml.h"
17
18#include <nlohmann/json.hpp>
19
20#include "qgsdistancearea.h"
21#include "qgsexpression.h"
22#include "qgsjsonutils.h"
23#include "qgslayout.h"
24#include "qgslayoutframe.h"
25#include "qgslayoutitemlabel.h"
26#include "qgslayoutitemmap.h"
29#include "qgslayoututils.h"
30#include "qgslogger.h"
31#include "qgsmapsettings.h"
33#include "qgspainting.h"
35#include "qgsproject.h"
36#include "qgsvectorlayer.h"
37
38#include <QString>
39
40#if defined( HAVE_WEBENGINE ) && defined( HAVE_PDF4QT )
41#define CAN_RENDER
42#include "qgswebenginepage.h"
43
44#include <QWebEnginePage>
45#include <QWebEngineSettings>
46#include <QWebEngineScript>
47#endif
48
50
51#include <QString>
52
53#include <QAbstractTextDocumentLayout>
54#include <QCoreApplication>
55#include <QImage>
56#include <QNetworkReply>
57#include <QPainter>
58#include <QString>
59#include <QThread>
60#include <QUrl>
61#include <QtConcurrentRun>
62#include <QTimer>
63
64#include "moc_qgslayoutitemhtml.cpp"
65
66using namespace Qt::StringLiterals;
67
68// clazy:excludeall=lambda-in-connect
69
72 , mPictureRasterizer( new QgsPictureRasterizer( this ) )
73{
74 mPictureRasterizer->setMaxCacheSize( 10000 );
75
76 mBackgroundUpdateTimer = new QTimer( this );
77 mBackgroundUpdateTimer->setSingleShot( true );
78 connect( mBackgroundUpdateTimer, &QTimer::timeout, this, &QgsLayoutItemHtml::recreateCachedImageInBackground );
79
80 connect( mPictureRasterizer, &QgsPictureRasterizer::rendered, this, [this] {
81 updateFrames();
82 emit previewRefreshed();
83 } );
84
85 //a html item added to a layout needs to have the initial expression context set,
86 //otherwise fields in the html aren't correctly evaluated until atlas preview feature changes (#9457)
87 setExpressionContext( mLayout->reportContext().feature(), mLayout->reportContext().layer() );
88
90 connect( &mLayout->reportContext(), &QgsLayoutReportContext::changed, this, &QgsLayoutItemHtml::refreshExpressionContext );
91
92 mFetcher = new QgsNetworkContentFetcher( this );
93 connect( mFetcher, &QgsNetworkContentFetcher::finished, this, &QgsLayoutItemHtml::onHtmlFetched );
94}
95
97{
98 mBackgroundUpdateTimer->stop();
99 cancelPendingFetch();
100 cancelRunningRenderJob( true );
102}
103
108
110{
111 return QgsApplication::getThemeIcon( u"/mLayoutItemHtml.svg"_s );
112}
113
115{
116#ifdef CAN_RENDER
117 return true;
118#else
119 return false;
120#endif
121}
122
127
129{
131 QgsLayoutFrame *frame = new QgsLayoutFrame( label->layout(), html );
132 frame->setVisible( label->isVisible() );
133 frame->setLocked( label->isLocked() );
134 frame->setItemOpacity( label->itemOpacity() );
135 frame->setRotation( label->rotation() );
136 frame->setReferencePoint( label->referencePoint() );
137 frame->attemptMove( label->positionWithUnits() );
138 frame->attemptResize( label->sizeWithUnits() );
139 frame->setZValue( label->zValue() );
140 frame->setParentGroup( label->parentGroup() );
141 frame->setBackgroundColor( label->backgroundColor() );
142 frame->setFrameEnabled( label->frameEnabled() );
143 frame->setFrameJoinStyle( label->frameJoinStyle() );
144 frame->setFrameStrokeWidth( label->frameStrokeWidth() );
145 frame->setFrameStrokeColor( label->frameStrokeColor() );
146 html->addFrame( frame );
147 html->setContentMode( QgsLayoutItemHtml::ManualHtml );
148 html->setHtml( label->currentText() );
149 html->setUserStylesheetEnabled( true );
150 html->setUserStylesheet( label->createStylesheet() );
151 html->loadHtml();
152 return html;
153}
154
156{
157 mUrl = url;
158 loadHtml( true );
159 emit changed();
160}
161
162void QgsLayoutItemHtml::setHtml( const QString &html )
163{
164 mHtml = html;
165 //TODO - this signal should be emitted, but without changing the signal which sets the html
166 //to an equivalent of editingFinished it causes a lot of problems. Need to investigate
167 //ways of doing this using QScintilla widgets.
168 //emit changed();
169}
170
172{
173 mEvaluateExpressions = evaluateExpressions;
174 loadHtml( true );
175 emit changed();
176}
177
178void QgsLayoutItemHtml::loadHtml( const bool useCache, const QgsExpressionContext *context )
179{
180 const QgsExpressionContext scopedContext = createExpressionContext();
181 const QgsExpressionContext *evalContext = context ? context : &scopedContext;
182
183 QString loadedHtml;
184 switch ( mContentMode )
185 {
187 {
188 QString currentUrl = mUrl.toString();
189
190 //data defined url set?
191 bool ok = false;
192 currentUrl = mDataDefinedProperties.valueAsString( QgsLayoutObject::DataDefinedProperty::SourceUrl, *evalContext, currentUrl, &ok );
193 if ( ok )
194 {
195 currentUrl = currentUrl.trimmed();
196 QgsDebugMsgLevel( u"exprVal Source Url:%1"_s.arg( currentUrl ), 2 );
197 }
198 if ( currentUrl.isEmpty() )
199 {
200 cancelPendingFetch();
201 finalizeLoadedHtml( QString(), QUrl(), evalContext );
202 return;
203 }
204
205 if ( useCache && mHasFetchedHtml && currentUrl == mLastFetchedUrl )
206 {
207 cancelPendingFetch();
208 finalizeLoadedHtml( mFetchedHtml, QUrl( mActualFetchedUrl ), evalContext );
209 }
210 else
211 {
212 if ( !( useCache && mFetching && currentUrl == mPendingFetchUrl ) )
213 {
214 cancelPendingFetch();
215 mBackgroundUpdateTimer->stop();
216 cancelRunningRenderJob( false );
217
218 mPendingFetchUrl = currentUrl;
219 mPendingExpressionContext = context ? std::optional< QgsExpressionContext >( *context ) : std::nullopt;
220 mCacheInvalidated = true;
221 startFetchHtml( QUrl( currentUrl ) );
222 updateFrames();
223 }
224 else if ( context )
225 {
226 mPendingExpressionContext = *context;
227 }
228
229 if ( !mLayout || !mLayout->renderContext().isPreviewRender() )
230 {
231 // if not a preview render, we HAVE to wait till we've loaded content
232 waitForPendingFetch();
233 }
234 }
235
236 break;
237 }
239 cancelPendingFetch();
240 const QUrl baseUrl = ( mLayout && mLayout->project() ) ? QUrl::fromLocalFile( mLayout->project()->absoluteFilePath() ) : QUrl();
241 finalizeLoadedHtml( mHtml, baseUrl, evalContext );
242 break;
243 }
244}
245
246void QgsLayoutItemHtml::startFetchHtml( const QUrl &url )
247{
249 mFetching = true;
250 mFetcher->fetchContent( url );
251}
252
253void QgsLayoutItemHtml::cancelPendingFetch()
254{
255 if ( !mFetching )
256 return;
257
258 mFetching = false;
259 mPendingFetchUrl.clear();
260 mPendingExpressionContext.reset();
261
262 mFetcher->disconnect( this );
263 mFetcher->cancel();
264 mFetcher->deleteLater();
265 mFetcher = new QgsNetworkContentFetcher( this );
266 connect( mFetcher, &QgsNetworkContentFetcher::finished, this, &QgsLayoutItemHtml::onHtmlFetched );
268}
269
270void QgsLayoutItemHtml::waitForPendingFetch()
271{
272 if ( !mFetching )
273 return;
274
275 QEventLoop loop;
276 connect( mFetcher, &QgsNetworkContentFetcher::finished, &loop, &QEventLoop::quit );
277 if ( mFetching )
278 {
279 loop.exec( QEventLoop::ExcludeUserInputEvents );
280 }
281}
282
283void QgsLayoutItemHtml::onHtmlFetched()
284{
285 if ( !mFetching )
286 return;
287
289 mFetching = false;
290 mFetchedHtml = mFetcher->contentAsString();
291 mActualFetchedUrl = mFetcher->reply() ? mFetcher->reply()->url().toString() : mPendingFetchUrl;
292 mLastFetchedUrl = mPendingFetchUrl;
293 mHasFetchedHtml = true;
294 mPendingFetchUrl.clear();
295
296 const std::optional< QgsExpressionContext > savedContext = std::move( mPendingExpressionContext );
297 mPendingExpressionContext = {};
298
299 const QgsExpressionContext scopedContext = createExpressionContext();
300 const QgsExpressionContext *evalContext = savedContext.has_value() ? &*savedContext : &scopedContext;
301 finalizeLoadedHtml( mFetchedHtml, QUrl( mActualFetchedUrl ), evalContext );
302}
303
304void QgsLayoutItemHtml::finalizeLoadedHtml( const QString &rawHtml, const QUrl &baseUrl, const QgsExpressionContext *context )
305{
306 QString loadedHtml = rawHtml;
307 if ( mEvaluateExpressions && !loadedHtml.isEmpty() )
308 {
309 loadedHtml = QgsExpression::replaceExpressionText( loadedHtml, context, &mDistanceArea );
310 }
311
312 mEvaluatedHtml = loadedHtml;
313 mResolvedBaseUrl = baseUrl;
314 mCacheInvalidated = true;
315
316 if ( !mLayout || !mLayout->renderContext().isPreviewRender() )
317 {
318 mBackgroundUpdateTimer->stop();
319 cancelRunningRenderJob( false );
320 renderHtmlSynchronously();
322 }
323 else
324 {
325 // render HTML in a background thread, so we don't block the user interface
326 mBackgroundUpdateTimer->start( 1 );
327 }
328}
329
330void QgsLayoutItemHtml::recreateCachedImageInBackground()
331{
332 if ( mFetching )
333 return;
334
335 cancelRunningRenderJob( false );
336
337 const double frameWidthLayoutUnits = maxFrameWidth();
338 if ( frameWidthLayoutUnits <= 0 || mEvaluatedHtml.isEmpty() )
339 {
340 mCacheInvalidated = false;
341 mLastRenderedWidth = frameWidthLayoutUnits;
342 mSize = QSizeF( 0, 0 );
343 mRenderedPicture = QPicture();
344 mRenderedPage = QImage();
345 mPictureRasterizer->clear();
347 emit contentsChanged();
348 updateFrames();
349 emit previewRefreshed();
351 return;
352 }
353
355 mCacheInvalidated = false;
356 mRenderJob = std::make_unique<
357 QgsLayoutItemHtmlRenderJob >( mEvaluatedHtml, mResolvedBaseUrl, mEnableUserStylesheet ? mUserStylesheet : QString(), mAtlasFeatureProperties, frameWidthLayoutUnits, layoutUnitsPerCssPixel() );
358 connect( mRenderJob.get(), &QgsLayoutItemHtmlRenderJob::finished, this, &QgsLayoutItemHtml::htmlRenderFinished );
359 mRenderJob->start();
360}
361
362void QgsLayoutItemHtml::htmlRenderFinished()
363{
364 if ( !mRenderJob )
365 return;
366
367 if ( !mRenderJob->success() && !mRenderJob->errorMessage().isEmpty() )
368 {
369 QgsDebugError( mRenderJob->errorMessage() );
370 }
371
372 mLastRenderedWidth = mRenderJob->frameWidthLayoutUnits();
373 mSize = mRenderJob->size();
374 mRenderedPicture = QgsPainting::deepCopyQPicture( mRenderJob->picture() );
375 mRenderedPage = mRenderJob->renderedPage();
376 mRenderJob.reset();
377
378 mPictureRasterizer->setPicture( mRenderedPicture );
379
381
383 emit contentsChanged();
384 updateFrames();
385 emit previewRefreshed();
386}
387
388void QgsLayoutItemHtml::renderHtmlSynchronously()
389{
390 if ( mFetching )
391 {
392 waitForPendingFetch();
393 return;
394 }
395
396 const double frameWidthLayoutUnits = maxFrameWidth();
397 mLastRenderedWidth = frameWidthLayoutUnits;
398 mCacheInvalidated = false;
399
400 if ( frameWidthLayoutUnits <= 0 || mEvaluatedHtml.isEmpty() )
401 {
402 mSize = QSizeF( 0, 0 );
403 mRenderedPicture = QPicture();
404 mRenderedPage = QImage();
405 mPictureRasterizer->clear();
407 emit contentsChanged();
408 return;
409 }
410
411 const double unitsPerCssPx = layoutUnitsPerCssPixel();
412 const double widthCssPx = frameWidthLayoutUnits / unitsPerCssPx;
413
414 QString errorMessage;
415 mRenderedPicture = QPicture();
416 QPainter painter( &mRenderedPicture );
417 painter.setRenderHint( QPainter::Antialiasing, true );
418 painter.setRenderHint( QPainter::TextAntialiasing, true );
419 painter.setRenderHint( QPainter::SmoothPixmapTransform, true );
420
421 QSizeF renderedSizeCssPx;
422
423 QgsHtmlRenderSettings htmlRenderSettings;
424 htmlRenderSettings.setBaseUrl( mResolvedBaseUrl );
425 if ( mEnableUserStylesheet )
426 {
427 htmlRenderSettings.setUserStylesheet( mUserStylesheet );
428 }
429 htmlRenderSettings.setFeatureJson( mAtlasFeatureProperties );
430
431#ifdef CAN_RENDER
432 if ( !QgsWebEnginePage::renderBlocking( mEvaluatedHtml, &painter, QRectF( 0, 0, widthCssPx, 9999 ), errorMessage, renderedSizeCssPx, htmlRenderSettings, nullptr ) )
433 {
434 QgsDebugError( errorMessage );
435 }
436#endif
437 painter.end();
438
439 const double heightCssPx = renderedSizeCssPx.height();
440 mRenderedPicture.setBoundingRect( QRect( 0, 0, static_cast< int >( std::ceil( widthCssPx ) ), static_cast< int >( std::ceil( heightCssPx ) ) ) );
441
442 mSize = QSizeF( frameWidthLayoutUnits, heightCssPx * unitsPerCssPx );
443
444 const QSize pageSizeCssPx( static_cast< int >( std::ceil( widthCssPx ) ), static_cast< int >( std::ceil( heightCssPx ) ) );
445 if ( mUseSmartBreaks && !pageSizeCssPx.isEmpty() )
446 {
447 mRenderedPage = QImage( pageSizeCssPx, QImage::Format_ARGB32 );
448 mRenderedPage.fill( Qt::transparent );
449 QPainter imagePainter( &mRenderedPage );
450 QgsPainting::drawPicture( &imagePainter, QPointF( 0, 0 ), mRenderedPicture );
451 imagePainter.end();
452 }
453 else
454 {
455 mRenderedPage = QImage();
456 }
457
458 mPictureRasterizer->setPicture( mRenderedPicture );
459
461 emit contentsChanged();
462}
463
464double QgsLayoutItemHtml::maxFrameWidth() const
465{
466 double maxWidth = 0;
468 {
469 maxWidth = std::max( maxWidth, static_cast< double >( frame->boundingRect().width() ) );
470 }
471
472 return maxWidth;
473}
474
476{
477 if ( frameCount() < 1 )
478 return;
479
480 if ( !mFetching )
481 {
482 const double currentWidth = maxFrameWidth();
483 if ( !qgsDoubleNear( currentWidth, mLastRenderedWidth ) && !mEvaluatedHtml.isEmpty() )
484 {
485 mCacheInvalidated = true;
486 if ( !mLayout || !mLayout->renderContext().isPreviewRender() )
487 {
488 mBackgroundUpdateTimer->stop();
489 cancelRunningRenderJob( false );
490 renderHtmlSynchronously();
491 return;
492 }
493 else
494 {
495 mBackgroundUpdateTimer->start( 1 );
496 }
497 }
498 }
499
501 emit changed();
502}
503
505{
506 return mSize;
507}
508
509void QgsLayoutItemHtml::render( QgsLayoutItemRenderContext &context, const QRectF &renderExtent, const int frameIndex )
510{
511#ifdef CAN_RENDER
512 QPainter *painter = context.renderContext().painter();
513 if ( !painter )
514 return;
515
516 if ( mLayout->renderContext().isPreviewRender() )
517 {
518 const double currentScaleFactor = context.renderContext().scaleFactor();
519
520 if ( !mFetching && ( mCacheInvalidated || !qgsDoubleNear( maxFrameWidth(), mLastRenderedWidth ) ) && !mRenderJob && !mBackgroundUpdateTimer->isActive() && !mEvaluatedHtml.isEmpty() )
521 {
522 mBackgroundUpdateTimer->start( 1 );
523 }
524
525 // main thread preview render ONLY draws the rasterized QImage from QgsPictureRasterizer
526 const QSize targetPixelSize = ( mSize * currentScaleFactor ).toSize();
527 const QImage previewImage = mPictureRasterizer->image( targetPixelSize );
528
529 if ( !previewImage.isNull() && !mSize.isEmpty() )
530 {
531 const QgsScopedQPainterState painterState( painter );
532 painter->scale( currentScaleFactor, currentScaleFactor );
533 painter->translate( -renderExtent.left(), -renderExtent.top() );
534 painter->setClipRect( renderExtent, Qt::IntersectClip );
535 painter->setRenderHint( QPainter::SmoothPixmapTransform, true );
536 painter->drawImage( QRectF( QPointF( 0, 0 ), mSize ), previewImage );
537 }
538 else if ( mFetching || mRenderJob || mBackgroundUpdateTimer->isActive() || mPictureRasterizer->isRendering() )
539 {
540 if ( QgsLayoutFrame *currentFrame = frame( frameIndex ) )
541 {
542 const QgsScopedQPainterState painterState( painter );
543 painter->scale( currentScaleFactor, currentScaleFactor );
544 const QRectF frameRect( 0, 0, currentFrame->rect().width(), currentFrame->rect().height() );
545 painter->setBrush( QBrush( QColor( 125, 125, 125, 125 ) ) );
546 painter->setPen( Qt::NoPen );
547 painter->drawRect( frameRect );
548 painter->setBrush( Qt::NoBrush );
549
550 QFont messageFont;
551 messageFont.setPointSize( 12 );
552 painter->setFont( messageFont );
553 painter->setPen( QColor( 255, 255, 255, 255 ) );
554 painter->drawText( frameRect, Qt::AlignCenter, tr( "Rendering HTML" ) );
555 }
556 }
557 return;
558 }
559
560 if ( mFetching )
561 {
562 waitForPendingFetch();
563 }
564
565 if ( mCacheInvalidated || mRenderJob || !qgsDoubleNear( maxFrameWidth(), mLastRenderedWidth ) )
566 {
567 mBackgroundUpdateTimer->stop();
568 cancelRunningRenderJob( false );
569 renderHtmlSynchronously();
570 }
571
572 const QgsScopedQPainterState painterState( painter );
573 painter->setRenderHint( QPainter::Antialiasing );
574 painter->setRenderHint( QPainter::SmoothPixmapTransform );
575
576 // painter is scaled to dots; scale back to layout units
577 painter->scale( context.renderContext().scaleFactor(), context.renderContext().scaleFactor() );
578 painter->translate( -renderExtent.left(), -renderExtent.top() );
579 painter->setClipRect( renderExtent, Qt::IntersectClip );
580 // scale from CSS pixels (mRenderedPicture's coordinate space) to layout units
581 const double unitsPerCssPx = layoutUnitsPerCssPixel();
582 painter->scale( unitsPerCssPx, unitsPerCssPx );
583
584 QgsPainting::drawPicture( painter, QPointF( 0, 0 ), mRenderedPicture );
585#else
586 Q_UNUSED( renderExtent )
587 if ( mLayout->renderContext().isPreviewRender() )
588 {
589 if ( QgsLayoutFrame *currentFrame = frame( frameIndex ) )
590 {
591 QPainter *painter = context.renderContext().painter();
592
593 // painter is scaled to dots, so scale back to layout units
594 const QRectF painterRect = QRectF(
595 currentFrame->rect().left() * context.renderContext().scaleFactor(),
596 currentFrame->rect().top() * context.renderContext().scaleFactor(),
597 currentFrame->rect().width() * context.renderContext().scaleFactor(),
598 currentFrame->rect().height() * context.renderContext().scaleFactor()
599 );
600
601 painter->setBrush( QBrush( QColor( 255, 125, 125, 125 ) ) );
602 painter->setPen( Qt::NoPen );
603 painter->drawRect( painterRect );
604 painter->setBrush( Qt::NoBrush );
605
606 painter->setPen( QColor( 200, 0, 0, 255 ) );
607 QTextDocument td;
608 td.setTextWidth( painterRect.width() );
609 td.setHtml( u"<span style=\"color: rgb(200,0,0);\"><b>%1</b><br>%2</span>"_s
610 .arg( tr( "HTML rendering not available!" ), tr( "The item cannot be rendered because this QGIS install was built without WebEngine or PDF4QT support." ) ) );
611 painter->setClipRect( painterRect );
612 QAbstractTextDocumentLayout::PaintContext ctx;
613 td.documentLayout()->draw( painter, ctx );
614 }
615 }
616#endif
617}
618
619double QgsLayoutItemHtml::layoutUnitsPerCssPixel() const
620{
621 if ( !mLayout )
622 return 25.4 / 96.0;
623
624 return mLayout->convertToLayoutUnits( QgsLayoutMeasurement( 1.0, Qgis::LayoutUnit::Inches ) ) / 96.0;
625}
626
627void QgsLayoutItemHtml::cancelRunningRenderJob( bool block )
628{
629 if ( !mRenderJob )
630 return;
631
632 disconnect( mRenderJob.get(), &QgsLayoutItemHtmlRenderJob::finished, this, &QgsLayoutItemHtml::htmlRenderFinished );
633 if ( block )
634 {
635 mRenderJob->cancelAndWait();
636 mRenderJob.reset();
637 }
638 else
639 {
640 QgsLayoutItemHtmlRenderJob *oldJob = mRenderJob.release();
641 connect( oldJob, &QgsLayoutItemHtmlRenderJob::finished, oldJob, &QObject::deleteLater );
642 oldJob->cancelWithoutBlocking();
643 }
644}
645
646void QgsLayoutItemHtml::updateFrames()
647{
648 for ( QgsLayoutFrame *frame : std::as_const( mFrameItems ) )
649 {
650 if ( frame )
651 frame->update();
652 }
653}
654
656{
657 mPictureRasterizer->invalidate();
658 updateFrames();
659}
660
661bool candidateSort( QPair<int, int> c1, QPair<int, int> c2 )
662{
663 if ( c1.second < c2.second )
664 return true;
665 else if ( c1.second > c2.second )
666 return false;
667 else if ( c1.first > c2.first )
668 return true;
669 else
670 return false;
671}
672
674{
675 if ( mRenderedPage.isNull() || !mUseSmartBreaks )
676 {
677 return yPos;
678 }
679
680 const double unitsPerCssPx = layoutUnitsPerCssPixel();
681 //convert yPos to pixels
682 const int idealPos = static_cast< int >( yPos / unitsPerCssPx );
683
684 //if ideal break pos is past end of page, there's nothing we need to do
685 if ( idealPos >= mRenderedPage.height() )
686 {
687 return yPos;
688 }
689
690 const int maxSearchDistance = static_cast< int >( mMaxBreakDistance / unitsPerCssPx );
691
692 //loop through all lines just before ideal break location, up to max distance
693 //of maxSearchDistance
694 int changes = 0;
695 QRgb currentColor;
696 bool currentPixelTransparent = false;
697 bool previousPixelTransparent = false;
698 QRgb pixelColor;
699 QList< QPair<int, int> > candidates;
700 const int minRow = std::max( idealPos - maxSearchDistance, 0 );
701 for ( int candidateRow = idealPos; candidateRow >= minRow; --candidateRow )
702 {
703 changes = 0;
704 currentColor = qRgba( 0, 0, 0, 0 );
705 //check all pixels in this line
706 for ( int col = 0; col < mRenderedPage.width(); ++col )
707 {
708 //count how many times the pixels change color in this row
709 //eventually, we select a row to break at with the minimum number of color changes
710 //since this is likely a line break, or gap between table cells, etc
711 //but very unlikely to be midway through a text line or picture
712 pixelColor = mRenderedPage.pixel( col, candidateRow );
713 currentPixelTransparent = qAlpha( pixelColor ) == 0;
714 if ( pixelColor != currentColor && !( currentPixelTransparent && previousPixelTransparent ) )
715 {
716 //color has changed
717 currentColor = pixelColor;
718 changes++;
719 }
720 previousPixelTransparent = currentPixelTransparent;
721 }
722 candidates.append( qMakePair( candidateRow, changes ) );
723 }
724
725 //sort candidate rows by number of changes ascending, row number descending
726 std::sort( candidates.begin(), candidates.end(), candidateSort );
727 //first candidate is now the largest row with smallest number of changes
728
729 //OK, now take the mid point of the best candidate position
730 //we do this so that the spacing between text lines is likely to be split in half
731 //otherwise the html will be broken immediately above a line of text, which
732 //looks a little messy
733 const int maxCandidateRow = candidates[0].first;
734 int minCandidateRow = maxCandidateRow + 1;
735 const int minCandidateChanges = candidates[0].second;
736
737 QList< QPair<int, int> >::iterator it;
738 for ( it = candidates.begin(); it != candidates.end(); ++it )
739 {
740 if ( ( *it ).second != minCandidateChanges || ( *it ).first != minCandidateRow - 1 )
741 {
742 //no longer in a consecutive block of rows of minimum pixel color changes
743 //so return the row mid-way through the block
744 //first converting back to layout units
745 return ( minCandidateRow + ( maxCandidateRow - minCandidateRow ) / 2 ) * unitsPerCssPx;
746 }
747 minCandidateRow = ( *it ).first;
748 }
749
750 //above loop didn't work for some reason
751 //return first candidate converted to layout units
752 return candidates[0].first * unitsPerCssPx;
753}
754
756{
757 if ( mUseSmartBreaks == useSmartBreaks )
758 return;
759
760 mUseSmartBreaks = useSmartBreaks;
761 if ( mUseSmartBreaks && mRenderedPage.isNull() && !mRenderedPicture.isNull() && !mSize.isEmpty() )
762 {
763 const double unitsPerCssPx = layoutUnitsPerCssPixel();
764 const QSize pageSizeCssPx( static_cast< int >( std::ceil( mSize.width() / unitsPerCssPx ) ), static_cast< int >( std::ceil( mSize.height() / unitsPerCssPx ) ) );
765 if ( !pageSizeCssPx.isEmpty() )
766 {
767 mRenderedPage = QImage( pageSizeCssPx, QImage::Format_ARGB32 );
768 mRenderedPage.fill( Qt::transparent );
769 QPainter imagePainter( &mRenderedPage );
770 QgsPainting::drawPicture( &imagePainter, QPointF( 0, 0 ), mRenderedPicture );
771 imagePainter.end();
772 }
773 }
774
776 emit changed();
777}
778
780{
781 mMaxBreakDistance = maxBreakDistance;
783 emit changed();
784}
785
786void QgsLayoutItemHtml::setUserStylesheet( const QString &stylesheet )
787{
788 mUserStylesheet = stylesheet;
789 //TODO - this signal should be emitted, but without changing the signal which sets the css
790 //to an equivalent of editingFinished it causes a lot of problems. Need to investigate
791 //ways of doing this using QScintilla widgets.
792 //emit changed();
793}
794
795void QgsLayoutItemHtml::setUserStylesheetEnabled( const bool stylesheetEnabled )
796{
797 if ( mEnableUserStylesheet != stylesheetEnabled )
798 {
799 mEnableUserStylesheet = stylesheetEnabled;
800 loadHtml( true );
801 emit changed();
802 }
803}
804
806{
807 return tr( "<HTML frame>" );
808}
809
810bool QgsLayoutItemHtml::writePropertiesToElement( QDomElement &htmlElem, QDomDocument &, const QgsReadWriteContext & ) const
811{
812 htmlElem.setAttribute( u"contentMode"_s, QString::number( static_cast< int >( mContentMode ) ) );
813 htmlElem.setAttribute( u"url"_s, mUrl.toString() );
814 htmlElem.setAttribute( u"html"_s, mHtml );
815 htmlElem.setAttribute( u"evaluateExpressions"_s, mEvaluateExpressions ? "true" : "false" );
816 htmlElem.setAttribute( u"useSmartBreaks"_s, mUseSmartBreaks ? "true" : "false" );
817 htmlElem.setAttribute( u"maxBreakDistance"_s, QString::number( mMaxBreakDistance ) );
818 htmlElem.setAttribute( u"stylesheet"_s, mUserStylesheet );
819 htmlElem.setAttribute( u"stylesheetEnabled"_s, mEnableUserStylesheet ? "true" : "false" );
820 return true;
821}
822
823bool QgsLayoutItemHtml::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &, const QgsReadWriteContext & )
824{
825 bool contentModeOK;
826 mContentMode = static_cast< QgsLayoutItemHtml::ContentMode >( itemElem.attribute( u"contentMode"_s ).toInt( &contentModeOK ) );
827 if ( !contentModeOK )
828 {
829 mContentMode = QgsLayoutItemHtml::Url;
830 }
831 mEvaluateExpressions = itemElem.attribute( u"evaluateExpressions"_s, u"true"_s ) == "true"_L1;
832 mUseSmartBreaks = itemElem.attribute( u"useSmartBreaks"_s, u"true"_s ) == "true"_L1;
833 mMaxBreakDistance = itemElem.attribute( u"maxBreakDistance"_s, u"10"_s ).toDouble();
834 mHtml = itemElem.attribute( u"html"_s );
835 mUserStylesheet = itemElem.attribute( u"stylesheet"_s );
836 mEnableUserStylesheet = itemElem.attribute( u"stylesheetEnabled"_s, u"false"_s ) == "true"_L1;
837
838 //finally load the set url
839 const QString urlString = itemElem.attribute( u"url"_s );
840 if ( !urlString.isEmpty() )
841 {
842 mUrl = urlString;
843 }
844
845 //since frames had to be created before, we need to emit a changed signal to refresh the widget
846 emit changed();
847 return true;
848}
849
851{
852 return mFetching || mRenderJob || mBackgroundUpdateTimer->isActive() || ( mPictureRasterizer && mPictureRasterizer->isRendering() );
853}
854
855void QgsLayoutItemHtml::setExpressionContext( const QgsFeature &feature, QgsVectorLayer *layer )
856{
857 mExpressionFeature = feature;
858 mExpressionLayer = layer;
859
860 //setup distance area conversion
861 if ( layer )
862 {
863 mDistanceArea.setSourceCrs( layer->crs(), mLayout->project()->transformContext() );
864 }
865 else if ( mLayout )
866 {
867 //set to composition's mapsettings' crs
868 QgsLayoutItemMap *referenceMap = mLayout->referenceMap();
869 if ( referenceMap )
870 mDistanceArea.setSourceCrs( referenceMap->crs(), mLayout->project()->transformContext() );
871 }
872 if ( mLayout )
873 {
874 mDistanceArea.setEllipsoid( mLayout->project()->ellipsoid() );
875 }
876
877 if ( feature.isValid() )
878 {
879 // create JSON representation of feature
880 QgsJsonExporter exporter( layer );
881 exporter.setIncludeRelated( true );
882 mAtlasFeatureProperties = QgsJsonUtils::jsonToVariant( exporter.exportFeatureToJsonObject( feature ) ).toMap();
883 }
884 else
885 {
886 mAtlasFeatureProperties.clear();
887 }
888}
889
890void QgsLayoutItemHtml::refreshExpressionContext()
891{
892 QgsVectorLayer *vl = nullptr;
893 QgsFeature feature;
894
895 if ( mLayout )
896 {
897 vl = mLayout->reportContext().layer();
898 feature = mLayout->reportContext().feature();
899 }
900
901 setExpressionContext( feature, vl );
902 loadHtml( true );
903}
904
906{
908
909 //updates data defined properties and redraws item to match
911 {
912 loadHtml( true, &context );
913 }
914}
915
916
917//
918// QgsLayoutItemHtmlRenderJob
919//
921QgsLayoutItemHtmlRenderJob::QgsLayoutItemHtmlRenderJob(
922 const QString &html, const QUrl &baseUrl, const QString &userStylesheet, const QVariantMap &featureJson, double frameWidthLayoutUnits, double unitsPerCssPx
923)
924 : mHtml( html )
925 , mBaseUrl( baseUrl )
926 , mUserStylesheet( userStylesheet )
927 , mFeatureJson( featureJson )
928 , mFrameWidthLayoutUnits( frameWidthLayoutUnits )
929 , mUnitsPerCssPx( unitsPerCssPx )
930{
931 connect( &mWatcher, &QFutureWatcher< void >::finished, this, &QgsLayoutItemHtmlRenderJob::finished );
932}
933
934void QgsLayoutItemHtmlRenderJob::start()
935{
936 mWatcher.setFuture( QtConcurrent::run( [this]() { run(); } ) );
937}
938
939void QgsLayoutItemHtmlRenderJob::cancelWithoutBlocking()
940{
941 mFeedback.cancel();
942}
943
944void QgsLayoutItemHtmlRenderJob::cancelAndWait()
945{
946 mFeedback.cancel();
947 mWatcher.waitForFinished();
948}
949
950bool QgsLayoutItemHtmlRenderJob::isCanceled() const
951{
952 return mFeedback.isCanceled();
953}
954
955void QgsLayoutItemHtmlRenderJob::run()
956{
957#ifdef CAN_RENDER
958 const double widthCssPx = mFrameWidthLayoutUnits / mUnitsPerCssPx;
959
960 QPainter painter( &mPicture );
961 QSizeF renderedSizeCssPx;
962
963 QgsHtmlRenderSettings htmlRenderSettings;
964 htmlRenderSettings.setBaseUrl( mBaseUrl );
965 htmlRenderSettings.setUserStylesheet( mUserStylesheet );
966 htmlRenderSettings.setFeatureJson( mFeatureJson );
967
968 mSuccess = QgsWebEnginePage::renderBlocking( mHtml, &painter, QRectF( 0, 0, widthCssPx, 9999 ), mErrorMessage, renderedSizeCssPx, htmlRenderSettings, &mFeedback );
969 painter.end();
970
971 if ( mFeedback.isCanceled() )
972 return;
973
974 const double heightCssPx = renderedSizeCssPx.height();
975 mPicture.setBoundingRect( QRect( 0, 0, static_cast< int >( std::ceil( widthCssPx ) ), static_cast< int >( std::ceil( heightCssPx ) ) ) );
976
977 mSize = QSizeF( mFrameWidthLayoutUnits, heightCssPx * mUnitsPerCssPx );
978
979 const QSize pageSizeCssPx( static_cast< int >( std::ceil( widthCssPx ) ), static_cast< int >( std::ceil( heightCssPx ) ) );
980 if ( !pageSizeCssPx.isEmpty() )
981 {
982 mRenderedPage = QImage( pageSizeCssPx, QImage::Format_ARGB32 );
983 mRenderedPage.fill( Qt::transparent );
984 QPainter imagePainter( &mRenderedPage );
985 QgsPainting::drawPicture( &imagePainter, QPointF( 0, 0 ), mPicture );
986 imagePainter.end();
987 }
988#else
989 mSuccess = false;
990 mErrorMessage = tr( "Rendering HTML requires a QGIS build with WebEngine and PDF4QT support" );
991#endif
992}
@ Inches
Inches.
Definition qgis.h:5794
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
static QString replaceExpressionText(const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea=nullptr)
This function replaces each expression between [% and %] in the string with the result of its evaluat...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
bool isValid() const
Returns the validity of this feature.
Encapsulates settings for rendering HTML content.
void setUserStylesheet(const QString &stylesheet)
Sets the user stylesheet CSS rules to use while rendering the HTML content.
void setBaseUrl(const QUrl &url)
Sets the base url to use when resolving relative links.
void setFeatureJson(const QVariantMap &json)
Sets the feature json (as a variant map).
static QVariant jsonToVariant(const json &value)
Converts a JSON value to a QVariant, in case of parsing error an invalid QVariant is returned.
int type() const override
Returns unique multiframe type id.
QSizeF totalSize() const override
Returns the total size of the multiframe's content, in layout units.
void setUrl(const QUrl &url)
Sets the url for content to display in the item when the item is using the QgsLayoutItemHtml::Url mod...
void invalidateCache()
Invalidates cached renders.
ContentMode
Source modes for the HTML content to render in the item.
@ ManualHtml
HTML content is manually set for the item.
@ Url
Using this mode item fetches its content via a url.
static bool isSupported()
Returns true if HTML item rendering is supported on the system.
void setEvaluateExpressions(bool evaluateExpressions)
Sets whether the html item will evaluate QGIS expressions prior to rendering the HTML content.
bool readPropertiesFromElement(const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context) override
Sets multiframe state from a DOM element.
QString html() const
Returns the HTML source displayed in the item if the item is using the QgsLayoutItemHtml::ManualHtml ...
void refreshDataDefinedProperty(QgsLayoutObject::DataDefinedProperty property=QgsLayoutObject::DataDefinedProperty::AllProperties) override
double maxBreakDistance() const
Returns the maximum distance allowed when calculating where to place page breaks in the html.
void previewRefreshed()
Emitted whenever the item's preview has been refreshed.
static QgsLayoutItemHtml * createFromLabel(QgsLayoutItemLabel *label)
Returns a new QgsLayoutItemHtml matching the content and rendering of a given label.
static QgsLayoutItemHtml * create(QgsLayout *layout)
Returns a new QgsLayoutItemHtml for the specified parent layout.
bool evaluateExpressions() const
Returns whether html item will evaluate QGIS expressions prior to rendering the HTML content.
double findNearbyPageBreak(double yPos) override
Finds the optimal position to break a frame at.
QUrl url() const
Returns the URL of the content displayed in the item if the item is using the QgsLayoutItemHtml::Url ...
void setMaxBreakDistance(double distance)
Sets the maximum distance allowed when calculating where to place page breaks in the html.
void setUserStylesheetEnabled(bool enabled)
Sets whether user stylesheets are enabled for the HTML content.
void setHtml(const QString &html)
Sets the html to display in the item when the item is using the QgsLayoutItemHtml::ManualHtml mode.
QString displayName() const override
Returns the multiframe display name.
void setUseSmartBreaks(bool useSmartBreaks)
Sets whether the html item should use smart breaks.
void recalculateFrameSizes() override
Recalculates the frame sizes for the current viewport dimensions.
void setUserStylesheet(const QString &stylesheet)
Sets the user stylesheet CSS rules to use while rendering the HTML content.
QIcon icon() const override
Returns the item's icon.
bool writePropertiesToElement(QDomElement &elem, QDomDocument &doc, const QgsReadWriteContext &context) const override
Stores multiframe state within an XML DOM element.
QgsLayoutItemHtml(QgsLayout *layout)
Constructor for QgsLayoutItemHtml, with the specified parent layout.
void loadHtml(bool useCache=false, const QgsExpressionContext *context=nullptr)
Reloads the html source from the url and redraws the item.
void render(QgsLayoutItemRenderContext &context, const QRectF &renderExtent, int frameIndex) override
Renders a portion of the multiframe's content into a render context.
bool renderInProgress() const override
Returns true if the multiframe is currently rendering content in a background thread.
bool useSmartBreaks() const
Returns whether html item is using smart breaks.
A layout item subclass for text labels.
QString currentText() const
Returns the text as it appears on the label (with evaluated expressions and other dynamic content).
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used for rendering the map.
@ LayoutHtml
Html multiframe item.
Contains settings and helpers relating to a render of a QgsLayoutItem.
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
QColor backgroundColor(bool useDataDefined=true) const
Returns the background color for this item.
QgsLayoutSize sizeWithUnits() const
Returns the item's current size, including units.
QgsLayoutItemGroup * parentGroup() const
Returns the item's parent group, if the item is part of a QgsLayoutItemGroup group.
QgsLayoutMeasurement frameStrokeWidth() const
Returns the frame's stroke width.
bool isLocked() const
Returns true if the item is locked, and cannot be interacted with using the mouse.
double itemOpacity() const
Returns the item's opacity.
ReferencePoint referencePoint() const
Returns the reference point for positioning of the layout item.
QgsLayoutPoint positionWithUnits() const
Returns the item's current position, including units.
bool frameEnabled() const
Returns true if the item includes a frame.
QColor frameStrokeColor() const
Returns the frame's stroke color.
Qt::PenJoinStyle frameJoinStyle() const
Returns the join style used for drawing the item's frame.
Provides a method of storing measurements for use in QGIS layouts using a variety of different measur...
int frameCount() const
Returns the number of frames associated with this multiframe.
QgsLayoutMultiFrame(QgsLayout *layout)
Construct a new multiframe item, attached to the specified layout.
void contentsChanged()
Emitted when the contents of the multi frame have changed and the frames must be redrawn.
QgsLayoutFrame * frame(int index) const
Returns the child frame at a specified index from the multiframe.
QgsExpressionContext createExpressionContext() const override
This method needs to be reimplemented in all classes which implement this interface and return an exp...
QList< QgsLayoutFrame * > mFrameItems
virtual void recalculateFrameSizes()
Recalculates the portion of the multiframe item which is shown in each of its component frames.
int frameIndex(QgsLayoutFrame *frame) const
Returns the index of a frame within the multiframe.
void backgroundTaskCountChanged(int count)
Emitted whenever the number of background tasks the multi frame is executing changes.
QgsPropertyCollection mDataDefinedProperties
const QgsLayout * layout() const
Returns the layout the object is attached to.
void changed()
Emitted when the object's properties change.
QPointer< QgsLayout > mLayout
DataDefinedProperty
Data defined properties for different item types.
@ AllProperties
All properties for item.
void changed()
Emitted certain settings in the context is changed, e.g.
void refreshed()
Emitted when the layout has been refreshed and items should also be refreshed and updated.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:91
HTTP network content fetcher.
void fetchContent(const QUrl &url, const QString &authcfg=QString(), const QgsHttpHeaders &headers=QgsHttpHeaders())
Fetches content from a remote URL and handles redirects.
void finished()
Emitted when content has loaded.
static QPicture deepCopyQPicture(const QPicture &picture)
Deep copies a QPicture, making a copy which is safe to use in a different thread.
static void drawPicture(QPainter *painter, const QPointF &point, const QPicture &picture)
Draws a picture onto a painter, correctly applying workarounds to avoid issues with incorrect scaling...
Rasterizes and caches a QPicture as a QImage at a requested size.
void rendered()
Emitted when a background rasterization finishes and a new cached image is available.
A container for the context for various read/write operations on objects.
double scaleFactor() const
Returns the scaling factor for the render to convert painter units to physical sizes.
QPainter * painter()
Returns the destination QPainter for the render operation.
Scoped object for saving and restoring a QPainter object's state.
Represents a vector layer which manages a vector based dataset.
static bool renderBlocking(const QString &html, QPainter *painter, const QRectF &painterRect, QString &errorMessage, QSizeF &renderedSize, const QgsHtmlRenderSettings &settings=QgsHtmlRenderSettings(), QgsFeedback *feedback=nullptr)
Renders HTML content to a painter asynchronously.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7811
bool candidateSort(QPair< int, int > c1, QPair< int, int > c2)
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71