37#include <QAbstractTextDocumentLayout>
38#include <QCoreApplication>
40#include <QNetworkReply>
46#include "moc_qgslayoutitemhtml.cpp"
48using namespace Qt::StringLiterals;
55 mHtmlUnitsToLayoutUnits = htmlUnitsToLayoutUnits();
58 if ( QThread::currentThread() == QApplication::instance()->thread() )
60 mWebPage = std::make_unique< QgsWebPage >();
69 mWebPage->setIdentifier( tr(
"Layout HTML item" ) );
70 mWebPage->mainFrame()->setScrollBarPolicy( Qt::Horizontal, Qt::ScrollBarAlwaysOff );
71 mWebPage->mainFrame()->setScrollBarPolicy( Qt::Vertical, Qt::ScrollBarAlwaysOff );
74 QPalette palette = mWebPage->palette();
75 palette.setBrush( QPalette::Base, Qt::transparent );
76 mWebPage->setPalette( palette );
83 setExpressionContext(
mLayout->reportContext().feature(),
mLayout->reportContext().layer() );
92 mFetcher->deleteLater();
114 frame->setVisible( label->isVisible() );
117 frame->setRotation( label->rotation() );
121 frame->setZValue( label->zValue() );
131 html->setUserStylesheetEnabled(
true );
132 html->setUserStylesheet( label->createStylesheet() );
176 switch ( mContentMode )
180 QString currentUrl = mUrl.toString();
187 currentUrl = currentUrl.trimmed();
190 if ( currentUrl.isEmpty() )
194 if ( !( useCache && currentUrl == mLastFetchedUrl ) )
196 loadedHtml = fetchHtml( QUrl( currentUrl ) );
197 mLastFetchedUrl = currentUrl;
201 loadedHtml = mFetchedHtml;
212 if ( mEvaluateExpressions )
220 connect( mWebPage.get(), &QWebPage::loadFinished, &loop, [&loaded, &loop] {
230 mWebPage->setViewportSize( QSize( maxFrameWidth() * mHtmlUnitsToLayoutUnits, 0 ) );
233 const QUrl baseUrl = mContentMode ==
QgsLayoutItemHtml::Url ? QUrl( mActualFetchedUrl ) : QUrl::fromLocalFile(
mLayout->project()->absoluteFilePath() );
235 mWebPage->mainFrame()->setHtml( loadedHtml, baseUrl );
239 if ( mEnableUserStylesheet && !mUserStylesheet.isEmpty() )
242 ba.append( mUserStylesheet.toUtf8() );
243 const QUrl cssFileURL = QUrl( QString(
"data:text/css;charset=utf-8;base64," + ba.toBase64() ) );
244 settings->setUserStyleSheetUrl( cssFileURL );
248 settings->setUserStyleSheetUrl( QUrl() );
252 loop.exec( QEventLoop::ExcludeUserInputEvents );
259double QgsLayoutItemHtml::maxFrameWidth()
const
264 maxWidth = std::max( maxWidth,
static_cast< double >(
frame->boundingRect().width() ) );
278 QSize contentsSize = mWebPage->mainFrame()->contentsSize();
281 const double maxWidth = maxFrameWidth();
283 contentsSize.setWidth( maxWidth * mHtmlUnitsToLayoutUnits );
285 mWebPage->setViewportSize( contentsSize );
286 mSize.setWidth( contentsSize.width() / mHtmlUnitsToLayoutUnits );
287 mSize.setHeight( contentsSize.height() / mHtmlUnitsToLayoutUnits );
288 if ( contentsSize.isValid() )
296void QgsLayoutItemHtml::renderCachedImage()
302 mRenderedPage = QImage( mWebPage->viewportSize(), QImage::Format_ARGB32 );
303 if ( mRenderedPage.isNull() )
307 mRenderedPage.fill( Qt::transparent );
309 painter.begin( &mRenderedPage );
310 mWebPage->mainFrame()->render( &painter );
314QString QgsLayoutItemHtml::fetchHtml(
const QUrl &url )
323 mFetcher->fetchContent(
url );
326 loop.exec( QEventLoop::ExcludeUserInputEvents );
328 mFetchedHtml = mFetcher->contentAsString();
329 mActualFetchedUrl = mFetcher->reply()->url().toString();
340 Q_UNUSED( renderExtent )
341 if (
mLayout->renderContext().isPreviewRender() )
348 const QRectF painterRect = QRectF(
355 painter->setBrush( QBrush( QColor( 255, 125, 125, 125 ) ) );
356 painter->setPen( Qt::NoPen );
357 painter->drawRect( painterRect );
358 painter->setBrush( Qt::NoBrush );
360 painter->setPen( QColor( 200, 0, 0, 255 ) );
362 td.setTextWidth( painterRect.width() );
364 u
"<span style=\"color: rgb(200,0,0);\"><b>%1</b><br>%2</span>"_s.arg( tr(
"WebKit not available!" ), tr(
"The item cannot be rendered because this QGIS install was built without WebKit support." ) )
366 painter->setClipRect( painterRect );
367 QAbstractTextDocumentLayout::PaintContext ctx;
368 td.documentLayout()->draw( painter, ctx );
373double QgsLayoutItemHtml::htmlUnitsToLayoutUnits()
385 if ( c1.second < c2.second )
387 else if ( c1.second > c2.second )
389 else if ( c1.first > c2.first )
397 if ( !mWebPage || mRenderedPage.isNull() || !mUseSmartBreaks )
403 const int idealPos = yPos * htmlUnitsToLayoutUnits();
406 if ( idealPos >= mRenderedPage.height() )
411 const int maxSearchDistance = mMaxBreakDistance * htmlUnitsToLayoutUnits();
417 bool currentPixelTransparent =
false;
418 bool previousPixelTransparent =
false;
420 QList< QPair<int, int> > candidates;
421 const int minRow = std::max( idealPos - maxSearchDistance, 0 );
422 for (
int candidateRow = idealPos; candidateRow >= minRow; --candidateRow )
425 currentColor = qRgba( 0, 0, 0, 0 );
427 for (
int col = 0; col < mRenderedPage.width(); ++col )
433 pixelColor = mRenderedPage.pixel( col, candidateRow );
434 currentPixelTransparent = qAlpha( pixelColor ) == 0;
435 if ( pixelColor != currentColor && !( currentPixelTransparent && previousPixelTransparent ) )
438 currentColor = pixelColor;
441 previousPixelTransparent = currentPixelTransparent;
443 candidates.append( qMakePair( candidateRow, changes ) );
447 std::sort( candidates.begin(), candidates.end(),
candidateSort );
454 const int maxCandidateRow = candidates[0].first;
455 int minCandidateRow = maxCandidateRow + 1;
456 const int minCandidateChanges = candidates[0].second;
458 QList< QPair<int, int> >::iterator it;
459 for ( it = candidates.begin(); it != candidates.end(); ++it )
461 if ( ( *it ).second != minCandidateChanges || ( *it ).first != minCandidateRow - 1 )
466 return ( minCandidateRow + ( maxCandidateRow - minCandidateRow ) / 2 ) / htmlUnitsToLayoutUnits();
468 minCandidateRow = ( *it ).first;
473 return candidates[0].first / htmlUnitsToLayoutUnits();
492 mUserStylesheet = stylesheet;
501 if ( mEnableUserStylesheet != stylesheetEnabled )
503 mEnableUserStylesheet = stylesheetEnabled;
511 return tr(
"<HTML frame>" );
516 htmlElem.setAttribute( u
"contentMode"_s, QString::number(
static_cast< int >( mContentMode ) ) );
517 htmlElem.setAttribute( u
"url"_s, mUrl.toString() );
518 htmlElem.setAttribute( u
"html"_s, mHtml );
519 htmlElem.setAttribute( u
"evaluateExpressions"_s, mEvaluateExpressions ?
"true" :
"false" );
520 htmlElem.setAttribute( u
"useSmartBreaks"_s, mUseSmartBreaks ?
"true" :
"false" );
521 htmlElem.setAttribute( u
"maxBreakDistance"_s, QString::number( mMaxBreakDistance ) );
522 htmlElem.setAttribute( u
"stylesheet"_s, mUserStylesheet );
523 htmlElem.setAttribute( u
"stylesheetEnabled"_s, mEnableUserStylesheet ?
"true" :
"false" );
531 if ( !contentModeOK )
535 mEvaluateExpressions = itemElem.attribute( u
"evaluateExpressions"_s, u
"true"_s ) ==
"true"_L1;
536 mUseSmartBreaks = itemElem.attribute( u
"useSmartBreaks"_s, u
"true"_s ) ==
"true"_L1;
537 mMaxBreakDistance = itemElem.attribute( u
"maxBreakDistance"_s, u
"10"_s ).toDouble();
538 mHtml = itemElem.attribute( u
"html"_s );
539 mUserStylesheet = itemElem.attribute( u
"stylesheet"_s );
540 mEnableUserStylesheet = itemElem.attribute( u
"stylesheetEnabled"_s, u
"false"_s ) ==
"true"_L1;
543 const QString urlString = itemElem.attribute( u
"url"_s );
544 if ( !urlString.isEmpty() )
557 mExpressionFeature = feature;
558 mExpressionLayer = layer;
568 QgsLayoutItemMap *referenceMap =
mLayout->referenceMap();
570 mDistanceArea.setSourceCrs( referenceMap->
crs(),
mLayout->project()->transformContext() );
574 mDistanceArea.setEllipsoid(
mLayout->project()->ellipsoid() );
580 QgsJsonExporter exporter( layer );
581 exporter.setIncludeRelated(
true );
582 mAtlasFeatureJSON = exporter.exportFeature( feature );
586 mAtlasFeatureJSON.clear();
590void QgsLayoutItemHtml::refreshExpressionContext()
592 QgsVectorLayer *vl =
nullptr;
597 vl =
mLayout->reportContext().layer();
598 feature =
mLayout->reportContext().feature();
601 setExpressionContext( feature, vl );
619void JavascriptExecutorLoop::done()
625void JavascriptExecutorLoop::execIfNotDone()
628 exec( QEventLoop::ExcludeUserInputEvents );
632 for (
int i = 0; i < 100; i++ )
633 qApp->processEvents();
636void JavascriptExecutorLoop::reportError(
const QString &error )
A collection of stubs to mimic the API of a QWebSettings on systems where QtWebkit is not available.
@ Millimeters
Millimeters.
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...
bool isValid() const
Returns the validity of this feature.
Base class for frame items, which form a layout multiframe item.
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...
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.
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
~QgsLayoutItemHtml() override
double maxBreakDistance() const
Returns the maximum distance allowed when calculating where to place page breaks in the html.
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 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.
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
friend class QgsLayoutFrame
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.
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.
@ SourceUrl
Html source url.
@ AllProperties
All properties for item.
void changed()
Emitted certain settings in the context is changed, e.g.
QgsCoordinateReferenceSystem crs
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
HTTP network content fetcher.
void finished()
Emitted when content has loaded.
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.
Represents a vector layer which manages a vector based dataset.
bool candidateSort(QPair< int, int > c1, QPair< int, int > c2)
#define QgsDebugMsgLevel(str, level)