QGIS API Documentation 4.5.0-Master (3b5d115045b)
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 switch ( mContentMode )
184 {
186 {
187 QString currentUrl = mUrl.toString();
188
189 //data defined url set?
190 bool ok = false;
191 currentUrl = mDataDefinedProperties.valueAsString( QgsLayoutObject::DataDefinedProperty::SourceUrl, *evalContext, currentUrl, &ok );
192 if ( ok )
193 {
194 currentUrl = currentUrl.trimmed();
195 QgsDebugMsgLevel( u"exprVal Source Url:%1"_s.arg( currentUrl ), 2 );
196 }
197 if ( currentUrl.isEmpty() )
198 {
199 cancelPendingFetch();
200 finalizeLoadedHtml( QString(), QUrl(), evalContext );
201 return;
202 }
203
204 if ( useCache && mHasFetchedHtml && currentUrl == mLastFetchedUrl )
205 {
206 cancelPendingFetch();
207 finalizeLoadedHtml( mFetchedHtml, QUrl( mActualFetchedUrl ), evalContext );
208 }
209 else
210 {
211 if ( !( useCache && mFetching && currentUrl == mPendingFetchUrl ) )
212 {
213 cancelPendingFetch();
214 mBackgroundUpdateTimer->stop();
215 cancelRunningRenderJob( false );
216
217 mPendingFetchUrl = currentUrl;
218 mPendingExpressionContext = context ? std::optional< QgsExpressionContext >( *context ) : std::nullopt;
219 mCacheInvalidated = true;
220 startFetchHtml( QUrl( currentUrl ) );
221 updateFrames();
222 }
223 else if ( context )
224 {
225 mPendingExpressionContext = *context;
226 }
227
228 if ( !mLayout || !mLayout->renderContext().isPreviewRender() )
229 {
230 // if not a preview render, we HAVE to wait till we've loaded content
231 waitForPendingFetch();
232 }
233 }
234
235 break;
236 }
238 cancelPendingFetch();
239 const QUrl baseUrl = ( mLayout && mLayout->project() ) ? QUrl::fromLocalFile( mLayout->project()->absoluteFilePath() ) : QUrl();
240 finalizeLoadedHtml( mHtml, baseUrl, evalContext );
241 break;
242 }
243}
244
245void QgsLayoutItemHtml::startFetchHtml( const QUrl &url )
246{
248 mFetching = true;
249 mFetcher->fetchContent( url );
250}
251
252void QgsLayoutItemHtml::cancelPendingFetch()
253{
254 if ( !mFetching )
255 return;
256
257 mFetching = false;
258 mPendingFetchUrl.clear();
259 mPendingExpressionContext.reset();
260
261 mFetcher->disconnect( this );
262 mFetcher->cancel();
263 mFetcher->deleteLater();
264 mFetcher = new QgsNetworkContentFetcher( this );
265 connect( mFetcher, &QgsNetworkContentFetcher::finished, this, &QgsLayoutItemHtml::onHtmlFetched );
267}
268
269void QgsLayoutItemHtml::waitForPendingFetch()
270{
271 if ( !mFetching )
272 return;
273
274 QEventLoop loop;
275 connect( mFetcher, &QgsNetworkContentFetcher::finished, &loop, &QEventLoop::quit );
276 if ( mFetching )
277 {
278 loop.exec( QEventLoop::ExcludeUserInputEvents );
279 }
280}
281
282void QgsLayoutItemHtml::onHtmlFetched()
283{
284 if ( !mFetching )
285 return;
286
288 mFetching = false;
289 mFetchedHtml = mFetcher->contentAsString();
290 mActualFetchedUrl = mFetcher->reply() ? mFetcher->reply()->url().toString() : mPendingFetchUrl;
291 mLastFetchedUrl = mPendingFetchUrl;
292 mHasFetchedHtml = true;
293 mPendingFetchUrl.clear();
294
295 const std::optional< QgsExpressionContext > savedContext = std::move( mPendingExpressionContext );
296 mPendingExpressionContext = {};
297
298 const QgsExpressionContext scopedContext = createExpressionContext();
299 const QgsExpressionContext *evalContext = savedContext.has_value() ? &*savedContext : &scopedContext;
300 finalizeLoadedHtml( mFetchedHtml, QUrl( mActualFetchedUrl ), evalContext );
301}
302
303void QgsLayoutItemHtml::finalizeLoadedHtml( const QString &rawHtml, const QUrl &baseUrl, const QgsExpressionContext *context )
304{
305 QString loadedHtml = rawHtml;
306 if ( mEvaluateExpressions && !loadedHtml.isEmpty() )
307 {
308 loadedHtml = QgsExpression::replaceExpressionText( loadedHtml, context, &mDistanceArea );
309 }
310
311 mEvaluatedHtml = loadedHtml;
312 mResolvedBaseUrl = baseUrl;
313 mCacheInvalidated = true;
314
315 if ( !mLayout || !mLayout->renderContext().isPreviewRender() )
316 {
317 mBackgroundUpdateTimer->stop();
318 cancelRunningRenderJob( false );
319 renderHtmlSynchronously();
321 }
322 else
323 {
324 // render HTML in a background thread, so we don't block the user interface
325 mBackgroundUpdateTimer->start( 1 );
326 }
327}
328
329void QgsLayoutItemHtml::recreateCachedImageInBackground()
330{
331 if ( mFetching )
332 return;
333
334 cancelRunningRenderJob( false );
335
336 const double frameWidthLayoutUnits = maxFrameWidth();
337 if ( frameWidthLayoutUnits <= 0 || mEvaluatedHtml.isEmpty() )
338 {
339 mCacheInvalidated = false;
340 mLastRenderedWidth = frameWidthLayoutUnits;
341 mSize = QSizeF( 0, 0 );
342 mRenderedPicture = QPicture();
343 mRenderedPage = QImage();
344 mPictureRasterizer->clear();
346 emit contentsChanged();
347 updateFrames();
348 emit previewRefreshed();
350 return;
351 }
352
354 mCacheInvalidated = false;
355 mRenderJob = std::make_unique<
356 QgsLayoutItemHtmlRenderJob >( mEvaluatedHtml, mResolvedBaseUrl, mEnableUserStylesheet ? mUserStylesheet : QString(), mAtlasFeatureProperties, frameWidthLayoutUnits, layoutUnitsPerCssPixel() );
357 connect( mRenderJob.get(), &QgsLayoutItemHtmlRenderJob::finished, this, &QgsLayoutItemHtml::htmlRenderFinished );
358 mRenderJob->start();
359}
360
361void QgsLayoutItemHtml::htmlRenderFinished()
362{
363 if ( !mRenderJob )
364 return;
365
366 if ( !mRenderJob->success() && !mRenderJob->errorMessage().isEmpty() )
367 {
368 QgsDebugError( mRenderJob->errorMessage() );
369 }
370
371 mLastRenderedWidth = mRenderJob->frameWidthLayoutUnits();
372 mSize = mRenderJob->size();
373 mRenderedPicture = QgsPainting::deepCopyQPicture( mRenderJob->picture() );
374 mRenderedPage = mRenderJob->renderedPage();
375 mRenderJob.reset();
376
377 mPictureRasterizer->setPicture( mRenderedPicture );
378
380
382 emit contentsChanged();
383 updateFrames();
384 emit previewRefreshed();
385}
386
387void QgsLayoutItemHtml::renderHtmlSynchronously()
388{
389 if ( mFetching )
390 {
391 waitForPendingFetch();
392 return;
393 }
394
395 const double frameWidthLayoutUnits = maxFrameWidth();
396 mLastRenderedWidth = frameWidthLayoutUnits;
397 mCacheInvalidated = false;
398
399 if ( frameWidthLayoutUnits <= 0 || mEvaluatedHtml.isEmpty() )
400 {
401 mSize = QSizeF( 0, 0 );
402 mRenderedPicture = QPicture();
403 mRenderedPage = QImage();
404 mPictureRasterizer->clear();
406 emit contentsChanged();
407 return;
408 }
409
410 const double unitsPerCssPx = layoutUnitsPerCssPixel();
411 const double widthCssPx = frameWidthLayoutUnits / unitsPerCssPx;
412
413 mRenderedPicture = QPicture();
414 QPainter painter( &mRenderedPicture );
415 painter.setRenderHint( QPainter::Antialiasing, true );
416 painter.setRenderHint( QPainter::TextAntialiasing, true );
417 painter.setRenderHint( QPainter::SmoothPixmapTransform, true );
418
419 QSizeF renderedSizeCssPx;
420
421 QgsHtmlRenderSettings htmlRenderSettings;
422 htmlRenderSettings.setBaseUrl( mResolvedBaseUrl );
423 if ( mEnableUserStylesheet )
424 {
425 htmlRenderSettings.setUserStylesheet( mUserStylesheet );
426 }
427 htmlRenderSettings.setFeatureJson( mAtlasFeatureProperties );
428
429#ifdef CAN_RENDER
430 QString errorMessage;
431 if ( !QgsWebEnginePage::renderBlocking( mEvaluatedHtml, &painter, QRectF( 0, 0, widthCssPx, 9999 ), errorMessage, renderedSizeCssPx, htmlRenderSettings, nullptr ) )
432 {
433 QgsDebugError( errorMessage );
434 }
435#endif
436 painter.end();
437
438 const double heightCssPx = renderedSizeCssPx.height();
439 mRenderedPicture.setBoundingRect( QRect( 0, 0, static_cast< int >( std::ceil( widthCssPx ) ), static_cast< int >( std::ceil( heightCssPx ) ) ) );
440
441 mSize = QSizeF( frameWidthLayoutUnits, heightCssPx * unitsPerCssPx );
442
443 const QSize pageSizeCssPx( static_cast< int >( std::ceil( widthCssPx ) ), static_cast< int >( std::ceil( heightCssPx ) ) );
444 if ( mUseSmartBreaks && !pageSizeCssPx.isEmpty() )
445 {
446 mRenderedPage = QImage( pageSizeCssPx, QImage::Format_ARGB32 );
447 mRenderedPage.fill( Qt::transparent );
448 QPainter imagePainter( &mRenderedPage );
449 QgsPainting::drawPicture( &imagePainter, QPointF( 0, 0 ), mRenderedPicture );
450 imagePainter.end();
451 }
452 else
453 {
454 mRenderedPage = QImage();
455 }
456
457 mPictureRasterizer->setPicture( mRenderedPicture );
458
460 emit contentsChanged();
461}
462
463double QgsLayoutItemHtml::maxFrameWidth() const
464{
465 double maxWidth = 0;
467 {
468 maxWidth = std::max( maxWidth, static_cast< double >( frame->boundingRect().width() ) );
469 }
470
471 return maxWidth;
472}
473
475{
476 if ( frameCount() < 1 )
477 return;
478
479 if ( !mFetching )
480 {
481 const double currentWidth = maxFrameWidth();
482 if ( !qgsDoubleNear( currentWidth, mLastRenderedWidth ) && !mEvaluatedHtml.isEmpty() )
483 {
484 mCacheInvalidated = true;
485 if ( !mLayout || !mLayout->renderContext().isPreviewRender() )
486 {
487 mBackgroundUpdateTimer->stop();
488 cancelRunningRenderJob( false );
489 renderHtmlSynchronously();
490 return;
491 }
492 else
493 {
494 mBackgroundUpdateTimer->start( 1 );
495 }
496 }
497 }
498
500 emit changed();
501}
502
504{
505 return mSize;
506}
507
508void QgsLayoutItemHtml::render( QgsLayoutItemRenderContext &context, const QRectF &renderExtent, const int frameIndex )
509{
510#ifdef CAN_RENDER
511 QPainter *painter = context.renderContext().painter();
512 if ( !painter )
513 return;
514
515 if ( mLayout->renderContext().isPreviewRender() )
516 {
517 const double currentScaleFactor = context.renderContext().scaleFactor();
518
519 if ( !mFetching && ( mCacheInvalidated || !qgsDoubleNear( maxFrameWidth(), mLastRenderedWidth ) ) && !mRenderJob && !mBackgroundUpdateTimer->isActive() && !mEvaluatedHtml.isEmpty() )
520 {
521 mBackgroundUpdateTimer->start( 1 );
522 }
523
524 // main thread preview render ONLY draws the rasterized QImage from QgsPictureRasterizer
525 const QSize targetPixelSize = ( mSize * currentScaleFactor ).toSize();
526 const QImage previewImage = mPictureRasterizer->image( targetPixelSize );
527
528 if ( !previewImage.isNull() && !mSize.isEmpty() )
529 {
530 const QgsScopedQPainterState painterState( painter );
531 painter->scale( currentScaleFactor, currentScaleFactor );
532 painter->translate( -renderExtent.left(), -renderExtent.top() );
533 painter->setClipRect( renderExtent, Qt::IntersectClip );
534 painter->setRenderHint( QPainter::SmoothPixmapTransform, true );
535 painter->drawImage( QRectF( QPointF( 0, 0 ), mSize ), previewImage );
536 }
537 else if ( mFetching || mRenderJob || mBackgroundUpdateTimer->isActive() || mPictureRasterizer->isRendering() )
538 {
539 if ( QgsLayoutFrame *currentFrame = frame( frameIndex ) )
540 {
541 const QgsScopedQPainterState painterState( painter );
542 painter->scale( currentScaleFactor, currentScaleFactor );
543 const QRectF frameRect( 0, 0, currentFrame->rect().width(), currentFrame->rect().height() );
544 painter->setBrush( QBrush( QColor( 125, 125, 125, 125 ) ) );
545 painter->setPen( Qt::NoPen );
546 painter->drawRect( frameRect );
547 painter->setBrush( Qt::NoBrush );
548
549 QFont messageFont;
550 messageFont.setPointSize( 12 );
551 painter->setFont( messageFont );
552 painter->setPen( QColor( 255, 255, 255, 255 ) );
553 painter->drawText( frameRect, Qt::AlignCenter, tr( "Rendering HTML" ) );
554 }
555 }
556 return;
557 }
558
559 if ( mFetching )
560 {
561 waitForPendingFetch();
562 }
563
564 if ( mCacheInvalidated || mRenderJob || !qgsDoubleNear( maxFrameWidth(), mLastRenderedWidth ) )
565 {
566 mBackgroundUpdateTimer->stop();
567 cancelRunningRenderJob( false );
568 renderHtmlSynchronously();
569 }
570
571 const QgsScopedQPainterState painterState( painter );
572 painter->setRenderHint( QPainter::Antialiasing );
573 painter->setRenderHint( QPainter::SmoothPixmapTransform );
574
575 // painter is scaled to dots; scale back to layout units
576 painter->scale( context.renderContext().scaleFactor(), context.renderContext().scaleFactor() );
577 painter->translate( -renderExtent.left(), -renderExtent.top() );
578 painter->setClipRect( renderExtent, Qt::IntersectClip );
579 // scale from CSS pixels (mRenderedPicture's coordinate space) to layout units
580 const double unitsPerCssPx = layoutUnitsPerCssPixel();
581 painter->scale( unitsPerCssPx, unitsPerCssPx );
582
583 QgsPainting::drawPicture( painter, QPointF( 0, 0 ), mRenderedPicture );
584#else
585 Q_UNUSED( renderExtent )
586 if ( mLayout->renderContext().isPreviewRender() )
587 {
588 if ( QgsLayoutFrame *currentFrame = frame( frameIndex ) )
589 {
590 QPainter *painter = context.renderContext().painter();
591
592 // painter is scaled to dots, so scale back to layout units
593 const QRectF painterRect = QRectF(
594 currentFrame->rect().left() * context.renderContext().scaleFactor(),
595 currentFrame->rect().top() * context.renderContext().scaleFactor(),
596 currentFrame->rect().width() * context.renderContext().scaleFactor(),
597 currentFrame->rect().height() * context.renderContext().scaleFactor()
598 );
599
600 painter->setBrush( QBrush( QColor( 255, 125, 125, 125 ) ) );
601 painter->setPen( Qt::NoPen );
602 painter->drawRect( painterRect );
603 painter->setBrush( Qt::NoBrush );
604
605 painter->setPen( QColor( 200, 0, 0, 255 ) );
606 QTextDocument td;
607 td.setTextWidth( painterRect.width() );
608 td.setHtml( u"<span style=\"color: rgb(200,0,0);\"><b>%1</b><br>%2</span>"_s
609 .arg( tr( "HTML rendering not available!" ), tr( "The item cannot be rendered because this QGIS install was built without WebEngine or PDF4QT support." ) ) );
610 painter->setClipRect( painterRect );
611 QAbstractTextDocumentLayout::PaintContext ctx;
612 td.documentLayout()->draw( painter, ctx );
613 }
614 }
615#endif
616}
617
618double QgsLayoutItemHtml::layoutUnitsPerCssPixel() const
619{
620 if ( !mLayout )
621 return 25.4 / 96.0;
622
623 return mLayout->convertToLayoutUnits( QgsLayoutMeasurement( 1.0, Qgis::LayoutUnit::Inches ) ) / 96.0;
624}
625
626void QgsLayoutItemHtml::cancelRunningRenderJob( bool block )
627{
628 if ( !mRenderJob )
629 return;
630
631 disconnect( mRenderJob.get(), &QgsLayoutItemHtmlRenderJob::finished, this, &QgsLayoutItemHtml::htmlRenderFinished );
632 if ( block )
633 {
634 mRenderJob->cancelAndWait();
635 mRenderJob.reset();
636 }
637 else
638 {
639 QgsLayoutItemHtmlRenderJob *oldJob = mRenderJob.release();
640 connect( oldJob, &QgsLayoutItemHtmlRenderJob::finished, oldJob, &QObject::deleteLater );
641 oldJob->cancelWithoutBlocking();
642 }
643}
644
645void QgsLayoutItemHtml::updateFrames()
646{
647 for ( QgsLayoutFrame *frame : std::as_const( mFrameItems ) )
648 {
649 if ( frame )
650 frame->update();
651 }
652}
653
655{
656 mPictureRasterizer->invalidate();
657 updateFrames();
658}
659
660bool candidateSort( QPair<int, int> c1, QPair<int, int> c2 )
661{
662 if ( c1.second < c2.second )
663 return true;
664 else if ( c1.second > c2.second )
665 return false;
666 else if ( c1.first > c2.first )
667 return true;
668 else
669 return false;
670}
671
673{
674 if ( mRenderedPage.isNull() || !mUseSmartBreaks )
675 {
676 return yPos;
677 }
678
679 const double unitsPerCssPx = layoutUnitsPerCssPixel();
680 //convert yPos to pixels
681 const int idealPos = static_cast< int >( yPos / unitsPerCssPx );
682
683 //if ideal break pos is past end of page, there's nothing we need to do
684 if ( idealPos >= mRenderedPage.height() )
685 {
686 return yPos;
687 }
688
689 const int maxSearchDistance = static_cast< int >( mMaxBreakDistance / unitsPerCssPx );
690
691 //loop through all lines just before ideal break location, up to max distance
692 //of maxSearchDistance
693 int changes = 0;
694 QRgb currentColor;
695 bool currentPixelTransparent = false;
696 bool previousPixelTransparent = false;
697 QRgb pixelColor;
698 QList< QPair<int, int> > candidates;
699 const int minRow = std::max( idealPos - maxSearchDistance, 0 );
700 for ( int candidateRow = idealPos; candidateRow >= minRow; --candidateRow )
701 {
702 changes = 0;
703 currentColor = qRgba( 0, 0, 0, 0 );
704 //check all pixels in this line
705 for ( int col = 0; col < mRenderedPage.width(); ++col )
706 {
707 //count how many times the pixels change color in this row
708 //eventually, we select a row to break at with the minimum number of color changes
709 //since this is likely a line break, or gap between table cells, etc
710 //but very unlikely to be midway through a text line or picture
711 pixelColor = mRenderedPage.pixel( col, candidateRow );
712 currentPixelTransparent = qAlpha( pixelColor ) == 0;
713 if ( pixelColor != currentColor && !( currentPixelTransparent && previousPixelTransparent ) )
714 {
715 //color has changed
716 currentColor = pixelColor;
717 changes++;
718 }
719 previousPixelTransparent = currentPixelTransparent;
720 }
721 candidates.append( qMakePair( candidateRow, changes ) );
722 }
723
724 //sort candidate rows by number of changes ascending, row number descending
725 std::sort( candidates.begin(), candidates.end(), candidateSort );
726 //first candidate is now the largest row with smallest number of changes
727
728 //OK, now take the mid point of the best candidate position
729 //we do this so that the spacing between text lines is likely to be split in half
730 //otherwise the html will be broken immediately above a line of text, which
731 //looks a little messy
732 const int maxCandidateRow = candidates[0].first;
733 int minCandidateRow = maxCandidateRow + 1;
734 const int minCandidateChanges = candidates[0].second;
735
736 QList< QPair<int, int> >::iterator it;
737 for ( it = candidates.begin(); it != candidates.end(); ++it )
738 {
739 if ( ( *it ).second != minCandidateChanges || ( *it ).first != minCandidateRow - 1 )
740 {
741 //no longer in a consecutive block of rows of minimum pixel color changes
742 //so return the row mid-way through the block
743 //first converting back to layout units
744 return ( minCandidateRow + ( maxCandidateRow - minCandidateRow ) / 2 ) * unitsPerCssPx;
745 }
746 minCandidateRow = ( *it ).first;
747 }
748
749 //above loop didn't work for some reason
750 //return first candidate converted to layout units
751 return candidates[0].first * unitsPerCssPx;
752}
753
755{
756 if ( mUseSmartBreaks == useSmartBreaks )
757 return;
758
759 mUseSmartBreaks = useSmartBreaks;
760 if ( mUseSmartBreaks && mRenderedPage.isNull() && !mRenderedPicture.isNull() && !mSize.isEmpty() )
761 {
762 const double unitsPerCssPx = layoutUnitsPerCssPixel();
763 const QSize pageSizeCssPx( static_cast< int >( std::ceil( mSize.width() / unitsPerCssPx ) ), static_cast< int >( std::ceil( mSize.height() / unitsPerCssPx ) ) );
764 if ( !pageSizeCssPx.isEmpty() )
765 {
766 mRenderedPage = QImage( pageSizeCssPx, QImage::Format_ARGB32 );
767 mRenderedPage.fill( Qt::transparent );
768 QPainter imagePainter( &mRenderedPage );
769 QgsPainting::drawPicture( &imagePainter, QPointF( 0, 0 ), mRenderedPicture );
770 imagePainter.end();
771 }
772 }
773
775 emit changed();
776}
777
779{
780 mMaxBreakDistance = maxBreakDistance;
782 emit changed();
783}
784
785void QgsLayoutItemHtml::setUserStylesheet( const QString &stylesheet )
786{
787 mUserStylesheet = stylesheet;
788 //TODO - this signal should be emitted, but without changing the signal which sets the css
789 //to an equivalent of editingFinished it causes a lot of problems. Need to investigate
790 //ways of doing this using QScintilla widgets.
791 //emit changed();
792}
793
794void QgsLayoutItemHtml::setUserStylesheetEnabled( const bool stylesheetEnabled )
795{
796 if ( mEnableUserStylesheet != stylesheetEnabled )
797 {
798 mEnableUserStylesheet = stylesheetEnabled;
799 loadHtml( true );
800 emit changed();
801 }
802}
803
805{
806 return tr( "<HTML frame>" );
807}
808
809bool QgsLayoutItemHtml::writePropertiesToElement( QDomElement &htmlElem, QDomDocument &, const QgsReadWriteContext & ) const
810{
811 htmlElem.setAttribute( u"contentMode"_s, QString::number( static_cast< int >( mContentMode ) ) );
812 htmlElem.setAttribute( u"url"_s, mUrl.toString() );
813 htmlElem.setAttribute( u"html"_s, mHtml );
814 htmlElem.setAttribute( u"evaluateExpressions"_s, mEvaluateExpressions ? "true" : "false" );
815 htmlElem.setAttribute( u"useSmartBreaks"_s, mUseSmartBreaks ? "true" : "false" );
816 htmlElem.setAttribute( u"maxBreakDistance"_s, QString::number( mMaxBreakDistance ) );
817 htmlElem.setAttribute( u"stylesheet"_s, mUserStylesheet );
818 htmlElem.setAttribute( u"stylesheetEnabled"_s, mEnableUserStylesheet ? "true" : "false" );
819 return true;
820}
821
822bool QgsLayoutItemHtml::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &, const QgsReadWriteContext & )
823{
824 bool contentModeOK;
825 mContentMode = static_cast< QgsLayoutItemHtml::ContentMode >( itemElem.attribute( u"contentMode"_s ).toInt( &contentModeOK ) );
826 if ( !contentModeOK )
827 {
828 mContentMode = QgsLayoutItemHtml::Url;
829 }
830 mEvaluateExpressions = itemElem.attribute( u"evaluateExpressions"_s, u"true"_s ) == "true"_L1;
831 mUseSmartBreaks = itemElem.attribute( u"useSmartBreaks"_s, u"true"_s ) == "true"_L1;
832 mMaxBreakDistance = itemElem.attribute( u"maxBreakDistance"_s, u"10"_s ).toDouble();
833 mHtml = itemElem.attribute( u"html"_s );
834 mUserStylesheet = itemElem.attribute( u"stylesheet"_s );
835 mEnableUserStylesheet = itemElem.attribute( u"stylesheetEnabled"_s, u"false"_s ) == "true"_L1;
836
837 //finally load the set url
838 const QString urlString = itemElem.attribute( u"url"_s );
839 if ( !urlString.isEmpty() )
840 {
841 mUrl = urlString;
842 }
843
844 //since frames had to be created before, we need to emit a changed signal to refresh the widget
845 emit changed();
846 return true;
847}
848
850{
851 return mFetching || mRenderJob || mBackgroundUpdateTimer->isActive() || ( mPictureRasterizer && mPictureRasterizer->isRendering() );
852}
853
854void QgsLayoutItemHtml::setExpressionContext( const QgsFeature &feature, QgsVectorLayer *layer )
855{
856 mExpressionFeature = feature;
857 mExpressionLayer = layer;
858
859 //setup distance area conversion
860 if ( layer )
861 {
862 mDistanceArea.setSourceCrs( layer->crs(), mLayout->project()->transformContext() );
863 }
864 else if ( mLayout )
865 {
866 //set to composition's mapsettings' crs
867 QgsLayoutItemMap *referenceMap = mLayout->referenceMap();
868 if ( referenceMap )
869 mDistanceArea.setSourceCrs( referenceMap->crs(), mLayout->project()->transformContext() );
870 }
871 if ( mLayout )
872 {
873 mDistanceArea.setEllipsoid( mLayout->project()->ellipsoid() );
874 }
875
876 if ( feature.isValid() )
877 {
878 // create JSON representation of feature
879 QgsJsonExporter exporter( layer );
880 exporter.setIncludeRelated( true );
881 mAtlasFeatureProperties = QgsJsonUtils::jsonToVariant( exporter.exportFeatureToJsonObject( feature ) ).toMap();
882 }
883 else
884 {
885 mAtlasFeatureProperties.clear();
886 }
887}
888
889void QgsLayoutItemHtml::refreshExpressionContext()
890{
891 QgsVectorLayer *vl = nullptr;
892 QgsFeature feature;
893
894 if ( mLayout )
895 {
896 vl = mLayout->reportContext().layer();
897 feature = mLayout->reportContext().feature();
898 }
899
900 setExpressionContext( feature, vl );
901 loadHtml( true );
902}
903
905{
907
908 //updates data defined properties and redraws item to match
910 {
911 loadHtml( true, &context );
912 }
913}
914
915
916//
917// QgsLayoutItemHtmlRenderJob
918//
920QgsLayoutItemHtmlRenderJob::QgsLayoutItemHtmlRenderJob(
921 const QString &html, const QUrl &baseUrl, const QString &userStylesheet, const QVariantMap &featureJson, double frameWidthLayoutUnits, double unitsPerCssPx
922)
923 : mHtml( html )
924 , mBaseUrl( baseUrl )
925 , mUserStylesheet( userStylesheet )
926 , mFeatureJson( featureJson )
927 , mFrameWidthLayoutUnits( frameWidthLayoutUnits )
928 , mUnitsPerCssPx( unitsPerCssPx )
929{
930 connect( &mWatcher, &QFutureWatcher< void >::finished, this, &QgsLayoutItemHtmlRenderJob::finished );
931}
932
933void QgsLayoutItemHtmlRenderJob::start()
934{
935 mWatcher.setFuture( QtConcurrent::run( [this]() { run(); } ) );
936}
937
938void QgsLayoutItemHtmlRenderJob::cancelWithoutBlocking()
939{
940 mFeedback.cancel();
941}
942
943void QgsLayoutItemHtmlRenderJob::cancelAndWait()
944{
945 mFeedback.cancel();
946 mWatcher.waitForFinished();
947}
948
949bool QgsLayoutItemHtmlRenderJob::isCanceled() const
950{
951 return mFeedback.isCanceled();
952}
953
954void QgsLayoutItemHtmlRenderJob::run()
955{
956#ifdef CAN_RENDER
957 const double widthCssPx = mFrameWidthLayoutUnits / mUnitsPerCssPx;
958
959 QPainter painter( &mPicture );
960 QSizeF renderedSizeCssPx;
961
962 QgsHtmlRenderSettings htmlRenderSettings;
963 htmlRenderSettings.setBaseUrl( mBaseUrl );
964 htmlRenderSettings.setUserStylesheet( mUserStylesheet );
965 htmlRenderSettings.setFeatureJson( mFeatureJson );
966
967 mSuccess = QgsWebEnginePage::renderBlocking( mHtml, &painter, QRectF( 0, 0, widthCssPx, 9999 ), mErrorMessage, renderedSizeCssPx, htmlRenderSettings, &mFeedback );
968 painter.end();
969
970 if ( mFeedback.isCanceled() )
971 return;
972
973 const double heightCssPx = renderedSizeCssPx.height();
974 mPicture.setBoundingRect( QRect( 0, 0, static_cast< int >( std::ceil( widthCssPx ) ), static_cast< int >( std::ceil( heightCssPx ) ) ) );
975
976 mSize = QSizeF( mFrameWidthLayoutUnits, heightCssPx * mUnitsPerCssPx );
977
978 const QSize pageSizeCssPx( static_cast< int >( std::ceil( widthCssPx ) ), static_cast< int >( std::ceil( heightCssPx ) ) );
979 if ( !pageSizeCssPx.isEmpty() )
980 {
981 mRenderedPage = QImage( pageSizeCssPx, QImage::Format_ARGB32 );
982 mRenderedPage.fill( Qt::transparent );
983 QPainter imagePainter( &mRenderedPage );
984 QgsPainting::drawPicture( &imagePainter, QPointF( 0, 0 ), mPicture );
985 imagePainter.end();
986 }
987#else
988 mSuccess = false;
989 mErrorMessage = tr( "Rendering HTML requires a QGIS build with WebEngine and PDF4QT support" );
990#endif
991}
@ Inches
Inches.
Definition qgis.h:5809
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:7826
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